TableAjax.php 222 KB

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