TableAjax.php 232 KB

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