TableAjax.php 218 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069
  1. <?php
  2. Lib::loadClass('ViewAjax');
  3. Lib::loadClass('TableAjaxMap');
  4. Lib::loadClass('Typespecial');
  5. Lib::loadClass('SE_Layout');
  6. Lib::loadClass('FoldersConfig');
  7. Lib::loadClass('FileUploader');
  8. Lib::loadClass('UserProfile');
  9. Lib::loadClass('ProcesHelper');
  10. Lib::loadClass('Router');
  11. class TableAjax extends ViewAjax {
  12. private $_cnf = '';// Column
  13. private $_htmlID = '';
  14. private $_rowFunctions = array();
  15. private $_pageSize = 10;
  16. private $_pageSizes = array();
  17. private $_filterInit = null;
  18. private $_forceFilterInit = null;
  19. private $_showProcesInit = true;
  20. public function __construct($tblAcl) {
  21. $this->_tbl = $tblAcl->getName();
  22. $this->_acl = $tblAcl;
  23. $this->_zasobID = $tblAcl->getID();
  24. $this->_pageSize = 10;
  25. {
  26. UserProfile::load();
  27. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  28. $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
  29. }
  30. $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
  31. $this->_filterInit = new stdClass();
  32. $hash = V::get('_hash', '', $_GET);
  33. if ($hash) {
  34. $this->_htmlID = $hash;
  35. $this->_readState();
  36. } else {
  37. $this->_htmlID = $this->generateHtmlID();
  38. $this->_readState();
  39. }
  40. }
  41. public function showProcesInit($bool = true) {
  42. $this->_showProcesInit = $bool;
  43. }
  44. private function _hasStateFilterInit() {
  45. return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
  46. }
  47. // TODO: read state from cache by key $this->_htmlID
  48. // TODO: load filters and state: table, edit, add, etc.
  49. // TODO: save this data in Workspace 1, 2, 3, etc.
  50. // TODO: default filters in VIEWTABLE_AJAX
  51. // $tbl->setLabel($zasobObj->OPIS);
  52. // $tbl->setFilterInit($filterInit);
  53. // $tbl->addRowFunction('edit');
  54. // $tbl->addRowFunction('hist');
  55. // $tbl->addRowFunction('files');
  56. // $tbl->addRowFunction('cp');
  57. private function _readState() {
  58. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  59. $_SESSION['TableAjax_Cache'] = array();
  60. }
  61. //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
  62. //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
  63. if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  64. foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
  65. //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
  66. switch ($k) {
  67. case '_label':
  68. $this->_label = $v;
  69. break;
  70. case '_filterInit':
  71. $this->_filterInit = $v;
  72. break;
  73. case '_rowFunctions':
  74. $this->_rowFunctions = $v;
  75. break;
  76. default:
  77. }
  78. }
  79. }
  80. }
  81. protected function _saveState($key = null) {
  82. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  83. $_SESSION['TableAjax_Cache'] = array();
  84. }
  85. if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  86. $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
  87. }
  88. if (!$key) {
  89. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  90. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  91. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  92. } else if ($key == '_label') {
  93. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  94. } else if ($key == '_filterInit') {
  95. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  96. } else if ($key == '_rowFunctions') {
  97. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  98. }
  99. }
  100. public function setPageSizes($pageSizes) {
  101. $this->_pageSizes = $pageSizes;
  102. }
  103. public function setFilterInit($filterInit) {
  104. if ($this->_hasStateFilterInit()) {
  105. return;
  106. }
  107. $this->_filterInit = (object)$filterInit;
  108. $this->_saveState();
  109. }
  110. /**
  111. * @param array $forceFilterInit
  112. */
  113. public function setForceFilterInit($forceFilterInit) {
  114. $this->_forceFilterInit = (object)$forceFilterInit;
  115. }
  116. private function setFilters($filterInit) {
  117. $this->_filterInit = (object)$filterInit;
  118. $this->_saveState();
  119. }
  120. public function addRowFunction($funName, $funParams = array()) {
  121. $defaultRowFunction = array();
  122. //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
  123. //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
  124. //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
  125. //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
  126. $defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord');
  127. $defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia');
  128. $defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki');
  129. $defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  130. $defaultRowFunction['msgs'] = array('href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości');
  131. if (array_key_exists($funName, $defaultRowFunction)) {
  132. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  133. }
  134. else {
  135. $this->_rowFunctions[$funName] = $funParams;
  136. }
  137. $this->_saveState('_rowFunctions');
  138. }
  139. private function _parseRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  140. $rowFunctions = array();
  141. foreach ($this->_rowFunctions as $kFunName => $vParams) {
  142. if (in_array($kFunName, $pomin)) continue;
  143. //$rowFunctionsOut .= str_replace('{0}', $recordID, $vUrl);
  144. $attrs = array();
  145. // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  146. $label = '';
  147. $ico = '';
  148. foreach ($vParams as $kParamName => $v) {
  149. if ($kParamName == 'ico') {
  150. $ico = '<span class="' . $v . '"></span>';
  151. continue;
  152. }
  153. $attr = $v;
  154. if ($recordID > 0) {
  155. $attr = str_replace('{0}', $recordID, $attr);
  156. }
  157. if ($showLabel && $kParamName == 'title') {
  158. $label = $attr;
  159. }
  160. $attr = $kParamName . '="' . $attr . '"';
  161. $attrs[] = $attr;
  162. }
  163. $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
  164. }
  165. return $rowFunctions;
  166. }
  167. private function _showRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  168. $rowFunctionsOut = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  169. $rowFunctionsOut = implode('', $rowFunctionsOut);
  170. return $rowFunctionsOut;
  171. }
  172. private function _showRowFunctionsJson($recordID = null, $pomin = array(), $showLabel = false) {
  173. $rowFunctions = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  174. $rowFunctions = (object)$rowFunctions;
  175. return $rowFunctions;
  176. }
  177. private function _showExportFieldsJson() {
  178. $exportFields = $this->_acl->getExportFieldList();
  179. return $exportFields;
  180. }
  181. private function getProcesInitSelected() {
  182. $userAcl = User::getAcl();
  183. return $userAcl->getPermsFiltrProcesId();
  184. }
  185. public function allowTreeView() {
  186. if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
  187. if ($this->_tbl == 'CRM_PROCES') return true;
  188. return false;
  189. }
  190. public function hasGeomFields() {
  191. $hasGeomFields = false;
  192. $fieldsList = $this->_acl->getFields();
  193. foreach ($fieldsList as $kID => $vCol) {
  194. if ($this->_acl->isGeomField($vCol['name'])) {
  195. if ($this->_acl->hasFieldPerm($kID, 'R')) {
  196. $hasGeomFields = true;
  197. break;
  198. }
  199. }
  200. }
  201. return $hasGeomFields;
  202. }
  203. public function render() {
  204. $hasGeomFlds = $this->hasGeomFields();
  205. $tblAjaxMap = null;
  206. if ($hasGeomFlds) {
  207. $tblAjaxMap = new TableAjaxMap($this->_acl, 512, 400);
  208. }
  209. $hasPermCreate = $this->_acl->hasCreatePerms();
  210. $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
  211. ob_start();
  212. ?>
  213. <div class="container">
  214. <?php SE_Layout::showMessagesForTable($this->_tbl); ?>
  215. </div>
  216. <?php if ($tblAjaxMap) $tblAjaxMap->printCSS(); ?>
  217. <?php if ($tblAjaxMap) $tblAjaxMap->printJS(); ?>
  218. <script src="stuff/jquery-ui-1.10.4.custom.min.js"></script>
  219. <link rel="stylesheet" type="text/css" href="stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css">
  220. <style type="text/css">
  221. .AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
  222. .AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
  223. .AjaxTable *,
  224. .AjaxTable.table {white-space:nowrap; width:auto;}
  225. .AjaxTable .popover * {white-space:normal;}
  226. .AjaxTable p {margin:0;}
  227. .AjaxTable td, .AjaxTable th {line-height:18px;}
  228. .AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
  229. .AjaxTable span.filter {background-color:#999;}
  230. .AjaxTable .indeterminate {opacity: 0.4;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";filter:alpha(opacity=40);}
  231. .AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
  232. .AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
  233. .AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
  234. .AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
  235. .AjaxTable input[type=text].filter {margin:0;padding:0 5px;box-shadow:none;width:100%;background:#eee;color:#000;}
  236. .AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
  237. .AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
  238. .AjaxTable .date-wrap {width:100%;min-width:115px;}
  239. .AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
  240. .AjaxTable .actions a {padding:0;margin:0;}
  241. .AjaxTableCont .text-right {text-align:right}
  242. .AjaxTableCont .breadcrumb em {color:#bbb;}
  243. .AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
  244. .AjaxTable-loading .loading-info,
  245. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
  246. .AjaxTableCont .loading-info {display:none;}
  247. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block;}
  248. .AjaxTableCont .table {margin-bottom:0px;}
  249. .AjaxTableCont .stickyCol1 a { color:#333; }
  250. .AjaxTableCont .stickyCol1 a:hover { color:#337AB7; text-decoration:none; }
  251. .AjaxTableTaskCnt {padding:0 10px 10px 10px;}
  252. .AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
  253. .AjaxTable .tbl-short-txt span{display:block; height:18px;}
  254. .AjaxTable .tooltip-inner{white-space:normal;}
  255. .AjaxTable thead .sort .ta-ordering {cursor:pointer;}
  256. .AjaxTable thead .sort .ta-ordering span {margin:0 10px 0 0; padding:0; background-repeat:no-repeat; background-position:right top;}
  257. .AjaxTable thead .sort .ta-ordering-down span:after{content:"\e252";font-family:"Glyphicons Halflings";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  258. .AjaxTable thead .sort .ta-ordering-up span:after{content:"\e253";font-family:"Glyphicons Halflings";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  259. .AjaxTable thead .sort .ta-ordering {position:relative;}
  260. .AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
  261. .AjaxTable thead .sort th .hover-show{display:none;}
  262. .AjaxTable thead .sort th:hover .hover-show{display:inline;}
  263. .AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none; color:#f00;}
  264. .AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
  265. .AjaxTableCont .pagination { margin:0; }
  266. .AjaxTableCont .pagination a { line-height:16px; }
  267. .AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
  268. .AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
  269. .AjaxTableCont .AjaxTableEdit .show-last-value .button-appendBack .glyphicon,
  270. .AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .button-appendBack .glyphicon {display:none;}
  271. .AjaxTableHist em {color:silver;}
  272. .AjaxTableCont .foot * { font-size:12px !important; }
  273. .AjaxTableCont .foot { margin:10px; }
  274. .AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
  275. .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
  276. .AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
  277. .tblAjax__head__specialFilter {margin:0;padding:4px 4px 4px 127px;}
  278. .tblAjax__head__specialFilter .btn-group {margin:0 4px;padding:0;}
  279. .tblAjax__head__specialFilter .btn-group .glyphicon-remove {color:#f00;}
  280. .tblAjax__head__specialFilter .btn-group button.disabled .glyphicon-remove {color:#bbb;}
  281. /* overwrite bootstrap table border */
  282. .AjaxTable, .AjaxTableEdit,
  283. .AjaxTable td, .AjaxTableEdit td,
  284. .AjaxTable th, .AjaxTableEdit th { border-color:#999; }
  285. /* cell A_STATUS */
  286. .AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
  287. .AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
  288. .AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
  289. .AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
  290. .AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
  291. .AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
  292. .AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
  293. /* cell Status */
  294. .AjaxTable .cell-Status-U { background:rgb(0,176,80); color:#000; text-align:center; }
  295. .AjaxTable .cell-Status-NU { background:#f00; color:#000; text-align:center; }
  296. .AjaxTable .cell-Status-P { background:rgb(112,48,160); color:#000; text-align:center; }
  297. .AjaxTable .cell-Status-PT { background:rgb(127,127,127); color:#000; text-align:center; }
  298. .AjaxTable .cell-Status-O { background:rgb(0,176,240); color:#000; text-align:center; }
  299. .AjaxTable .cell-Status-DZ { background:rgb(0,112,192); color:#000; text-align:center; }
  300. .AjaxTable .cell-Status-Z {}
  301. /* map */
  302. .AjaxTable .cell-mapfld { cursor:pointer; }
  303. .AjaxTable .cell-mapfld:hover { opacity:1; }
  304. .AjaxTable .cell-mapfld-remove { display:none; }
  305. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { color:#f00; }
  306. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
  307. .AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; color:#eee; border:1px solid #999; }
  308. .AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
  309. .AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
  310. .AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
  311. .AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
  312. .AjaxTableCont .mapEditor-map { background:#fff; height:400px; }
  313. .AjaxTableCont-mapEditorContainer .mapEditor-map { border:1px solid #999; overflow:hidden; }
  314. /* .mapEditor-btnBackToWindow "olControlSave",overview_replacement */
  315. .olControlEditingToolbar .mapEditor-btnBackToWindowItemInactive,
  316. .olControlEditingToolbar .mapEditor-btnBackToWindowItemActive {
  317. background-image: url(icon/map.window.png);
  318. background-position: 0 0;
  319. background-repeat: no-repeat;
  320. }
  321. /*
  322. .mapEditor-btnBackToWindowItemInactive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  323. .mapEditor-btnBackToWindowItemActive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  324. */
  325. .ui-dialog-content .mapEditor-btnBackToWindowItemInactive,
  326. .ui-dialog-content .mapEditor-btnBackToWindowItemActive { display:none; }
  327. .AjaxTableCont .valign-btns-bottom a { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
  328. .ui-resizable-s { bottom:0; }
  329. .ui-resizable-e { right:0; }
  330. .AjaxTableCont-mapEditorContainer .ui-resizable-s { background-color:#ddd; }
  331. .AjaxTableCont-mapEditorContainer .ui-resizable-s:hover { background-color:#888; }
  332. </style>
  333. <div class="AjaxTableCont">
  334. <ul class="breadcrumb">
  335. <li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>
  336. <!-- TODO: if has perm 'C' then add btn to create new record -->
  337. <?php if ($hasPermCreate) : ?>
  338. <li><a title="Dodaj nowy rekord"
  339. class=""
  340. href="#CREATE"><span class="glyphicon glyphicon-plus"></span> Dodaj nowy rekord</a></li>
  341. <?php endif; ?>
  342. <?php if ($this->_showProcesInit) : ?>
  343. <div class="btn-group pull-right">
  344. <a class="btn btn-xs btn-info dropdown-toggle"
  345. data-toggle="dropdown"
  346. href="#"
  347. title="Uruchom filtr procesu powiązanego z tabelą <?php echo $this->getLabel(); ?>"
  348. onclick="return <?php echo $jsToogleFiltrProcesuFunctionName; ?>(this);">
  349. Filtr procesu <span class="caret"></span>
  350. </a>
  351. <ul class="dropdown-menu pull-left" style="max-height:250px;overflow:auto;">
  352. <li class="disabled"><a href="#" onclick="return false;"> loading ... </a></li>
  353. </ul>
  354. </div>
  355. <?php endif; ?>
  356. <?php if ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') : ?>
  357. <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}"; ?>"><i class="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  358. <?php elseif ($this->allowTreeView()) : ?>
  359. <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="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  360. <?php endif; ?>
  361. </ul>
  362. <div id="<?php echo $this->_htmlID; ?>"></div>
  363. </div>
  364. <script>
  365. (function($) {
  366. var TableAjaxGeomField = function() {
  367. var priv = {}; //private api
  368. var publ = {}; //public api
  369. priv.options = {};
  370. var defaults = {
  371. recordID: '',
  372. fieldValue: '',
  373. hasValueClassName: 'TableAjaxGeomField-hasValue',
  374. linkClassNamePrefix: 'TableAjaxGeomField',
  375. linkSelectClassName: 'select',
  376. linkSelectAddClassNames: '', // 'glyphicon glyphicon-map-marker'
  377. linkRemoveClassName: 'remove',
  378. linkRemoveAddClassNames: '', // 'glyphicon glyphicon-remove'
  379. removeUrl: '',
  380. onSelect: null,
  381. onRemove: null,
  382. debug: false
  383. };
  384. priv.init = function() {
  385. priv.render();
  386. };
  387. priv.render = function() {
  388. var state = priv.options;
  389. var cellMapSelect = jQuery('<i title="Pokaż/utwórz obiekt na mapie"></i>');
  390. cellMapSelect.addClass(state.linkClassNamePrefix + '-' + state.linkSelectClassName);
  391. if (state.linkSelectAddClassNames) {
  392. cellMapSelect.addClass(state.linkSelectAddClassNames);
  393. }
  394. cellMapSelect.on('click', {recordID: priv.options.recordID, fieldValue: priv.options.fieldValue}, function(e) {
  395. if (typeof state.onSelect == "function") {
  396. state.onSelect.call(this, e.data.recordID, e.data.fieldValue);
  397. }
  398. });
  399. var cellMapRemove = jQuery('<i title="Usuń obiekt z mapy"></i>');
  400. cellMapRemove.addClass(state.linkClassNamePrefix + '-' + state.linkRemoveClassName);
  401. if (state.linkRemoveAddClassNames) {
  402. cellMapRemove.addClass(state.linkRemoveAddClassNames);
  403. }
  404. cellMapRemove.on('click', {recordID: state.recordID, fieldValue: state.fieldValue}, function(e) {
  405. if (typeof state.onRemove == "function") {
  406. state.onRemove.call(this, publ, e.data.recordID, e.data.fieldValue);
  407. }
  408. });
  409. var node = $(state.id);
  410. node.empty();
  411. node.addClass(state.linkClassNamePrefix);
  412. node.removeClass(state.hasValueClassName);
  413. if (state.fieldValue) {
  414. node.addClass(state.hasValueClassName);
  415. }
  416. node.append(cellMapSelect);
  417. node.append(cellMapRemove);
  418. };
  419. publ.setValue = function(value) {
  420. if (priv.options.debug) console.log('TEST setValue: ', value, 'this', this);
  421. priv.options.fieldValue = value;
  422. priv.render();
  423. };
  424. publ.init = function(options) {
  425. if (priv.options.debug) console.log('TableAjaxGeomField initialization...', options);
  426. //merge supplied options with defaults
  427. $.extend(priv.options, defaults, options);
  428. priv.init();
  429. return publ;
  430. };
  431. return publ;
  432. };
  433. $.fn.TableAjaxGeomFieldSetValue = function(value) {
  434. return this.each(function() {
  435. var tblAjaxMapGeomFld = $(this).data('TableAjaxGeomField');
  436. if (tblAjaxMapGeomFld) {
  437. tblAjaxMapGeomFld.setValue(value);
  438. }
  439. });
  440. return this;
  441. };
  442. $.fn.TableAjaxGeomField = function(options) {
  443. options = options || {};
  444. return this.each(function() {
  445. options.id = this;
  446. if (!$(this).data('TableAjaxGeomField')) {
  447. $(this).data('TableAjaxGeomField', new TableAjaxGeomField().init(options));
  448. }
  449. });
  450. return this;
  451. };
  452. }(jQuery));
  453. (function($, undefined) {
  454. var TableAjax = function() {
  455. var priv = {}; //private api
  456. var publ = {}; //public api
  457. priv.options = {};
  458. var defaults = {
  459. url: '', //webservice url
  460. urlData: '', //webservice params
  461. urlPost: false, //use POST instead of GET
  462. debug: false, //prints debug info to console
  463. filter: false, //show filter row
  464. filterInit: false,// init filters data
  465. forceFilterInit: false,
  466. columnPicker: false, //show columnpicker
  467. checkboxes: false, //show body checkboxes
  468. actions: '', //holds action links
  469. pageSize: 10, //current pagesize
  470. pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
  471. hidePagerOnEmpty: false, //removes pager if no rows
  472. types: { //type specific options
  473. string: {},
  474. number: {},
  475. bool: {},
  476. date: {}
  477. },
  478. rowFunctions: false,
  479. tblFunctions: false,
  480. specialFilterFunctions: false,
  481. filtersClean: false,
  482. router: false,
  483. longDesc: false,
  484. exportFields: [],
  485. mapEditor: false, // mapEditor visible or not
  486. mapEditorContainer: 'window' // 'window' or 'dock'
  487. };
  488. var _uiNodeCont; // container holding table
  489. var _uiNode$Table; // the table node
  490. var _head; // table header
  491. var _headSort; // table header sorting row
  492. var _headFilter; // table header columns filter row
  493. var _headSpecialFilter; // table header special filter row
  494. var _bodyNode; // table body
  495. var _body; // TODO: table body need render?
  496. var _foot; // table footer
  497. var _inlineEditBox; // inline edit box with form
  498. var _popoverCell; // inline popover cell
  499. var _popoverCellCurrent; // inline popover cell
  500. var _popoverCellAjaxXhr;
  501. var _mapEditor; // map editor node
  502. var _mapEditorWrap; // map editor wrapper node
  503. var _mapEditorDialog; // map editor jquery ui dialog node
  504. var _state = {};// state - to replace variables below (date, ...)
  505. var _data; //columns and rows
  506. var _totalPages; // total pages
  507. var _currDpOp; // clicked datetimepicker operator
  508. var _filterFields = {}; // array with filter DOM elements
  509. var _filterTimeout; // timer for delayed filtering
  510. var _uniqueCols = {}; // array with checked rows /// TODO: mv to _state.
  511. var _checkToggleChecked = false; // check-all toggle state
  512. var _exportFieldsSelect = {};
  513. var _tableWidth;
  514. /*
  515. initialize the plugin.
  516. */
  517. priv.init = function() {
  518. _uiNodeCont = priv.options.id;
  519. _state = {};// init state
  520. _state.page = 1;
  521. _state.specialFilters = {};
  522. _state.filters = {};
  523. _state.filters.currSortCol = '';
  524. _state.filters.currSortFlip = false;
  525. _state.filters.filterCols = {};
  526. priv.initEvents();
  527. priv.initialRender();// set up _uiNode$...
  528. priv.options.types.string = ((priv.options.types || {}).string || {});
  529. priv.options.types.number = ((priv.options.types || {}).number || {});
  530. priv.options.types.bool = ((priv.options.types || {}).bool || {});
  531. priv.options.types.date = ((priv.options.types || {}).date || {});
  532. if (priv.options.mapEditorContainer != 'dock'
  533. && priv.options.mapEditorContainer != 'window') {
  534. priv.options.mapEditorContainer = 'window';
  535. }
  536. if (priv.options.filterInit) {
  537. priv.setStateFilters(priv.options.filterInit);
  538. }
  539. $.each(priv.options.exportFields, function(ind, col) {
  540. _exportFieldsSelect[col] = true;
  541. });
  542. //try call webservice for data
  543. priv.update(priv.options.router);
  544. if (typeof priv.options.router == "function") {
  545. $(window).bind('hashchange', function() {
  546. priv.options.router.apply(this);
  547. });
  548. }
  549. };
  550. priv.initEvents = function() {
  551. jQuery(_uiNodeCont).on('TableAjax:render', priv.onRender);
  552. };
  553. priv.onRender = function(e) {
  554. if (priv.options.debug) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
  555. if (arguments.length > 1) {
  556. for (var i=1; i<arguments.length; i++) {
  557. switch (arguments[i]) {
  558. case 'head': _head = undefined; break;
  559. case 'body': _body = undefined; break;
  560. case 'foot': _foot = undefined; break;
  561. case 'foot_pagination': {
  562. priv.renderFooterInfo();
  563. priv.renderFooterPagination();
  564. priv.renderFooterPageSizes();
  565. }
  566. break;
  567. case 'footer__toolbar__info': priv.renderFooterInfo(); break;
  568. case 'footer__toolbar__pagination': priv.renderFooterPagination(); break;
  569. case 'footer__toolbar__pagesizes': priv.renderFooterPageSizes(); break;
  570. case 'foot__columnPicker': priv.renderFooterColumnPicker(); break;
  571. case 'head__specialFilters': priv.renderHeadSpecialFilters(); break;
  572. }
  573. }
  574. priv.renderTable();
  575. }
  576. };
  577. priv.initialRender = function() {
  578. _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiNodeCont);
  579. _head = $('<thead></thead>').prependTo(_uiNode$Table);
  580. _headSort = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head);
  581. _headFilter = $('<tr class="filter tblAjax__head__filter"></tr>').appendTo(_head);
  582. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  583. $('<tfoot></tfoot>').insertAfter(_bodyNode);
  584. _foot = $('<div class="foot tblAjax__footer"></div>').insertAfter(_uiNodeCont);
  585. var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar"></div>').appendTo(_foot);
  586. $('<span class="tblAjax__footer__toolbar__info"></span>').appendTo(footToolbar);
  587. $('<span class="tblAjax__footer__toolbar__pagination"></span>').appendTo(footToolbar);
  588. $('<span class="tblAjax__footer__toolbar__pagesizes"></span>').appendTo(footToolbar);
  589. $('<span class="tblAjax__footer__toolbar__columnPicker"></span>').appendTo(footToolbar);
  590. $('<span class="tblAjax__footer__toolbar__functions"></span>').appendTo(footToolbar);
  591. $('<span class="tblAjax__footer__toolbar__export"></span>').appendTo(footToolbar);
  592. _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
  593. _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
  594. _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
  595. $('<div class="tblAjax__inlineEditBox"></div>').insertAfter(_foot);
  596. $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>').insertBefore(_uiNodeCont);
  597. priv.renderInlineEditBox();// .tblAjax__inlineEditBox
  598. _foot = _head = _body = _headSort = _headFilter = undefined;// TODO: refactor
  599. /// console.log('L.<?php echo __LINE__; ?> priv.initialRender, _uiNode$Table: ', _uiNode$Table.html())
  600. }
  601. /*
  602. creates the table with all its parts and handlers.
  603. note that only the parts we need is created.
  604. (yeah, the function is huge)
  605. */
  606. priv.renderTable = function() {
  607. //create table itself
  608. /// console.log('renderTable:: _data', _data);//TODO:DBG:RMME
  609. /// console.log('renderTable:: _uiNode$Table', _uiNode$Table);//TODO:DBG:RMME
  610. //create the header which will later hold both sorting and filtering
  611. /// console.log('L.<?php echo __LINE__; ?> renderTable:: _head', _head);//TODO:DBG:RMME
  612. if (!_head) {
  613. _headSort = _headFilter = _headSpecialFilter = undefined;
  614. //_head = $('<thead></thead>');
  615. // $('<tr class="sort"></tr>').prependTo(_head);
  616. //_uiNode$Table.find('thead').replaceWith(_head);
  617. _head = _uiNode$Table.find('thead');
  618. }
  619. //create the header sorting row
  620. if (!_headSort) {
  621. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadSort...');//TODO:DBG:RMME
  622. priv.renderTableTheadSort();
  623. }
  624. //create the header filtering row
  625. if (!_headFilter && priv.options.filter) {
  626. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  627. priv.renderTableTheadFilter();
  628. _headFilter = true;
  629. }
  630. //create the header special filters row
  631. if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
  632. priv.renderHeadSpecialFilters();
  633. _headSpecialFilter = true;
  634. }
  635. //create the body
  636. if (!_body) {
  637. _uiNode$Table.find('tbody').remove();
  638. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  639. //_bodyNode.on('change', '.unique', priv.rowChecked);
  640. //find out what rows to show next...
  641. var rowsAdded = 0;
  642. //slice out the chunk of data we need and create rows
  643. $.each(_data.rows, function(index, props) {
  644. var rowNode = priv.renderRow(props);
  645. if (rowNode) rowNode.appendTo(_bodyNode);
  646. rowsAdded++;
  647. //enough rows created?
  648. if (rowsAdded >= priv.options.pageSize) {
  649. return false;
  650. }
  651. });
  652. if (_state.page == 1) {
  653. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  654. }
  655. //pad with empty rows if we're at last page.
  656. if (_state.page == _totalPages) {
  657. while (rowsAdded < priv.options.pageSize) {
  658. var rowNode = priv.renderRowEmptyNode();
  659. if (rowNode) rowNode.appendTo(_bodyNode);
  660. rowsAdded++;
  661. }
  662. }
  663. }
  664. //create the footer
  665. if (!_foot) {
  666. priv.renderTableTfoot();
  667. priv.renderFooter();
  668. }
  669. _foot = $(_uiNodeCont).next('.foot');
  670. var stickyCol1Width = (12 + 3) * 4 + 2 * 5 + 1;
  671. var stickyCol2Width = 50 + 2 * 5 + 1;
  672. if (undefined === _tableWidth) {
  673. _tableWidth = true;
  674. var contW = jQuery(_uiNodeCont).width();
  675. var th1 = _uiNode$Table.find('.stickyCol1:first');
  676. var th2 = th1.next();
  677. var th1W = th1.innerWidth();
  678. var th2W = 50 + 2 * 5;//th2.innerWidth();
  679. var colsW = stickyCol1Width + stickyCol2Width;
  680. jQuery(_uiNodeCont).css({width:'' + (contW - colsW) + 'px', marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
  681. }
  682. _uiNode$Table.find('.stickyCol1').css({position:'absolute',
  683. left:'0',
  684. top:'auto',
  685. width:'' + stickyCol1Width + 'px',
  686. });
  687. //_uiNode$Table.find('.filter').find('.stickyCol1').css({height:'34px'});
  688. var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
  689. _uiNode$Table.find('.sort').find('.stickyCol1').css({height: sortStickyColHeight + 'px'});
  690. _uiNode$Table.find('.sort').find('.stickyCol2').css({height: sortStickyColHeight + 'px'});
  691. _uiNode$Table.find('.stickyCol2').css({position:'absolute',
  692. left:'' + (stickyCol1Width) + 'px',
  693. top:'auto',
  694. width:'' + stickyCol2Width + 'px',
  695. borderRight: '1px solid silver'
  696. });
  697. if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
  698. $('.btn-toolbar', _foot).remove();
  699. }
  700. if (priv.options.debug) console.log('table created L.<?php echo __LINE__; ?>');
  701. if (typeof priv.options.tableCreated == 'function') {
  702. priv.options.tableCreated.call(_uiNode$Table.get(0), {table: _uiNode$Table.get(0)});
  703. }
  704. };
  705. priv.renderRow = function(props) {
  706. var rowNode = $('<tr></tr>'),
  707. uniqueColName = _state.uniqueCol,
  708. rowPK = (uniqueColName in props)? props[uniqueColName] : null,
  709. cellNode
  710. ;
  711. if (priv.options.rowFunctions || priv.options.filtersClean) {
  712. cellNode = priv.renderCellRowFunctions(priv.options.rowFunctions, rowPK, props);
  713. cellNode.addClass('text-right stickyCol1');
  714. cellNode.appendTo(rowNode);
  715. }
  716. //create checkbox
  717. if (_state.uniqueCol && priv.options.checkboxes) {
  718. var check = _uniqueCols[props[_state.uniqueCol]] != undefined ? 'checked' : '';
  719. var checkable = props['checkable'] === false ? 'disabled' : '';
  720. cellNode = $('<td></td>').appendTo(rowNode);
  721. $('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cellNode);
  722. }
  723. if (uniqueColName) rowNode.data('unique', rowPK);
  724. //create cells
  725. for (var i = 0; i < _state.colsSorted.length; i++) {
  726. var columnName = _state.colsSorted[i],
  727. columnProps = _data.cols[columnName],
  728. val = '',
  729. cellNode,
  730. cellCnt,
  731. format,
  732. showTooltip
  733. ;
  734. if (!columnProps) continue;
  735. if (columnProps.hidden) continue;// TODO: "unique" is hidden
  736. val = props[columnName];
  737. cellNode = $('<td></td>').appendTo(rowNode);
  738. if (columnName !== uniqueColName) {
  739. cellNode.on('dblclick', {id:rowPK, col:columnName}, priv.rowDblClicked);
  740. }
  741. if (i == 1) {// primaryKey(ID)
  742. cellCnt = $('<div></div>').appendTo(cellNode);// fix dblclick for copy
  743. cellNode.addClass('stickyCol2');
  744. } else {
  745. cellCnt = $('<span></span>').appendTo(cellNode);
  746. }
  747. cellNode.data('column', columnName);
  748. if (val === undefined) continue;
  749. format = props[columnName + 'Format'] || columnProps.format || '{0}';
  750. showTooltip = true;
  751. switch (columnProps.type) {
  752. case "string":
  753. cellCnt.html(format.f(val));
  754. break;
  755. case "number":
  756. val = Number(val);
  757. var forceDecimals = !isNaN(columnProps.decimals);
  758. if (forceDecimals) cellCnt.html(format.f(val.toFixed(columnProps.decimals)));
  759. else {
  760. (val || 0) % 1 === 0
  761. ? cellCnt.html(format.f(val))
  762. : cellCnt.html(format.f(val.toFixed(priv.options.types.number.decimals || 2)));
  763. }
  764. break;
  765. case "date":
  766. cellCnt.html(format.f(val));
  767. break;
  768. case "bool":
  769. $('<input type="checkbox" {0} disabled />'.f(val ? "checked" : "")).appendTo(cellCnt);
  770. break;
  771. case "special":
  772. cellCnt.html(format.f(val));
  773. break;
  774. case "simpleLink":
  775. var valLink = String(val);
  776. if (undefined !== columnProps._tsRetId
  777. && (0 === columnProps._tsRetId || '0' === columnProps._tsRetId)
  778. && undefined !== columnProps._tsSimpleLink) {
  779. valLink = columnProps._tsSimpleLink.format;
  780. $.each(columnProps._tsSimpleLink.aliasMap, function(i, v) {
  781. //console.log('simpleLink aliasMap columnName:', columnName, 'i:', i, 'v:', v, 'props['+v+']', props[v], 'val', val, 'typeof val', typeof val);
  782. if (undefined !== props[v]) {
  783. valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), props[v]);
  784. }
  785. });
  786. }
  787. cellCnt.html(format.f(valLink));
  788. break;
  789. case "geom":
  790. cellCnt.TableAjaxGeomField({
  791. recordID: rowPK,
  792. fieldValue: val,
  793. hasValueClassName: 'cell-mapfld-hasValue',
  794. //removeUrl: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + rowPK,
  795. linkClassNamePrefix: 'cell-mapfld',
  796. linkSelectClassName: 'select',
  797. linkSelectAddClassNames: 'glyphicon glyphicon-map-marker',
  798. linkRemoveClassName: 'remove',
  799. linkRemoveAddClassNames: 'glyphicon glyphicon-remove',
  800. onSelect: function(recordID, geomShape) {
  801. if (priv.options.debug) console.log('recordID:', recordID, 'geomShape:', geomShape);
  802. priv.mapEditorShow();
  803. _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
  804. },
  805. onRemove: function(geomField, recordID, geomShape) {
  806. if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
  807. if (!recordID) return;
  808. var selectedRecordId = recordID;
  809. function notifyAjaxCallback(data) {
  810. var notify = {};
  811. notify.type = (data && data.type)? data.type : '';
  812. notify.msg = (data && data.msg)? data.msg : '';
  813. switch (notify.type) {
  814. case 'success':
  815. if (!notify.msg) notify.msg = 'Usunięto obiekt z mapy dla rekordu ' + selectedRecordId;
  816. break;
  817. case 'info':
  818. if (!notify.msg) notify.msg = 'Rekord nie był powiązany z żadnym obiektem na mapie';
  819. break;
  820. case 'error':
  821. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  822. break;
  823. case 'warning':
  824. notify.type = 'warn';
  825. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  826. break;
  827. default:
  828. notify.msg = 'Nieznany błąd';
  829. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  830. notify.type = '';
  831. }
  832. jQuery.notify(notify.msg, notify.type);
  833. }
  834. $.ajax({
  835. data: {},
  836. dataType: 'json',
  837. type: "POST",
  838. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + recordID
  839. })
  840. .done(function(data, textStatus, jqXHR){
  841. notifyAjaxCallback(data);
  842. if (priv.options.debug) console.log('data.record.the_geom:', data.record.the_geom);
  843. if (data && data.record && data.record.the_geom) {
  844. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  845. geomField.setValue(data.record.the_geom);
  846. }
  847. else if (data && data.record) {
  848. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  849. geomField.setValue(data.record.the_geom);
  850. }
  851. _mapEditor.TableAjaxMapRefresh();
  852. })
  853. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  854. if (jqXHR.responseJSON) {
  855. notifyAjaxCallback(jqXHR.responseJSON);
  856. }
  857. else {
  858. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  859. if (jqXHR.status == 404) {
  860. jQuery.notify(jqXHR.responseText, 'error');
  861. } else {
  862. jQuery.notify(jqXHR.responseText, 'warn');
  863. }
  864. }
  865. });
  866. }
  867. }
  868. });
  869. break;
  870. }
  871. if (columnProps._tsRetId) {
  872. showTooltip = false;
  873. if (columnProps._tsRetId > 0) {
  874. cellCnt.on('click', {id:rowPK, col:columnName, friendly:columnProps.friendly, value:format.f(val)}, priv.popoverCellTypeSpecial);
  875. }
  876. }
  877. if (i > 1 && priv.options.longDesc) {// TODO: use better check for columns: functions and pk
  878. cellNode.addClass('tbl-short-txt');
  879. if (showTooltip) {
  880. cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
  881. }
  882. }
  883. }
  884. return rowNode;
  885. };
  886. priv.renderCellRowFunctions = function(rowFunctions, rowPK, rowProps) {
  887. var cellNode = $('<td></td>'),
  888. keys = Object.keys(rowFunctions),
  889. total = keys.length,
  890. moreFuncBtnNode,
  891. moreFunctions = [],
  892. idx
  893. ;
  894. if (priv.options.debug) console.log('TableAjax::renderCellRowFunctions: rowFunctions', rowFunctions);
  895. idx = keys.indexOf('hist');
  896. if (idx !== -1) {
  897. histFunc = keys.splice(idx, 1);
  898. keys.push('hist');
  899. }
  900. moreFunctions = keys.splice(3);
  901. keys.forEach(function(key) {
  902. var funObj = rowFunctions[key],
  903. funcNode = priv.generateFunctionNode(funObj, rowPK, {ico: true, label: false})
  904. ;
  905. funcNode.appendTo(cellNode);
  906. });
  907. moreFuncBtnNode = $('<a href="#" style="margin:0 2px;text-decoration:none" title="Więcej funkcji dla rekordu nr '+rowPK+'" class="glyphicon glyphicon-menu-hamburger"> </a>');
  908. moreFuncBtnNode.on('click', {rowPK: rowPK, rowFunctions: rowFunctions, more: moreFunctions}, priv.popoverCellMoreFunctions);
  909. moreFuncBtnNode.appendTo(cellNode);
  910. return cellNode;
  911. };
  912. priv.popoverCellMoreFunctions = function(e) {
  913. e.preventDefault();
  914. e.stopPropagation();
  915. if (priv.options.debug) console.log('TableAjax::popoverCellMoreFunctions: rowPK', e.data.rowPK, 'moreFunctions', e.data.more, 'rowFunctions', e.data.rowFunctions);
  916. if ('rowPK' in e.data && e.data.rowPK > 0) {
  917. var lastId = _popoverCell.data('rowid'),
  918. lastCol = _popoverCell.data('col'),
  919. rowPK = e.data.rowPK,
  920. moreFunctions = e.data.more,
  921. rowFunctions = e.data.rowFunctions,
  922. funcListNode
  923. ;
  924. if (lastId == e.data.rowPK && lastCol == 'moreFunctions') {
  925. //_popoverCellCurrent.popover('toggle');
  926. }
  927. else {
  928. if (_popoverCellCurrent) {
  929. _popoverCellCurrent.popover('destroy');
  930. }
  931. _popoverCell.data('rowid', rowPK);
  932. _popoverCell.data('col', 'rowFunctions');
  933. _popoverCell.empty();
  934. funcListNode = $('<ul class="list-unstyled popoverRowFunctions"></ul>').appendTo(_popoverCell);
  935. moreFunctions.forEach(function(funcName) {
  936. var funcItemNode = $('<li></li>').appendTo(funcListNode),
  937. funObj = rowFunctions[funcName],
  938. funcNode = priv.generateFunctionNode(funObj, rowPK, {ico: true, label: true})
  939. ;
  940. funcNode.addClass('func_name-' + funcName);
  941. funcItemNode.append(funcNode);
  942. });
  943. _popoverCell.append('<div class="popoverCellContent" style="white-space:normal"></div>');
  944. _popoverCellCurrent = jQuery(e.currentTarget);
  945. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  946. var opts = {
  947. container: 'body',
  948. placement: 'right',
  949. trigger: 'click',
  950. template: '',
  951. html: true,
  952. content: _popoverCell.html()
  953. }
  954. opts.template += '<div class="popover" role="tooltip" style="max-width:400px;width:300px;">';
  955. {
  956. opts.template += '<div class="arrow"></div>';
  957. //opts.template += '<h3 class="popover-title"></h3>';
  958. opts.template += '<div style="display:block;position:relative;">';
  959. {
  960. opts.template += '<div class="popover-title">';
  961. opts.template += '</div>';
  962. opts.template += '<button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:8px;top:6px;">&times;</button>';
  963. }
  964. opts.template += '</div>';
  965. opts.template += '<div class="popover-content"></div>';
  966. }
  967. opts.template += '</div>';
  968. _popoverCellCurrent.popover(opts);
  969. _popoverCellCurrent.on('shown.bs.popover', function(e) {
  970. if (_popoverCellCurrent) {
  971. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  972. if (popoverNodeId) {
  973. jQuery('#' + popoverNodeId).find('.popoverCellContent').html('<p class="text-muted">Pobieranie funkcji...<p>');
  974. }
  975. }
  976. priv.ajaxLoadMoreFunctionsCell(rowPK);
  977. });
  978. _popoverCellCurrent.popover('show');
  979. }
  980. } else {
  981. if (priv.options.debug) console.log('NO data');
  982. return false;
  983. }
  984. return;
  985. };
  986. priv.generateFunctionNode = function(funObj, rowPK, props) {
  987. var defaultsProps = {
  988. ico: true,
  989. label: false
  990. },
  991. props = $.extend({}, defaultsProps, props);
  992. funcNode = $('<a href="#" style="margin:0 2px;"></a>')
  993. ;
  994. if ('href' in funObj) funcNode.attr('href', funObj.href.f(rowPK));
  995. if (props.ico) {
  996. if ('ico' in funObj) funcNode.append('<span class="' + funObj.ico + '"></span>');
  997. }
  998. if ('onclick' in funObj) funcNode.attr('onclick', funObj.onclick.f(rowPK));
  999. if ('title' in funObj) funcNode.attr('title', funObj.title);
  1000. if (props.label) {
  1001. if ('label' in funObj) {
  1002. funcNode.append(' ' + funObj.label);
  1003. } else if ('title' in funObj) {
  1004. funcNode.append(' ' + funObj.title);
  1005. }
  1006. }
  1007. return funcNode;
  1008. };
  1009. priv.ajaxLoadMoreFunctionsCell = function(rowPK) {
  1010. if (_popoverCellAjaxXhr) {
  1011. _popoverCellAjaxXhr.abort();
  1012. }
  1013. _popoverCellAjaxXhr = $.ajax({
  1014. type: 'GET',
  1015. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=MORE_FUNCTIONS_CELL&ID=' + rowPK,
  1016. dataType: 'json',
  1017. contentType: "application/json; charset=utf-8",
  1018. data: ''
  1019. })
  1020. .done(function(data, textStatus, jqXHR){
  1021. if (data && 'success' === data.type) {
  1022. var popoverCellContent,
  1023. rowFunctions = [],
  1024. funcNodesToUpdate = []
  1025. ;
  1026. if (data.rowFunctions && data.rowFunctions.length > 0) {
  1027. rowFunctions = data.rowFunctions;
  1028. }
  1029. if (rowFunctions.length > 0) {
  1030. var popoverCellContent = $('<ul class="list-unstyled"></ul>');
  1031. rowFunctions.forEach(function(funObj) {
  1032. var funcNode = priv.generateFunctionNode(funObj, rowPK, {ico: true, label: true});
  1033. if (funObj.id) {
  1034. funcNodesToUpdate.push({id: funObj.id, node: funcNode});
  1035. } else {
  1036. var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
  1037. funcItemNode.append(funcNode);
  1038. }
  1039. });
  1040. } else {
  1041. popoverCellContent = '<p class="text-muted">Brak dodatkowych funkcji</p>';
  1042. }
  1043. //_popoverCell.append(popoverCellContent);// cache
  1044. if (_popoverCellCurrent) {
  1045. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  1046. if (popoverNodeId) {
  1047. var popoverNode = jQuery('#' + popoverNodeId),
  1048. popoverCntNode = popoverNode.find('.popoverCellContent'),
  1049. popoverRowFuncNode = popoverNode.find('.popoverRowFunctions');
  1050. ;
  1051. {// fix generated row Functions by loaded from ajax call
  1052. console.log('popoverRowFunctions. popoverRowFuncNode', popoverRowFuncNode);
  1053. console.log('popoverRowFunctions. funcNodesToUpdate', funcNodesToUpdate);
  1054. funcNodesToUpdate.forEach(function(funcNodeInfo) {
  1055. var className = 'func_name-' + funcNodeInfo.id,
  1056. foundRowFuncNode = null
  1057. ;
  1058. console.log('popoverRowFunctions. funcNodesToUpdate loop:', funcNodeInfo);
  1059. popoverRowFuncNode.find('li > a').each(function(ind, n) {
  1060. var n$ = $(n);
  1061. console.log('popoverRowFunctions loop(',ind,'):', n, 'data(func_name)', n$.data('func_name'), 'data', n$.data());
  1062. if (n$.hasClass(className)) {
  1063. foundRowFuncNode = n$;
  1064. }
  1065. });
  1066. if (foundRowFuncNode) {
  1067. foundRowFuncNode.replaceWith(funcNodeInfo.node);
  1068. } else {
  1069. var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
  1070. funcItemNode.append(foundRowFuncNode);
  1071. }
  1072. });
  1073. }
  1074. popoverCntNode.empty().append(popoverCellContent);
  1075. if (rowFunctions.length <= 0) {
  1076. popoverCntNode.find('p.text-muted').delay(600).hide(300);
  1077. }
  1078. }
  1079. }
  1080. }
  1081. });
  1082. };
  1083. priv.renderRowEmptyNode = function() {
  1084. var rowNode = $('<tr></tr>');
  1085. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1086. $('<td class="text-right stickyCol1">&nbsp;</td>').appendTo(rowNode);
  1087. }
  1088. if (_state.uniqueCol && priv.options.checkboxes) {
  1089. $('<td><input disabled type="checkbox" /></td>').appendTo(rowNode);
  1090. }
  1091. for (var i = 0; i < _state.colsSorted.length; i++) {
  1092. var columnName = _state.colsSorted[i],
  1093. columnProps = _data.cols[columnName]
  1094. ;
  1095. if (!columnProps) return;
  1096. if (columnProps.hidden) continue;// "unique" is hidden - TODO: rm "unique" from _state.colsSorted ?
  1097. if (i == 1) {// TODO: 1 is pk - use better check
  1098. $('<td class="stickyCol2">&nbsp;</td>').appendTo(rowNode);
  1099. } else {
  1100. $('<td>&nbsp;</td>').appendTo(rowNode);
  1101. }
  1102. }
  1103. return rowNode;
  1104. };
  1105. priv.renderTableTheadSort = function() {
  1106. var nodeClass = 'tblAjax__' + 'head__sort',
  1107. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  1108. node;
  1109. // currentNode.find('i').tooltip('hide');
  1110. node = $('<tr class="sort ' + nodeClass + '"></tr>');
  1111. //create the functions column
  1112. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1113. var headCell = $('<th class="text-right head-info stickyCol1"></th>').appendTo(node);
  1114. $.map(priv.options.tblFunctions, function(funObj, funName){
  1115. var funHtml = $('<a></a>');
  1116. funHtml.attr('href', funObj.href || '#');
  1117. if (funObj.title) funHtml.attr('title', funObj.title);
  1118. if (funObj.icon) funHtml.html('<span class="glyphicon glyphicon-' + funObj.icon + '"></span> ');
  1119. if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
  1120. funHtml.on('click', priv[funObj.method]);
  1121. }
  1122. funHtml.appendTo(headCell);
  1123. });
  1124. }
  1125. //create the checkall toggle
  1126. if (_state.uniqueCol && priv.options.checkboxes) {
  1127. var checked = _checkToggleChecked ? 'checked' : '';
  1128. var headCell = $('<th></th>').appendTo(node);
  1129. var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
  1130. elem.on('change', priv.checkToggleChanged);
  1131. }
  1132. //create the sortable headers
  1133. for (var i = 0; i < _state.colsSorted.length; i++) {
  1134. var column = _state.colsSorted[i];
  1135. var props = _data.cols[column];
  1136. if (!props.hidden) {
  1137. var headCell = $('<th class="ta-ordering"></th>').appendTo(node);
  1138. if (i == 1) headCell.addClass('stickyCol2');
  1139. if (false) {// TODO: old way
  1140. var link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
  1141. link.on('click', {column: column}, priv.columnClicked).appendTo(headCell);
  1142. if (props.tooltip) {
  1143. $('<i class="glyphicon glyphicon-info-sign"></i>').tooltip({
  1144. title: props.tooltip.trim(),
  1145. html: true,
  1146. container: 'body',
  1147. placement: "top",
  1148. delay: {
  1149. show: 500,
  1150. hide: 100
  1151. }
  1152. }).appendTo(link);
  1153. }
  1154. //Add sort arrow
  1155. if (column == _state.filters.currSortCol) {
  1156. if (_state.filters.currSortFlip) $('<i class="glyphicon glyphicon-chevron-down pull-right"></i>').appendTo(headCell);
  1157. else $('<i class="glyphicon glyphicon-chevron-up pull-right"></i>').appendTo(headCell);
  1158. }
  1159. //Add hide btn
  1160. if (column != 'ID') {
  1161. var hideColBtn = $('<i class="glyphicon glyphicon-remove pull-right hover-show"></i>');
  1162. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  1163. hideColBtn.appendTo(headCell);
  1164. }
  1165. }
  1166. if (props.type != 'special' && props.type != 'geom') {
  1167. headCell.on('click', {column: column}, priv.columnClicked);
  1168. }
  1169. var colTitle = column;
  1170. if (props.description && props.description.length > 0) {
  1171. colTitle = props.description;
  1172. colTitle += ' (' + column + ')';
  1173. }
  1174. else if (props._tsRetId > 0) {
  1175. colTitle = 'Kliknij na pole i przejdź do powiązanych rekordów (' + colTitle + ')';
  1176. }
  1177. if (props.friendly) {
  1178. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(props.friendly, colTitle));
  1179. } else {
  1180. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(column, colTitle));
  1181. }
  1182. headCnt.appendTo(headCell);
  1183. //Add sort arrow
  1184. if (column == _state.filters.currSortCol) {
  1185. if (_state.filters.currSortFlip) headCell.addClass('ta-ordering-down');
  1186. else headCell.addClass('ta-ordering-up');
  1187. }
  1188. if (column != 'ID') {
  1189. var hideColBtn = $('<i class="glyphicon glyphicon-remove remove-cell"></i>');
  1190. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  1191. hideColBtn.appendTo(headCell);
  1192. }
  1193. }
  1194. }
  1195. currentNode.replaceWith(node);
  1196. };
  1197. priv.renderHeadSpecialFilters = function() {
  1198. var nodeClass = 'tblAjax__' + 'head__specialFilter',
  1199. currentNode = $(_uiNodeCont).prev('.' + nodeClass),
  1200. node;
  1201. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderHeadSpecialFilters...');//TODO:DBG:RMME
  1202. if (!priv.options.specialFilterFunctions) {
  1203. return;
  1204. }
  1205. var node = $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>');
  1206. $.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
  1207. var btnHtml,
  1208. btnSelected,
  1209. groupLabel = groupObj.label || groupName,
  1210. groupHtml = $('<div class="btn-group"></div>')
  1211. ;
  1212. // _state.specialFilters[e.data.group] = e.data.value;
  1213. if (groupName in _state.specialFilters) {
  1214. btnSelected = _state.specialFilters[groupName];
  1215. }
  1216. if (groupObj.icon) {
  1217. $('<button class="btn btn-xs btn-default" title="' + groupLabel + '"><i class="' + groupObj.icon + '"></i></button>').appendTo(groupHtml);
  1218. }
  1219. $.map(groupObj.btns, function(btnObj, btnName) {
  1220. btnHtml = $('<button class="btn btn-xs btn-default' + ((btnSelected && btnSelected == btnObj.value)? ' active' : '') + '">' + btnName + '</button>').appendTo(groupHtml);
  1221. btnHtml.on('click', {group: groupName, value: btnObj.value}, priv.specialFilterChanged);
  1222. });
  1223. btnHtml = $('<button class="btn btn-xs btn-default' + ((!btnSelected)? ' disabled' : '') + '" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  1224. btnHtml.on('click', {group: groupName, value: ''}, priv.specialFilterChanged);
  1225. groupHtml.appendTo(node);
  1226. });
  1227. currentNode.replaceWith(node);
  1228. };
  1229. priv.renderTableTheadFilter = function() {
  1230. var nodeClass = 'tblAjax__' + 'head__filter',
  1231. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  1232. node;
  1233. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  1234. // currentNode.find('i').tooltip('hide');
  1235. node = $('<tr class="filter ' + nodeClass + '"></tr>');
  1236. //_head.find(".filter").remove();
  1237. //_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
  1238. var headCell;
  1239. var elem;
  1240. var placeHolder = '';
  1241. var tooltip = '';
  1242. //create the functions column
  1243. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1244. var headCell = $('<th class="text-right stickyCol1"></th>').appendTo(node);
  1245. headCell.css({padding: '0'});
  1246. if (priv.options.filtersClean) {
  1247. var elem = $('<button title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button>').appendTo(headCell);
  1248. elem.on('click', priv.filtersClean);
  1249. }
  1250. }
  1251. //create the filter checkbox
  1252. if (_state.uniqueCol && priv.options.checkboxes) {
  1253. tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
  1254. headCell = $('<th></th>').appendTo(node);
  1255. elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
  1256. $.map(_state.filters.filterCols, function(colProps, col) {
  1257. if (col == "unique") {
  1258. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1259. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1260. else if (colProps.filter == '') elem.addClass('indeterminate');
  1261. }
  1262. });
  1263. if (tooltip) {
  1264. elem.tooltip({
  1265. title: tooltip.trim(),
  1266. html: true,
  1267. container: 'body',
  1268. trigger: 'hover',
  1269. placement: 'top',
  1270. delay: {
  1271. show: 500,
  1272. hide: 100
  1273. }
  1274. });
  1275. }
  1276. elem.on('click', {column: "unique"}, priv.filterChanged);
  1277. }
  1278. //create the column filters
  1279. for (var i = 0; i < _state.colsSorted.length; i++) {
  1280. var column = _state.colsSorted[i];
  1281. var props = _data.cols[column];
  1282. tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
  1283. placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
  1284. if (!props.hidden) {
  1285. headCell = $('<th></th>').appendTo(node);
  1286. headCell.css({padding: '0'});
  1287. if (i == 1) headCell.addClass('stickyCol2');
  1288. // @mark MarkTableAjaxFilterColType
  1289. switch (props.type || 'string') {
  1290. case "number":
  1291. if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
  1292. placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
  1293. if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
  1294. tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
  1295. elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
  1296. elem.on('keyup', {column: column}, priv.filterChanged);
  1297. break;
  1298. case "date":
  1299. if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
  1300. placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
  1301. if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
  1302. tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
  1303. elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));
  1304. if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
  1305. {
  1306. if ($().datepicker)
  1307. {
  1308. elem.addClass('date-wrap');
  1309. var today = 0;//new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
  1310. var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
  1311. $('<input style="display:none" type="text" />').appendTo(dp);
  1312. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
  1313. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-left"></i></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
  1314. dp.datepicker({weekStart:1});
  1315. dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
  1316. }
  1317. else
  1318. if (priv.options.debug) console.log('datepicker plugin not found');
  1319. }
  1320. elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
  1321. break;
  1322. case "bool":
  1323. if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
  1324. tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
  1325. elem = $('<input class="filter indeterminate" checked type="checkbox" />');
  1326. elem.on('click', {column: column}, priv.filterChanged);
  1327. break;
  1328. case "string":
  1329. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1330. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1331. if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
  1332. tooltip = (tooltip === true || tooltip == undefined) ? 'Find str: str<br/>Find all but str: !str<br/>Find str inside: %str%' : tooltip === false ? '' : tooltip;
  1333. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1334. elem.on('keyup', {column: column}, priv.filterChanged);
  1335. break;
  1336. case "special":
  1337. elem = $('<div>&nbsp;</div>');
  1338. break;
  1339. case "simpleLink":
  1340. elem = $('<div>&nbsp;</div>');
  1341. break;
  1342. case "geom":
  1343. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1344. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1345. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1346. elem.on('keyup', {column: column}, priv.filterChanged);
  1347. break;
  1348. case "none":
  1349. elem = $('<div>&nbsp;</div>');
  1350. break;
  1351. }
  1352. if (false) {// tooltip OFF - (tooltip)
  1353. elem.tooltip({
  1354. title: tooltip.trim(),
  1355. html: true,
  1356. container: 'body',
  1357. trigger: 'focus',
  1358. placement: 'top',
  1359. delay: {
  1360. show: 500,
  1361. hide: 100
  1362. }
  1363. });
  1364. }
  1365. if (elem && props.filter) {
  1366. $.map(_state.filters.filterCols, function(colProps, col) {
  1367. if (col == column) {
  1368. var columnSettings = _data.cols[col];
  1369. if (columnSettings.type == 'bool') {
  1370. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1371. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1372. else if (colProps.filter == '') elem.addClass('indeterminate');
  1373. }
  1374. else elem.val(colProps.filter);
  1375. }
  1376. });
  1377. if (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]) {
  1378. elem.prop('disabled', true);
  1379. }
  1380. elem.appendTo(headCell);
  1381. _filterFields[column] = elem;
  1382. }
  1383. }
  1384. }
  1385. currentNode.replaceWith(node);
  1386. };
  1387. priv.renderTableTfoot = function() {
  1388. _uiNode$Table.find('tfoot').remove();
  1389. _foot = $('<tfoot></tfoot>').insertAfter(_bodyNode);
  1390. //$(_uiNodeCont).next('.foot').replaceWith(_foot);
  1391. };
  1392. priv.renderFooter = function() {
  1393. priv.renderFooterInfo();
  1394. priv.renderFooterPagination();
  1395. priv.renderFooterPageSizes();
  1396. priv.renderFooterColumnPicker();
  1397. priv.renderFooterFunctions();
  1398. priv.renderFooterExport();
  1399. };
  1400. priv.renderFooterInfo = function() {
  1401. var nodeClass = 'tblAjax__' + 'footer__toolbar__info',
  1402. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1403. node;
  1404. if (priv.options.debug) console.log('Render: ', nodeClass);
  1405. node = $('<div class="foot-info ' + nodeClass + '"></div>');
  1406. //console.log('renderFooterInfo total', _data.total, 'page', _state.page, 'priv.options.pageSize', priv.options.pageSize);
  1407. var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
  1408. var total = _data.total;
  1409. var toRow = Math.min(fromRow + _state.pageSize, total);
  1410. if (_data.total > 0) {
  1411. $('<p>Wiersze od {0} do {1} z {2}</p>'.f(fromRow + 1, toRow, total)).appendTo(node);
  1412. } else {
  1413. $('<p>Brak wierszy pasujących do kryteriów wyszukiwania</p>').appendTo(node);
  1414. }
  1415. currentNode.replaceWith(node);
  1416. };
  1417. priv.renderFooterPagination = function() {
  1418. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
  1419. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1420. node;
  1421. var currPage = _state.page;
  1422. var totalPages = Math.ceil(_data.total / _state.pageSize);
  1423. if (priv.options.debug) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
  1424. /// console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage, '_state.page', _state.page);
  1425. if (_data.total > 0) {
  1426. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1427. //create the pager.
  1428. var lowerPage = currPage - 2;
  1429. var upperPage = currPage + 2;
  1430. if (upperPage > totalPages) {
  1431. var diff = upperPage - totalPages;
  1432. upperPage = totalPages;
  1433. lowerPage -= diff;
  1434. }
  1435. if (lowerPage < 1) lowerPage = 1;
  1436. if (upperPage < 5) upperPage = 5;
  1437. //$('<li class="{0}"><a href="#">&lt;&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1438. $('<button type="button" class="btn btn-default{0}">&lt;&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1439. .on('click', {pageIndex: 1}, priv.pageChanged)
  1440. .appendTo(node);
  1441. //$('<li class="{0}"><a href="#">&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1442. $('<button type="button" class="btn btn-default{0}">&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1443. .on('click', {pageIndex: currPage - 1}, priv.pageChanged)
  1444. .appendTo(node);
  1445. for (var i = lowerPage; i <= upperPage; i++) {
  1446. var link;
  1447. //if (i != currPage) link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > totalPages ? 'disabled' : ''));
  1448. if (i != currPage) link = $('<button type="button" class="btn btn-default{1}">{0}</button>'.f(i, i > totalPages ? 'disabled' : ''));
  1449. //if (i == currPage) link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));
  1450. if (i == currPage) link = $('<button type="button" class="btn btn-default active">{0}</button>'.f(i));
  1451. if (link) {
  1452. link.on('click', {pageIndex: i}, priv.pageChanged);
  1453. link.appendTo(node);
  1454. }
  1455. }
  1456. //$('<li class="{0}"><a href="#">&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1457. $('<button type="button" class="btn btn-default{0}">&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1458. .on('click', {pageIndex: currPage + 1}, priv.pageChanged)
  1459. .appendTo(node);
  1460. //$('<li class="{0}"><a href="#">&gt;&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1461. $('<button type="button" class="btn btn-default{0}">&gt;&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1462. .on('click', {pageIndex: totalPages}, priv.pageChanged)
  1463. .appendTo(node);
  1464. } else {
  1465. node = $('<span class="' + nodeClass + '"></span>');
  1466. }
  1467. currentNode.replaceWith(node);
  1468. };
  1469. priv.renderFooterPageSizes = function() {
  1470. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagesizes',
  1471. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1472. node;
  1473. if (priv.options.debug) console.log('Render: ', nodeClass);
  1474. if (_data.total > 0 && priv.options.pageSizes.length > 0) {
  1475. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1476. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy&nbsp;</button>').appendTo(node);
  1477. var span = $('<span class="caret"></span>').appendTo(btn);
  1478. var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
  1479. $.each(priv.options.pageSizes, function(index, val) {
  1480. var li = $('<li></li>').appendTo(ul);
  1481. if (val == priv.options.pageSize) {
  1482. $('<a style="color:#337AB7;">{0}</a>'.f(val)).appendTo(li);
  1483. } else {
  1484. $('<a href="#">{0}</a>'.f(val)).appendTo(li);
  1485. }
  1486. });
  1487. node.on('click', 'a', priv.pageSizeChanged);
  1488. } else {
  1489. node = $('<span class="' + nodeClass + '"></span>');
  1490. }
  1491. currentNode.replaceWith(node);
  1492. };
  1493. priv.renderFooterColumnPicker = function() {
  1494. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  1495. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1496. node;
  1497. if (priv.options.debug) console.log('Render: ', nodeClass);
  1498. if (priv.options.columnPicker) {
  1499. node = $('<div class="btn-group dropup columnpicker ' + nodeClass + '"></div>');
  1500. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Kolumny&nbsp;</button>').appendTo(node);
  1501. var span = $('<span class="caret"></span>').appendTo(btn);
  1502. var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
  1503. var columnFilters = priv.modelColFilter_getFilters();
  1504. var selectedFilter = priv.modelColFilter_getSelected();
  1505. $.each(columnFilters, function(idx, colFltr) {
  1506. var li = $('<li></li>').appendTo(ul),
  1507. selected = (selectedFilter && selectedFilter == colFltr.name)? 'checked="checked"' : '',
  1508. input = '<input ' + selected + ' type="radio" style="margin:0"/>',
  1509. a = $('<a href="#" data-col_filter="' + colFltr.name + '" style="padding:0px 20px;">' + input + ' ' + colFltr.label + '</a>').appendTo(li);
  1510. });
  1511. $('<li class="divider"></li>').appendTo(ul);
  1512. $.each(_data.cols, function(col, props) {
  1513. if (props.type != "unique" && col != 'ID') {
  1514. var li = $('<li></li>').appendTo(ul),
  1515. label = (props.friendly || col).replace(/<br\/?>/g, ' '),
  1516. input = '<input {0} type="checkbox" title="{1}" value="{1}" style="margin:0"/>&nbsp;{2}'.f((props.hidden) ? '' : 'checked', col, label),
  1517. a = $('<a href="#" style="padding:0px 20px;">' + input + '</a>').appendTo(li);
  1518. }
  1519. });
  1520. node.on('click', 'input[type="checkbox"]', priv.columnPickerClicked);
  1521. node.on('click', 'a', priv.columnPickerLinkClicked);
  1522. } else {
  1523. node = $('<span class="' + nodeClass + '"></span>');
  1524. }
  1525. currentNode.replaceWith(node);
  1526. };
  1527. priv.renderFooterFunctions = function() {
  1528. var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
  1529. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1530. node;
  1531. if (priv.options.debug) console.log('Render: ', nodeClass);
  1532. if (priv.options.tblFunctions) {
  1533. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1534. $.map(priv.options.tblFunctions, function(funObj, funName){
  1535. var funHtml = $('<button class="btn btn-sm btn-default"></button>');
  1536. if (funObj.title) funHtml.attr('title', funObj.title);
  1537. if (funObj.method) funHtml.on('click', priv[funObj.method]);
  1538. else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
  1539. var funIconHtml = $('<i></i>');
  1540. if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
  1541. funIconHtml.prependTo(funHtml);
  1542. funHtml.addClass('btn');
  1543. funHtml.appendTo(node);
  1544. });
  1545. } else {
  1546. node = $('<span class="' + nodeClass + '"></span>');
  1547. }
  1548. currentNode.replaceWith(node);
  1549. };
  1550. priv.renderFooterExport = function() {
  1551. var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
  1552. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1553. node;
  1554. if (priv.options.debug) console.log('Render: ', nodeClass);
  1555. if (priv.options.exportFields.length) {
  1556. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1557. var btn = $('<button class="btn btn-sm dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
  1558. var span = $('<span class="caret"></span>').appendTo(btn);
  1559. var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
  1560. $.each(_data.cols, function(col, props) {
  1561. if (-1 !== priv.options.exportFields.indexOf(col)) {
  1562. var li = $('<li></li>').appendTo(ul);
  1563. $('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col)).appendTo(li);
  1564. li.on('click', 'input', priv.exportFieldChanged);
  1565. }
  1566. });
  1567. var li = $('<li></li>').appendTo(ul);
  1568. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
  1569. li.on('click', 'a', priv.exportToHTML);
  1570. var li = $('<li></li>').appendTo(ul);
  1571. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
  1572. li.on('click', 'a', priv.exportToCSV);
  1573. } else {
  1574. node = $('<span class="' + nodeClass + '"></span>');
  1575. }
  1576. currentNode.replaceWith(node);
  1577. };
  1578. priv.renderInlineEditBox = function() {
  1579. var nodeClass = 'tblAjax__' + 'inlineEditBox',
  1580. currentNode = $(_uiNodeCont).parent().children('.' + nodeClass),
  1581. node;
  1582. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  1583. /// console.log('L.<?php echo __LINE__; ?> Render: priv.renderInlineEditBox, currentNode.html:', currentNode.html(), currentNode);
  1584. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  1585. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  1586. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  1587. var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
  1588. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
  1589. $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
  1590. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  1591. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  1592. $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  1593. $('<input type="hidden" name="col" value="">').appendTo(iebBody);
  1594. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  1595. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  1596. $('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  1597. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  1598. frmInlineEdit.on('submit', function() {
  1599. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  1600. var data = inlineEditBox$Node.find('form').serialize();
  1601. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  1602. function notifyAjaxCallback(data) {
  1603. var notify = {};
  1604. notify.type = (data && data.type)? data.type : '';
  1605. notify.msg = (data && data.msg)? data.msg : '';
  1606. switch (notify.type) {
  1607. case 'success':
  1608. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  1609. break;
  1610. case 'info':
  1611. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  1612. break;
  1613. case 'error':
  1614. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1615. break;
  1616. case 'warning':
  1617. notify.type = 'warn';
  1618. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1619. break;
  1620. default:
  1621. notify.msg = 'Nieznany błąd';
  1622. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1623. notify.type = '';
  1624. }
  1625. jQuery.notify(notify.msg, notify.type);
  1626. }
  1627. $.ajax({
  1628. data: data,
  1629. dataType: 'json',
  1630. type: "POST",
  1631. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE'
  1632. })
  1633. .done(function(data, textStatus, jqXHR){
  1634. notifyAjaxCallback(data);
  1635. publ.refresh();
  1636. inlineEditBox$Node.modal('hide');
  1637. })
  1638. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  1639. if (jqXHR.responseJSON) {
  1640. notifyAjaxCallback(jqXHR.responseJSON);
  1641. }
  1642. else {
  1643. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  1644. if (jqXHR.status == 404) {
  1645. jQuery.notify(jqXHR.responseText, 'error');
  1646. } else {
  1647. jQuery.notify(jqXHR.responseText, 'warn');
  1648. }
  1649. }
  1650. inlineEditBox$Node.modal('hide');
  1651. });
  1652. return false;
  1653. });
  1654. currentNode.replaceWith(node);
  1655. };
  1656. priv.exportFieldChanged = function(e) {
  1657. e.stopPropagation();
  1658. var column = $(this).val();
  1659. _exportFieldsSelect[column] = !_exportFieldsSelect[column];
  1660. };
  1661. priv.exportToHTML = function(e) {
  1662. priv.exportData('html', $(this), e);
  1663. };
  1664. priv.exportToCSV = function(e) {
  1665. priv.exportData('csv', $(this), e);
  1666. };
  1667. priv.exportData = function(format, node, e) {
  1668. var exportFields = [];
  1669. $.each(_exportFieldsSelect, function(col, selected) {
  1670. if (selected) {
  1671. exportFields.push(col);
  1672. }
  1673. });
  1674. if (!exportFields.length) {
  1675. alert('Nie wybrano żadnych pól do eksportu.');
  1676. e.preventDefault();
  1677. return false;
  1678. }
  1679. var limit = 10000;
  1680. if (!_data.total || _data.total <= 0) {
  1681. alert('Brak rekordów do eksportu.');
  1682. e.preventDefault();
  1683. return false;
  1684. }
  1685. if (_data.total > limit) {
  1686. if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
  1687. e.preventDefault();
  1688. return false;
  1689. }
  1690. }
  1691. var exportUrl = 'index.php?MENU_INIT=VIEWTABLE_AJAX_EXPORT&ZASOB_ID=<?php echo $this->_zasobID; ?>';
  1692. if ('csv' == format) exportUrl += '&HEADER_NOT_INIT=YES';
  1693. exportUrl += '&format=' + format;
  1694. exportUrl += '&flds=' + exportFields.join(',');
  1695. exportUrl += '&sortCol=' + (_state.filters.currSortCol || '');
  1696. exportUrl += '&sortDir=' + (_state.filters.currSortFlip ? "desc" : "asc");
  1697. if (Object.keys(_state.filters.filterCols).length > 0) {
  1698. $.each(_state.filters.filterCols, function(col, colProps) {
  1699. if (colProps.filter && colProps.filter.length > 0) {
  1700. exportUrl += '&f_' + col + '=' + colProps.filter;
  1701. }
  1702. });
  1703. }
  1704. // specialFilters
  1705. $.each(_state.specialFilters, function(groupName, btnValue) {
  1706. if (btnValue.length > 0) {
  1707. exportUrl += '&sf_' + groupName + '=' + btnValue;
  1708. }
  1709. });
  1710. if (priv.options.forceFilterInit) {
  1711. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  1712. exportUrl += '&sf_' + fltr + '=' + fltrProps;
  1713. });
  1714. }
  1715. node.attr('href', exportUrl);
  1716. };
  1717. /*
  1718. calls the webservice(if defined).
  1719. used only inside priv.init
  1720. */
  1721. priv.update = function(callback) {
  1722. var skipCols, resetChecked;// undefined
  1723. if (!priv.options.url) {
  1724. if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
  1725. return;
  1726. }
  1727. 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) || ''));
  1728. var initUrlAdd = '',
  1729. reqData = {},
  1730. filtersInitSet = false;
  1731. initUrlAdd += '&currSortCol=' + _state.filters.currSortCol;
  1732. initUrlAdd += '&currSortFlip=' + ((_state.filters.currSortCol)? "desc" : "asc");
  1733. if (Object.keys(_state.filters.filterCols).length > 0) {
  1734. $.each(_state.filters.filterCols, function(col, colProps) {
  1735. if (colProps.filter && colProps.filter.length > 0) {
  1736. initUrlAdd += '&f_' + col + '=' + colProps.filter;
  1737. filtersInitSet = true;
  1738. }
  1739. });
  1740. }
  1741. $.each(_state.specialFilters, function(groupName, btnValue) {
  1742. if (btnValue.length > 0) {
  1743. initUrlAdd += '&sf_' + groupName + '=' + btnValue;
  1744. filtersInitSet = true;
  1745. }
  1746. });
  1747. if (priv.options.forceFilterInit) {
  1748. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  1749. reqData['f_' + fltr] = fltrProps;
  1750. filtersInitSet = true;
  1751. });
  1752. }
  1753. $.ajax({
  1754. url: priv.options.url + initUrlAdd,
  1755. type: priv.options.urlPost ? 'POST' : 'GET',
  1756. dataType: 'json',
  1757. contentType: "application/json; charset=utf-8",
  1758. data: reqData,
  1759. async: true,
  1760. success: function(data) {
  1761. if (priv.options.debug) console.log('request finished L.<?php echo __LINE__; ?>');
  1762. // assign the new data
  1763. if (data && data.cols) {
  1764. priv.setStateCols(data.cols, data.uniqueCol);
  1765. }
  1766. // set initial filters (_state.filters.filterCols)
  1767. if (filtersInitSet && _data && _data.cols) {
  1768. $.map(reqData, function(fltrValue, fltr){
  1769. var colName = null;
  1770. if (fltr.substr(0, 3) == 'sf_') {
  1771. colName = fltr.substr(3);
  1772. }
  1773. else if (fltr.substr(0, 2) == 'f_') {
  1774. colName = fltr.substr(2);
  1775. }
  1776. if (colName && _data.cols[colName]) {
  1777. //add the filter to the filter array
  1778. _state.filters.filterCols[colName] = {
  1779. filter: fltrValue,
  1780. colName: colName
  1781. };
  1782. }
  1783. });
  1784. }
  1785. // assign the new state (data)
  1786. state = {data: {}};
  1787. if (!skipCols) state.data.cols = data.cols || {};
  1788. state.data.rows = data.rows || [];
  1789. state.data.total = data.total || 0;
  1790. state.page = data.page || 0;
  1791. state.pageSize = data.pageSize || priv.options.pageSize;
  1792. state.filters = data.filters || {};
  1793. priv.setState(state);
  1794. if (typeof callback == "function")
  1795. callback.call(this);
  1796. },
  1797. error: function(err) {
  1798. //console.log('request error: {0}'.f(JSON.stringify(err)));
  1799. if (typeof callback == "function")
  1800. callback.call(this);
  1801. }
  1802. });
  1803. };
  1804. /*
  1805. assigns the new data.
  1806. */
  1807. priv.setState = function(state) {
  1808. var oldState = _state,// TODO: use to check what really changed (use extend!)
  1809. renderParts = {};
  1810. if (state.data) {
  1811. if (state.data.cols && state.data.cols.length > 0) {// TODO: never happen, but if happend then rerender all
  1812. priv.setStateCols(state.data.cols, state.data.uniqueCol);
  1813. priv.setStateData(state.data);
  1814. renderParts['head'] = true;
  1815. } else {
  1816. priv.setStateData(state.data, true);
  1817. }
  1818. renderParts['body'] = true;
  1819. renderParts['foot_pagination'] = true;
  1820. }
  1821. if (state.hasOwnProperty('specialFilters')) {
  1822. _state.specialFilters = state.specialFilters;
  1823. renderParts['head__specialFilters'] = true;
  1824. }
  1825. if (state.hasOwnProperty('page')) {
  1826. if (state.page != _state.page) {
  1827. _state.page = state.page;
  1828. renderParts['foot_pagination'] = true;
  1829. }
  1830. }
  1831. if (state.hasOwnProperty('pageSize')) {
  1832. if (state.pageSize != _state.pageSize) {
  1833. _state.pageSize = state.pageSize;
  1834. renderParts['foot_pagination'] = true;
  1835. }
  1836. }
  1837. if (state.hasOwnProperty('filters')) {
  1838. /// console.log('L.<?php echo __LINE__; ?> setState::state.filters: ', state.filters);//TODO:DBG:RMME
  1839. priv.setStateFilters(state.filters);
  1840. // TODO: if state diff's
  1841. renderParts['head__specialFilters'] = true;
  1842. renderParts['foot_pagination'] = true;
  1843. }
  1844. renderParts = Object.keys(renderParts);
  1845. if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1846. ///console.log('L.<?php echo __LINE__; ?> setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1847. if (renderParts.length > 0) {
  1848. jQuery(_uiNodeCont).trigger('TableAjax:render', renderParts);
  1849. }
  1850. };
  1851. priv.setStateCols = function(cols, uniqueCol) {
  1852. _state.cols = cols;
  1853. _state.uniqueCol = uniqueCol;
  1854. // fix col name - props.column
  1855. $.each(_state.cols, function(col, props) {
  1856. props.column = col;
  1857. });
  1858. // fix col types - default 'string'
  1859. $.each(_state.cols, function(col, props) {
  1860. if (!props.type) cols[col].type = "string";
  1861. });
  1862. // fix props.filter - set true if not set - TODO: allow filter this col?
  1863. $.each(_state.cols, function(col, props) {
  1864. if (props.filter == undefined) props.filter = true;
  1865. });
  1866. if (_state.uniqueCol) {
  1867. //create a unique column definition
  1868. _state.cols["unique"] = {
  1869. column: "unique",
  1870. type: "unique",
  1871. index: -1,
  1872. hidden: true
  1873. };
  1874. }
  1875. _state.colsSorted = Object.keys(_state.cols).sort(function(a, b) {
  1876. return _state.cols[a].index - _state.cols[b].index;
  1877. });
  1878. };
  1879. priv.setStateFilters = function(stateFilters) {
  1880. var newFilterCols = {},
  1881. newSpecialFilters = {};
  1882. $.map(stateFilters, function(fltrProps, fltr) {
  1883. switch (fltr) {
  1884. case 'currSortCol': _state.filters.currSortCol = fltrProps; break;
  1885. case 'currSortFlip': _state.filters.currSortFlip = (fltrProps == 'desc')? true : false; break;
  1886. default:
  1887. if (fltr.substr(0, 2) == 'f_') {
  1888. newFilterCols[fltr.substr(2)] = {
  1889. filter: fltrProps,
  1890. colName: fltr.substr(2)
  1891. };
  1892. }
  1893. else if (fltr.substr(0, 3) == 'sf_') {
  1894. var groupName = fltr.substr(3);
  1895. if (priv.options.specialFilterFunctions.hasOwnProperty(groupName)) {
  1896. newSpecialFilters[groupName] = fltrProps;
  1897. }
  1898. }
  1899. }
  1900. });
  1901. _state.filters.filterCols = newFilterCols;
  1902. _state.specialFilters = newSpecialFilters;
  1903. };
  1904. priv.setStateData = function(pData, skipCols, resetChecked) {
  1905. var data = $.extend(true, {}, pData);
  1906. data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
  1907. _data = data;
  1908. _data.rowsOrg = _data.rows;
  1909. //we might have more/less data now. Recalculate stuff.
  1910. if (_state.page > 1) {
  1911. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  1912. }
  1913. //keep any previously checked rows around?
  1914. if (resetChecked === true || resetChecked === undefined)
  1915. _uniqueCols = {};
  1916. else {
  1917. for (var key in _uniqueCols)
  1918. _uniqueCols[key] = priv.getRow(key);
  1919. }
  1920. if (_state.uniqueCol) {
  1921. //add rows that needs to be pre-checked
  1922. $.each(_data.rows, function(index, row) {
  1923. if (row["checked"] === true)
  1924. _uniqueCols[row[_state.uniqueCol]] = row;
  1925. });
  1926. }
  1927. };
  1928. /*
  1929. sorts the data on the current sorting column
  1930. */
  1931. priv.sort = function() {
  1932. if (!_data.cols[_state.filters.currSortCol]) _state.filters.currSortCol = "";
  1933. if (!_state.filters.currSortCol) return;
  1934. publ.loadPage(0);
  1935. };
  1936. /*
  1937. helper that returns the underlying data by the unique value
  1938. */
  1939. priv.getRow = function(uniqueValue) {
  1940. var row;
  1941. $.each(_data.rowsOrg, function(i, r) {
  1942. if (r[_state.uniqueCol] == uniqueValue) {
  1943. row = r;
  1944. return false;
  1945. }
  1946. });
  1947. return row;
  1948. };
  1949. /*
  1950. when: typing a filter
  1951. what: triggers filtering on the value
  1952. */
  1953. priv.filterChanged = function(e) {
  1954. //clear old timer if we're typing fast enough
  1955. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?>');
  1956. if (_filterTimeout) {
  1957. clearTimeout(_filterTimeout);
  1958. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?> previous filtering cancelled');
  1959. }
  1960. var filter = this.value
  1961. , fltr = $(this)
  1962. , col = _data.cols[e.data.column]
  1963. , timeout = 300;
  1964. if (this.value) {
  1965. if (!fltr.hasClass('filter-active')) {
  1966. fltr.addClass('filter-active');
  1967. }
  1968. } else {
  1969. if (fltr.hasClass('filter-active')) {
  1970. fltr.removeClass('filter-active');
  1971. }
  1972. }
  1973. //boolean filters needs some special care
  1974. if (col.type == "bool" || col.type == "unique") {
  1975. timeout = 0;
  1976. var elem = $(this);
  1977. var cssClass = 'indeterminate';
  1978. if (elem.hasClass(cssClass)) {
  1979. e.preventDefault();
  1980. elem.removeClass(cssClass);
  1981. filter = true;
  1982. } else {
  1983. if (!elem.is(':checked')) {
  1984. filter = false;
  1985. } else {
  1986. elem.addClass(cssClass);
  1987. filter = '';
  1988. }
  1989. }
  1990. }
  1991. //add the filter to the filter array
  1992. _state.filters.filterCols[col.column] = {
  1993. filter: filter,
  1994. colName: col.column
  1995. };
  1996. //wait a few deciseconds before filtering
  1997. _filterTimeout = setTimeout(function(filterValue, colName) {
  1998. _state.filters.filterCols[colName] = {
  1999. filter: filterValue,
  2000. colName: colName
  2001. };
  2002. priv.filter();
  2003. }, timeout, filter, col.column);
  2004. };
  2005. priv.filtersClean = function(e) {
  2006. if (_filterTimeout) {
  2007. clearTimeout(_filterTimeout);
  2008. if (priv.options.debug) console.log('filtering cancelled - filtersClean');
  2009. }
  2010. var filtersActive = false;
  2011. $.map(_state.filters.filterCols, function(colProps, col) {
  2012. if (colProps.filter.length > 0) {
  2013. filtersActive = true;
  2014. colProps.filter = '';
  2015. }
  2016. });
  2017. if (filtersActive) {
  2018. // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
  2019. /// TODO: rerender _head (thead.filter)
  2020. var elems = _uiNode$Table.find('thead').find('.filter').find('input');
  2021. elems.val('').prop('disabled', false);
  2022. elems.removeClass('filter-active');
  2023. priv.filter();
  2024. }
  2025. return false;
  2026. },
  2027. /**
  2028. * Filters the data.
  2029. */
  2030. priv.filter = function() {
  2031. if (!priv.options.filter) return;
  2032. if (Object.keys(_state.filters.filterCols).length == 0) return;
  2033. priv.loadPage(0);
  2034. };
  2035. /**
  2036. * Filters the data by specialFilter.
  2037. * when: click on special filter
  2038. * what: triggers filtering on the value
  2039. */
  2040. priv.specialFilterChanged = function(e) {
  2041. if (priv.options.debug) console.log('specialFilterChanged e.data:', e.data);
  2042. var state = {};
  2043. state.specialFilters = _state.specialFilters;
  2044. state.specialFilters[e.data.group] = e.data.value;
  2045. priv.setState(state);
  2046. publ.loadPage(0);
  2047. };
  2048. priv.longTextChanged = function(e) {
  2049. priv.options.longDesc = !priv.options.longDesc;
  2050. _bodyNode.find('td').each(function(ind, el){
  2051. var $el = jQuery(el);
  2052. if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
  2053. //console.log(el.attr('class') + ': ' + el.text());
  2054. if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
  2055. if (priv.options.longDesc) {
  2056. $el.addClass('tbl-short-txt');
  2057. var $elSpan = jQuery(el.firstChild);
  2058. $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
  2059. } else {
  2060. $el.removeClass('tbl-short-txt');
  2061. }
  2062. }
  2063. }
  2064. });
  2065. return false;
  2066. };
  2067. priv.mapEditorHide = function() {
  2068. priv.options.mapEditor = false;
  2069. if ('window' == priv.options.mapEditorContainer) {
  2070. //_mapEditorDialog.dialog("close");
  2071. _mapEditorDialog.dialog("destroy");
  2072. }
  2073. _mapEditorWrap.hide();
  2074. _mapEditor.hide();
  2075. };
  2076. priv.mapEditorShow = function() {
  2077. //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
  2078. priv.options.mapEditor = true;
  2079. _mapEditor.show();
  2080. _mapEditorWrap.show();
  2081. _mapEditor.TableAjaxMap({
  2082. //debug: true,
  2083. wpsUrl: 'http://biuro.biall-net.pl/wps',
  2084. wfsUrl: 'http://biuro.biall-net.pl/wps',
  2085. showAddLayerWidget: <?php echo ($this->hasAdditionalLayers())? 'true' : 'false'; ?>,
  2086. zoomStrategyActivate: 14,
  2087. layerName: '<?php echo $this->getLabelHtml(); ?>',
  2088. addBtn: {
  2089. title: 'Przenieś mapę do okna',
  2090. displayClass: 'mapEditor-btnBackToWindow',
  2091. trigger: function() {
  2092. priv.mapEditorHide();
  2093. priv.options.mapEditorContainer = 'window';
  2094. priv.mapEditorShow();
  2095. priv.resizableMapDockNode('destroy');
  2096. }
  2097. },
  2098. onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
  2099. if (priv.options.debug) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
  2100. if (!selectedRecordId) {
  2101. alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
  2102. return;
  2103. }
  2104. function notifyAjaxCallback(data) {
  2105. var notify = {};
  2106. notify.type = (data && data.type)? data.type : '';
  2107. notify.msg = (data && data.msg)? data.msg : '';
  2108. switch (notify.type) {
  2109. case 'success':
  2110. if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
  2111. break;
  2112. case 'info':
  2113. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  2114. break;
  2115. case 'error':
  2116. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2117. break;
  2118. case 'warning':
  2119. notify.type = 'warn';
  2120. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2121. break;
  2122. default:
  2123. notify.msg = 'Nieznany błąd';
  2124. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2125. notify.type = '';
  2126. }
  2127. jQuery.notify(notify.msg, notify.type);
  2128. }
  2129. $.ajax({
  2130. data: {polygon: selectedFeatureExtent},
  2131. dataType: 'json',
  2132. type: "POST",
  2133. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
  2134. })
  2135. .done(function(data, textStatus, jqXHR){
  2136. notifyAjaxCallback(data);
  2137. //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
  2138. publ.loadPage(0);// TODO: reload table data
  2139. })
  2140. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2141. if (jqXHR.responseJSON) {
  2142. notifyAjaxCallback(jqXHR.responseJSON);
  2143. }
  2144. else {
  2145. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2146. if (jqXHR.status == 404) {
  2147. jQuery.notify(jqXHR.responseText, 'error');
  2148. } else {
  2149. jQuery.notify(jqXHR.responseText, 'warn');
  2150. }
  2151. }
  2152. });
  2153. },
  2154. onSelectBox: function(bounds) {
  2155. if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
  2156. var column = 'the_geom';
  2157. if (undefined !== _filterFields['the_geom']) {
  2158. var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
  2159. _filterFields[column].val(filter);
  2160. _state.filters.filterCols[column] = {
  2161. filter: filter,
  2162. colName: column
  2163. };
  2164. priv.filter();
  2165. }
  2166. }
  2167. }
  2168. });
  2169. priv.mapEditorShowElement();
  2170. };
  2171. priv.mapEditorShowElement = function() {
  2172. if ('window' == priv.options.mapEditorContainer) {
  2173. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2174. if (!mapEditor || !mapEditor.length) {
  2175. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2176. var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
  2177. if (!mapEditor || !mapEditor.length) {
  2178. // TODO: create new map
  2179. }
  2180. _mapEditorWrap.append(mapEditor);
  2181. }
  2182. _mapEditorWrap.css({padding:'5px'});
  2183. _mapEditorDialog = _mapEditorWrap.dialog({
  2184. width: 540,
  2185. minWidth: 400,
  2186. minHeight: 400,
  2187. open: function(e, ui) {
  2188. var n = jQuery(this),
  2189. mapWrap = n.children(":first"),
  2190. map = mapWrap.children(":first");
  2191. map.css({width: n.width() - 5, height: n.height() - 5});
  2192. _mapEditor.TableAjaxMapUpdateSize();
  2193. },
  2194. resizeStart: function(e, ui) {
  2195. jQuery(this).children(":first").children(":first").css({display:'none'});
  2196. },
  2197. resizeStop: function(e, ui){
  2198. var n = jQuery(this),
  2199. map = n.children(":first").children(":first");
  2200. n.css({width: n.parent().width()});
  2201. map.css({display: 'block', height: n.height(), width: n.width()});
  2202. _mapEditor.TableAjaxMapUpdateSize();
  2203. },
  2204. dragStop: function(e, ui){
  2205. _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
  2206. }
  2207. });
  2208. _mapEditorWrap.bind('dialogclose', function(e) {
  2209. priv.options.mapEditor = false;
  2210. });
  2211. var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
  2212. var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
  2213. if (dialogTitleBarCloseBtn) {
  2214. var btnToggle = jQuery('<span style="width:18px;height:18px;position:absolute;top:50%;right:25px;margin-top:-9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"><i style="margin-top:3px;" class="glyphicon glyphicon-fullscreen"></i></span>');
  2215. btnToggle.on('click', function(e) {
  2216. priv.options.mapEditorContainer = 'dock';
  2217. _mapEditorWrap.dialog('close');
  2218. priv.mapEditorShowElement();
  2219. });
  2220. btnToggle.insertBefore(dialogTitleBarCloseBtn);
  2221. }
  2222. }
  2223. else if ('dock' == priv.options.mapEditorContainer) {
  2224. priv.resizableMapDockNode('prepare');
  2225. _mapEditor.TableAjaxMapUpdateSize();
  2226. }
  2227. };
  2228. priv.resizableMapDockNode = function(task) {
  2229. if ('prepare' == task) {
  2230. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2231. if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
  2232. var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
  2233. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2234. tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
  2235. var breadcrumb = tblCont.children('.breadcrumb');
  2236. if (!breadcrumb || !breadcrumb.length) {
  2237. tblCont.prepend(mapDockNode);
  2238. } else {
  2239. mapDockNode.insertAfter(breadcrumb);
  2240. }
  2241. mapDockNode.append(mapEditor);
  2242. }
  2243. var mapDockResizable = mapEditor.parent();
  2244. mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
  2245. var resizeLineHeigth = 6;
  2246. mapDockResizable.children(":first").css({height: 'auto'});
  2247. mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
  2248. mapEditor.css({marginBottom: resizeLineHeigth+'px'});
  2249. mapEditor.children(":first").css({width: mapEditor.width()});
  2250. mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
  2251. mapDockResizable.on('resizestart', function(event, ui) {
  2252. ui.element.children(":first").children(":first").css({display:'none'})
  2253. });
  2254. mapDockResizable.on('resizestop', function(event, ui) {
  2255. ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
  2256. });
  2257. } else if ('destroy' == task) {
  2258. var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
  2259. mapDockResizable.resizable('destroy');
  2260. mapDockResizable.remove();
  2261. }
  2262. };
  2263. priv.mapEditorChanged = function(e) {
  2264. if (priv.options.debug) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
  2265. priv.options.mapEditor = !priv.options.mapEditor;
  2266. if (priv.options.mapEditor) {
  2267. priv.mapEditorShow();
  2268. }
  2269. else {
  2270. priv.mapEditorHide();
  2271. }
  2272. return false;
  2273. };
  2274. /*
  2275. when: changing page in pager
  2276. what: triggers table to be created with new page
  2277. */
  2278. priv.pageChanged = function(e) {
  2279. e.preventDefault();
  2280. var totalPages = Math.ceil(_data.total / _state.pageSize);
  2281. if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
  2282. //set the new page
  2283. _state.page = e.data.pageIndex;
  2284. publ.loadPage(_state.page);
  2285. };
  2286. /*
  2287. when: changing pagesize in pagesize dropdown
  2288. what: triggers table to be created with new pagesize
  2289. */
  2290. priv.pageSizeChanged = function(e) {
  2291. e.preventDefault();
  2292. var val = $(this).text();
  2293. if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
  2294. if (parseInt(val) == priv.options.pageSize) {
  2295. return false;
  2296. }
  2297. priv.options.pageSize = parseInt(val);
  2298. publ.loadPage(1, priv.options.pageSize);
  2299. jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
  2300. priv.saveProfilePageSize(priv.options.pageSize);
  2301. };
  2302. /*
  2303. when: clicking a column
  2304. what: triggers table to be sorted by the column
  2305. */
  2306. priv.columnClicked = function(e) {
  2307. e.preventDefault();
  2308. if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
  2309. //set the new sorting column
  2310. if (_state.filters.currSortCol == e.data.column) _state.filters.currSortFlip = !_state.filters.currSortFlip;
  2311. _state.filters.currSortCol = e.data.column;
  2312. /// TODO: var state = {}; state.currSortCol = ''; state.currSortFlip = ''; priv.setState(state);
  2313. _headSort = undefined;
  2314. _body = undefined;
  2315. priv.sort();
  2316. };
  2317. priv.saveProfilePageSize = function(pageSize) {
  2318. var reqData = {};
  2319. reqData.pageSize = pageSize;
  2320. $.ajax({
  2321. data: reqData,
  2322. type: "POST",
  2323. dataType: 'json',
  2324. // async: true,
  2325. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PAGE_SIZE_SAVE'
  2326. })
  2327. .done(function(data, textStatus, jqXHR){
  2328. if (data && data.type && data.type == 'info') {
  2329. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2330. } else {
  2331. jQuery.notify('Zapisano ustawienia', 'success');
  2332. }
  2333. })
  2334. .fail(function(){
  2335. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2336. });
  2337. };
  2338. priv.saveHiddenCols = function() {
  2339. var reqData = {};
  2340. $.each(_data.cols, function(col, props) {
  2341. if (props.type != "unique" && col != 'unique' && col != 'ID') {
  2342. reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
  2343. }
  2344. });
  2345. $.ajax({
  2346. data: reqData,
  2347. type: "POST",
  2348. dataType: 'json',
  2349. // async: true,
  2350. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
  2351. })
  2352. .done(function(data, textStatus, jqXHR){
  2353. if (data && data.type && data.type == 'info') {
  2354. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2355. } else {
  2356. jQuery.notify('Zapisano ustawienia', 'success');
  2357. }
  2358. })
  2359. .fail(function(){
  2360. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2361. });
  2362. };
  2363. /*
  2364. when: clicking a column in columnpicker
  2365. what: triggers table to show/hide the column
  2366. */
  2367. priv.columnPickerClicked = function(e) {
  2368. e.stopPropagation();
  2369. var column = $(this).val();
  2370. //toggle column visibility
  2371. priv.modelColFilter_toggleColumn(column);
  2372. priv.saveHiddenCols();
  2373. //_data.cols[column].index = new priv.ext.XDate();
  2374. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2375. };
  2376. priv.modelColFilter_init = function() {
  2377. var isAllSelected = true;
  2378. if (undefined === _state._modelColFilter) {
  2379. var columnFilters = [];
  2380. {
  2381. var fltrAll = {'name': 'all', 'label': 'Wszystkie', visibleCols: []};
  2382. $.each(_data.cols, function(col, props) {
  2383. if ("unique" == props.type) return;
  2384. fltrAll.visibleCols.push(col);
  2385. if (_data.cols[col].hidden) isAllSelected = false;
  2386. });
  2387. columnFilters.push(fltrAll);
  2388. }
  2389. {
  2390. var fltrMostUsed = {'name': 'most_used', 'label': 'Najczęściej używane', visibleCols: []};
  2391. var fltrMostUsedLimit = 10;
  2392. $.each(_data.cols, function(col, props) {
  2393. if ("unique" == props.type) return;
  2394. if (fltrMostUsedLimit-- > 0) {
  2395. fltrMostUsed.visibleCols.push(col);
  2396. }
  2397. });
  2398. columnFilters.push(fltrMostUsed);
  2399. }
  2400. _state._modelColFilter = {
  2401. selected: (isAllSelected)? 'all' : null,
  2402. filters: columnFilters
  2403. };
  2404. }
  2405. };
  2406. priv.modelColFilter_getFilters = function() {
  2407. priv.modelColFilter_init();
  2408. return _state._modelColFilter.filters;
  2409. };
  2410. priv.modelColFilter_getSelected = function() {
  2411. priv.modelColFilter_init();
  2412. return _state._modelColFilter.selected;
  2413. };
  2414. priv.modelColFilter_setFilter = function(filterKey) {
  2415. priv.modelColFilter_init();
  2416. _state._modelColFilter.selected = filterKey;
  2417. priv.modelColFilter_uiUncheckAllColFilters();
  2418. priv.modelColFilter_uiCheckColFilter(filterKey);
  2419. };
  2420. priv.modelColFilter_toggleColumn = function(column, value) {
  2421. priv.modelColFilter_init();
  2422. _state._modelColFilter.selected = null;
  2423. if (!_data.cols[column] || !_data.cols[column]) return;
  2424. _data.cols[column].hidden = (undefined !== value)? value : !_data.cols[column].hidden;
  2425. priv.modelColFilter_uiUncheckAllColFilters();
  2426. {
  2427. var isAllSelected = true;
  2428. $.each(_data.cols, function(col, props) {
  2429. if ("unique" == props.type) return;
  2430. if (_data.cols[col].hidden) isAllSelected = false;
  2431. });
  2432. if (isAllSelected) {
  2433. _state._modelColFilter.selected = 'all';
  2434. priv.modelColFilter_uiCheckColFilter('all');
  2435. }
  2436. }
  2437. };
  2438. priv.modelColFilter_uiUncheckAllColFilters = function() {
  2439. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2440. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2441. ;
  2442. currentNode.find('input[type="radio"]').prop("checked", false);
  2443. };
  2444. priv.modelColFilter_uiCheckColFilter = function(filterKey) {
  2445. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2446. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2447. ;
  2448. currentNode.find('input[type="radio"]').each(function(idx, input) {
  2449. var input$ = jQuery(input);
  2450. if (filterKey == jQuery(input$).parent().data('col_filter')) {
  2451. input$.prop("checked", true);
  2452. } else {
  2453. input$.prop("checked", false);
  2454. }
  2455. });
  2456. };
  2457. priv.columnPickerLinkClicked = function(e) {
  2458. e.stopPropagation();
  2459. var input$ = $(this).find('input'),
  2460. col_filter = $(this).data('col_filter'),
  2461. columnFilters = priv.modelColFilter_getFilters()
  2462. ;
  2463. if (col_filter) {
  2464. var filter = null;
  2465. $.each(columnFilters, function(idx, colFltr) {
  2466. if (col_filter == colFltr.name) {
  2467. filter = colFltr;
  2468. }
  2469. });
  2470. if (!filter) return;
  2471. $.each(_data.cols, function(col, props) {
  2472. var isHidden = (-1 === filter.visibleCols.indexOf(col));
  2473. priv.modelColFilter_toggleColumn(col, isHidden);
  2474. });
  2475. priv.modelColFilter_setFilter(col_filter);
  2476. priv.saveHiddenCols();
  2477. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2478. } else {
  2479. e.preventDefault();
  2480. if (input$.length != 1) return;
  2481. var column = input$.val();
  2482. if (!column) return;
  2483. //toggle column visibility
  2484. priv.modelColFilter_toggleColumn(column);
  2485. input$.prop("checked", !input$.is(':checked'));// update view
  2486. priv.saveHiddenCols();
  2487. //_data.cols[column].index = new priv.ext.XDate();
  2488. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2489. }
  2490. };
  2491. priv.columnHideClicked = function(e) {
  2492. e.stopPropagation();
  2493. var column;
  2494. if (e.data && e.data.column) {
  2495. column = e.data.column;
  2496. } else {
  2497. return;
  2498. }
  2499. //toggle column visibility
  2500. priv.modelColFilter_toggleColumn(column);
  2501. priv.saveHiddenCols();
  2502. //_data.cols[column].index = new priv.ext.XDate();
  2503. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2504. };
  2505. /*
  2506. when: clicking a row checkbox
  2507. what: toggles checked state on row, and add/removes it from checked array
  2508. */
  2509. priv.rowChecked = function(e) {
  2510. var elem = $(this);
  2511. //get the row's unique value
  2512. var unique = elem.closest('tr').data('unique');
  2513. if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
  2514. //store the row in checked array
  2515. if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
  2516. else delete _uniqueCols[unique];
  2517. };
  2518. /*
  2519. when: clicking anywhere on a row
  2520. what: row data and other info is returned to caller
  2521. */
  2522. // priv.rowClicked = function(e) {// TODO: not used
  2523. // if (!_state.uniqueCol) {
  2524. // if (priv.options.debug) console.log('no unique column specified');
  2525. // return;
  2526. // }
  2527. // //gather callback data
  2528. // var elem = $(this);
  2529. // var column = _data.cols[elem.data('column')];
  2530. // var unique = elem.closest('tr').data('unique');
  2531. // var row = priv.getRow(unique);
  2532. // var isChecked = elem.closest('tr').find('.unique').is(':checked');
  2533. // //trigger callback
  2534. // if (typeof priv.options.rowClicked == 'function') {
  2535. // priv.options.rowClicked.call(e.target, {
  2536. // event: e,
  2537. // row: row,
  2538. // column: column,
  2539. // checked: isChecked
  2540. // });
  2541. // }
  2542. // };
  2543. /**
  2544. * Inline edit.
  2545. */
  2546. priv.rowDblClicked = function(e) {
  2547. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  2548. // hide popover for typespecial fld on click
  2549. if (_popoverCellCurrent) {
  2550. _popoverCellCurrent.popover('hide');
  2551. }
  2552. // e.clientX: 1002; e.clientY: 245
  2553. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2554. inlineEditBox$Node.modal();
  2555. inlineEditBox$Node.show();
  2556. inlineEditBox$Node.on('shown.bs.modal', function(e) {
  2557. var dialogBox = jQuery(this).find('.modal-dialog'),
  2558. modalBody = dialogBox.find('.modal-body'),
  2559. boudingRect = dialogBox.get(0).getBoundingClientRect();
  2560. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  2561. modalBody.css({overflow: 'scroll'});
  2562. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  2563. dialogBox.draggable({handle: '.modal-header'});
  2564. });
  2565. inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  2566. var dialogBox = jQuery(this).find('.modal-dialog'),
  2567. modalBody = dialogBox.find('.modal-body');
  2568. dialogBox.removeAttr('style');
  2569. modalBody.removeAttr('style');
  2570. modalBody.css({padding: '0'});
  2571. dialogBox.resizable();
  2572. dialogBox.draggable();
  2573. dialogBox.resizable('destroy');
  2574. dialogBox.draggable('destroy');
  2575. });
  2576. inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  2577. inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  2578. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  2579. $.ajax({
  2580. 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,
  2581. type: 'GET',
  2582. dataType: 'text',
  2583. data: '',
  2584. async: true,
  2585. success: function(data) {
  2586. inlineEditBox$Node.find('.inlineEditBox-cnt').html(data);
  2587. inlineEditBox$Node.find('.btn-save').show();
  2588. initDateTimePicker(inlineEditBox$Node);
  2589. inlineEditBox$Node.find('textarea').autosize();
  2590. var fld = inlineEditBox$Node.find('input[id^="f"]');
  2591. if (fld && !fld.hasClass('se_type-date')) {
  2592. fld.focus();
  2593. fld.keydown(function(event) {
  2594. if (event.which == 13) {
  2595. event.preventDefault();
  2596. inlineEditBox$Node.find('form').submit();
  2597. }
  2598. });
  2599. }
  2600. },
  2601. error: function(err) {
  2602. if (priv.options.debug) console.log('err');
  2603. }
  2604. });
  2605. } else {
  2606. if (priv.options.debug) console.log('NO data');
  2607. return false;
  2608. }
  2609. };
  2610. priv.ajaxLoadTypeSpeciallCell = function(id, col) {
  2611. if (_popoverCellAjaxXhr) {
  2612. _popoverCellAjaxXhr.abort();
  2613. }
  2614. _popoverCellAjaxXhr = $.ajax({
  2615. type: 'GET',
  2616. 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,
  2617. dataType: 'json',
  2618. contentType: "application/json; charset=utf-8",
  2619. data: '',
  2620. success: function(req){
  2621. if (req.data && req.data.tbl_id > 0) {
  2622. var addHtml = '';
  2623. for(var i in req.data.items){
  2624. var url = 'index.php?MENU_INIT=VIEWTABLE_AJAX';
  2625. url += '&ZASOB_ID=' + req.data.tbl_id;
  2626. url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
  2627. url += '&_hash=' + Math.random().toString(36).substring(2);
  2628. addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
  2629. addHtml += '<br>';
  2630. }
  2631. //_popoverCell.append(addHtml);// cache
  2632. if (_popoverCellCurrent) {
  2633. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  2634. if (popoverNodeId) {
  2635. jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
  2636. }
  2637. }
  2638. }
  2639. }
  2640. });
  2641. };
  2642. priv.popoverCellTypeSpecial = function(e) {
  2643. e.preventDefault();
  2644. e.stopPropagation();
  2645. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2646. var lastId = _popoverCell.data('rowid'),
  2647. lastCol = _popoverCell.data('col'),
  2648. rowPK = e.data.id,
  2649. colName = e.data.col
  2650. ;
  2651. if (lastId == rowPK && lastCol == colName) {
  2652. //_popoverCellCurrent.popover('toggle');
  2653. }
  2654. else {
  2655. if (_popoverCellCurrent) {
  2656. _popoverCellCurrent.popover('destroy');
  2657. }
  2658. _popoverCell.data('rowid', rowPK);
  2659. _popoverCell.data('col', colName);
  2660. _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
  2661. _popoverCellCurrent = jQuery(e.currentTarget);
  2662. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  2663. var opts = {
  2664. placement: 'left'
  2665. , trigger: 'click'
  2666. // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
  2667. , title: '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (e.data.friendly || colName) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>'
  2668. , html: true
  2669. , content: _popoverCell.html()
  2670. }
  2671. _popoverCellCurrent.popover(opts);
  2672. if (_data.cols[colName]) {
  2673. if (_data.cols[colName]._tsRetId > 0) {
  2674. _popoverCellCurrent.on('shown.bs.popover', function() {
  2675. priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
  2676. });
  2677. }
  2678. }
  2679. _popoverCellCurrent.popover('show');
  2680. }
  2681. } else {
  2682. if (priv.options.debug) console.log('NO data');
  2683. return false;
  2684. }
  2685. return;
  2686. };
  2687. priv.routeChanged = function(e) {
  2688. hash = e.data.hash || '';
  2689. if (hash.length == 0) {
  2690. return;
  2691. }
  2692. if (hash.substring(0, 1) != '#') {
  2693. hash = '#' + hash;
  2694. }
  2695. location.hash = hash;
  2696. };
  2697. priv.refresh = function(e) {
  2698. e.preventDefault();
  2699. publ.loadPage(_state.page);
  2700. };
  2701. publ.init = function(options) {
  2702. if (priv.options.debug) console.log('TableAjax initialization...');
  2703. //merge supplied options with defaults
  2704. $.extend(priv.options, defaults, options);
  2705. priv.init();
  2706. return publ;
  2707. };
  2708. publ.refresh = function() {
  2709. publ.loadPage(_state.page);
  2710. };
  2711. publ.loadPage = function(page, pageSize) {
  2712. priv.loadPage(page, pageSize);
  2713. }
  2714. priv.loadPage = function(page, pageSize) {
  2715. var skipCols = true, // skipCols = true - prevent columns delete
  2716. resetChecked = false;
  2717. var reqData = {
  2718. page: page,
  2719. pageSize: (pageSize || priv.options.pageSize),
  2720. currSortCol: (_state.filters.currSortCol || ''),
  2721. currSortFlip: _state.filters.currSortFlip ? "desc" : "asc"
  2722. };
  2723. if (Object.keys(_state.filters.filterCols).length > 0) {
  2724. $.each(_state.filters.filterCols, function(col, colProps) {
  2725. if (colProps.filter && colProps.filter.length > 0) {
  2726. reqData['f_' + col] = colProps.filter;
  2727. }
  2728. });
  2729. skipCols = true;
  2730. }
  2731. // specialFilters
  2732. $.each(_state.specialFilters, function(groupName, btnValue) {
  2733. if (btnValue.length > 0) {
  2734. reqData['sf_' + groupName] = btnValue;
  2735. }
  2736. });
  2737. if (priv.options.forceFilterInit) {
  2738. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  2739. reqData['f_' + fltr] = fltrProps;
  2740. filtersInitSet = true;
  2741. });
  2742. }
  2743. _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
  2744. $.ajax({
  2745. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2746. type: 'GET',
  2747. dataType: 'json',
  2748. contentType: "application/json; charset=utf-8",
  2749. data: reqData,
  2750. async: true,
  2751. success: function(data) {
  2752. state = {data: {}};
  2753. state.data.rows = data.rows || [];
  2754. state.data.total = data.total || 0;
  2755. state.page = data.page || 0;
  2756. state.pageSize = data.pageSize || priv.options.pageSize;
  2757. state.filters = data.filters || {};
  2758. priv.setState(state);
  2759. _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
  2760. },
  2761. error: function(err) {
  2762. if (priv.options.debug) console.log('request error: {0}'.f(JSON.stringify(err)));
  2763. }
  2764. });
  2765. };
  2766. publ.getCurrentPage = function() {
  2767. return _state.page;
  2768. };
  2769. publ.popoverCellRemove = function() {
  2770. if (_popoverCellCurrent) {
  2771. _popoverCellCurrent.popover('destroy');
  2772. }
  2773. _popoverCell.data('rowid', -1);
  2774. _popoverCell.data('col', -1);
  2775. _popoverCell.html('');
  2776. };
  2777. return publ;
  2778. }
  2779. $.fn.TableAjax = function(options) {
  2780. options = options || {};
  2781. return this.each(function() {
  2782. options.id = this;
  2783. $(this).data('TableAjax', new TableAjax().init(options));
  2784. });
  2785. };
  2786. $.fn.TableAjaxLoadPage = function(page, pageSize) {
  2787. return this.each(function() {
  2788. var tblAjax = jQuery(this).data('TableAjax');
  2789. var curPage = page || tblAjax.getCurrentPage();
  2790. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  2791. });
  2792. };
  2793. $.fn.TableAjaxRefresh = function(page, pageSize) {
  2794. return this.each(function() {
  2795. var tblAjax = jQuery(this).data('TableAjax');
  2796. if (tblAjax) tblAjax.refresh();
  2797. });
  2798. };
  2799. String.prototype.format = String.prototype.f = function() {
  2800. var s = this;
  2801. i = arguments.length;
  2802. while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
  2803. return s;
  2804. };
  2805. })(jQuery);
  2806. </script>
  2807. <?php
  2808. $filterInit = $this->_filterInit;
  2809. $forceFilterInit = $this->_forceFilterInit;
  2810. $pageSizes = $this->_pageSizes;
  2811. $pageSize = $this->_pageSize;
  2812. $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
  2813. $exportFields = $this->_showExportFieldsJson();
  2814. ?>
  2815. <script>
  2816. jQuery(document).ready(function(){
  2817. jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
  2818. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2819. columnPicker: true,
  2820. filter: true,
  2821. filterInit: <?php echo json_encode($filterInit); ?>,
  2822. forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
  2823. debug: false,
  2824. height: 400,
  2825. sorting: true,
  2826. paging: true,
  2827. pageSize: <?php echo $pageSize; ?>,
  2828. pageSizes: <?php echo json_encode($pageSizes); ?>,
  2829. tblFunctions: {
  2830. shortdesc: {
  2831. icon: 'align-left',
  2832. title: 'Long desc',
  2833. method: 'longTextChanged'
  2834. },
  2835. <?php if ($hasGeomFlds) : ?>
  2836. mapeditor: {
  2837. icon: 'map-marker',
  2838. title: 'Mapa',
  2839. method: 'mapEditorChanged'
  2840. },
  2841. <?php endif; ?>
  2842. create: {
  2843. href: '#CREATE',
  2844. icon: 'plus',
  2845. title: 'Dodaj nowy rekord'
  2846. },
  2847. refresh: {
  2848. icon: 'refresh',
  2849. title: 'Odśwież dane',
  2850. method: 'refresh'
  2851. }
  2852. },
  2853. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  2854. exportFields: <?php echo json_encode($exportFields); ?>,
  2855. specialFilterFunctions: <?php
  2856. $fltrs = $this->_acl->getSpecialFilters();
  2857. if (!empty($fltrs)) {
  2858. echo json_encode($fltrs);
  2859. } else {
  2860. echo 'false';
  2861. }
  2862. echo ',';
  2863. ?>
  2864. router: function() {
  2865. var routes = {
  2866. EDIT: function(args) {
  2867. var recordID = args;
  2868. if (typeof args == 'object') {
  2869. recordID = args.shift();
  2870. recordID = parseInt(recordID);
  2871. }
  2872. if (typeof recordID !== 'number' || recordID <= 0) {
  2873. // TODO: msg
  2874. return false;
  2875. }
  2876. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2877. cont.hide();
  2878. // remove previous task content
  2879. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2880. taskCnt.parent().remove();
  2881. taskCnt.remove();
  2882. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2883. jQuery('<ul class="breadcrumb">' +
  2884. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2885. '<li class="active">Edytuj rekord</li>' +
  2886. '</ul>').appendTo(taskCont);
  2887. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2888. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2889. jQuery.ajax({
  2890. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
  2891. type: 'GET',
  2892. dataType: 'text',
  2893. data: '',
  2894. async: true,
  2895. success: function(data) {
  2896. taskCnt.removeClass('AjaxTable-loading');
  2897. jQuery(data).appendTo(taskCnt);
  2898. initDateTimePicker(taskCnt);
  2899. },
  2900. error: function(err) {
  2901. taskCnt.removeClass('AjaxTable-loading');
  2902. //console.log('request error: {0}'.f(err));
  2903. }
  2904. });
  2905. //return false;
  2906. },
  2907. HIST: function(args) {
  2908. var recordID = args;
  2909. if (typeof args == 'object') {
  2910. recordID = args.shift();
  2911. recordID = parseInt(recordID);
  2912. }
  2913. if (typeof recordID !== 'number' || recordID <= 0) {
  2914. // TODO: msg
  2915. return false;
  2916. }
  2917. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2918. cont.hide();
  2919. // remove previous task content
  2920. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2921. taskCnt.parent().remove();
  2922. taskCnt.remove();
  2923. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2924. jQuery('<ul class="breadcrumb">' +
  2925. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2926. '<li class="active">Historia rekordu</li>' +
  2927. '</ul>').appendTo(taskCont);
  2928. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2929. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2930. jQuery.ajax({
  2931. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
  2932. type: 'GET',
  2933. dataType: 'text',
  2934. data: '',
  2935. async: true,
  2936. success: function(data) {
  2937. taskCnt.removeClass('AjaxTable-loading');
  2938. //console.log('request finished L.<?php echo __LINE__; ?>');
  2939. jQuery(data).appendTo(taskCnt);
  2940. },
  2941. error: function(err) {
  2942. taskCnt.removeClass('AjaxTable-loading');
  2943. //console.log('request error: {0}'.f(err));
  2944. }
  2945. });
  2946. //return false;
  2947. },
  2948. FILES: function tableAjaxFiles(args) {
  2949. var recordID = args;
  2950. if (typeof args == 'object') {
  2951. recordID = args.shift();
  2952. recordID = parseInt(recordID);
  2953. }
  2954. if (typeof recordID !== 'number' || recordID <= 0) {
  2955. // TODO: msg
  2956. return false;
  2957. }
  2958. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2959. cont.hide();
  2960. // remove previous task content
  2961. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2962. taskCnt.parent().remove();
  2963. taskCnt.remove();
  2964. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2965. jQuery('<ul class="breadcrumb">' +
  2966. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2967. '<li class="active">Pliki</li>' +
  2968. '</ul>').appendTo(taskCont);
  2969. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  2970. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2971. jQuery.ajax({
  2972. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  2973. type: 'GET',
  2974. dataType: 'text',
  2975. data: '',
  2976. async: true,
  2977. success: function(data) {
  2978. taskCnt.removeClass('AjaxTable-loading');
  2979. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  2980. jQuery(data).appendTo(taskCnt);
  2981. },
  2982. error: function(jqXHR, textStatus, errorThrown) {
  2983. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  2984. taskCnt.removeClass('AjaxTable-loading');
  2985. var txt = jqXHR.responseText || 'Error';
  2986. if (jqXHR.status == 404) {
  2987. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2988. } else {
  2989. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2990. }
  2991. }
  2992. });
  2993. //return false;
  2994. },
  2995. CREATE: function tableAjaxCreate() {
  2996. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2997. cont.hide();
  2998. // remove previous task content
  2999. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3000. taskCnt.parent().remove();
  3001. taskCnt.remove();
  3002. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3003. jQuery('<ul class="breadcrumb">' +
  3004. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3005. '<li class="active">Dodaj nowy rekord</li>' +
  3006. '</ul>').appendTo(taskCont);
  3007. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3008. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3009. var reqData = {};
  3010. var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
  3011. if (forceFilterInit) {
  3012. $.map(forceFilterInit, function(fltrProps, fltr) {
  3013. reqData['ff_' + fltr] = fltrProps;
  3014. });
  3015. }
  3016. jQuery.ajax({
  3017. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
  3018. type: 'GET',
  3019. dataType: 'text',
  3020. data: reqData,
  3021. async: true,
  3022. success: function(data) {
  3023. taskCnt.removeClass('AjaxTable-loading');
  3024. //console.log('request finished L.<?php echo __LINE__; ?>');
  3025. jQuery(data).appendTo(taskCnt);
  3026. initDateTimePicker(taskCnt);
  3027. },
  3028. error: function(err) {
  3029. taskCnt.removeClass('AjaxTable-loading');
  3030. //console.log('request error: {0}'.f(err));
  3031. }
  3032. });
  3033. //return false;
  3034. }
  3035. };
  3036. var routePath = location.hash;
  3037. //console.log('location.hash: ' + routePath);
  3038. if (location.hash == '' || location.hash == '#') {
  3039. return false;
  3040. }
  3041. if (routePath.charAt(0) == '#') {
  3042. routePath = routePath.substr(1);
  3043. }
  3044. //console.log('routePath: ' + routePath);
  3045. var parts = routePath.split('/');
  3046. var task = parts.shift();
  3047. //console.log('task(' + task + ') parts:');
  3048. //console.log(parts);
  3049. if (task in routes && typeof routes[task] == 'function') {
  3050. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3051. if (con) {
  3052. var tblAjax = con.data('TableAjax');
  3053. if (tblAjax) {
  3054. tblAjax.popoverCellRemove();
  3055. }
  3056. }
  3057. routes[task](parts);
  3058. } else {
  3059. return false;
  3060. }
  3061. },
  3062. filtersClean: true,
  3063. longDesc: true
  3064. });
  3065. });
  3066. function tableAjaxBackToTable() {
  3067. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3068. cont.show();
  3069. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  3070. taskCont.remove();
  3071. // reload first page
  3072. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3073. con.TableAjaxLoadPage();// TODO: load current page
  3074. }
  3075. function tableAjaxCopy(args) {
  3076. var recordID = args;
  3077. if (typeof args == 'object') {
  3078. recordID = args.shift();
  3079. recordID = parseInt(recordID);
  3080. }
  3081. if (typeof recordID !== 'number' || recordID <= 0) {
  3082. // TODO: msg
  3083. return false;
  3084. }
  3085. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  3086. return false;
  3087. }
  3088. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3089. function notifyAjaxCallback(data) {
  3090. var notify = {};
  3091. notify.type = (data && data.type)? data.type : '';
  3092. notify.msg = (data && data.msg)? data.msg : '';
  3093. switch (notify.type) {
  3094. case 'success':
  3095. if (!notify.msg) notify.msg = 'OK';
  3096. break;
  3097. case 'info':
  3098. if (!notify.msg) notify.msg = '';
  3099. break;
  3100. case 'error':
  3101. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3102. break;
  3103. case 'warning':
  3104. notify.type = 'warn';
  3105. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3106. break;
  3107. default:
  3108. notify.msg = 'Nieznany błąd';
  3109. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3110. notify.type = '';
  3111. }
  3112. jQuery.notify(notify.msg, notify.type);
  3113. }
  3114. var reqData = {};
  3115. jQuery.ajax({
  3116. data: reqData,
  3117. dataType: 'json',
  3118. type: "GET",
  3119. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  3120. })
  3121. .done(function(data, textStatus, jqXHR){
  3122. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3123. con.TableAjaxRefresh();
  3124. notifyAjaxCallback(data);
  3125. })
  3126. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3127. if (jqXHR.responseJSON) {
  3128. notifyAjaxCallback(jqXHR.responseJSON);
  3129. }
  3130. else {
  3131. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3132. if (jqXHR.status == 404) {
  3133. jQuery.notify(jqXHR.responseText, 'error');
  3134. } else {
  3135. jQuery.notify(jqXHR.responseText, 'warn');
  3136. }
  3137. }
  3138. });
  3139. return false;
  3140. }
  3141. function hidePopover() {
  3142. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3143. if (con) {
  3144. var tblAjax = con.data('TableAjax');
  3145. if (tblAjax) {
  3146. tblAjax.popoverCellRemove();
  3147. }
  3148. }
  3149. return false;
  3150. }
  3151. function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
  3152. var $n = jQuery(n);
  3153. var $ul = $n.next();
  3154. if ($n.data('fetched')) return false;
  3155. function parseProcesInitData(pInitData) {
  3156. var procesInitMapHtml = '';
  3157. if (!pInitData) {
  3158. return '<li><a href="#">' + "Brak danych" + '</a></li>';
  3159. } else {
  3160. function _viewProcesInitListItem(pInitId, gotoIds, pInitList) {
  3161. var label = pInitList[pInitId];
  3162. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + pInitId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  3163. var out = '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + pInitId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + pInitId + "} " + label + '">';
  3164. out += ' <i class="glyphicon glyphicon-info-sign"';
  3165. out += ' onclick="' + jsInfo + '"';
  3166. out += ' style="color:#aaa;"';
  3167. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3168. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3169. out += " {" + pInitId + "} " + label;
  3170. out += '</a>';
  3171. return out;
  3172. }
  3173. function _viewProcesGotoAndRetListItem(gotoId, pInitList) {
  3174. var label = pInitList[gotoId];
  3175. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  3176. var out = '';
  3177. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoId + "} " + label + '">';
  3178. out += ' <span style="padding:10px;"></span>';
  3179. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3180. out += ' <i class="glyphicon glyphicon-info-sign"';
  3181. out += ' onclick="' + jsInfo + '"';
  3182. out += ' style="color:#aaa;"';
  3183. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3184. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3185. out += " {" + gotoId + "} " + label;
  3186. out += '</a>';
  3187. return out;
  3188. }
  3189. function _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitList) {
  3190. var label = pInitList[gotoLvl2Id];
  3191. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoLvl2Id + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  3192. var out = '';
  3193. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoLvl2Id + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoLvl2Id + "} " + label + '">';
  3194. out += ' <span style="padding:20px;"></span>';
  3195. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3196. out += ' <i class="glyphicon glyphicon-info-sign"';
  3197. out += ' onclick="' + jsInfo + '"';
  3198. out += ' style="color:#aaa;"';
  3199. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3200. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3201. out += " {" + gotoLvl2Id + "} " + label;
  3202. out += '</a>';
  3203. return out;
  3204. }
  3205. var sel = '',
  3206. liStyle = "white-space:nowrap; overflow:hidden; max-width:500px; /* text-overflow:ellipsis; */";
  3207. $.map(pInitData.mapTree, function(gotoIds, vInitId) {
  3208. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3209. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3210. procesInitMapHtml += _viewProcesInitListItem(vInitId, gotoIds, pInitData.pInitList);
  3211. procesInitMapHtml += '</li>' + "\n";
  3212. $.map(gotoIds, function(gotoLvl2Ids, gotoId) {
  3213. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3214. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3215. procesInitMapHtml += _viewProcesGotoAndRetListItem(gotoId, pInitData.pInitList);
  3216. procesInitMapHtml += '</li>' + "\n";
  3217. $.map(gotoLvl2Ids, function(vBool, gotoLvl2Id) {
  3218. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3219. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3220. procesInitMapHtml += _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitData.pInitList);
  3221. procesInitMapHtml += '</li>' + "\n";
  3222. });
  3223. });
  3224. });
  3225. }
  3226. return procesInitMapHtml;
  3227. }
  3228. jQuery.ajax({
  3229. data: null,
  3230. dataType: 'json',
  3231. type: "GET",
  3232. async: true,
  3233. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PROCES_INIT_FILTR',
  3234. })
  3235. .always(function(data, textStatus, jqXHR) {
  3236. var type = data.type || null,
  3237. msg = data.msg || "Error",
  3238. pInitData = data.pInitData || null;
  3239. if (type) {
  3240. if ('success' == type) {
  3241. $ul.html(parseProcesInitData(pInitData));
  3242. } else if ('error' == type) {
  3243. $ul.html('<li><a href="#">' + msg + '</a></li>');
  3244. } else {
  3245. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3246. }
  3247. } else {
  3248. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3249. }
  3250. $n.data('fetched', true);
  3251. });
  3252. return false;
  3253. }
  3254. </script>
  3255. <?php
  3256. $out = ob_get_contents();
  3257. ob_end_clean();
  3258. return $out;
  3259. }
  3260. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  3261. $vLabel = $pInitList[$vInitId];
  3262. $kId = $vInitId;
  3263. ?>
  3264. <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}"); ?>">
  3265. <i class="glyphicon glyphicon-info-sign"
  3266. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3267. style="color:#aaa;"
  3268. onmouseover="this.style.color='#337AB7'"
  3269. onmouseout="this.style.color='#aaa'"></i>
  3270. <?php echo "{{$kId}} {$vLabel}"; ?>
  3271. </a>
  3272. <?php
  3273. }
  3274. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  3275. $vLabel = $pInitList[$vGotoId];
  3276. $kId = $vGotoId;
  3277. // TODO:?: prevent to execute procedure
  3278. ?>
  3279. <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}"); ?>">
  3280. <span style="padding:10px;"></span>
  3281. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3282. <i class="glyphicon glyphicon-info-sign"
  3283. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3284. style="color:#aaa;"
  3285. onmouseover="this.style.color='#337AB7'"
  3286. onmouseout="this.style.color='#aaa'"></i>
  3287. <?php echo "{{$kId}} {$vLabel}"; ?>
  3288. </a>
  3289. <?php
  3290. }
  3291. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  3292. $vLabel = $pInitList[$vGotoLvl2Id];
  3293. $kId = $vGotoLvl2Id;
  3294. // TODO:?: prevent to execute procedure
  3295. ?>
  3296. <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}"); ?>">
  3297. <span style="padding:20px;"></span>
  3298. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3299. <i class="glyphicon glyphicon-info-sign"
  3300. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3301. style="color:#aaa;"
  3302. onmouseover="this.style.color='#337AB7'"
  3303. onmouseout="this.style.color='#aaa'"></i>
  3304. <?php echo "{{$kId}} {$vLabel}"; ?>
  3305. </a>
  3306. <?php
  3307. }
  3308. public function hasAdditionalLayers() {
  3309. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  3310. return !empty($layers);
  3311. }
  3312. public function ajaxTask($task) {
  3313. switch ($task) {
  3314. case 'EDIT': {
  3315. $id = V::get('ID', 0, $_REQUEST, 'int');
  3316. if ($id > 0) {
  3317. $this->sendAjaxEdit($id, $_REQUEST);
  3318. } else {
  3319. echo '404';
  3320. }
  3321. break;
  3322. }
  3323. case 'EDIT_SAVE': {
  3324. $this->sendAjaxResponseJson('ajaxEditSave', $_REQUEST);
  3325. break;
  3326. }
  3327. case 'EDIT_INLINE': {
  3328. $id = V::get('ID', 0, $_REQUEST, 'int');
  3329. $col = V::get('col', '', $_REQUEST);
  3330. if ($id > 0 && !empty($col)) {
  3331. $this->sendAjaxEditInline($id, $col, $_REQUEST);
  3332. } else {
  3333. echo '404';
  3334. }
  3335. break;
  3336. }
  3337. case 'EDIT_INLINE_SAVE': {
  3338. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  3339. break;
  3340. }
  3341. case 'COPY': {
  3342. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  3343. break;
  3344. }
  3345. case 'CREATE': {
  3346. $this->sendAjaxCreate($_REQUEST);
  3347. break;
  3348. }
  3349. case 'CREATE_SAVE': {
  3350. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  3351. break;
  3352. }
  3353. case 'HIST': {
  3354. $id = V::get('ID', 0, $_REQUEST, 'int');
  3355. if ($id > 0) {
  3356. $this->sendAjaxHistory($id, $_REQUEST);
  3357. } else {
  3358. echo '404';
  3359. }
  3360. break;
  3361. }
  3362. case 'FILES': {
  3363. try {
  3364. $id = V::get('ID', 0, $_REQUEST, 'int');
  3365. if ($id <= 0) throw new HttpException("404", 404);
  3366. $this->sendAjaxFiles($id, $_REQUEST);
  3367. } catch (HttpException $e) {
  3368. Http::sendHeaderByCode($e->getCode());
  3369. echo $e->getMessage();
  3370. //SE_Layout::alert('danger', $e->getMessage());
  3371. } catch (Exception $e) {
  3372. echo '<div class="container">';
  3373. SE_Layout::alert('danger', $e->getMessage());
  3374. echo '</div>';
  3375. }
  3376. break;
  3377. }
  3378. case 'FILES_UPLOAD': {
  3379. $this->sendAjaxResponseJson('ajaxFileUpload', $_REQUEST);
  3380. break;
  3381. }
  3382. case 'FILES_LIST': {
  3383. $this->sendAjaxResponseJson('ajaxFileList', $_REQUEST);
  3384. break;
  3385. }
  3386. case 'FILE_REMOVE': {
  3387. $args = array();
  3388. $args['ID'] = V::get('ID', '', $_REQUEST);
  3389. $args['filename'] = V::get('filename', '', $_POST);
  3390. $this->sendAjaxResponseJson('ajaxFileRemove', $args);
  3391. break;
  3392. }
  3393. case 'filePermsRefresh': {
  3394. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  3395. break;
  3396. }
  3397. case 'FILES_CONN_TBL_LIST': {
  3398. $id = V::get('ID', 0, $_REQUEST, 'int');
  3399. if ($id > 0) {
  3400. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  3401. } else {
  3402. echo '404';
  3403. }
  3404. break;
  3405. }
  3406. case 'TYPESPECIAL': {
  3407. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  3408. if ($fldID > 0) {
  3409. $this->sendTypeSpecial($fldID, $_REQUEST);
  3410. } else {
  3411. echo '404';
  3412. }
  3413. break;
  3414. }
  3415. case 'TYPESPECIALL_CELL': {
  3416. $id = V::get('ID', 0, $_REQUEST, 'int');
  3417. $col = V::get('col', '', $_REQUEST);
  3418. if ($id > 0 && !empty($col)) {
  3419. $this->sendTypeSpecialCell($id, $col, $_REQUEST);
  3420. } else {
  3421. echo '404';
  3422. }
  3423. break;
  3424. }
  3425. case 'MORE_FUNCTIONS_CELL': {
  3426. $this->sendAjaxResponseJson('ajaxMoreFunctionsCell', $_REQUEST);
  3427. break;
  3428. }
  3429. case 'HIDDEN_COLS_SAVE': {
  3430. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  3431. break;
  3432. }
  3433. case 'PAGE_SIZE_SAVE': {
  3434. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  3435. break;
  3436. }
  3437. case 'THE_GEOM_SAVE': {
  3438. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  3439. break;
  3440. }
  3441. case 'THE_GEOM_REMOVE': {
  3442. $this->sendAjaxResponseJson('ajaxTheGeomRemove', $_REQUEST);
  3443. break;
  3444. }
  3445. case 'PROCES_INIT_FILTR': {
  3446. $this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
  3447. break;
  3448. }
  3449. default:
  3450. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  3451. }
  3452. }
  3453. /**
  3454. * ajax url: &_task=EDIT_INLINE
  3455. * @param $rowID - $_GET['ID']
  3456. * @param $fieldName - $_GET['col']
  3457. */
  3458. private function sendAjaxEditInline($rowID, $fieldName, $args) {
  3459. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3460. header("Content-type: text/plain");
  3461. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3462. if (!$fieldID) {
  3463. echo "404: No field by name ({$fieldName})";
  3464. exit;
  3465. }
  3466. if ($DBG) echo "fieldID: {$fieldID}\n";
  3467. $row = $this->_acl->getItem($rowID);
  3468. if (!$row) {
  3469. echo "404: No item ID({$rowID})";
  3470. exit;
  3471. }
  3472. if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
  3473. if ($DBG) echo " R not allowed\n";
  3474. } else {
  3475. if ($DBG) echo " R allowed\n";
  3476. }
  3477. if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
  3478. if ($DBG) echo " W not allowed\n";
  3479. } else {
  3480. if ($DBG) echo " W allowed\n";
  3481. }
  3482. $fieldVal = '';
  3483. if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
  3484. $fieldVal = V::get($fieldName, $fieldVal, $row);
  3485. } else {
  3486. $fieldVal = '*****';
  3487. }
  3488. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  3489. $vCol = $this->_acl->getField($fieldID);
  3490. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3491. $tsValues = array();
  3492. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  3493. if ($typeSpecial) {
  3494. 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>';}
  3495. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  3496. 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>';}
  3497. if (!empty($specialValues)) {
  3498. $tsValues[$row->ID] = implode('<br>', $specialValues);
  3499. }
  3500. }
  3501. ?>
  3502. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  3503. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  3504. <?php if (!empty($vCol['opis'])) : ?>
  3505. <em><?php echo $vCol['opis']; ?></em>
  3506. <?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
  3507. <?php endif; ?>
  3508. </label>
  3509. <?php
  3510. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  3511. if (!empty($tsValues[$row->ID])) {
  3512. $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  3513. }
  3514. $vDefault = $this->_acl->getColDefault($fieldName);
  3515. if (!empty($vDefault)) {
  3516. $fieldParams['default'] = $vDefault;
  3517. }
  3518. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  3519. if ($typeSpecial
  3520. || $this->_acl->isDateField($fieldName)
  3521. || $this->_acl->isDateTimeField($fieldName)
  3522. ) {
  3523. echo '<p style="padding:120px 0;"></p>';
  3524. }
  3525. exit;
  3526. }
  3527. private function ajaxEditInlineSave($args) {
  3528. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3529. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3530. $fieldName = V::get('col', '', $_REQUEST);
  3531. if (empty($primaryKey) || empty($fieldName)) {
  3532. throw new HttpException("Wrong param id or col!", 400);
  3533. }
  3534. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3535. if (!$fieldID) {
  3536. throw new HttpException("Field not exists!", 404);
  3537. }
  3538. $item = $this->_acl->getItem($primaryKey);
  3539. if (!$item) {
  3540. throw new HttpException("Item not exists!", 404);
  3541. }
  3542. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3543. if (!isset($itemFromUser[$fieldName])) {
  3544. throw new HttpException("Field not set!", 400);
  3545. }
  3546. $itemPatch = array();
  3547. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  3548. $itemPatch[$primaryKeyField] = $primaryKey;
  3549. $response = new stdClass();
  3550. try {
  3551. $affected = $this->_acl->updateItem($itemPatch);
  3552. if ($affected > 0) {
  3553. $response->type = 'success';
  3554. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3555. } else if ($affected == 0) {
  3556. $response->type = 'info';
  3557. $response->msg = "Nie wprowadzono żadnych zmian";
  3558. }
  3559. $response->record = $this->_acl->getItem($primaryKey);
  3560. }
  3561. catch (Exception $e) {
  3562. $response->type = 'error';
  3563. $response->msg = $e->getMessage();
  3564. }
  3565. return $response;
  3566. }
  3567. private function sendAjaxEdit($id, $args) {
  3568. header("Content-type: text/plain");
  3569. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3570. $cols = array();
  3571. $record = $this->_acl->getItem($id);
  3572. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  3573. echo '<div class="alert alert-danger">';
  3574. echo "Brak dostępu do rekordu";// TODO: more info - reason
  3575. echo '</div>';
  3576. return;
  3577. }
  3578. $fieldsList = $this->_acl->getFields();
  3579. foreach ($fieldsList as $kID => $vCol) {
  3580. if ($vCol['name'] == 'ID') {
  3581. unset($fieldsList[$kID]);
  3582. continue;
  3583. }
  3584. $cols[$kID] = '';
  3585. if ($this->_acl->isAllowed($kID, 'R', $record)) {
  3586. $cols[$kID] = V::get($vCol['name'], '', $record);
  3587. } else {
  3588. $cols[$kID] = '*****';
  3589. }
  3590. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  3591. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
  3592. }
  3593. $tsValues = array();
  3594. 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>';}
  3595. if (!empty($fieldsList)) {
  3596. foreach ($fieldsList as $vColID => $vCol) {
  3597. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  3598. if ($typeSpecial) {
  3599. 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>';}
  3600. $colValue = V::get($vCol['name'], '', $record);
  3601. 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>';}
  3602. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
  3603. 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>';}
  3604. if (!empty($specialValues)) {
  3605. $tsValues[$vColID] = implode('<br>', $specialValues);
  3606. }
  3607. }
  3608. }
  3609. }
  3610. 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>';}
  3611. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);
  3612. ?>
  3613. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  3614. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
  3615. <fieldset>
  3616. <legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
  3617. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3618. <?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
  3619. <div class="form-group">
  3620. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3621. <i class="glyphicon glyphicon-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>
  3622. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3623. </label>
  3624. <div class="col-xs-12 col-sm-9 col-md-10">
  3625. <?php
  3626. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3627. if (!empty($tsValues[$kID])) {
  3628. $fieldParams['typespecialValue'] = $tsValues[$kID];
  3629. }
  3630. echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  3631. ?>
  3632. </div>
  3633. </div>
  3634. <?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
  3635. <div class="form-group">
  3636. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3637. <i class="glyphicon glyphicon-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>
  3638. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3639. </label>
  3640. <div class="col-xs-12 col-sm-9 col-md-10">
  3641. <p style="margin-top:5px;">
  3642. <?php
  3643. //echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  3644. if (!empty($tsValues[$kID])) {
  3645. echo $tsValues[$kID];
  3646. } else if (!empty($record->{$vCol['name']})) {
  3647. echo $record->{$vCol['name']};
  3648. }
  3649. ?>
  3650. </p>
  3651. </div>
  3652. </div>
  3653. <?php endif; ?>
  3654. <?php endforeach; ?>
  3655. <div class="form-group">
  3656. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3657. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
  3658. </div>
  3659. </div>
  3660. </fieldset>
  3661. </form>
  3662. <p style="padding:100px 0;"></p>
  3663. </div>
  3664. <script>
  3665. jQuery(document).ready(function(){
  3666. jQuery('textarea').autosize();
  3667. jQuery('.frm-help').popover({trigger:'hover'});
  3668. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3669. var data = jQuery(this).serialize();
  3670. // TODO: change Edit btn to return to edit record with fields -> show form
  3671. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  3672. //taskCont.empty();
  3673. taskCont.children().fadeOut('slow');
  3674. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  3675. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  3676. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
  3677. function notifyAjaxCallback(data) {
  3678. var notify = {}, outMsg = '';
  3679. notify.type = (data && data.type)? data.type : '';
  3680. notify.msg = (data && data.msg)? data.msg : '';
  3681. switch (notify.type) {
  3682. case 'success':
  3683. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  3684. break;
  3685. case 'info':
  3686. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  3687. break;
  3688. case 'error':
  3689. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3690. break;
  3691. case 'warning':
  3692. notify.type = 'warn';
  3693. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3694. break;
  3695. default:
  3696. notify.msg = 'Nieznany błąd';
  3697. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3698. notify.type = '';
  3699. }
  3700. jQuery.notify(notify.msg, notify.type);
  3701. var alertType = ('error' == notify.type) ? 'danger' : notify.type;
  3702. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  3703. return outMsg;
  3704. }
  3705. $.ajax({
  3706. data: data,
  3707. dataType: 'json',
  3708. type: "POST",
  3709. 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; ?>',
  3710. })
  3711. .done(function(data, textStatus, jqXHR){
  3712. var outMsg = notifyAjaxCallback(data);
  3713. alertCntWrap.removeClass('AjaxTable-loading');
  3714. //console.log('request finished L.<?php echo __LINE__; ?>');
  3715. alertCnt.empty();
  3716. var out = '';
  3717. out += outMsg;
  3718. out += '<div class="breadcrumb">' +
  3719. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  3720. ' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
  3721. '</div>';
  3722. jQuery(out).appendTo(alertCnt);
  3723. })
  3724. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3725. if (jqXHR.responseJSON) {
  3726. notifyAjaxCallback(jqXHR.responseJSON);
  3727. }
  3728. else {
  3729. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3730. if (jqXHR.status == 404) {
  3731. jQuery.notify(jqXHR.responseText, 'error');
  3732. } else {
  3733. jQuery.notify(jqXHR.responseText, 'warn');
  3734. }
  3735. }
  3736. alertCntWrap.removeClass('AjaxTable-loading');
  3737. //console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
  3738. alertCnt.empty();
  3739. jQuery(errorTxt).appendTo(alertCnt);
  3740. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  3741. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  3742. 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);
  3743. backToEditBtn.on('click', function(){
  3744. alertCnt.remove();
  3745. taskCont.children().fadeIn('slow');
  3746. return false;
  3747. });
  3748. });
  3749. return false;
  3750. });
  3751. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  3752. var input, btn, btnIco;
  3753. input = jQuery(e.target);
  3754. btn = input.next('.button-appendBack');
  3755. btnIco = btn.find('.glyphicon');
  3756. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3757. if (btn.attr('title') != input.val()) {
  3758. btnIco.show();
  3759. } else {
  3760. btnIco.hide();
  3761. }
  3762. });
  3763. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  3764. var input, btn, btnIco;
  3765. btn = jQuery(this);
  3766. btnIco = btn.find('.glyphicon');
  3767. input = btn.prev();
  3768. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3769. if (input.is('input')) {
  3770. if (btn.attr('title') != input.val()) {
  3771. input.val(btn.attr('title'));
  3772. btnIco.hide();
  3773. }
  3774. }
  3775. });
  3776. });
  3777. </script>
  3778. <?php
  3779. exit;
  3780. }
  3781. private function ajaxEditSave($args) {
  3782. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3783. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3784. if (empty($primaryKey)) {
  3785. throw new HttpException("Wrong param id!", 400);
  3786. }
  3787. $item = $this->_acl->getItem($primaryKey);
  3788. if (!$item) {
  3789. throw new HttpException("Item not exists!", 404);
  3790. }
  3791. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3792. $response = new stdClass();
  3793. try {
  3794. $itemFromUser[$primaryKeyField] = $primaryKey;
  3795. $affected = $this->_acl->updateItem($itemFromUser);
  3796. if ($affected > 0) {
  3797. $response->type = 'success';
  3798. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3799. } else if ($affected == 0) {
  3800. $response->type = 'info';
  3801. $response->msg = "Nie wprowadzono żadnych zmian";
  3802. }
  3803. $response->record = $this->_acl->getItem($primaryKey);
  3804. }
  3805. catch (Exception $e) {
  3806. $response->type = 'error';
  3807. $response->msg = "Wystąpiły błędy!";
  3808. $response->msg .= $e->getMessage();
  3809. }
  3810. return $response;
  3811. }
  3812. private function sendAjaxCreate($args) {
  3813. header("Content-type: text/plain");
  3814. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3815. if (!$this->_acl->hasCreatePerms()) {
  3816. ?>
  3817. <div class="container">
  3818. <div class="alert alert-danger">
  3819. Brak uprawnień do utworzenia nowego rekordu.
  3820. </div>
  3821. </div>
  3822. <?php
  3823. return;
  3824. }
  3825. $cols = array();
  3826. $forceFilterInit = array();
  3827. $defaultAclGroup = User::getDefaultAclGroup();
  3828. if ($defaultAclGroup) {
  3829. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  3830. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  3831. }
  3832. foreach ($_GET as $k => $v) {
  3833. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  3834. $fldName = substr($k, 3);
  3835. $forceFilterInit[$fldName] = $v;
  3836. }
  3837. }
  3838. $fieldsList = $this->_acl->getFields();
  3839. foreach ($fieldsList as $kID => $vCol) {
  3840. $defaultValue = '';
  3841. if ($vCol['name'] == 'ID') {
  3842. unset($fieldsList[$kID]);
  3843. continue;
  3844. }
  3845. if (!empty($forceFilterInit[$vCol['name']])) {
  3846. $defaultValue = $forceFilterInit[$vCol['name']];
  3847. }
  3848. // TODO: read from session cache
  3849. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  3850. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3851. }
  3852. ?>
  3853. <div class="container AjaxFrmHorizontalEdit">
  3854. <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  3855. <fieldset>
  3856. <legend>Dodaj nowy rekord</legend>
  3857. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3858. <?php if ($this->_acl->isAllowed($kID, 'C')) : ?>
  3859. <div class="form-group">
  3860. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3861. <i class="glyphicon glyphicon-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>
  3862. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3863. </label>
  3864. <div class="col-xs-12 col-sm-9 col-md-10">
  3865. <?php
  3866. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3867. echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  3868. ?>
  3869. </div>
  3870. </div>
  3871. <?php endif; ?>
  3872. <?php endforeach; ?>
  3873. <div class="form-group">
  3874. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3875. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  3876. </div>
  3877. </div>
  3878. </fieldset>
  3879. </form>
  3880. </div>
  3881. <script>
  3882. jQuery(document).ready(function(){
  3883. jQuery('textarea').autosize();
  3884. jQuery('.frm-help').popover({trigger:'hover'});
  3885. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3886. var data = jQuery(this).serialize();
  3887. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  3888. taskCont = taskContLast.parent();
  3889. taskContLast.fadeOut('slow');
  3890. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3891. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);
  3892. function notifyAjaxCallback(data) {
  3893. var notify = {};
  3894. notify.type = (data && data.type)? data.type : '';
  3895. notify.msg = (data && data.msg)? data.msg : '';
  3896. switch (notify.type) {
  3897. case 'success':
  3898. if (!notify.msg) notify.msg = 'OK';
  3899. break;
  3900. case 'info':
  3901. if (!notify.msg) notify.msg = '';
  3902. break;
  3903. case 'error':
  3904. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3905. break;
  3906. case 'warning':
  3907. notify.type = 'warn';
  3908. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3909. break;
  3910. default:
  3911. notify.msg = 'Nieznany błąd';
  3912. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3913. notify.type = '';
  3914. }
  3915. jQuery.notify(notify.msg, notify.type);
  3916. }
  3917. $.ajax({
  3918. data: data,
  3919. dataType: 'json',
  3920. type: "POST",
  3921. async: true,
  3922. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  3923. })
  3924. .always(function(dataOrJqXHR){
  3925. var data;
  3926. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  3927. if ('responseJSON' in dataOrJqXHR) {
  3928. data = dataOrJqXHR.responseJSON;
  3929. } else {
  3930. data = {};
  3931. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  3932. if (dataOrJqXHR.status == 404) {
  3933. data.type = 'error';
  3934. } else {
  3935. data.type = 'warning';
  3936. }
  3937. }
  3938. }
  3939. else {
  3940. data = dataOrJqXHR;
  3941. }
  3942. notifyAjaxCallback(data);
  3943. taskCnt.removeClass('AjaxTable-loading');
  3944. taskCnt.empty();
  3945. if (data.type == 'error' || data.type == 'warning') {
  3946. var out = '<div class="container">' +
  3947. '<div class="alert alert-danger">' +
  3948. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  3949. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  3950. '</div>';
  3951. out += '<div class="breadcrumb">' +
  3952. ' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do formularza i popraw dane</a></li>' +
  3953. '</div>' +
  3954. '</div>';
  3955. jQuery(out).appendTo(taskCnt);
  3956. var taskContLastNode = taskContLast
  3957. , taskCntNode = taskCnt;
  3958. taskCnt.find('.create-fix').click(function(){
  3959. taskCntNode.remove();
  3960. taskContLastNode.fadeIn('slow');
  3961. return false;
  3962. });
  3963. }
  3964. else if (data.type == 'success') {
  3965. var msg = '';
  3966. if (data.id && data.id > 0) {
  3967. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  3968. } else if (data.msg) {
  3969. msg = data.msg;
  3970. } else {
  3971. msg = 'OK';
  3972. }
  3973. var out = '<div class="container">';
  3974. out += '<div class="alert alert-success">' + msg + '</div>';
  3975. out += '<div class="breadcrumb">' +
  3976. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  3977. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  3978. ' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-plus"></i> Dodaj nowy rekord</a></li>' +
  3979. '</div>';
  3980. out += '</div>';
  3981. jQuery(out).appendTo(taskCnt);
  3982. }
  3983. });
  3984. return false;
  3985. });
  3986. });
  3987. </script>
  3988. <?php
  3989. exit;
  3990. }
  3991. private function ajaxCreateSave($args) {
  3992. $response = new stdClass();
  3993. $createdId = null;
  3994. try {
  3995. $item = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3996. $createdId = $this->_acl->addItem($item);
  3997. if ($createdId) {
  3998. $response->type = 'success';
  3999. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  4000. $response->id = $createdId;
  4001. $response->record = $this->_acl->getItem($createdId);
  4002. }
  4003. else {
  4004. $response->type = 'error';
  4005. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  4006. }
  4007. }
  4008. catch (Exception $e) {
  4009. $response->type = 'error';
  4010. $response->msg = "Wystąpiły błędy!";
  4011. $response->msg = $e->getMessage();
  4012. }
  4013. return $response;
  4014. }
  4015. private function ajaxCopy($args) {
  4016. $id = V::get('ID', 0, $_REQUEST, 'int');
  4017. if ($id <= 0) {
  4018. throw new HttpException("Wrong param ID!", 404);
  4019. }
  4020. $item = $this->_acl->getItem($id);
  4021. if (!$item) {
  4022. throw new HttpException("Item '{$id}' not exists!", 404);
  4023. }
  4024. $response = new stdClass();
  4025. $itemCopy = $this->_acl->createItemCopy($item);
  4026. $createdId = null;
  4027. try {
  4028. $createdId = $this->_acl->addItem($itemCopy);
  4029. if ($createdId) {
  4030. $response->type = 'success';
  4031. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  4032. $response->id = $createdId;
  4033. $response->record = $this->_acl->getItem($createdId);
  4034. }
  4035. else {
  4036. $response->type = 'error';
  4037. $response->msg = "Nie udało się skopiować rekordu!";
  4038. }
  4039. }
  4040. catch (Exception $e) {
  4041. $response->type = 'error';
  4042. $response->msg = "Wystąpiły błędy!";
  4043. $response->msg = $e->getMessage();
  4044. }
  4045. return $response;
  4046. }
  4047. private function sendAjaxHistory($id, $args) {
  4048. header("Content-type: text/plain");
  4049. $record = $this->_acl->getItem($id);
  4050. if (!$record) {
  4051. header('HTTP/1.0 404 Not Found');
  4052. echo "404: No item ID({$rowID})";
  4053. exit;
  4054. }
  4055. $visibleCols = $this->_acl->getRealFieldList();
  4056. $rowsHist = $this->_acl->getHistItems($id);
  4057. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);
  4058. $visibleColsWithIds = array();
  4059. $visibleColsLabels = array();
  4060. foreach ($visibleCols as $vColName) {
  4061. $fldId = $this->_acl->getFieldIdByName($vColName);
  4062. if ($fldId) {
  4063. $visibleColsWithIds[$fldId] = $vColName;
  4064. $label = $this->_acl->getFieldLabel($fldId);
  4065. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  4066. $visibleColsLabels[$fldId] = $label;
  4067. }
  4068. }
  4069. ?>
  4070. <fieldset>
  4071. <legend>Historia rekordu Nr <?php echo $id; ?>
  4072. <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
  4073. </legend>
  4074. </fieldset>
  4075. <?php if (empty($rowsHist)) : ?>
  4076. <div class="alert alert-info">
  4077. <h4>Brak danych</h4>
  4078. </div>
  4079. <?php else: ?>
  4080. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  4081. <thead>
  4082. <tr>
  4083. <th>Data</th>
  4084. <th>User</th>
  4085. <th>Zmiany</th>
  4086. </tr>
  4087. </thead>
  4088. <tbody>
  4089. <?php foreach ($rowsHist as $row) : ?>
  4090. <tr>
  4091. <td style="white-space:nowrap"><?php echo $row->_created; ?></td>
  4092. <td><?php echo $row->_author; ?></td>
  4093. <td>
  4094. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  4095. <?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
  4096. <?php if ($row->$colName == 'N/S;') continue; ?>
  4097. <p><em><?php echo $visibleColsLabels[$fldId]; ?></em>:
  4098. <?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  4099. <?php echo $row->$colName; ?>
  4100. <?php else : ?>
  4101. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  4102. <?php endif; ?>
  4103. </p>
  4104. <?php endforeach; ?>
  4105. </td>
  4106. </tr>
  4107. <?php endforeach; ?>
  4108. </tbody>
  4109. </table>
  4110. <div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
  4111. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  4112. <thead>
  4113. <tr>
  4114. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  4115. <th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
  4116. <?php endforeach; ?>
  4117. </tr>
  4118. </thead>
  4119. <tbody>
  4120. <?php foreach ($rowsHist as $row) : ?>
  4121. <tr>
  4122. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  4123. <td>
  4124. <?php if ($row->$colName == 'N/S;') : ?>
  4125. <em>N/S;</em>
  4126. <?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  4127. <?php echo $row->$colName; ?>
  4128. <?php else : ?>
  4129. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  4130. <?php endif; ?>
  4131. </td>
  4132. <?php endforeach; ?>
  4133. </tr>
  4134. <?php endforeach; ?>
  4135. </tbody>
  4136. </table>
  4137. </div>
  4138. <?php endif; ?>
  4139. <?php
  4140. exit;
  4141. }
  4142. public function ajaxFileUpload($args) {
  4143. $id = V::get('ID', 0, $args, 'int');
  4144. if ($id <= 0) throw new HttpException("404", 404);
  4145. $dbID = $this->_acl->getDB();
  4146. $db = DB::getDB($dbID);
  4147. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4148. $record = $this->_acl->getItem($id);
  4149. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4150. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4151. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  4152. $tblName = $this->_acl->getName();
  4153. $confTblName = "{$tblName}_COLUMN";
  4154. $folderConfAll = FoldersConfig::getRawData();
  4155. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4156. $folderConf = FoldersConfig::getAll($confTblName);
  4157. $uploader = new FileUploader($confTblName, $record);
  4158. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4159. $uploader->findFolder();
  4160. $errorMsg = '';
  4161. if (!empty($args['SCANS_COLUMN_ADD'])) {
  4162. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  4163. }
  4164. else {
  4165. $uploaded = $uploader->tryUploadAjax($errorMsg);
  4166. }
  4167. $retJson = new stdClass();
  4168. if (!$uploaded) throw new Exception($errorMsg);
  4169. $uploadedFileName = '';
  4170. $uploadedFile = $uploader->getLastUploadedFile();
  4171. if ($uploadedFile) {
  4172. $uploadedFileName = explode('/', $uploadedFile);
  4173. $uploadedFileName = end($uploadedFileName);
  4174. }
  4175. //echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  4176. $retJson->type = 'SUCCESS';
  4177. $retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
  4178. if (!empty($uploadedFileName)) {
  4179. $sqlObj = new stdClass();
  4180. $sqlObj->ID = $record->ID;
  4181. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  4182. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  4183. }
  4184. return $retJson;
  4185. }
  4186. public function ajaxFileRemove($args) {
  4187. $id = V::get('ID', 0, $args, 'int');
  4188. if ($id <= 0) throw new HttpException("404", 404);
  4189. $filename = V::get('filename', '', $args);
  4190. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  4191. $dbID = $this->_acl->getDB();
  4192. $db = DB::getDB($dbID);
  4193. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4194. $record = $this->_acl->getItem($id);
  4195. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4196. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4197. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  4198. $tblName = $this->_acl->getName();
  4199. $confTblName = "{$tblName}_COLUMN";
  4200. $folderConfAll = FoldersConfig::getRawData();
  4201. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4202. $folderConf = FoldersConfig::getAll($confTblName);
  4203. $uploader = new FileUploader($confTblName, $record);
  4204. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4205. $uploader->findFolder();
  4206. $errorMsg = '';
  4207. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  4208. if (!$removed) throw new Exception($errorMsg);
  4209. $retJson = new stdClass();
  4210. $retJson->type = 'SUCCESS';
  4211. $retJson->msg = 'Plik został poprawnie usunięty';
  4212. return $retJson;
  4213. }
  4214. public function ajaxFileList($args) {
  4215. $id = V::get('ID', 0, $args, 'int');
  4216. if ($id <= 0) throw new HttpException("404", 404);
  4217. $dbID = $this->_acl->getDB();
  4218. $db = DB::getDB($dbID);
  4219. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4220. $record = $this->_acl->getItem($id);
  4221. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4222. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4223. $tblName = $this->_acl->getName();
  4224. $confTblName = "{$tblName}_COLUMN";
  4225. $folderConfAll = FoldersConfig::getRawData();
  4226. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4227. $folderConf = FoldersConfig::getAll($confTblName);
  4228. $uploader = new FileUploader($confTblName, $record);
  4229. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4230. $uploader->findFolder();
  4231. $mainFolder = $uploader->getDestFolder();
  4232. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4233. $localPath = $uploader->getLocalPath();
  4234. $folderWeb = $uploader->getFolderWeb();
  4235. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4236. return $jsonFiles;
  4237. }
  4238. private function ajaxFilePermsRefresh($args) {
  4239. $id = V::get('ID', 0, $args, 'int');
  4240. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  4241. $dbID = $this->_acl->getDB();
  4242. $db = DB::getDB($dbID);
  4243. if (!$db) throw new HttpException("No DB", 406);
  4244. $record = $this->_acl->getItem($id);
  4245. if (!$record) throw new Exception("No item ID({$rowID})", 404);
  4246. $tblName = $this->_acl->getName();
  4247. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  4248. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  4249. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  4250. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  4251. $mainDB = DB::getDB();
  4252. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  4253. $sql = "insert into `_SYNC_FILE_PERMS` (
  4254. `ID_PROJECT`,
  4255. `A_SYNCHRONIZED`
  4256. )
  4257. values (
  4258. '{$record->ID}'
  4259. , 0
  4260. )
  4261. ON DUPLICATE KEY UPDATE
  4262. `A_SYNCHRONIZED`=0
  4263. ";
  4264. }
  4265. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  4266. $sql = "insert into `_SYNC_FILE_PERMS` (
  4267. `ID_PROJECT`,
  4268. `A_SYNCHRONIZED`
  4269. )
  4270. values (
  4271. '{$record->ID_PROJECT}'
  4272. , 0
  4273. )
  4274. ON DUPLICATE KEY UPDATE
  4275. `A_SYNCHRONIZED`=0
  4276. ";
  4277. }
  4278. else {
  4279. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  4280. `TBL_NAME`,
  4281. `TBL_ID`,
  4282. `L_APPOITMENT_USER`,
  4283. `A_ADM_COMPANY`,
  4284. `A_CLASSIFIED`,
  4285. `A_SYNCHRONIZED`
  4286. )
  4287. values (
  4288. '{$tblName}'
  4289. , '{$id}'
  4290. , '{$sql_L_APPOITMENT_USER}'
  4291. , '{$sql_A_ADM_COMPANY}'
  4292. , '{$sql_A_CLASSIFIED}'
  4293. , 0
  4294. )
  4295. ON DUPLICATE KEY UPDATE
  4296. `A_SYNCHRONIZED`=0
  4297. ";
  4298. }
  4299. $res = $mainDB->query($sql);
  4300. if ($mainDB->has_errors()) {
  4301. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  4302. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'</pre>';
  4303. throw new Exception("Nie udało się dodać zadania");
  4304. }
  4305. // TODO: this blocks browser ajax query
  4306. //$limit = 3;
  4307. //while ($limit--) {
  4308. // sleep(10);
  4309. // TODO: check if task is done
  4310. //}
  4311. $confTblName = "{$tblName}_COLUMN";
  4312. $folderConfAll = FoldersConfig::getRawData();
  4313. if (!FoldersConfig::hasConfig($confTblName)) {
  4314. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  4315. }
  4316. $folderConf = FoldersConfig::getAll($confTblName);
  4317. $uploader = new FileUploader($confTblName, $record);
  4318. if (!$uploader->setConfig($folderConf)) {
  4319. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4320. }
  4321. $uploader->findFolder();
  4322. $mainFolder = $uploader->getDestFolder();
  4323. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4324. $localPath = $uploader->getLocalPath();
  4325. $folderWeb = $uploader->getFolderWeb();
  4326. $jsonData = new stdClass();
  4327. $jsonData->msg = 'Zadanie dodane';
  4328. $jsonData->type = 'success';
  4329. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4330. return $jsonData;
  4331. }
  4332. private function sendAjaxFilesConnTblList($id, $args) {
  4333. header("Content-type: application/json");
  4334. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4335. $dbID = $this->_acl->getDB();
  4336. $db = DB::getDB($dbID);
  4337. if (!$db) {
  4338. header('HTTP/1.0 406 Not Acceptable');
  4339. echo 'No DB (' . $dbID . ')';
  4340. exit;
  4341. }
  4342. $record = $this->_acl->getItem($id);
  4343. if (!$record) {
  4344. header('HTTP/1.0 404 Not Found');
  4345. echo 'No item ID(' . $rowID . ')';
  4346. exit;
  4347. }
  4348. $connTblName = '';
  4349. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  4350. if ($connTblID <= 0) {
  4351. header('HTTP/1.0 406 Not Acceptable');
  4352. echo 'No conn Table ID';
  4353. exit;
  4354. }
  4355. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  4356. if (empty($connTblTypespecials)) {
  4357. header('HTTP/1.0 406 Not Acceptable');
  4358. echo "No conn Table (ID={$connTblID})";
  4359. exit;
  4360. }
  4361. 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>';}
  4362. if(1) {
  4363. header('HTTP/1.0 404 Not Found');
  4364. echo 'TODO: ...';
  4365. exit;
  4366. }
  4367. $tblName = $this->_acl->getName();
  4368. $confTblName = "{$tblName}_COLUMN";
  4369. $folderConfAll = FoldersConfig::getRawData();
  4370. if (!FoldersConfig::hasConfig($confTblName)) {
  4371. header('HTTP/1.0 404 Not Found');
  4372. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4373. exit;
  4374. }
  4375. $folderConf = FoldersConfig::getAll($confTblName);
  4376. $uploader = new FileUploader($confTblName, $record);
  4377. if (!$uploader->setConfig($folderConf)) {
  4378. header('HTTP/1.0 404 Not Found');
  4379. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4380. exit;
  4381. }
  4382. $uploader->findFolder();
  4383. $mainFolder = $uploader->getDestFolder();
  4384. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4385. $localPath = $uploader->getLocalPath();
  4386. $folderWeb = $uploader->getFolderWeb();
  4387. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4388. echo json_encode($jsonFiles);
  4389. exit;
  4390. }
  4391. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  4392. $jsonFiles = array();
  4393. if (!is_array($files) || empty($files)) {
  4394. return $jsonFiles;
  4395. }
  4396. sort($files);
  4397. foreach ($files as $vFilePath) {
  4398. $file = new stdClass();
  4399. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  4400. //$file->name = explode('/', $vFilePath);
  4401. //$file->name = end($file->name);
  4402. $file->size = filesize($vFilePath);
  4403. $file->sizeStr = round($file->size, 2) . "B";
  4404. if ($file->size > 1024 * 1024) {
  4405. $file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
  4406. } else if ($file->size > 1024) {
  4407. $file->sizeStr = round(($file->size / 1024), 2) . "K";
  4408. }
  4409. $file->type = '';
  4410. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  4411. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  4412. $jsonFiles[] = $file;
  4413. }
  4414. return $jsonFiles;
  4415. }
  4416. private function getConnectedTables() {
  4417. $connTbls = array();
  4418. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  4419. $fields = $this->_acl->getVisibleFieldList();
  4420. if (!empty($fields)) {
  4421. foreach ($fields as $vColID => $vCol) {
  4422. $typeSpecial = Typespecial::getInstance($vColID);
  4423. if ($typeSpecial) {
  4424. $tsConnTbls = $typeSpecial->getTblAliasList();
  4425. if (!empty($tsConnTbls)) {
  4426. foreach ($tsConnTbls as $kID => $vName) {
  4427. $connTbls[$kID] = $vName;
  4428. }
  4429. }
  4430. }
  4431. }
  4432. }
  4433. return $connTbls;
  4434. }
  4435. private function getConnectedTblTypespecials($connTblID) {
  4436. $connTblTypespecials = array();
  4437. $fields = $this->_acl->getVisibleFieldList();
  4438. if (!empty($fields)) {
  4439. foreach ($fields as $vColID => $vCol) {
  4440. $typeSpecial = Typespecial::getInstance($vColID);
  4441. if ($typeSpecial) {
  4442. $tsConnTbls = $typeSpecial->getTblAliasList();
  4443. if (array_key_exists($connTblID, $tsConnTbls)) {
  4444. $connTblTypespecials[] = $typeSpecial;
  4445. }
  4446. }
  4447. }
  4448. }
  4449. return $connTblTypespecials;
  4450. }
  4451. private function sendAjaxFiles($id, $args) {
  4452. header("Content-type: text/plain");
  4453. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4454. $dbID = $this->_acl->getDB();
  4455. $db = DB::getDB($dbID);
  4456. if (!$db) throw new HttpException("", 406);
  4457. $record = $this->_acl->getItem($id);
  4458. if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
  4459. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4460. $tblName = $this->_acl->getName();
  4461. $confTblName = "{$tblName}_COLUMN";
  4462. $folderConfAll = FoldersConfig::getRawData();
  4463. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
  4464. $folderConf = FoldersConfig::getAll($confTblName);
  4465. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  4466. $uploader = new FileUploader($confTblName, $record);
  4467. $errMsg = '';
  4468. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})" . '<br>' . "\n" . $errMsg, 404);
  4469. $uploader->findFolder();
  4470. 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>'; }
  4471. $mainFolder = $uploader->getDestFolder();
  4472. 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>'; }
  4473. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4474. 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>'; }
  4475. $sharePoint = V::get('share_point', null, $folderConf);
  4476. if ($sharePoint) {
  4477. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  4478. }
  4479. $localPath = $uploader->getLocalPath();
  4480. $folderWeb = $uploader->getFolderWeb();
  4481. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4482. 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>'; }
  4483. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  4484. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  4485. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  4486. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  4487. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  4488. sort($skanyFiles);
  4489. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  4490. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
  4491. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  4492. $fileIndex = V::get($fileIndexField, $record->ID, $record);
  4493. ?>
  4494. <script src="stuff/jquery.form.js"></script>
  4495. <div class="container">
  4496. <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
  4497. <?php if ($sharePoint) : ?>
  4498. <a href="<?php echo $sharePoint; ?>"><span class="glyphicon glyphicon-folder-open"></span><code><?php echo $mainFolder; ?></code></a>
  4499. <?php else : ?>
  4500. <code><?php echo $mainFolder; ?></code>
  4501. <?php endif; ?>
  4502. <span class="pull-right valign-btns-bottom">
  4503. <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
  4504. <?php echo $rowFunctionsOut; ?>
  4505. </span>
  4506. </h4>
  4507. <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
  4508. <table class="table table-bordered table-hover">
  4509. <colgroup>
  4510. <col style="">
  4511. <col style="width:30px;">
  4512. <?php if ($sharePoint) : ?>
  4513. <col style="width:30px;">
  4514. <?php endif; ?>
  4515. <col style="width:80px;">
  4516. <col style="width:140px;">
  4517. </colgroup>
  4518. <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
  4519. <?php if (empty($mainFolder)) : ?>
  4520. <tr>
  4521. <td colspan="5">
  4522. <div class="alert alert-warning">
  4523. <h4>Brak folderu!</h4>
  4524. Folder dla tego rekordu nie został utworzony.
  4525. </div>
  4526. </td>
  4527. </tr>
  4528. <?php elseif (empty($files)) : ?>
  4529. <tr>
  4530. <td colspan="5">
  4531. <div class="alert alert-info">
  4532. <h4>Brak plików</h4>
  4533. </div>
  4534. </td>
  4535. </tr>
  4536. <?php endif; ?>
  4537. </tbody>
  4538. </table>
  4539. </div>
  4540. <br>
  4541. <br>
  4542. <?php if (!$this->_acl->canWriteRecord($record)) : ?>
  4543. <div class="alert alert-warning">
  4544. Brak uprawnień do dodawania plików
  4545. </div>
  4546. <?php else : ?>
  4547. <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
  4548. <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
  4549. <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
  4550. <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
  4551. <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
  4552. <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
  4553. </ul>
  4554. <div id="myTabContent" class="tab-content">
  4555. <div class="tab-pane fade in active" id="local" style="text-align: center;">
  4556. <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'">
  4557. </div>
  4558. <div class="tab-pane fade" id="scan">
  4559. <?php if (empty($skanyFiles)) : ?>
  4560. <div class="alert alert-info">
  4561. <h4>Brak plików</h4>
  4562. <?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>"; ?>
  4563. </div>
  4564. <?php else : ?>
  4565. <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
  4566. <table class="table table-bordered table-hover">
  4567. <colgroup>
  4568. <col style="width:30px;">
  4569. <col style="">
  4570. <col style="width:30px;">
  4571. <col style="width:80px;">
  4572. <col style="width:140px;">
  4573. </colgroup>
  4574. <tbody>
  4575. <?php foreach ($skanyFiles as $vFilePath) : ?>
  4576. <tr>
  4577. <?php
  4578. $vFileName = explode('/', $vFilePath);
  4579. $vFileName = end($vFileName);
  4580. $vFileSize = filesize($vFilePath);
  4581. $vFileSizeOut = round($vFileSize, 2) . "B";
  4582. if ($vFileSize > 1024 * 1024) {
  4583. $vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
  4584. } else if ($vFileSize > 1024) {
  4585. $vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
  4586. }
  4587. ?>
  4588. <td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
  4589. <td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
  4590. <td style="white-space:nowrap; text-align:center;"><a href="<?php echo str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath); ?>" target="_blank" class="glyphicon glyphicon-download-alt"></a></td>
  4591. <td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
  4592. <td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
  4593. </tr>
  4594. <?php endforeach; ?>
  4595. </tbody>
  4596. </table>
  4597. </div>
  4598. <?php endif; ?>
  4599. </div>
  4600. </div>
  4601. <br>
  4602. <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
  4603. <?php //TODO: link do procesu o obiegu dokumentów <i class="glyphicon glyphicon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i> ?>
  4604. </h4>
  4605. <table style="width:100%" class="table table-bordered">
  4606. <tr>
  4607. <th>Nr</th>
  4608. <th>Typ</th>
  4609. <th style="width:40%;">Opis <i class="glyphicon glyphicon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
  4610. <th style="width:16%">Data wersji</th>
  4611. <th style="width:12%">Numer wersji</th>
  4612. </tr>
  4613. <tr>
  4614. <td>
  4615. <?php echo $fileIndex; ?>
  4616. </td>
  4617. <td>
  4618. <select class="form-control" name="M_DIST_FILES_TYPE">
  4619. <?php foreach ($fileTypes as $kType => $vLabel) : ?>
  4620. <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
  4621. <?php endforeach; ?>
  4622. </select>
  4623. <br>
  4624. <label class="checkbox">
  4625. <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
  4626. Wykrycie automatyczne typu z wysylanego pliku
  4627. </label>
  4628. <label class="checkbox">
  4629. <input type="checkbox" name="M_DIST_FILES_TEMP">
  4630. Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
  4631. </label>
  4632. </td>
  4633. <td>
  4634. <input class="form-control" style="width:100%" type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
  4635. <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
  4636. </td>
  4637. <td>
  4638. <div class="input-group">
  4639. <input name="M_DIST_FILES_DATE" type="text" value="<?php echo date('Y-m-d');?>" class="se_type-date form-control" data-format="yyyy-MM-dd" maxlength="10"><span class="input-group-addon">
  4640. <span class="glyphicon glyphicon-calendar"></span>
  4641. </span>
  4642. </div>
  4643. <!--
  4644. <input class="form-control" type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10">
  4645. -->
  4646. <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
  4647. </td>
  4648. <td>
  4649. <input class="form-control" style="width:100%" type="number" name="M_DIST_FILES_VERSION">
  4650. <br>
  4651. <label class="checkbox">
  4652. <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
  4653. Automatycznie dodaj wersje
  4654. </label>
  4655. </td>
  4656. </tr>
  4657. <tr>
  4658. <td colspan="5">
  4659. <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
  4660. <p>
  4661. <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
  4662. </p>
  4663. <p>
  4664. <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
  4665. <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
  4666. </p>
  4667. </td>
  4668. </tr>
  4669. </table>
  4670. </form>
  4671. </div>
  4672. <?php endif; ?>
  4673. <script>
  4674. function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
  4675. var postData = {};
  4676. jQuery.ajax({
  4677. 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; ?>',
  4678. type: 'POST',
  4679. //dataType: 'json',
  4680. //contentType: "application/json; charset=utf-8",
  4681. data: postData,
  4682. success: function(data) {
  4683. fileListUpdate<?php echo $this->_htmlID; ?>(data);
  4684. },
  4685. error: function(jhr, textStatus, errorThrown) {
  4686. console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
  4687. }
  4688. });
  4689. }
  4690. function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4691. var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
  4692. fileListNode.empty();
  4693. fileListJson.map(function(file){
  4694. var node = $('<tr></tr>');
  4695. <?php if (!$this->_acl->canWriteRecord($record)) : ?>
  4696. var fFun = null;
  4697. <?php else : ?>
  4698. var fFun = $('<i class="glyphicon glyphicon-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
  4699. <?php endif; ?>
  4700. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4701. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4702. if (fFun) fName.append(fFun);
  4703. fName.append(file.name);
  4704. fName.appendTo(fNameCell);
  4705. node.append(fNameCell);
  4706. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  4707. <?php if ($sharePoint) : ?>
  4708. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="<?php echo $sharePoint; ?>/' + file.name + '" target="_blank" class="glyphicon glyphicon-folder-open"></a>' + '</td>');
  4709. <?php endif; ?>
  4710. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4711. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4712. node.appendTo(fileListNode);
  4713. if (fFun) {
  4714. $(fFun).click(function(e){
  4715. var n = $(e.target);
  4716. var fname= n.data('filename');
  4717. if (!fname) {
  4718. return false;
  4719. }
  4720. if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
  4721. var postData = {filename: fname};
  4722. jQuery.ajax({
  4723. 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; ?>',
  4724. type: 'POST',
  4725. //dataType: 'json',
  4726. //contentType: "application/json; charset=utf-8",
  4727. data: postData,
  4728. success: function(data) {
  4729. if (data && data.type) {
  4730. if (data.type == 'SUCCESS') {
  4731. n.parents('tr').remove();
  4732. //console.log('TODO: SUCCESS msg: ', data.msg);
  4733. }
  4734. else if (data.type == 'error') {
  4735. console.log('TODO: ERROR msg: ', data.msg);
  4736. }
  4737. } else {
  4738. console.log('TODO: ??? data: ', data);
  4739. }
  4740. },
  4741. error: function(jhr, textStatus, errorThrown) {
  4742. console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
  4743. }
  4744. });
  4745. }
  4746. });
  4747. }
  4748. });
  4749. }
  4750. function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
  4751. var postData = {};
  4752. // clear current file list
  4753. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
  4754. jQuery.ajax({
  4755. 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,
  4756. type: 'POST',
  4757. //dataType: 'json',
  4758. //contentType: "application/json; charset=utf-8",
  4759. data: postData,
  4760. success: function(data) {
  4761. connTblListUpdate<?php echo $this->_htmlID; ?>(data);
  4762. },
  4763. error: function(jqXHR, textStatus, errorThrown) {
  4764. var txt = jqXHR.responseText || 'Error';
  4765. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').html('<tr><td colspan="6"><div class="alert alert-danger">' + txt + '</div></td></tr>');
  4766. if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
  4767. }
  4768. });
  4769. }
  4770. function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4771. var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
  4772. fileListNode.empty();
  4773. fileListJson.map(function(file){
  4774. var node = $('<tr></tr>');
  4775. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4776. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4777. fName.append(file.name);
  4778. fName.appendTo(fNameCell);
  4779. node.append(fNameCell);
  4780. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  4781. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4782. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4783. node.appendTo(fileListNode);
  4784. });
  4785. }
  4786. function fileListActions<?php echo $this->_htmlID; ?>() {
  4787. var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
  4788. var btnReload = jQuery('<button class="btn-link btn-sm" title="odśwież uprawnienia do plików"><span class="glyphicon glyphicon-refresh"></span>Odśwież</button>');
  4789. btnReload.on('click', function(e) {
  4790. //console.log('TODO: click reload perms...');
  4791. function notifyAjaxCallback(data) {
  4792. var notify = {};
  4793. notify.type = (data && data.type)? data.type : '';
  4794. notify.msg = (data && data.msg)? data.msg : '';
  4795. switch (notify.type) {
  4796. case 'success':
  4797. if (!notify.msg) notify.msg = 'OK';
  4798. break;
  4799. case 'info':
  4800. if (!notify.msg) notify.msg = '';
  4801. break;
  4802. case 'error':
  4803. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4804. break;
  4805. case 'warning':
  4806. notify.type = 'warn';
  4807. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4808. break;
  4809. default:
  4810. notify.msg = 'Nieznany błąd';
  4811. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4812. notify.type = '';
  4813. }
  4814. jQuery.notify(notify.msg, notify.type);
  4815. }
  4816. var reqData = {};
  4817. jQuery.ajax({
  4818. data: reqData,
  4819. dataType: 'json',
  4820. type: "GET",
  4821. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=filePermsRefresh&ID=<?php echo $record->ID; ?>',
  4822. })
  4823. .done(function(data, textStatus, jqXHR){
  4824. notifyAjaxCallback(data);
  4825. if (data && data.files) {
  4826. fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
  4827. }
  4828. })
  4829. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  4830. if (jqXHR.responseJSON) {
  4831. notifyAjaxCallback(jqXHR.responseJSON);
  4832. }
  4833. else {
  4834. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  4835. if (jqXHR.status == 404) {
  4836. jQuery.notify(jqXHR.responseText, 'error');
  4837. } else {
  4838. jQuery.notify(jqXHR.responseText, 'warn');
  4839. }
  4840. }
  4841. });
  4842. });
  4843. filePermsReload.append(btnReload);
  4844. }
  4845. jQuery(document).ready(function(){
  4846. $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function(e) {
  4847. e.preventDefault();
  4848. $(this).tab('show');
  4849. })
  4850. .on('shown.bs.tab', function(e) {
  4851. var fileSource = $(e.target).data('toggle')
  4852. , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
  4853. if (frm['M_DIST_UPLOAD_SOURCE']) {
  4854. frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
  4855. }
  4856. })
  4857. jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
  4858. 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; ?>',
  4859. beforeSubmit: function(args, $form, options) {
  4860. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
  4861. var argsMap = [];
  4862. args.map(function(v, k) {
  4863. argsMap[v.name] = v.value;
  4864. });
  4865. // validate
  4866. if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
  4867. if (!argsMap['M_DIST_FILES_NAME']) {
  4868. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
  4869. return false;
  4870. }
  4871. }
  4872. else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
  4873. if (!argsMap['SCANS_COLUMN_ADD']) {
  4874. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
  4875. return false;
  4876. }
  4877. }
  4878. else {
  4879. return false;
  4880. }
  4881. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4882. $out.html('Wysyłanie...');
  4883. },
  4884. success: function(data) {
  4885. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->success()...');
  4886. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4887. var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
  4888. if (typeof data == 'object') {
  4889. if (data.type == 'error') {
  4890. $out.html('<div class="alert alert-danger">' + btnClose + data.msg + '</div>');
  4891. } else if (data.type == 'SUCCESS') {
  4892. $out.html('<div class="alert alert-success">' + btnClose + data.msg + '</div>');
  4893. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4894. // TODO: scanFileListUpdateAjax...
  4895. }
  4896. } else {
  4897. if (data.substr(0, 7) == 'WARNING') {
  4898. data = data.substr(7);
  4899. $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
  4900. } else if (data.substr(0, 5) == 'error') {
  4901. data = data.substr(5);
  4902. $out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
  4903. } else if (data.substr(0, 7) == 'SUCCESS') {
  4904. data = data.substr(7);
  4905. $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
  4906. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4907. // TODO: scanFileListUpdateAjax...
  4908. } else if (data.substr(0, 4) == 'INFO') {
  4909. data = data.substr(4);
  4910. $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
  4911. }
  4912. }
  4913. }
  4914. });
  4915. fileListActions<?php echo $this->_htmlID; ?>();
  4916. var fileList = <?php echo json_encode($jsonFiles); ?>;
  4917. fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
  4918. var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
  4919. if (connTbls) {
  4920. var connTblsOut = '';
  4921. for(var key in connTbls) {
  4922. connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
  4923. };
  4924. if (connTblsOut) {
  4925. connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
  4926. connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
  4927. '<table class="table table-bordered table-hover">' +
  4928. '<colgroup>' +
  4929. '<col style="">' +
  4930. '<col style="width:30px;">' +
  4931. <?php if ($sharePoint) : ?>
  4932. '<col style="width:30px;">' +
  4933. <?php endif; ?>
  4934. '<col style="width:80px;">' +
  4935. '<col style="width:140px;">' +
  4936. '</colgroup>' +
  4937. '<tbody class="files-list">' +
  4938. '</tbody>' +
  4939. '</table>' +
  4940. '</div>';
  4941. var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
  4942. _connTblsWrap.css('marginBottom', '26px');
  4943. _connTblsWrap.html(connTblsOut);
  4944. _connTblsWrap.find('.conn-tbl-load').each(function(){
  4945. jQuery(this).click(function(e){
  4946. var tblID = jQuery(e.target).data('zasobid');
  4947. if (tblID) {
  4948. connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
  4949. }// TODO: else show error
  4950. });
  4951. });
  4952. }
  4953. }
  4954. initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
  4955. });
  4956. </script>
  4957. <?php
  4958. exit;
  4959. }
  4960. private function sendTypeSpecial($fldID, $args) {
  4961. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4962. header("Content-type: application/json");
  4963. $fldName = '';
  4964. $fld = $this->_acl->getField($fldID);
  4965. 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>';}
  4966. if (!$fld) {
  4967. // 404
  4968. } else {
  4969. $fldName = $fld['name'];
  4970. }
  4971. $jsonData = array();
  4972. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  4973. if ($typeSpecial) {
  4974. $query = V::get('q', '', $_REQUEST);
  4975. $rawRows = null;
  4976. $rows = $typeSpecial->getValuesWithExports($query);
  4977. 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>';}
  4978. foreach ($rows as $kID => $vItem) {
  4979. $itemJson = new stdClass();
  4980. $itemJson->id = $vItem->id;
  4981. $itemJson->name = $vItem->param_out;
  4982. if (!empty($vItem->exports)) {
  4983. $itemJson->exports = $vItem->exports;
  4984. }
  4985. $jsonData[] = $itemJson;
  4986. }
  4987. }
  4988. /*
  4989. MENU_INIT:VIEWTABLE_AJAX
  4990. ZASOB_ID:1188
  4991. _task:TYPESPECIAL
  4992. fldID:3866
  4993. Form Dataview sourceview URL encoded
  4994. q:te
  4995. */
  4996. echo json_encode($jsonData);
  4997. exit;
  4998. }
  4999. private function sendTypeSpecialCell($id, $fldName, $args) {
  5000. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5001. header("Content-type: application/json");
  5002. $jsonData = new stdClass();
  5003. $fldID = $this->_acl->getFieldIdByName($fldName);
  5004. 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>';}
  5005. $item = $this->_acl->getItem($id);
  5006. if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
  5007. $jsonData->msg = 'Brak dostępu';
  5008. echo json_encode($jsonData);
  5009. exit;
  5010. }
  5011. if (!$fldID) {
  5012. $jsonData->msg = 'Wrong field';
  5013. echo json_encode($jsonData);
  5014. exit;
  5015. }
  5016. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  5017. if ($typeSpecial) {
  5018. $jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
  5019. 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>';}
  5020. }
  5021. echo json_encode($jsonData);
  5022. exit;
  5023. }
  5024. private function ajaxData($args) {
  5025. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5026. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  5027. $page = V::get('page', 0, $args, 'int');
  5028. $currSortCol = V::get('currSortCol', '', $args);
  5029. $currSortFlip = V::get('currSortFlip', '', $args);
  5030. if ($page > 0) {
  5031. $page -= 1;
  5032. }
  5033. else {
  5034. }
  5035. $params = array();
  5036. $params['limit'] = $pageSize;
  5037. $params['limitstart'] = $page * $params['limit'];
  5038. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  5039. $params['order_dir'] = $currSortFlip;
  5040. $filters = new stdClass();
  5041. $filters->currSortCol = $currSortCol;
  5042. $filters->currSortFlip = $currSortFlip;
  5043. foreach ($args as $k => $v) {
  5044. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  5045. $params[$k] = $v;
  5046. $filters->{$k} = $v;
  5047. }
  5048. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  5049. $params[$k] = $v;
  5050. $filters->{$k} = $v;
  5051. }
  5052. }
  5053. $this->setFilters($filters);
  5054. $vCols = $this->_acl->getVirtualFieldList();
  5055. if (!empty($vCols)) {
  5056. 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>';}
  5057. }
  5058. $visibleCols = $this->_acl->getVisibleFieldList();
  5059. 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>';}
  5060. $jsonData = new stdClass();
  5061. $jsonData->page = $page + 1;
  5062. $jsonData->pageSize = $pageSize;
  5063. $jsonData->filters = $filters;
  5064. $jsonData->cols = new stdClass();
  5065. $jsonData->uniqueCol = $this->_acl->getPrimaryKeyField();
  5066. $ind = 0;
  5067. foreach ($visibleCols as $fieldID => $col) {
  5068. $ind++;
  5069. $columnConfig = (object)array('index'=>$ind);
  5070. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  5071. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  5072. }
  5073. else if (in_array($col, array('Status'))) {
  5074. // Ahmes problems Status colors
  5075. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  5076. }
  5077. else if ($this->_acl->isGeomField($col)) {
  5078. $columnConfig->type = 'geom';
  5079. }
  5080. if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
  5081. $columnConfig->friendly = $label;
  5082. }
  5083. $colType = $this->_acl->getFieldType($col);
  5084. if ($colType) {// @see MarkTableAjaxFilterColType
  5085. if ($colType['type'] == 'date') {
  5086. //$columnConfig->type = 'date';// TODO: require datetimepicker
  5087. }
  5088. } else {// typespecial - no type
  5089. $columnConfig->type = 'special';
  5090. }
  5091. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  5092. if ($typeSpecial) {
  5093. 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>';}
  5094. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  5095. if ($columnConfig->_tsRetId == 0) {
  5096. $tsParamOut = V::get('param_out', null, $typeSpecial);
  5097. if ($tsParamOut) {
  5098. $tsFormat = V::get('format', null, $tsParamOut);
  5099. $tsValues = V::get('values', null, $tsParamOut);
  5100. $tsAliases = V::get('alias', null, $tsParamOut);
  5101. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  5102. $tsAliasMap = array();
  5103. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  5104. $bugTsColsNotVisible = array();
  5105. foreach ($tsValues as $kVarName => $vIdZasob) {
  5106. if (array_key_exists($vIdZasob, $tsAliases)) {
  5107. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  5108. } else {
  5109. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  5110. }
  5111. if (!array_key_exists($vIdZasob, $visibleCols)) {
  5112. $bugTsColsNotVisible[] = $vIdZasob;
  5113. }
  5114. }
  5115. if (empty($bugTsColsNotVisible)) {
  5116. $tsSimpleLink = new stdClass();
  5117. $tsSimpleLink->format = $tsFormat;
  5118. $tsSimpleLink->aliasMap = $tsAliasMap;
  5119. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  5120. $columnConfig->type = 'simpleLink';
  5121. } else {
  5122. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  5123. }
  5124. }
  5125. }
  5126. }
  5127. }
  5128. // @see ajaxHiddenColsSave
  5129. if (UserProfile::isHiddenColumn($this->_zasobID, $fieldID)) {
  5130. $columnConfig->hidden = true;
  5131. }
  5132. $columnConfig->description = $this->_acl->getFieldOpis($fieldID);
  5133. $jsonData->cols->{$col} = $columnConfig;
  5134. }
  5135. $jsonData->rows = array();
  5136. $jsonData->total = $this->_acl->getTotal($params);
  5137. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">get_total (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData->total);echo'</pre>';}
  5138. $items = $this->_acl->getItems($params);
  5139. 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>';}
  5140. // TODO: add virtual data by Typespecial
  5141. if (!empty($vCols) && !empty($items)) {
  5142. foreach ($vCols as $vColID => $vCol) {
  5143. $colType = $this->_acl->getFieldTypeById($vColID);
  5144. if ($colType) {
  5145. continue;// pomin Typespecial dla realnych komorek w bazie danych
  5146. }
  5147. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  5148. if ($typeSpecial) {
  5149. $columnConfig = V::get($vCol, null, $jsonData->cols);
  5150. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  5151. // pomin simple link values - mved to js render
  5152. } else {
  5153. 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>';}
  5154. $ids = array_keys($items);
  5155. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  5156. 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>';}
  5157. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  5158. $tsValue = implode('<br>', $vValues);
  5159. 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>';}
  5160. if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
  5161. $items[$kItemID]->{$vCol} .= ": {$tsValue}";
  5162. } else {
  5163. $items[$kItemID]->{$vCol} = $tsValue;
  5164. }
  5165. }
  5166. }
  5167. }
  5168. }
  5169. }
  5170. foreach ($items as $vItem) {
  5171. // TODO: hide items without 'R'
  5172. foreach ($visibleCols as $kID => $vCol) {
  5173. // TODO: ID default 'R'
  5174. if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
  5175. $vItem->{$vCol} = '*****';
  5176. }
  5177. // null => empty string
  5178. if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
  5179. 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>';}
  5180. $vItem->{$vCol} = '';
  5181. }
  5182. }
  5183. $jsonData->rows[] = $vItem;
  5184. }
  5185. return $jsonData;
  5186. }
  5187. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  5188. $value = '';
  5189. $type = $this->_acl->getFieldTypeById($fieldID);
  5190. if ($type) {
  5191. if ($type['type'] == 'date') {
  5192. $value = $type['default'];
  5193. }
  5194. // fix bug when field is unique and is null allowed: change empty string to null
  5195. if ($type['null']) {
  5196. $value = 'NULL';
  5197. }
  5198. // fix bug when field is enum and is set to '0': for php '0' is empty
  5199. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  5200. if (false !== strpos($type['type'], "''")) {
  5201. // enum('', '1','2')
  5202. $value = '';
  5203. } else if (false !== strpos($type['type'], "'0'")) {
  5204. // enum('0', '1','2')
  5205. $value = '0';
  5206. } else {
  5207. $value = $type['default'];
  5208. }
  5209. }
  5210. }
  5211. return $value;
  5212. }
  5213. /**
  5214. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  5215. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  5216. */
  5217. private function ajaxHiddenColsSave($args) {
  5218. $response = new stdClass();
  5219. if (empty($args)) {
  5220. $response->type = 'info';
  5221. return $response;
  5222. }
  5223. UserProfile::load();
  5224. // clean up old, wrong values
  5225. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5226. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5227. }
  5228. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  5229. $fields = $this->_acl->getFields();
  5230. foreach ($fields as $kFldId => $vFld) {
  5231. $vFldName = $vFld['name'];
  5232. if (isset($args[$vFldName])) {
  5233. if ($args[$vFldName] == 'SHOW') {
  5234. $colVis[$kFldId] = 1;
  5235. } else if ($args[$vFldName] == 'HIDE') {
  5236. $colVis[$kFldId] = 0;
  5237. }
  5238. }
  5239. }
  5240. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  5241. UserProfile::save();
  5242. $response->type = 'success';
  5243. return $response;
  5244. }
  5245. private function ajaxPageSizeSave($args) {
  5246. $response = new stdClass();
  5247. if (empty($args)) {
  5248. $response->type = 'info';
  5249. return $response;
  5250. }
  5251. $pageSize = V::get('pageSize', 0, $args, 'int');
  5252. UserProfile::load();
  5253. // clean up old, wrong values
  5254. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5255. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5256. }
  5257. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  5258. $tableAjaxSettings['pageSize'] = $pageSize;
  5259. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  5260. UserProfile::save();
  5261. $response->type = 'success';
  5262. return $response;
  5263. }
  5264. private function ajaxTheGeomSave($args) {
  5265. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5266. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5267. $polygon = V::get('polygon', 0, $args);
  5268. $geomFieldName = 'the_geom';
  5269. if ($primaryKey <= 0) {
  5270. throw new HttpException("Wrong param ID", 404);
  5271. }
  5272. // 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)))
  5273. $record = $this->_acl->getItem($primaryKey);
  5274. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5275. throw new HttpException("Brak dostępu do rekordu", 403);
  5276. }
  5277. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  5278. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  5279. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5280. }
  5281. $itemPatch = array();
  5282. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  5283. $itemPatch[$primaryKeyField] = $primaryKey;
  5284. $response = new stdClass();
  5285. try {
  5286. $affected = $this->_acl->updateItem($itemPatch);
  5287. if ($affected > 0) {
  5288. $response->type = 'success';
  5289. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5290. } else if ($affected == 0) {
  5291. $response->type = 'info';
  5292. $response->msg = "Nie wprowadzono żadnych zmian";
  5293. }
  5294. $response->record = $this->_acl->getItem($primaryKey);
  5295. }
  5296. catch (Exception $e) {
  5297. $response->type = 'error';
  5298. $response->msg = $e->getMessage();
  5299. }
  5300. return $response;
  5301. }
  5302. private function sendAjaxResponseJson($method, $args) {
  5303. try {
  5304. $response = $this->{$method}($args);
  5305. }
  5306. catch (HttpException $e) {
  5307. $response = new stdClass();
  5308. $response->type = 'error';
  5309. $response->msg = $e->getMessage();
  5310. $response->errorCode = $e->getCode();
  5311. Http::sendHeaderByCode($e->getCode());
  5312. }
  5313. catch (Exception $e) {
  5314. $response = new stdClass();
  5315. $response->type = 'error';
  5316. $response->msg = $e->getMessage();
  5317. $response->errorCode = $e->getCode();
  5318. }
  5319. header('Content-type: application/json');
  5320. if (!$response) $response = new stdClass();
  5321. echo json_encode($response);
  5322. exit;
  5323. }
  5324. private function ajaxTheGeomRemove($args) {// ajax task 'THE_GEOM_REMOVE'
  5325. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5326. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5327. $geomFieldName = 'the_geom';
  5328. $response = new stdClass();
  5329. if ($primaryKey <= 0) {
  5330. throw new HttpException("Wrong param ID", 404);
  5331. }
  5332. $record = $this->_acl->getItem($primaryKey);
  5333. if (!$record) {
  5334. throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  5335. }
  5336. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5337. throw new HttpException("Brak dostępu do rekordu nr {$primaryKey}", 403);
  5338. }
  5339. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  5340. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  5341. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5342. }
  5343. if (empty($record->{$geomFieldName})) {
  5344. $response->type = 'info';
  5345. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  5346. $response->record = $record;
  5347. return $response;
  5348. }
  5349. $itemPatch = array();
  5350. $itemPatch[$geomFieldName] = "NULL";
  5351. $itemPatch[$primaryKeyField] = $primaryKey;
  5352. $response = new stdClass();
  5353. try {
  5354. $affected = $this->_acl->updateItem($itemPatch);
  5355. if ($affected > 0) {
  5356. $response->type = 'success';
  5357. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5358. } else if ($affected == 0) {
  5359. $response->type = 'info';
  5360. $response->msg = "Nie wprowadzono żadnych zmian";
  5361. }
  5362. $response->record = $this->_acl->getItem($primaryKey);
  5363. }
  5364. catch (Exception $e) {
  5365. $response->type = 'error';
  5366. $response->msg = $e->getMessage();
  5367. }
  5368. return $response;
  5369. }
  5370. private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
  5371. $response = new stdClass();
  5372. $pInitList = array();// [proces_init_id] => label (DESC)
  5373. if (!$this->_showProcesInit) {
  5374. $response->type = 'error';
  5375. return $response;
  5376. }
  5377. $userAcl = User::getAcl();
  5378. $pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
  5379. if (!empty($pInitList)) {
  5380. $procesIds = array_keys($pInitList);
  5381. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  5382. DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
  5383. DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
  5384. $pInitListSelected = $this->getProcesInitSelected();
  5385. $response->pInitData = new stdClass();
  5386. $response->pInitData->pInitList = $pInitList;
  5387. $response->pInitData->mapTree = $mapTree;
  5388. $response->pInitData->pInitListSelected = $pInitListSelected;
  5389. }
  5390. $response->type = 'success';
  5391. return $response;
  5392. }
  5393. function ajaxMoreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  5394. $id = V::get('ID', 0, $args, 'int');
  5395. if ($id <= 0) throw new HttpException("404", 404);
  5396. $response = new stdClass();
  5397. $response->type = 'success';
  5398. $response->msg = 'Funkcje';
  5399. $response->rowFunctions = [];
  5400. $tableName = $this->_acl->getName();
  5401. if(1){// TODO: fetch $totalMsgs from TableMsgs
  5402. $msgs = Router::getRoute('Msgs');
  5403. $msgsList = $msgs->getActiveMessagesForTableRecord($tableName, $id);
  5404. $totalMsgs = count($msgsList);
  5405. $rowFunc = new stdClass();
  5406. $rowFunc->id = 'msgs';
  5407. $rowFunc->ico = 'glyphicon glyphicon-envelope';
  5408. $rowFunc->href = 'index.php?_route=TableMsgs&_task=tableRow&idTable=' . $this->_zasobID . '&idRow=' . $id;
  5409. $rowFunc->title = "Wiadomości ({$totalMsgs})";
  5410. $rowFunc->label = "Wiadomości <span class=\"badge\">{$totalMsgs}</span>";
  5411. $response->rowFunctions[] = $rowFunc;
  5412. }
  5413. if ('CRM_PROCES' == $this->_acl->getName()) {// TODO: mv to table gui xml or php class
  5414. $record = $this->_acl->getItem($id);
  5415. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  5416. $rowFunc = new stdClass();
  5417. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  5418. $rowFunc->href = "procesy5.php?task=CRM_PROCES&filtr_id={$id}";
  5419. $rowFunc->title = "Zobacz na drzewie procesów {{$id}}";
  5420. $response->rowFunctions[] = $rowFunc;
  5421. $wskazniki = ProcesHelper::get_wskazniki($id);
  5422. $connectedZasobyTotal = count($wskazniki);
  5423. $rowFunc = new stdClass();
  5424. $rowFunc->ico = 'glyphicon glyphicon-random';
  5425. $rowFunc->href = "index.php?MENU_INIT=PROCES_ADD_ZASOB&procesID={$id}";
  5426. $rowFunc->title = "Powiązane zasoby <span class=\"badge\">{$connectedZasobyTotal}</span>";
  5427. $response->rowFunctions[] = $rowFunc;
  5428. }
  5429. if ('CRM_LISTA_ZASOBOW' == $this->_acl->getName()) {// TODO: mv to table gui xml or php class
  5430. $record = $this->_acl->getItem($id);
  5431. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  5432. $rowFunc = new stdClass();
  5433. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  5434. $rowFunc->href = "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$id}";
  5435. $rowFunc->title = "Zobacz na drzewie zasobów [{$id}]";
  5436. $response->rowFunctions[] = $rowFunc;
  5437. // index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob=22001
  5438. $rowFunc = new stdClass();
  5439. $rowFunc->ico = 'glyphicon glyphicon-random';
  5440. $rowFunc->href = "index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob={$id}";
  5441. $rowFunc->title = "Powiązane procesy (OB)";
  5442. $response->rowFunctions[] = $rowFunc;
  5443. // index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob=22001
  5444. $rowFunc = new stdClass();
  5445. $rowFunc->ico = 'glyphicon glyphicon-random';
  5446. $rowFunc->href = "index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob={$id}";
  5447. $rowFunc->title = "Powiązane dane (IDS)";
  5448. $response->rowFunctions[] = $rowFunc;
  5449. $groupTypeList = array();
  5450. $groupTypeList[] = 'STANOWISKO';
  5451. $groupTypeList[] = 'PODMIOT';
  5452. $groupTypeList[] = 'DZIAL';
  5453. if (in_array($record->TYPE, $groupTypeList)) {
  5454. $rowFunc = new stdClass();
  5455. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  5456. $rowFunc->href = "index.php?_route=Users&_task=syncGroup&idGroup={$id}";
  5457. $rowFunc->title = "Synchronizuj do LDAP";
  5458. $response->rowFunctions[] = $rowFunc;
  5459. }
  5460. }
  5461. if ('ADMIN_USERS' == $this->_acl->getName()) {// TODO: mv to table gui xml
  5462. $record = $this->_acl->getItem($id);
  5463. $isAllowedoReadUserLogin = false;
  5464. if ($this->_acl->canReadRecord($record)) {
  5465. $idFieldUserLogin = $this->_acl->getFieldIdByName('ADM_ACCOUNT');
  5466. if ($idFieldUserLogin) {
  5467. if ($this->_acl->isAllowed($idFieldUserLogin, 'R', $record)) {
  5468. $isAllowedoReadUserLogin = true;
  5469. }
  5470. }
  5471. }
  5472. if ($isAllowedoReadUserLogin) {
  5473. $rowFunc = new stdClass();
  5474. $rowFunc->ico = 'glyphicon glyphicon-user';
  5475. $rowFunc->href = 'index.php?_route=Users&_task=userGroups&usrLogin=' . $record->ADM_ACCOUNT;
  5476. $rowFunc->title = "Ustal stanowisko";
  5477. $response->rowFunctions[] = $rowFunc;
  5478. $rowFunc = new stdClass();
  5479. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  5480. $rowFunc->href = 'index.php?_route=Users&_task=syncUser&usrLogin=' . $record->ADM_ACCOUNT;
  5481. $rowFunc->title = "Synchronizuj do LDAP";
  5482. $response->rowFunctions[] = $rowFunc;
  5483. $rowFunc = new stdClass();
  5484. $rowFunc->ico = 'glyphicon glyphicon-minus';
  5485. $rowFunc->href = 'index.php?MENU_INIT=USER_OCENA_PRACOWNIKA&usrLogin=' . $record->ADM_ACCOUNT;
  5486. $rowFunc->title = "Ocena pracownika";
  5487. $response->rowFunctions[] = $rowFunc;
  5488. }
  5489. }
  5490. return $response;
  5491. }
  5492. }