TableAjax.php 231 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276
  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. });
  1660. {// if (!selectedFilter) {// save current filter
  1661. var li = $('<li style="text-align:center"></li>').appendTo(ul)
  1662. priv.modelColFilter_getSaveBtn().appendTo(li);
  1663. }
  1664. $('<li class="divider"></li>').appendTo(ul);
  1665. $.each(_data.cols, function(col, props) {
  1666. if (props.type != "unique" && col != 'ID') {
  1667. var li = $('<li></li>').appendTo(ul),
  1668. label = (props.friendly || col).replace(/<br\/?>/g, ' '),
  1669. input = '<input {0} type="checkbox" title="{1}" value="{1}" style="margin:0"/>&nbsp;{2}'.f((props.hidden) ? '' : 'checked', col, label),
  1670. a = $('<a href="#" style="padding:0px 20px;">' + input + '</a>').appendTo(li);
  1671. }
  1672. });
  1673. node.on('click', 'input[type="checkbox"]', priv.columnPickerClicked);
  1674. node.on('click', 'a', priv.columnPickerLinkClicked);
  1675. } else {
  1676. node = $('<span class="' + nodeClass + '"></span>');
  1677. }
  1678. currentNode.replaceWith(node);
  1679. };
  1680. priv.renderFooterFunctions = function() {
  1681. var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
  1682. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1683. node;
  1684. if (priv.options.debug) console.log('Render: ', nodeClass);
  1685. if (priv.options.tblFunctions) {
  1686. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1687. $.map(priv.options.tblFunctions, function(funObj, funName){
  1688. var funHtml = $('<button class="btn btn-sm btn-default"></button>');
  1689. if (funObj.title) funHtml.attr('title', funObj.title);
  1690. if (funObj.method) funHtml.on('click', priv[funObj.method]);
  1691. else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
  1692. var funIconHtml = $('<i></i>');
  1693. if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
  1694. funIconHtml.prependTo(funHtml);
  1695. funHtml.addClass('btn');
  1696. funHtml.appendTo(node);
  1697. });
  1698. } else {
  1699. node = $('<span class="' + nodeClass + '"></span>');
  1700. }
  1701. currentNode.replaceWith(node);
  1702. };
  1703. priv.renderFooterExport = function() {
  1704. var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
  1705. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1706. node;
  1707. if (priv.options.debug) console.log('Render: ', nodeClass);
  1708. if (priv.options.exportFields && priv.options.exportFields.length) {
  1709. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1710. var btn = $('<button class="btn btn-sm dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
  1711. var span = $('<span class="caret"></span>').appendTo(btn);
  1712. var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
  1713. $.each(_data.cols, function(col, props) {
  1714. if (-1 !== priv.options.exportFields.indexOf(col)) {
  1715. var li = $('<li></li>').appendTo(ul);
  1716. $('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col)).appendTo(li);
  1717. li.on('click', 'input', priv.exportFieldChanged);
  1718. }
  1719. });
  1720. var li = $('<li></li>').appendTo(ul);
  1721. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
  1722. li.on('click', 'a', priv.exportToHTML);
  1723. var li = $('<li></li>').appendTo(ul);
  1724. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
  1725. li.on('click', 'a', priv.exportToCSV);
  1726. } else {
  1727. node = $('<span class="' + nodeClass + '"></span>');
  1728. }
  1729. currentNode.replaceWith(node);
  1730. };
  1731. priv.renderInlineEditBox = function() {
  1732. var nodeClass = 'tblAjax__' + 'inlineEditBox',
  1733. currentNode = $(_uiNodeCont).parent().children('.' + nodeClass),
  1734. node;
  1735. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  1736. /// console.log('L.<?php echo __LINE__; ?> Render: priv.renderInlineEditBox, currentNode.html:', currentNode.html(), currentNode);
  1737. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  1738. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  1739. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  1740. var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
  1741. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
  1742. $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
  1743. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  1744. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  1745. $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  1746. $('<input type="hidden" name="col" value="">').appendTo(iebBody);
  1747. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  1748. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  1749. $('<button class="btn btn-close" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  1750. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  1751. frmInlineEdit.on('submit', function() {
  1752. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  1753. var data = inlineEditBox$Node.find('form').serialize();
  1754. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  1755. function notifyAjaxCallback(data) {
  1756. var notify = {};
  1757. notify.type = (data && data.type)? data.type : '';
  1758. notify.msg = (data && data.msg)? data.msg : '';
  1759. switch (notify.type) {
  1760. case 'success':
  1761. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  1762. break;
  1763. case 'info':
  1764. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  1765. break;
  1766. case 'error':
  1767. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1768. break;
  1769. case 'warning':
  1770. notify.type = 'warn';
  1771. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1772. break;
  1773. default:
  1774. notify.msg = 'Nieznany błąd';
  1775. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1776. notify.type = '';
  1777. }
  1778. jQuery.notify(notify.msg, notify.type);
  1779. }
  1780. $.ajax({
  1781. data: data,
  1782. dataType: 'json',
  1783. type: "POST",
  1784. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE'
  1785. })
  1786. .done(function(data, textStatus, jqXHR){
  1787. notifyAjaxCallback(data);
  1788. publ.refresh();
  1789. inlineEditBox$Node.modal('hide');
  1790. })
  1791. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  1792. if (jqXHR.responseJSON) {
  1793. notifyAjaxCallback(jqXHR.responseJSON);
  1794. }
  1795. else {
  1796. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  1797. if (jqXHR.status == 404) {
  1798. jQuery.notify(jqXHR.responseText, 'error');
  1799. } else {
  1800. jQuery.notify(jqXHR.responseText, 'warn');
  1801. }
  1802. }
  1803. inlineEditBox$Node.modal('hide');
  1804. });
  1805. return false;
  1806. });
  1807. currentNode.replaceWith(node);
  1808. };
  1809. priv.exportFieldChanged = function(e) {
  1810. e.stopPropagation();
  1811. var column = $(this).val();
  1812. _exportFieldsSelect[column] = !_exportFieldsSelect[column];
  1813. };
  1814. priv.exportToHTML = function(e) {
  1815. priv.exportData('html', $(this), e);
  1816. };
  1817. priv.exportToCSV = function(e) {
  1818. priv.exportData('csv', $(this), e);
  1819. };
  1820. priv.exportData = function(format, node, e) {
  1821. var exportFields = [];
  1822. $.each(_exportFieldsSelect, function(col, selected) {
  1823. if (selected) {
  1824. exportFields.push(col);
  1825. }
  1826. });
  1827. if (!exportFields.length) {
  1828. alert('Nie wybrano żadnych pól do eksportu.');
  1829. e.preventDefault();
  1830. return false;
  1831. }
  1832. var limit = 10000;
  1833. if (!_data.total || _data.total <= 0) {
  1834. alert('Brak rekordów do eksportu.');
  1835. e.preventDefault();
  1836. return false;
  1837. }
  1838. if (_data.total > limit) {
  1839. if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
  1840. e.preventDefault();
  1841. return false;
  1842. }
  1843. }
  1844. var exportUrl = 'index.php?_route=ViewTableAjax&_task=export&namespace=<?= $acl->getNamespace(); ?>';
  1845. exportUrl += '&format=' + format;
  1846. exportUrl += '&flds=' + exportFields.join(',');
  1847. exportUrl += '&sortCol=' + (_state.filters.currSortCol || '');
  1848. exportUrl += '&sortDir=' + (_state.filters.currSortFlip ? "desc" : "asc");
  1849. if (Object.keys(_state.filters.filterCols).length > 0) {
  1850. $.each(_state.filters.filterCols, function(col, colProps) {
  1851. if (colProps.filter && colProps.filter.length > 0) {
  1852. exportUrl += '&f_' + col + '=' + colProps.filter;
  1853. }
  1854. });
  1855. }
  1856. // specialFilters
  1857. $.each(_state.specialFilters, function(groupName, btnValue) {
  1858. if (btnValue.length > 0) {
  1859. exportUrl += '&sf_' + groupName + '=' + btnValue;
  1860. }
  1861. });
  1862. if (priv.options.forceFilterInit) {
  1863. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  1864. exportUrl += '&sf_' + fltr + '=' + fltrProps;
  1865. });
  1866. }
  1867. node.attr('href', exportUrl);
  1868. };
  1869. /*
  1870. calls the webservice(if defined).
  1871. used only inside priv.init
  1872. */
  1873. priv.update = function(callback) {
  1874. var skipCols, resetChecked;// undefined
  1875. if (!priv.options.url) {
  1876. if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
  1877. return;
  1878. }
  1879. 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) || ''));
  1880. var initUrlAdd = '',
  1881. filtersInitSet = false;
  1882. initUrlAdd += '&currSortCol=' + _state.filters.currSortCol;
  1883. initUrlAdd += '&currSortFlip=' + ((_state.filters.currSortCol)? "desc" : "asc");
  1884. if (Object.keys(_state.filters.filterCols).length > 0) {
  1885. $.each(_state.filters.filterCols, function(col, colProps) {
  1886. if (colProps.filter && colProps.filter.length > 0) {
  1887. initUrlAdd += '&f_' + col + '=' + colProps.filter;
  1888. filtersInitSet = true;
  1889. }
  1890. });
  1891. }
  1892. $.each(_state.specialFilters, function(groupName, btnValue) {
  1893. if (btnValue.length > 0) {
  1894. initUrlAdd += '&sf_' + groupName + '=' + btnValue;
  1895. filtersInitSet = true;
  1896. }
  1897. });
  1898. if (priv.options.forceFilterInit) {
  1899. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  1900. initUrlAdd += '&f_' + fltr + '=' + fltrProps;
  1901. filtersInitSet = true;
  1902. });
  1903. }
  1904. // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych (init) ...'});
  1905. fetch(priv.options.url + initUrlAdd, {
  1906. method: priv.options.urlPost ? 'POST' : 'GET',
  1907. credentials: 'same-origin',// add cookies
  1908. }).then(function (response) {
  1909. return response.json()
  1910. }).then(function (data) {
  1911. if (priv.options.debug) console.log('loadDataAjax:fetch: request finished L.<?php echo __LINE__; ?> data:', data);
  1912. if ('success' == data.type) {
  1913. // p5UI__notifyAjaxCallback(data);
  1914. if (data && data.cols) {
  1915. priv.setStateCols(data.cols, data.uniqueCol);
  1916. }
  1917. // set initial filters (_state.filters.filterCols)
  1918. if (filtersInitSet && _data && _data.cols) {
  1919. $.map(reqData, function(fltrValue, fltr){
  1920. var colName = null;
  1921. if (fltr.substr(0, 3) == 'sf_') {
  1922. colName = fltr.substr(3);
  1923. }
  1924. else if (fltr.substr(0, 2) == 'f_') {
  1925. colName = fltr.substr(2);
  1926. }
  1927. if (colName && _data.cols[colName]) {
  1928. //add the filter to the filter array
  1929. _state.filters.filterCols[colName] = {
  1930. filter: fltrValue,
  1931. colName: colName
  1932. };
  1933. }
  1934. });
  1935. }
  1936. // assign the new state (data)
  1937. state = {data: {}};
  1938. if (!skipCols) state.data.cols = data.cols || {};
  1939. state.data.rows = data.rows || [];
  1940. state.data.total = data.total || 0;
  1941. state.page = data.page || 0;
  1942. state.pageSize = data.pageSize || priv.options.pageSize;
  1943. state.filters = data.filters || {};
  1944. priv.setState(state);
  1945. if (typeof callback == "function") {
  1946. callback.call(this);
  1947. }
  1948. } else if ('error' == data.type) {
  1949. p5UI__notifyAjaxCallback(data);
  1950. } else {
  1951. p5UI__notifyAjaxCallback(data);
  1952. }
  1953. }).catch(function (e) {
  1954. console.log('loadDataAjax:fetch: ERR:', e);
  1955. });
  1956. };
  1957. /*
  1958. assigns the new data.
  1959. */
  1960. priv.setState = function(state) {
  1961. var oldState = _state,// TODO: use to check what really changed (use extend!)
  1962. renderParts = {};
  1963. if (state.data) {
  1964. if (state.data.cols && state.data.cols.length > 0) {// TODO: never happen, but if happend then rerender all
  1965. priv.setStateCols(state.data.cols, state.data.uniqueCol);
  1966. priv.setStateData(state.data);
  1967. renderParts['head'] = true;
  1968. } else {
  1969. priv.setStateData(state.data, true);
  1970. }
  1971. renderParts['body'] = true;
  1972. renderParts['foot_pagination'] = true;
  1973. }
  1974. if (state.hasOwnProperty('specialFilters')) {
  1975. _state.specialFilters = state.specialFilters;
  1976. renderParts['head__specialFilters'] = true;
  1977. }
  1978. if (state.hasOwnProperty('page')) {
  1979. if (state.page != _state.page) {
  1980. _state.page = state.page;
  1981. renderParts['foot_pagination'] = true;
  1982. }
  1983. }
  1984. if (state.hasOwnProperty('pageSize')) {
  1985. if (state.pageSize != _state.pageSize) {
  1986. _state.pageSize = state.pageSize;
  1987. renderParts['foot_pagination'] = true;
  1988. }
  1989. }
  1990. if (state.hasOwnProperty('filters')) {
  1991. /// console.log('L.<?php echo __LINE__; ?> setState::state.filters: ', state.filters);//TODO:DBG:RMME
  1992. priv.setStateFilters(state.filters);
  1993. // TODO: if state diff's
  1994. renderParts['head__specialFilters'] = true;
  1995. renderParts['foot_pagination'] = true;
  1996. }
  1997. renderParts = Object.keys(renderParts);
  1998. if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1999. ///console.log('L.<?php echo __LINE__; ?> setState::renderParts: ', renderParts);//TODO:DBG:RMME
  2000. if (renderParts.length > 0) {
  2001. jQuery(_uiNodeCont).trigger('TableAjax:render', renderParts);
  2002. }
  2003. };
  2004. priv.setStateCols = function(cols, uniqueCol) {
  2005. _state.cols = cols;
  2006. _state.uniqueCol = uniqueCol;
  2007. // fix col name - props.column
  2008. $.each(_state.cols, function(col, props) {
  2009. props.column = col;
  2010. });
  2011. // fix col types - default 'string'
  2012. $.each(_state.cols, function(col, props) {
  2013. if (!props.type) cols[col].type = "string";
  2014. });
  2015. // fix props.filter - set true if not set - TODO: allow filter this col?
  2016. $.each(_state.cols, function(col, props) {
  2017. if (props.filter == undefined) props.filter = true;
  2018. });
  2019. if (_state.uniqueCol) {
  2020. //create a unique column definition
  2021. _state.cols["unique"] = {
  2022. column: "unique",
  2023. type: "unique",
  2024. index: -1,
  2025. hidden: true
  2026. };
  2027. }
  2028. _state.colsSorted = Object.keys(_state.cols).sort(function(a, b) {
  2029. return _state.cols[a].index - _state.cols[b].index;
  2030. });
  2031. };
  2032. priv.setStateFilters = function(stateFilters) {
  2033. var newFilterCols = {},
  2034. newSpecialFilters = {};
  2035. $.map(stateFilters, function(fltrProps, fltr) {
  2036. switch (fltr) {
  2037. case 'currSortCol': _state.filters.currSortCol = fltrProps; break;
  2038. case 'currSortFlip': _state.filters.currSortFlip = (fltrProps == 'desc')? true : false; break;
  2039. default:
  2040. if (fltr.substr(0, 2) == 'f_') {
  2041. newFilterCols[fltr.substr(2)] = {
  2042. filter: fltrProps,
  2043. colName: fltr.substr(2)
  2044. };
  2045. }
  2046. else if (fltr.substr(0, 3) == 'sf_') {
  2047. var groupName = fltr.substr(3);
  2048. if (priv.options.specialFilterFunctions.hasOwnProperty(groupName)) {
  2049. newSpecialFilters[groupName] = fltrProps;
  2050. }
  2051. }
  2052. }
  2053. });
  2054. _state.filters.filterCols = newFilterCols;
  2055. _state.specialFilters = newSpecialFilters;
  2056. };
  2057. priv.setStateData = function(pData, skipCols, resetChecked) {
  2058. var data = $.extend(true, {}, pData);
  2059. data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
  2060. _data = data;
  2061. _data.rowsOrg = _data.rows;
  2062. //we might have more/less data now. Recalculate stuff.
  2063. if (_state.page > 1) {
  2064. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  2065. }
  2066. //keep any previously checked rows around?
  2067. if (resetChecked === true || resetChecked === undefined)
  2068. _uniqueCols = {};
  2069. else {
  2070. for (var key in _uniqueCols)
  2071. _uniqueCols[key] = priv.getRow(key);
  2072. }
  2073. if (_state.uniqueCol) {
  2074. //add rows that needs to be pre-checked
  2075. $.each(_data.rows, function(index, row) {
  2076. if (row["checked"] === true)
  2077. _uniqueCols[row[_state.uniqueCol]] = row;
  2078. });
  2079. }
  2080. };
  2081. /*
  2082. sorts the data on the current sorting column
  2083. */
  2084. priv.sort = function() {
  2085. if (!_data.cols[_state.filters.currSortCol]) _state.filters.currSortCol = "";
  2086. if (!_state.filters.currSortCol) return;
  2087. publ.loadPage(0);
  2088. };
  2089. /*
  2090. helper that returns the underlying data by the unique value
  2091. */
  2092. priv.getRow = function(uniqueValue) {
  2093. var row;
  2094. $.each(_data.rowsOrg, function(i, r) {
  2095. if (r[_state.uniqueCol] == uniqueValue) {
  2096. row = r;
  2097. return false;
  2098. }
  2099. });
  2100. return row;
  2101. };
  2102. /*
  2103. when: typing a filter
  2104. what: triggers filtering on the value
  2105. */
  2106. priv.filterChanged = function(e) {
  2107. //clear old timer if we're typing fast enough
  2108. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?>');
  2109. if (_filterTimeout) {
  2110. clearTimeout(_filterTimeout);
  2111. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?> previous filtering cancelled');
  2112. }
  2113. var filter = this.value
  2114. , fltr = $(this)
  2115. , col = _data.cols[e.data.column]
  2116. , timeout = 300;
  2117. if (this.value) {
  2118. if (!fltr.hasClass('filter-active')) {
  2119. fltr.addClass('filter-active');
  2120. }
  2121. } else {
  2122. if (fltr.hasClass('filter-active')) {
  2123. fltr.removeClass('filter-active');
  2124. }
  2125. }
  2126. //boolean filters needs some special care
  2127. if (col.type == "bool" || col.type == "unique") {
  2128. timeout = 0;
  2129. var elem = $(this);
  2130. var cssClass = 'indeterminate';
  2131. if (elem.hasClass(cssClass)) {
  2132. e.preventDefault();
  2133. elem.removeClass(cssClass);
  2134. filter = true;
  2135. } else {
  2136. if (!elem.is(':checked')) {
  2137. filter = false;
  2138. } else {
  2139. elem.addClass(cssClass);
  2140. filter = '';
  2141. }
  2142. }
  2143. }
  2144. //add the filter to the filter array
  2145. _state.filters.filterCols[col.column] = {
  2146. filter: filter,
  2147. colName: col.column
  2148. };
  2149. //wait a few deciseconds before filtering
  2150. _filterTimeout = setTimeout(function(filterValue, colName) {
  2151. _state.filters.filterCols[colName] = {
  2152. filter: filterValue,
  2153. colName: colName
  2154. };
  2155. priv.filter();
  2156. }, timeout, filter, col.column);
  2157. };
  2158. priv.filtersClean = function(e) {
  2159. if (_filterTimeout) {
  2160. clearTimeout(_filterTimeout);
  2161. if (priv.options.debug) console.log('filtering cancelled - filtersClean');
  2162. }
  2163. var filtersActive = false;
  2164. $.map(_state.filters.filterCols, function(colProps, col) {
  2165. if (colProps.filter.length > 0) {
  2166. filtersActive = true;
  2167. colProps.filter = '';
  2168. }
  2169. });
  2170. if (filtersActive) {
  2171. // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
  2172. /// TODO: rerender _head (thead.filter)
  2173. var elems = _uiNode$Table.find('thead').find('.filter').find('input');
  2174. elems.val('').prop('disabled', false);
  2175. elems.removeClass('filter-active');
  2176. priv.filter();
  2177. }
  2178. return false;
  2179. },
  2180. /**
  2181. * Filters the data.
  2182. */
  2183. priv.filter = function() {
  2184. if (!priv.options.filter) return;
  2185. if (Object.keys(_state.filters.filterCols).length == 0) return;
  2186. priv.loadPage(0);
  2187. };
  2188. /**
  2189. * Filters the data by specialFilter.
  2190. * when: click on special filter
  2191. * what: triggers filtering on the value
  2192. */
  2193. priv.specialFilterChanged = function(e) {
  2194. if (priv.options.debug) console.log('specialFilterChanged e.data:', e.data);
  2195. var state = {};
  2196. state.specialFilters = _state.specialFilters;
  2197. state.specialFilters[e.data.group] = e.data.value;
  2198. priv.setState(state);
  2199. publ.loadPage(0);
  2200. };
  2201. priv.longTextChanged = function(e) {
  2202. priv.options.longDesc = !priv.options.longDesc;
  2203. _bodyNode.find('td').each(function(ind, el){
  2204. var $el = jQuery(el);
  2205. if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
  2206. //console.log(el.attr('class') + ': ' + el.text());
  2207. if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
  2208. if (priv.options.longDesc) {
  2209. $el.addClass('tbl-short-txt');
  2210. var $elSpan = jQuery(el.firstChild);
  2211. $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
  2212. } else {
  2213. $el.removeClass('tbl-short-txt');
  2214. }
  2215. }
  2216. }
  2217. });
  2218. return false;
  2219. };
  2220. priv.mapEditorHide = function() {
  2221. priv.options.mapEditor = false;
  2222. if ('window' == priv.options.mapEditorContainer) {
  2223. //_mapEditorDialog.dialog("close");
  2224. _mapEditorDialog.dialog("destroy");
  2225. }
  2226. _mapEditorWrap.hide();
  2227. _mapEditor.hide();
  2228. };
  2229. priv.mapEditorShow = function() {
  2230. //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
  2231. priv.options.mapEditor = true;
  2232. _mapEditor.show();
  2233. _mapEditorWrap.show();
  2234. _mapEditor.TableAjaxMap({
  2235. //debug: true,
  2236. wpsUrl: 'http://biuro.biall-net.pl/wps',
  2237. wfsUrl: 'http://biuro.biall-net.pl/wps',
  2238. showAddLayerWidget: <?php echo ($this->hasAdditionalLayers())? 'true' : 'false'; ?>,
  2239. zoomStrategyActivate: 14,
  2240. layerName: '<?php echo $this->getLabelHtml(); ?>',
  2241. addBtn: {
  2242. title: 'Przenieś mapę do okna',
  2243. displayClass: 'mapEditor-btnBackToWindow',
  2244. trigger: function() {
  2245. priv.mapEditorHide();
  2246. priv.options.mapEditorContainer = 'window';
  2247. priv.mapEditorShow();
  2248. priv.resizableMapDockNode('destroy');
  2249. }
  2250. },
  2251. onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
  2252. if (priv.options.debug) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
  2253. if (!selectedRecordId) {
  2254. alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
  2255. return;
  2256. }
  2257. function notifyAjaxCallback(data) {
  2258. var notify = {};
  2259. notify.type = (data && data.type)? data.type : '';
  2260. notify.msg = (data && data.msg)? data.msg : '';
  2261. switch (notify.type) {
  2262. case 'success':
  2263. if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
  2264. break;
  2265. case 'info':
  2266. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  2267. break;
  2268. case 'error':
  2269. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2270. break;
  2271. case 'warning':
  2272. notify.type = 'warn';
  2273. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2274. break;
  2275. default:
  2276. notify.msg = 'Nieznany błąd';
  2277. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2278. notify.type = '';
  2279. }
  2280. jQuery.notify(notify.msg, notify.type);
  2281. }
  2282. $.ajax({
  2283. data: {polygon: selectedFeatureExtent},
  2284. dataType: 'json',
  2285. type: "POST",
  2286. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
  2287. })
  2288. .done(function(data, textStatus, jqXHR){
  2289. notifyAjaxCallback(data);
  2290. //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
  2291. publ.loadPage(0);// TODO: reload table data
  2292. })
  2293. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2294. if (jqXHR.responseJSON) {
  2295. notifyAjaxCallback(jqXHR.responseJSON);
  2296. }
  2297. else {
  2298. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2299. if (jqXHR.status == 404) {
  2300. jQuery.notify(jqXHR.responseText, 'error');
  2301. } else {
  2302. jQuery.notify(jqXHR.responseText, 'warn');
  2303. }
  2304. }
  2305. });
  2306. },
  2307. onSelectBox: function(bounds) {
  2308. if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
  2309. var column = 'the_geom';
  2310. if (undefined !== _filterFields['the_geom']) {
  2311. var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
  2312. _filterFields[column].val(filter);
  2313. _state.filters.filterCols[column] = {
  2314. filter: filter,
  2315. colName: column
  2316. };
  2317. priv.filter();
  2318. }
  2319. }
  2320. }
  2321. });
  2322. priv.mapEditorShowElement();
  2323. };
  2324. priv.mapEditorShowElement = function() {
  2325. if ('window' == priv.options.mapEditorContainer) {
  2326. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2327. if (!mapEditor || !mapEditor.length) {
  2328. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2329. var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
  2330. if (!mapEditor || !mapEditor.length) {
  2331. // TODO: create new map
  2332. }
  2333. _mapEditorWrap.append(mapEditor);
  2334. }
  2335. _mapEditorWrap.css({padding:'5px'});
  2336. _mapEditorDialog = _mapEditorWrap.dialog({
  2337. width: 540,
  2338. minWidth: 400,
  2339. minHeight: 400,
  2340. open: function(e, ui) {
  2341. var n = jQuery(this),
  2342. mapWrap = n.children(":first"),
  2343. map = mapWrap.children(":first");
  2344. map.css({width: n.width() - 5, height: n.height() - 5});
  2345. _mapEditor.TableAjaxMapUpdateSize();
  2346. },
  2347. resizeStart: function(e, ui) {
  2348. jQuery(this).children(":first").children(":first").css({display:'none'});
  2349. },
  2350. resizeStop: function(e, ui){
  2351. var n = jQuery(this),
  2352. map = n.children(":first").children(":first");
  2353. n.css({width: n.parent().width()});
  2354. map.css({display: 'block', height: n.height(), width: n.width()});
  2355. _mapEditor.TableAjaxMapUpdateSize();
  2356. },
  2357. dragStop: function(e, ui){
  2358. _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
  2359. }
  2360. });
  2361. _mapEditorWrap.bind('dialogclose', function(e) {
  2362. priv.options.mapEditor = false;
  2363. });
  2364. var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
  2365. var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
  2366. if (dialogTitleBarCloseBtn) {
  2367. 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>');
  2368. btnToggle.on('click', function(e) {
  2369. priv.options.mapEditorContainer = 'dock';
  2370. _mapEditorWrap.dialog('close');
  2371. priv.mapEditorShowElement();
  2372. });
  2373. btnToggle.insertBefore(dialogTitleBarCloseBtn);
  2374. }
  2375. }
  2376. else if ('dock' == priv.options.mapEditorContainer) {
  2377. priv.resizableMapDockNode('prepare');
  2378. _mapEditor.TableAjaxMapUpdateSize();
  2379. }
  2380. };
  2381. priv.resizableMapDockNode = function(task) {
  2382. if ('prepare' == task) {
  2383. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2384. if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
  2385. var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
  2386. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2387. tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
  2388. var breadcrumb = tblCont.children('.breadcrumb');
  2389. if (!breadcrumb || !breadcrumb.length) {
  2390. tblCont.prepend(mapDockNode);
  2391. } else {
  2392. mapDockNode.insertAfter(breadcrumb);
  2393. }
  2394. mapDockNode.append(mapEditor);
  2395. }
  2396. var mapDockResizable = mapEditor.parent();
  2397. mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
  2398. var resizeLineHeigth = 6;
  2399. mapDockResizable.children(":first").css({height: 'auto'});
  2400. mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
  2401. mapEditor.css({marginBottom: resizeLineHeigth+'px'});
  2402. mapEditor.children(":first").css({width: mapEditor.width()});
  2403. mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
  2404. mapDockResizable.on('resizestart', function(event, ui) {
  2405. ui.element.children(":first").children(":first").css({display:'none'})
  2406. });
  2407. mapDockResizable.on('resizestop', function(event, ui) {
  2408. ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
  2409. });
  2410. } else if ('destroy' == task) {
  2411. var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
  2412. mapDockResizable.resizable('destroy');
  2413. mapDockResizable.remove();
  2414. }
  2415. };
  2416. priv.mapEditorChanged = function(e) {
  2417. if (priv.options.debug) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
  2418. priv.options.mapEditor = !priv.options.mapEditor;
  2419. if (priv.options.mapEditor) {
  2420. priv.mapEditorShow();
  2421. }
  2422. else {
  2423. priv.mapEditorHide();
  2424. }
  2425. return false;
  2426. };
  2427. /*
  2428. when: changing page in pager
  2429. what: triggers table to be created with new page
  2430. */
  2431. priv.pageChanged = function(e) {
  2432. e.preventDefault();
  2433. var totalPages = Math.ceil(_data.total / _state.pageSize);
  2434. if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
  2435. //set the new page
  2436. _state.page = e.data.pageIndex;
  2437. publ.loadPage(_state.page);
  2438. };
  2439. /*
  2440. when: changing pagesize in pagesize dropdown
  2441. what: triggers table to be created with new pagesize
  2442. */
  2443. priv.pageSizeChanged = function(e) {
  2444. e.preventDefault();
  2445. var val = $(this).text();
  2446. if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
  2447. if (parseInt(val) == priv.options.pageSize) {
  2448. return false;
  2449. }
  2450. priv.options.pageSize = parseInt(val);
  2451. publ.loadPage(1, priv.options.pageSize);
  2452. jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
  2453. priv.saveProfilePageSize(priv.options.pageSize);
  2454. };
  2455. /*
  2456. when: clicking a column
  2457. what: triggers table to be sorted by the column
  2458. */
  2459. priv.columnClicked = function(e) {
  2460. e.preventDefault();
  2461. if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
  2462. //set the new sorting column
  2463. if (_state.filters.currSortCol == e.data.column) _state.filters.currSortFlip = !_state.filters.currSortFlip;
  2464. _state.filters.currSortCol = e.data.column;
  2465. /// TODO: var state = {}; state.currSortCol = ''; state.currSortFlip = ''; priv.setState(state);
  2466. _headSort = undefined;
  2467. _body = undefined;
  2468. priv.sort();
  2469. };
  2470. priv.saveProfilePageSize = function(pageSize) {
  2471. var reqData = {};
  2472. reqData.pageSize = pageSize;
  2473. $.ajax({
  2474. data: reqData,
  2475. type: "POST",
  2476. dataType: 'json',
  2477. // async: true,
  2478. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PAGE_SIZE_SAVE'
  2479. })
  2480. .done(function(data, textStatus, jqXHR){
  2481. if (data && data.type && data.type == 'info') {
  2482. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2483. } else {
  2484. jQuery.notify('Zapisano ustawienia', 'success');
  2485. }
  2486. })
  2487. .fail(function(){
  2488. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2489. });
  2490. };
  2491. priv.saveHiddenCols = function() {
  2492. var reqData = {};
  2493. $.each(_data.cols, function(col, props) {
  2494. if (props.type != "unique" && col != 'unique' && col != 'ID') {
  2495. reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
  2496. }
  2497. });
  2498. $.ajax({
  2499. data: reqData,
  2500. type: "POST",
  2501. dataType: 'json',
  2502. // async: true,
  2503. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
  2504. })
  2505. .done(function(data, textStatus, jqXHR){
  2506. if (data && data.type && data.type == 'info') {
  2507. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2508. } else {
  2509. jQuery.notify('Zapisano ustawienia', 'success');
  2510. }
  2511. })
  2512. .fail(function(){
  2513. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2514. });
  2515. };
  2516. /*
  2517. when: clicking a column in columnpicker
  2518. what: triggers table to show/hide the column
  2519. */
  2520. priv.columnPickerClicked = function(e) {
  2521. e.stopPropagation();
  2522. var column = $(this).val();
  2523. //toggle column visibility
  2524. priv.modelColFilter_toggleColumn(column);
  2525. priv.saveHiddenCols();
  2526. //_data.cols[column].index = new priv.ext.XDate();
  2527. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2528. };
  2529. priv.modelColFilter_init = function() {// run only once, set _state._modelColFilter {selected, filters: [ {name, label, visibleCols} ]}
  2530. var isAllSelected = true;
  2531. if (undefined === _state._modelColFilter) {
  2532. var columnFilters = [];
  2533. {
  2534. var fltrAll = {'name': 'all', 'label': 'Wszystkie', visibleCols: []};
  2535. $.each(_data.cols, function(col, props) {
  2536. if ("unique" == props.type) return;
  2537. fltrAll.visibleCols.push(col);
  2538. if (_data.cols[col].hidden) isAllSelected = false;
  2539. });
  2540. columnFilters.push(fltrAll);
  2541. }
  2542. // {
  2543. // var fltrMostUsed = {'name': 'most_used', 'label': 'Najczęściej używane', visibleCols: []};
  2544. // var fltrMostUsedLimit = 10;
  2545. // $.each(_data.cols, function(col, props) {
  2546. // if ("unique" == props.type) return;
  2547. // if (fltrMostUsedLimit-- > 0) {
  2548. // fltrMostUsed.visibleCols.push(col);
  2549. // }
  2550. // });
  2551. // columnFilters.push(fltrMostUsed);
  2552. // }
  2553. _state._modelColFilter = {
  2554. selected: (isAllSelected)? 'all' : null,
  2555. filters: columnFilters,
  2556. saveBtn: $('<button class="btn btn-xs btn-primary" disabled="disabled">Zapisz widoczne kolumny</button>')
  2557. };
  2558. _state._modelColFilter.saveBtn.on('click', priv.modelColFilter_saveBtnClicked)
  2559. fetch('<?= Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=getUserTableFilterAjax" ?>', {
  2560. method: 'POST',
  2561. headers: {
  2562. 'Content-Type': 'application/json'
  2563. },
  2564. credentials: 'same-origin',// add cookies
  2565. body: JSON.stringify({
  2566. namespace: '<?= $acl->getNamespace(); ?>',
  2567. })
  2568. }).then(function (response) {
  2569. return response.json()
  2570. }).then(function (result) {
  2571. if ('success' == result.type) {
  2572. // p5UI__notifyAjaxCallback(result)
  2573. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  2574. return ('all' === filter.name || 'most_used' == filter.name)
  2575. }).concat(Object.keys(result.data).map(function (fltr) {
  2576. return {
  2577. name: fltr,
  2578. label: fltr,
  2579. visibleCols: result.data[fltr].split(',')
  2580. }
  2581. }))
  2582. jQuery(_uiNodeCont).trigger('TableAjax:render', ['foot__columnPicker']);
  2583. } else {
  2584. p5UI__notifyAjaxCallback(result)
  2585. }
  2586. }).catch(function (e) {
  2587. // TODO: show error ("ajax response error: " + e)
  2588. });
  2589. }
  2590. };
  2591. priv.modelColFilter_saveBtnClicked = function (e) {
  2592. swal({
  2593. title: 'Zapisz widoczne kolumny',
  2594. html: '',
  2595. animation: true,
  2596. input: 'text',
  2597. inputPlaceholder: 'nazwa filtra',
  2598. // inputValue: null,
  2599. // inputAttributes: {'step': '0.01'},
  2600. showCancelButton: true,
  2601. confirmButtonText: 'Zapisz',
  2602. showLoaderOnConfirm: true,
  2603. showCloseButton: true,
  2604. preConfirm: function(filtrName) {
  2605. return new Promise(function(resolve, reject) {
  2606. if (!filtrName) reject('Proszę podać nazwę filtra')
  2607. if (filtrName.length > 255) reject('Nazwa za długa')
  2608. fetch('<?= Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=addUserTableFilterAjax" ?>', {
  2609. method: 'POST',
  2610. headers: {
  2611. 'Content-Type': 'application/json'
  2612. },
  2613. credentials: 'same-origin',// add cookies
  2614. body: JSON.stringify({
  2615. namespace: '<?= $acl->getNamespace(); ?>',
  2616. filtrName: filtrName,
  2617. visibleCols: Object.keys(_data.cols).filter(function(col) {
  2618. return !_data.cols[col].hidden
  2619. }).join(','),
  2620. })
  2621. }).then(function (response) {
  2622. return response.json()
  2623. }).then(function (result) {
  2624. if ('success' == result.type) {
  2625. p5UI__notifyAjaxCallback(result)
  2626. resolve(result.data)
  2627. } else {
  2628. p5UI__notifyAjaxCallback(result)
  2629. reject(result.msg || "Wystąpił błąd!")
  2630. }
  2631. }).catch(function (e) {
  2632. reject("ajax response error: " + e)
  2633. });
  2634. })
  2635. },
  2636. allowOutsideClick: false
  2637. }).then(function(userTableFilters) {
  2638. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  2639. return ('all' === filter.name || 'most_used' == filter.name)
  2640. }).concat(Object.keys(userTableFilters).map(function (fltr) {
  2641. return {
  2642. name: fltr,
  2643. label: fltr,
  2644. visibleCols: userTableFilters[fltr].split(',')
  2645. }
  2646. }))
  2647. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2648. }).catch(function(e) {
  2649. // eg. hit Cancel
  2650. })
  2651. }
  2652. priv.modelColFilter_getSaveBtn = function () {
  2653. priv.modelColFilter_init();
  2654. return _state._modelColFilter.saveBtn
  2655. }
  2656. priv.modelColFilter_getFilters = function() {
  2657. priv.modelColFilter_init();
  2658. return _state._modelColFilter.filters;
  2659. };
  2660. priv.modelColFilter_getSelected = function() {
  2661. priv.modelColFilter_init();
  2662. return _state._modelColFilter.selected;
  2663. };
  2664. priv.modelColFilter_setFilter = function(filterKey) {
  2665. priv.modelColFilter_init();
  2666. _state._modelColFilter.selected = filterKey;
  2667. priv.modelColFilter_uiUncheckAllColFilters();
  2668. priv.modelColFilter_uiCheckColFilter(filterKey);
  2669. };
  2670. priv.modelColFilter_toggleColumn = function(column, value) {
  2671. priv.modelColFilter_init();
  2672. _state._modelColFilter.selected = null;
  2673. if (!_data.cols[column] || !_data.cols[column]) return;
  2674. _data.cols[column].hidden = (undefined !== value)? value : !_data.cols[column].hidden;
  2675. priv.modelColFilter_uiUncheckAllColFilters();
  2676. {
  2677. var isAllSelected = true;
  2678. $.each(_data.cols, function(col, props) {
  2679. if ("unique" == props.type) return;
  2680. if (_data.cols[col].hidden) isAllSelected = false;
  2681. });
  2682. if (isAllSelected) {
  2683. _state._modelColFilter.selected = 'all';
  2684. priv.modelColFilter_uiCheckColFilter('all');
  2685. }
  2686. }
  2687. };
  2688. priv.modelColFilter_uiUncheckAllColFilters = function() {
  2689. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2690. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2691. ;
  2692. currentNode.find('input[type="radio"]').prop("checked", false);
  2693. };
  2694. priv.modelColFilter_uiCheckColFilter = function(filterKey) {
  2695. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2696. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  2697. ;
  2698. currentNode.find('input[type="radio"]').each(function(idx, input) {
  2699. var input$ = jQuery(input);
  2700. if (filterKey == jQuery(input$).parent().data('col_filter')) {
  2701. input$.prop("checked", true);
  2702. } else {
  2703. input$.prop("checked", false);
  2704. }
  2705. });
  2706. };
  2707. priv.columnPickerLinkClicked = function(e) {
  2708. e.stopPropagation();
  2709. var input$ = $(this).find('input'),
  2710. col_filter = $(this).data('col_filter'),
  2711. columnFilters = priv.modelColFilter_getFilters()
  2712. ;
  2713. if (col_filter) {
  2714. var filter = null;
  2715. $.each(columnFilters, function(idx, colFltr) {
  2716. if (col_filter == colFltr.name) {
  2717. filter = colFltr;
  2718. }
  2719. });
  2720. if (!filter) return;
  2721. $.each(_data.cols, function(col, props) {
  2722. var isHidden = (-1 === filter.visibleCols.indexOf(col));
  2723. priv.modelColFilter_toggleColumn(col, isHidden);
  2724. });
  2725. priv.modelColFilter_setFilter(col_filter);
  2726. priv.saveHiddenCols();
  2727. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2728. } else {
  2729. e.preventDefault();
  2730. if (input$.length != 1) return;
  2731. var column = input$.val();
  2732. if (!column) return;
  2733. //toggle column visibility
  2734. priv.modelColFilter_toggleColumn(column);
  2735. input$.prop("checked", !input$.is(':checked'));// update view
  2736. priv.saveHiddenCols();
  2737. //_data.cols[column].index = new priv.ext.XDate();
  2738. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2739. }
  2740. };
  2741. priv.columnHideClicked = function(e) {
  2742. e.stopPropagation();
  2743. var column;
  2744. if (e.data && e.data.column) {
  2745. column = e.data.column;
  2746. } else {
  2747. return;
  2748. }
  2749. //toggle column visibility
  2750. priv.modelColFilter_toggleColumn(column);
  2751. priv.saveHiddenCols();
  2752. //_data.cols[column].index = new priv.ext.XDate();
  2753. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2754. };
  2755. /*
  2756. when: clicking a row checkbox
  2757. what: toggles checked state on row, and add/removes it from checked array
  2758. */
  2759. priv.rowChecked = function(e) {
  2760. var elem = $(this);
  2761. //get the row's unique value
  2762. var unique = elem.closest('tr').data('unique');
  2763. if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
  2764. //store the row in checked array
  2765. if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
  2766. else delete _uniqueCols[unique];
  2767. };
  2768. /*
  2769. when: clicking anywhere on a row
  2770. what: row data and other info is returned to caller
  2771. */
  2772. // priv.rowClicked = function(e) {// TODO: not used
  2773. // if (!_state.uniqueCol) {
  2774. // if (priv.options.debug) console.log('no unique column specified');
  2775. // return;
  2776. // }
  2777. // //gather callback data
  2778. // var elem = $(this);
  2779. // var column = _data.cols[elem.data('column')];
  2780. // var unique = elem.closest('tr').data('unique');
  2781. // var row = priv.getRow(unique);
  2782. // var isChecked = elem.closest('tr').find('.unique').is(':checked');
  2783. // //trigger callback
  2784. // if (typeof priv.options.rowClicked == 'function') {
  2785. // priv.options.rowClicked.call(e.target, {
  2786. // event: e,
  2787. // row: row,
  2788. // column: column,
  2789. // checked: isChecked
  2790. // });
  2791. // }
  2792. // };
  2793. /**
  2794. * Inline edit.
  2795. */
  2796. priv.rowDblClicked = function(e) {
  2797. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  2798. // hide popover for typespecial fld on click
  2799. if (_popoverCellCurrent) {
  2800. _popoverCellCurrent.popover('hide');
  2801. }
  2802. // e.clientX: 1002; e.clientY: 245
  2803. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2804. inlineEditBox$Node.modal();
  2805. inlineEditBox$Node.show();
  2806. inlineEditBox$Node.on('shown.bs.modal', function(e) {
  2807. var dialogBox = jQuery(this).find('.modal-dialog'),
  2808. modalBody = dialogBox.find('.modal-body'),
  2809. boudingRect = dialogBox.get(0).getBoundingClientRect();
  2810. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  2811. modalBody.css({overflow: 'scroll'});
  2812. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  2813. dialogBox.draggable({handle: '.modal-header'});
  2814. });
  2815. inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  2816. var dialogBox = jQuery(this).find('.modal-dialog'),
  2817. modalBody = dialogBox.find('.modal-body');
  2818. dialogBox.removeAttr('style');
  2819. modalBody.removeAttr('style');
  2820. modalBody.css({padding: '0'});
  2821. dialogBox.resizable();
  2822. dialogBox.draggable();
  2823. dialogBox.resizable('destroy');
  2824. dialogBox.draggable('destroy');
  2825. });
  2826. inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  2827. inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  2828. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  2829. $.ajax({
  2830. 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,
  2831. type: 'GET',
  2832. dataType: 'json',
  2833. success: function(data) {
  2834. if ('p5:www_link' == _.get(data, 'simpleType')) {
  2835. inlineEditBox$Node.find('.inlineEditBox-cnt').empty();
  2836. var label = jQuery('<label>');// for="' + data.htmlFieldName + '">');// "<label for="f22579" class="AjaxTableEdit-label"> ... </label>
  2837. label.attr('for', data.htmlFieldName);
  2838. label.attr('class', 'AjaxTableEdit-label');
  2839. inlineEditBox$Node.find('.inlineEditBox-cnt').append(label);
  2840. var inLabel = jQuery('<strong title="[' + data.idZasob + '] ' + data.fieldLabel + '">' + data.fieldLabel + '</strong>');
  2841. label.append(inLabel);
  2842. var frmItem = jQuery('<input>');
  2843. frmItem.attr('type', 'text');
  2844. frmItem.attr('name', data.htmlFieldName);
  2845. frmItem.attr('value', data.formItem.value);
  2846. frmItem.attr('maxlength', _.get(data, 'restrictions.maxLength', 255));
  2847. frmItem.attr('style', 'width:98%');
  2848. frmItem.attr('class', 'form-control');
  2849. frmItem.insertAfter(label);
  2850. } else {
  2851. var content = _.get(data, 'legacy_html', "Nieznany błąd");
  2852. inlineEditBox$Node.find('.inlineEditBox-cnt').html(content);
  2853. }
  2854. inlineEditBox$Node.find('.btn-save').show();
  2855. initDateTimePicker(inlineEditBox$Node);
  2856. inlineEditBox$Node.find('textarea').autosize();
  2857. var fld = inlineEditBox$Node.find('input[name^="f"]');
  2858. if (fld.length > 0 && !fld.hasClass('se_type-date')) {
  2859. fld.keydown(function(event) {
  2860. if (event.which == 13) {
  2861. event.preventDefault();
  2862. inlineEditBox$Node.find('form').submit();
  2863. }
  2864. });
  2865. }
  2866. (function setFocusAtFirstInlineEditFormFld(modal$node){
  2867. var fld, dbg = false;
  2868. if(dbg)console.log('focus...');
  2869. fld = modal$node.find('input[name^="f"]:first');
  2870. if (fld.length > 0 && !fld.hasClass('se_type-date')) {
  2871. if(dbg)console.log('set focus to first input element');
  2872. fld.focus(); return;
  2873. }
  2874. fld = modal$node.find('select[name^="f"]:first');
  2875. if (fld.length) {
  2876. if (fld.get(0).selectize) {
  2877. if(dbg)console.log('set focus to first typepecial element');
  2878. } else {
  2879. if(dbg)console.log('set focus to first select element');
  2880. fld.focus(); return;
  2881. }
  2882. }
  2883. if(dbg)console.log('set focus to close btn');
  2884. modal$node.find('.btn-close').focus();
  2885. })(inlineEditBox$Node);
  2886. },
  2887. error: function(err) {
  2888. if (priv.options.debug) console.log('err');
  2889. }
  2890. });
  2891. } else {
  2892. if (priv.options.debug) console.log('NO data');
  2893. return false;
  2894. }
  2895. };
  2896. priv.ajaxLoadTypeSpeciallCell = function(id, col) {
  2897. if (_popoverCellAjaxXhr) {
  2898. _popoverCellAjaxXhr.abort();
  2899. }
  2900. _popoverCellAjaxXhr = $.ajax({
  2901. type: 'GET',
  2902. url: 'index.php?_route=ViewTableAjax&_task=typeSpecialCell&namespace=<?= $acl->getNamespace(); ?>' + '&ID=' + id + '&col=' + col,
  2903. dataType: 'json',
  2904. contentType: "application/json; charset=utf-8",
  2905. data: '',
  2906. success: function(req){
  2907. if (_.get(req, 'data.tbl_id') > 0) {
  2908. var addHtml = '';
  2909. for (var i in req.data.items) {
  2910. var url = 'index.php?_route=ViewTableAjax';
  2911. url += '&namespace=' + req.namespace;
  2912. url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
  2913. url += '&_hash=' + Math.random().toString(36).substring(2);
  2914. addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
  2915. addHtml += '<br>';
  2916. }
  2917. //_popoverCell.append(addHtml);// cache
  2918. if (_popoverCellCurrent) {
  2919. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  2920. if (popoverNodeId) {
  2921. jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
  2922. }
  2923. }
  2924. }
  2925. }
  2926. });
  2927. };
  2928. priv.popoverCellTypeSpecial = function(e) {
  2929. e.preventDefault();
  2930. e.stopPropagation();
  2931. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2932. var lastId = _popoverCell.data('rowid'),
  2933. lastCol = _popoverCell.data('col'),
  2934. rowPK = e.data.id,
  2935. colName = e.data.col
  2936. ;
  2937. if (lastId == rowPK && lastCol == colName) {
  2938. //_popoverCellCurrent.popover('toggle');
  2939. }
  2940. else {
  2941. if (_popoverCellCurrent) {
  2942. _popoverCellCurrent.popover('destroy');
  2943. }
  2944. _popoverCell.data('rowid', rowPK);
  2945. _popoverCell.data('col', colName);
  2946. _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
  2947. _popoverCellCurrent = jQuery(e.currentTarget);
  2948. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  2949. var opts = {
  2950. placement: 'left'
  2951. , trigger: 'click'
  2952. // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
  2953. , 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>'
  2954. , html: true
  2955. , content: _popoverCell.html()
  2956. }
  2957. _popoverCellCurrent.popover(opts);
  2958. if (_data.cols[colName]) {
  2959. if (_data.cols[colName]._tsRetId > 0) {
  2960. _popoverCellCurrent.on('shown.bs.popover', function() {
  2961. priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
  2962. });
  2963. }
  2964. }
  2965. _popoverCellCurrent.popover('show');
  2966. }
  2967. } else {
  2968. if (priv.options.debug) console.log('NO data');
  2969. return false;
  2970. }
  2971. return;
  2972. };
  2973. priv.routeChanged = function(e) {
  2974. hash = e.data.hash || '';
  2975. if (hash.length == 0) {
  2976. return;
  2977. }
  2978. if (hash.substring(0, 1) != '#') {
  2979. hash = '#' + hash;
  2980. }
  2981. location.hash = hash;
  2982. };
  2983. priv.refresh = function(e) {
  2984. e.preventDefault();
  2985. publ.loadPage(_state.page);
  2986. };
  2987. publ.init = function(options) {
  2988. if (priv.options.debug) console.log('TableAjax initialization...');
  2989. //merge supplied options with defaults
  2990. $.extend(priv.options, defaults, options);
  2991. priv.init();
  2992. return publ;
  2993. };
  2994. publ.refresh = function() {
  2995. publ.loadPage(_state.page);
  2996. };
  2997. publ.loadPage = function(page, pageSize) {
  2998. priv.loadPage(page, pageSize);
  2999. }
  3000. priv.loadPage = function(page, pageSize) {
  3001. var skipCols = true, // skipCols = true - prevent columns delete
  3002. resetChecked = false;
  3003. var reqData = {
  3004. page: page,
  3005. pageSize: (pageSize || priv.options.pageSize),
  3006. currSortCol: (_state.filters.currSortCol || ''),
  3007. currSortFlip: _state.filters.currSortFlip ? "desc" : "asc"
  3008. };
  3009. var urlAdd = '';
  3010. urlAdd += '&page=' + page;
  3011. urlAdd += '&pageSize=' + (pageSize || priv.options.pageSize);
  3012. urlAdd += '&currSortCol=' + (_state.filters.currSortCol || '');
  3013. urlAdd += '&currSortFlip=' + (_state.filters.currSortFlip ? "desc" : "asc");
  3014. if (Object.keys(_state.filters.filterCols).length > 0) {
  3015. $.each(_state.filters.filterCols, function(col, colProps) {
  3016. if (colProps.filter && colProps.filter.length > 0) {
  3017. urlAdd += '&f_' + col + '=' + colProps.filter;
  3018. }
  3019. });
  3020. skipCols = true;
  3021. }
  3022. // specialFilters
  3023. $.each(_state.specialFilters, function(groupName, btnValue) {
  3024. if (btnValue.length > 0) {
  3025. urlAdd += '&sf_' + groupName + '=' + btnValue;
  3026. }
  3027. });
  3028. if (priv.options.forceFilterInit) {
  3029. $.map(priv.options.forceFilterInit, function(fltrProps, fltr) {
  3030. urlAdd += '&f_' + fltr + '=' + fltrProps;
  3031. filtersInitSet = true;
  3032. });
  3033. }
  3034. _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
  3035. // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych...'});
  3036. fetch(priv.options.url + urlAdd, {
  3037. method: priv.options.urlPost ? 'POST' : 'GET',
  3038. credentials: 'same-origin',// add cookies
  3039. }).then(function (response) {
  3040. return response.json()
  3041. }).then(function (data) {
  3042. if (priv.options.debug) console.log('loadDataAjax:fetch: request finished L.<?php echo __LINE__; ?> data:', data);
  3043. // p5UI__notifyAjaxCallback(data);
  3044. if ('success' == data.type) {
  3045. state = {data: {}};
  3046. if (!skipCols) state.data.cols = data.cols || {};
  3047. state.data.rows = data.rows || [];
  3048. state.data.total = data.total || 0;
  3049. state.page = data.page || 0;
  3050. state.pageSize = data.pageSize || priv.options.pageSize;
  3051. state.filters = data.filters || {};
  3052. priv.setState(state);
  3053. _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
  3054. } else if ('error' == data.type) {
  3055. p5UI__notifyAjaxCallback(data);
  3056. } else {
  3057. p5UI__notifyAjaxCallback(data);
  3058. }
  3059. }).catch(function (e) {
  3060. console.log('loadDataAjax:fetch: ERR:', e);
  3061. });
  3062. };
  3063. publ.getCurrentPage = function() {
  3064. return _state.page;
  3065. };
  3066. publ.popoverCellRemove = function() {
  3067. if (_popoverCellCurrent) {
  3068. _popoverCellCurrent.popover('destroy');
  3069. }
  3070. _popoverCell.data('rowid', -1);
  3071. _popoverCell.data('col', -1);
  3072. _popoverCell.html('');
  3073. };
  3074. return publ;
  3075. }
  3076. $.fn.TableAjax = function(options) {
  3077. options = options || {};
  3078. return this.each(function() {
  3079. options.id = this;
  3080. $(this).data('TableAjax', new TableAjax().init(options));
  3081. });
  3082. };
  3083. $.fn.TableAjaxLoadPage = function(page, pageSize) {
  3084. return this.each(function() {
  3085. var tblAjax = jQuery(this).data('TableAjax');
  3086. var curPage = page || tblAjax.getCurrentPage();
  3087. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  3088. });
  3089. };
  3090. $.fn.TableAjaxRefresh = function(page, pageSize) {
  3091. return this.each(function() {
  3092. var tblAjax = jQuery(this).data('TableAjax');
  3093. if (tblAjax) tblAjax.refresh();
  3094. });
  3095. };
  3096. String.prototype.format = String.prototype.f = function() {
  3097. var s = this;
  3098. i = arguments.length;
  3099. while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
  3100. return s;
  3101. };
  3102. })(jQuery);
  3103. </script>
  3104. <?php
  3105. $filterInit = $this->_filterInit;
  3106. $forceFilterInit = $this->_forceFilterInit;
  3107. $pageSizes = $this->_pageSizes;
  3108. $pageSize = $this->_pageSize;
  3109. $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
  3110. $exportFields = Core_AclHelper::getExportFieldList($acl);
  3111. ?>
  3112. <script>
  3113. function TableAjax__HIST_Route(args) {
  3114. var recordID = args;
  3115. if (typeof args == 'object') {
  3116. recordID = args.shift();
  3117. recordID = parseInt(recordID);
  3118. }
  3119. if (typeof recordID !== 'number' || recordID <= 0) {
  3120. // TODO: msg
  3121. return false;
  3122. }
  3123. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3124. cont.hide();
  3125. // remove previous task content
  3126. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3127. taskCnt.parent().remove();
  3128. taskCnt.remove();
  3129. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3130. jQuery('<ul class="breadcrumb">' +
  3131. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3132. '<li class="active">Historia rekordu</li>' +
  3133. '</ul>').appendTo(taskCont);
  3134. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3135. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3136. $.ajax({
  3137. dataType: 'json',
  3138. type: "GET",
  3139. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
  3140. })
  3141. .done(function(data, textStatus, jqXHR){
  3142. taskCnt.removeClass('AjaxTable-loading');
  3143. <?php if(DBG::isActive() && V::get('DBG', '', $_GET)) : ?>console.log('TODO #L.<?= __LINE__; ?> done loading HIST_AJAX - data:', data);<?php endif; ?>
  3144. histAjaxOut = '<fieldset>' +
  3145. '<legend>' + data['label'] +
  3146. '<span class="pull-right valign-btns-bottom">';
  3147. for (i in data['row_functions']) {
  3148. histAjaxOut += data['row_functions'][i];
  3149. // TODO: fetch more row functions
  3150. }
  3151. histAjaxOut += '</span>' +
  3152. '</legend>'
  3153. '</fieldset>';
  3154. if (!data['rows']) {
  3155. histAjaxOut += '<div class="alert alert-info">' +
  3156. '<h4>Brak danych</h4>' +
  3157. '</div>';
  3158. } else {
  3159. histAjaxOut += '<table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">' +
  3160. '<thead>' +
  3161. '<tr>' +
  3162. '<th>Data</th>' +
  3163. '<th>User</th>' +
  3164. '<th>Zmiany</th>' +
  3165. '</tr>' +
  3166. '</thead>' +
  3167. '<tbody>';
  3168. for (i in data['rows']) {
  3169. var row = data['rows'][i];
  3170. histAjaxOut += '<tr data-id_hist="' + row['ID'] + '">' +
  3171. '<td style="white-space:nowrap">' + row['_created'] + '</td>' +
  3172. '<td>' + row['_author'] + '</td>' +
  3173. '<td>';
  3174. for (j in row['changes']) {
  3175. var change = row['changes'][j];
  3176. var fieldName = change['fieldName'];
  3177. if (['ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'].indexOf(fieldName) >= 0) continue;
  3178. if ('N/S;' == change['value']) continue;
  3179. histAjaxOut += '<p>' +
  3180. '<em>' + (data['field_label'][fieldName] || fieldName) + '</em>: ';
  3181. histAjaxOut += (change['acl_read'])
  3182. ? change['value']
  3183. : '<span title="Brak uprawnień do odczytu tego pola">*****</span>'
  3184. if (change['revert_function_url']) {
  3185. histAjaxOut += ' <button' +
  3186. ' class="btn btn-xs btn-default"' +
  3187. ' onClick="return p5UI__ajaxLinkClick(this, \''+change['revert_function_url']+'\', \''+change['revert_function_data']+'\')"' +
  3188. ' title="Cofnij dane do tej wartości">' +
  3189. '<i class="glyphicon glyphicon-floppy-disk"></i> cofnij' +
  3190. '</button>';
  3191. }
  3192. histAjaxOut += '</p>';
  3193. }
  3194. histAjaxOut += '</td>' +
  3195. '</tr>';
  3196. }
  3197. histAjaxOut += '</tbody>' +
  3198. '</table>';
  3199. }
  3200. {// old view - flat table
  3201. histAjaxOut += '<div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">' +
  3202. '<table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">' +
  3203. '<thead>' +
  3204. '<tr>';
  3205. for (j in data['fields']) {
  3206. var fieldName = data['fields'][j];
  3207. histAjaxOut += '<th>' + (data['field_label'][fieldName] || fieldName).replace('_', ' ') + '</th>';
  3208. }
  3209. histAjaxOut += '</tr>' +
  3210. '</thead>' +
  3211. '<tbody>';
  3212. for (i in data['rows']) {
  3213. var row = data['rows'][i];
  3214. histAjaxOut += '<tr>';
  3215. for (j in data['fields']) {
  3216. var fieldName = data['fields'][j];
  3217. histAjaxOut += '<td>';
  3218. ( (!(fieldName in row['changes']) || row['changes'][fieldName]['value'] == 'N/S;')
  3219. ? histAjaxOut += '<em>N/S;</em>'
  3220. : ( (row['changes'][fieldName]['acl_read'])
  3221. ? histAjaxOut += row['changes'][fieldName]['value']
  3222. : histAjaxOut += '<span title="Brak uprawnień do odczytu tego pola">*****</span>'
  3223. )
  3224. );
  3225. histAjaxOut += '</td>';
  3226. }
  3227. histAjaxOut += '</tr>';
  3228. }
  3229. histAjaxOut += '</tbody>' +
  3230. '</table>' +
  3231. '</div>';
  3232. }
  3233. jQuery(histAjaxOut).appendTo(taskCnt);
  3234. })
  3235. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3236. taskCnt.removeClass('AjaxTable-loading');
  3237. if (jqXHR.responseJSON) {
  3238. notifyAjaxCallback(jqXHR.responseJSON);
  3239. }
  3240. else {
  3241. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3242. if (jqXHR.status == 404) {
  3243. jQuery.notify(jqXHR.responseText, 'error');
  3244. } else {
  3245. jQuery.notify(jqXHR.responseText, 'warn');
  3246. }
  3247. }
  3248. console.log('TODO #L.<?= __LINE__; ?> fail loading HIST_AJAX - jqXHR.responseText:', jqXHR.responseText);
  3249. });
  3250. function notifyAjaxCallback(data) {
  3251. var notify = {};
  3252. notify.type = (data && data.type)? data.type : '';
  3253. notify.msg = (data && data.msg)? data.msg : '';
  3254. switch (notify.type) {
  3255. case 'success':
  3256. if (!notify.msg) notify.msg = 'OK';
  3257. break;
  3258. case 'info':
  3259. if (!notify.msg) notify.msg = '';
  3260. break;
  3261. case 'error':
  3262. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3263. break;
  3264. case 'warning':
  3265. notify.type = 'warn';
  3266. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3267. break;
  3268. default:
  3269. notify.msg = 'Nieznany błąd';
  3270. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3271. notify.type = '';
  3272. }
  3273. jQuery.notify(notify.msg, notify.type);
  3274. }
  3275. //return false;
  3276. }
  3277. </script>
  3278. <script>
  3279. jQuery(document).ready(function(){
  3280. jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
  3281. url: '<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=loadDataAjax',// priv.options.url
  3282. columnPicker: true,
  3283. filter: true,
  3284. filterInit: <?php echo json_encode($filterInit); ?>,
  3285. forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
  3286. debug: false,
  3287. height: 400,
  3288. sorting: true,
  3289. paging: true,
  3290. pageSize: <?php echo $pageSize; ?>,
  3291. pageSizes: <?php echo json_encode($pageSizes); ?>,
  3292. tblFunctions: {
  3293. shortdesc: {
  3294. icon: 'align-left',
  3295. title: 'Long desc',
  3296. method: 'longTextChanged'
  3297. },
  3298. <?php if ($hasGeomFlds) : ?>
  3299. mapeditor: {
  3300. icon: 'map-marker',
  3301. title: 'Mapa',
  3302. method: 'mapEditorChanged'
  3303. },
  3304. <?php endif; ?>
  3305. create: {
  3306. href: '#CREATE',
  3307. icon: 'plus',
  3308. title: 'Dodaj nowy rekord'
  3309. },
  3310. refresh: {
  3311. icon: 'refresh',
  3312. title: 'Odśwież dane',
  3313. method: 'refresh'
  3314. }
  3315. },
  3316. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  3317. exportFields: <?php echo json_encode($exportFields); ?>,
  3318. specialFilterFunctions: <?php
  3319. $fltrs = (method_exists($acl, 'getSpecialFilters')) ? $acl->getSpecialFilters() : null;
  3320. if (!empty($fltrs)) {
  3321. echo json_encode($fltrs);
  3322. } else {
  3323. echo 'false';
  3324. }
  3325. echo ',';
  3326. ?>
  3327. router: function() {
  3328. var routes = {
  3329. EDIT: function(args) {
  3330. var recordID = args;
  3331. if (typeof args == 'object') {
  3332. recordID = args.shift();
  3333. recordID = parseInt(recordID);
  3334. }
  3335. if (typeof recordID !== 'number' || recordID <= 0) {
  3336. // TODO: msg
  3337. return false;
  3338. }
  3339. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3340. cont.hide();
  3341. // remove previous task content
  3342. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3343. taskCnt.parent().remove();
  3344. taskCnt.remove();
  3345. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3346. jQuery('<ul class="breadcrumb">' +
  3347. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3348. '<li class="active">Edytuj rekord</li>' +
  3349. '</ul>').appendTo(taskCont);
  3350. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3351. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3352. jQuery.ajax({
  3353. url: '<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editForm&_primaryKey=' + recordID,
  3354. type: 'GET',
  3355. dataType: 'text',
  3356. data: '',
  3357. async: true,
  3358. success: function(data) {
  3359. taskCnt.removeClass('AjaxTable-loading');
  3360. jQuery(data).appendTo(taskCnt);
  3361. initDateTimePicker(taskCnt);
  3362. },
  3363. error: function(err) {
  3364. taskCnt.removeClass('AjaxTable-loading');
  3365. //console.log('request error: {0}'.f(err));
  3366. }
  3367. });
  3368. //return false;
  3369. },
  3370. HIST: TableAjax__HIST_Route,
  3371. FILES: function tableAjaxFiles(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">Pliki</li>' +
  3391. '</ul>').appendTo(taskCont);
  3392. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  3393. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3394. jQuery.ajax({
  3395. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  3396. type: 'GET',
  3397. dataType: 'text',
  3398. data: '',
  3399. async: true,
  3400. success: function(data) {
  3401. taskCnt.removeClass('AjaxTable-loading');
  3402. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  3403. jQuery(data).appendTo(taskCnt);
  3404. },
  3405. error: function(jqXHR, textStatus, errorThrown) {
  3406. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  3407. taskCnt.removeClass('AjaxTable-loading');
  3408. var txt = jqXHR.responseText || 'Error';
  3409. if (jqXHR.status == 404) {
  3410. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  3411. } else {
  3412. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  3413. }
  3414. }
  3415. });
  3416. //return false;
  3417. },
  3418. CREATE: function tableAjaxCreate() {
  3419. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3420. cont.hide();
  3421. // remove previous task content
  3422. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  3423. taskCnt.parent().remove();
  3424. taskCnt.remove();
  3425. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  3426. jQuery('<ul class="breadcrumb">' +
  3427. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  3428. '<li class="active">Dodaj nowy rekord</li>' +
  3429. '</ul>').appendTo(taskCont);
  3430. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3431. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  3432. var reqData = {};
  3433. var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
  3434. if (forceFilterInit) {
  3435. $.map(forceFilterInit, function(fltrProps, fltr) {
  3436. reqData['ff_' + fltr] = fltrProps;
  3437. });
  3438. }
  3439. jQuery.ajax({
  3440. 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
  3441. // TODO: url: 'index.php?_route=ViewTableAjax&_task=createForm&namespace=<?= $acl->getNamespace(); ?>&_hash=<?php echo $this->_htmlID; ?>',
  3442. type: 'GET',
  3443. dataType: 'text',
  3444. data: reqData,
  3445. async: true,
  3446. success: function(data) {
  3447. taskCnt.removeClass('AjaxTable-loading');
  3448. // console.log('request finished L.<?php echo __LINE__; ?>', data);
  3449. jQuery(data).appendTo(taskCnt);
  3450. initDateTimePicker(taskCnt);
  3451. },
  3452. error: function(err) {
  3453. taskCnt.removeClass('AjaxTable-loading');
  3454. //console.log('request error: {0}'.f(err));
  3455. }
  3456. });
  3457. //return false;
  3458. }
  3459. };
  3460. var routePath = location.hash;
  3461. //console.log('location.hash: ' + routePath);
  3462. if (location.hash == '' || location.hash == '#') {
  3463. return false;
  3464. }
  3465. if (routePath.charAt(0) == '#') {
  3466. routePath = routePath.substr(1);
  3467. }
  3468. //console.log('routePath: ' + routePath);
  3469. var parts = routePath.split('/');
  3470. var task = parts.shift();
  3471. //console.log('task(' + task + ') parts:');
  3472. //console.log(parts);
  3473. if (task in routes && typeof routes[task] == 'function') {
  3474. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3475. if (con) {
  3476. var tblAjax = con.data('TableAjax');
  3477. if (tblAjax) {
  3478. tblAjax.popoverCellRemove();
  3479. }
  3480. }
  3481. routes[task](parts);
  3482. } else {
  3483. return false;
  3484. }
  3485. },
  3486. filtersClean: true,
  3487. longDesc: true
  3488. });
  3489. });
  3490. function tableAjaxBackToTable() {
  3491. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3492. cont.show();
  3493. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  3494. taskCont.remove();
  3495. // reload first page
  3496. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3497. con.TableAjaxLoadPage();// TODO: load current page
  3498. }
  3499. function tableAjaxCopy(args) {
  3500. var recordID = args;
  3501. if (typeof args == 'object') {
  3502. recordID = args.shift();
  3503. recordID = parseInt(recordID);
  3504. }
  3505. if (typeof recordID !== 'number' || recordID <= 0) {
  3506. // TODO: msg
  3507. return false;
  3508. }
  3509. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  3510. return false;
  3511. }
  3512. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  3513. function notifyAjaxCallback(data) {
  3514. var notify = {};
  3515. notify.type = (data && data.type)? data.type : '';
  3516. notify.msg = (data && data.msg)? data.msg : '';
  3517. switch (notify.type) {
  3518. case 'success':
  3519. if (!notify.msg) notify.msg = 'OK';
  3520. break;
  3521. case 'info':
  3522. if (!notify.msg) notify.msg = '';
  3523. break;
  3524. case 'error':
  3525. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3526. break;
  3527. case 'warning':
  3528. notify.type = 'warn';
  3529. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3530. break;
  3531. default:
  3532. notify.msg = 'Nieznany błąd';
  3533. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3534. notify.type = '';
  3535. }
  3536. jQuery.notify(notify.msg, notify.type);
  3537. }
  3538. var reqData = {};
  3539. jQuery.ajax({
  3540. data: reqData,
  3541. dataType: 'json',
  3542. type: "GET",
  3543. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  3544. })
  3545. .done(function(data, textStatus, jqXHR){
  3546. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3547. con.TableAjaxRefresh();
  3548. notifyAjaxCallback(data);
  3549. })
  3550. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3551. if (jqXHR.responseJSON) {
  3552. notifyAjaxCallback(jqXHR.responseJSON);
  3553. }
  3554. else {
  3555. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3556. if (jqXHR.status == 404) {
  3557. jQuery.notify(jqXHR.responseText, 'error');
  3558. } else {
  3559. jQuery.notify(jqXHR.responseText, 'warn');
  3560. }
  3561. }
  3562. });
  3563. return false;
  3564. }
  3565. function hidePopover() {
  3566. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  3567. if (con) {
  3568. var tblAjax = con.data('TableAjax');
  3569. if (tblAjax) {
  3570. tblAjax.popoverCellRemove();
  3571. }
  3572. }
  3573. return false;
  3574. }
  3575. function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
  3576. var $n = jQuery(n);
  3577. var $ul = $n.next();
  3578. if ($n.data('fetched')) return false;
  3579. function parseProcesInitData(pInitData) {
  3580. var procesInitMapHtml = '';
  3581. if (!pInitData) {
  3582. return '<li><a href="#">' + "Brak danych" + '</a></li>';
  3583. } else {
  3584. function _viewProcesInitListItem(pInitId, gotoIds, pInitList) {
  3585. var label = pInitList[pInitId];
  3586. 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;";
  3587. 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}
  3588. out += ' <i class="glyphicon glyphicon-info-sign"';
  3589. out += ' onclick="' + jsInfo + '"';
  3590. out += ' style="color:#aaa;"';
  3591. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3592. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3593. out += " {" + pInitId + "} " + label;
  3594. out += '</a>';
  3595. return out;
  3596. }
  3597. function _viewProcesGotoAndRetListItem(gotoId, pInitList) {
  3598. var label = pInitList[gotoId];
  3599. 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;";
  3600. var out = '';
  3601. 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}
  3602. out += ' <span style="padding:10px;"></span>';
  3603. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3604. out += ' <i class="glyphicon glyphicon-info-sign"';
  3605. out += ' onclick="' + jsInfo + '"';
  3606. out += ' style="color:#aaa;"';
  3607. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3608. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3609. out += " {" + gotoId + "} " + label;
  3610. out += '</a>';
  3611. return out;
  3612. }
  3613. function _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitList) {
  3614. var label = pInitList[gotoLvl2Id];
  3615. 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;";
  3616. var out = '';
  3617. 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}
  3618. out += ' <span style="padding:20px;"></span>';
  3619. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  3620. out += ' <i class="glyphicon glyphicon-info-sign"';
  3621. out += ' onclick="' + jsInfo + '"';
  3622. out += ' style="color:#aaa;"';
  3623. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  3624. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  3625. out += " {" + gotoLvl2Id + "} " + label;
  3626. out += '</a>';
  3627. return out;
  3628. }
  3629. var sel = '',
  3630. liStyle = "white-space:nowrap; overflow:hidden; max-width:500px; /* text-overflow:ellipsis; */";
  3631. $.map(pInitData.mapTree, function(gotoIds, vInitId) {
  3632. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3633. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3634. procesInitMapHtml += _viewProcesInitListItem(vInitId, gotoIds, pInitData.pInitList);
  3635. procesInitMapHtml += '</li>' + "\n";
  3636. $.map(gotoIds, function(gotoLvl2Ids, gotoId) {
  3637. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3638. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3639. procesInitMapHtml += _viewProcesGotoAndRetListItem(gotoId, pInitData.pInitList);
  3640. procesInitMapHtml += '</li>' + "\n";
  3641. $.map(gotoLvl2Ids, function(vBool, gotoLvl2Id) {
  3642. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  3643. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  3644. procesInitMapHtml += _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitData.pInitList);
  3645. procesInitMapHtml += '</li>' + "\n";
  3646. });
  3647. });
  3648. });
  3649. }
  3650. return procesInitMapHtml;
  3651. }
  3652. jQuery.ajax({
  3653. data: null,
  3654. dataType: 'json',
  3655. type: "GET",
  3656. async: true,
  3657. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PROCES_INIT_FILTR',
  3658. })
  3659. .always(function(data, textStatus, jqXHR) {
  3660. var type = data.type || null,
  3661. msg = data.msg || "Error",
  3662. pInitData = data.pInitData || null;
  3663. if (type) {
  3664. if ('success' == type) {
  3665. $ul.html(parseProcesInitData(pInitData));
  3666. } else if ('error' == type) {
  3667. $ul.html('<li><a href="#">' + msg + '</a></li>');
  3668. } else {
  3669. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3670. }
  3671. } else {
  3672. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3673. }
  3674. $n.data('fetched', true);
  3675. });
  3676. return false;
  3677. }
  3678. </script>
  3679. <?php
  3680. UI::setTitle($this->_acl->getRawLabel(100) . " - " . UI::getTitle());
  3681. $out = ob_get_contents();
  3682. ob_end_clean();
  3683. return $out;
  3684. }
  3685. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  3686. $vLabel = $pInitList[$vInitId];
  3687. $kId = $vInitId;
  3688. ?>
  3689. <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}"); ?>">
  3690. <i class="glyphicon glyphicon-info-sign"
  3691. 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;"
  3692. style="color:#aaa;"
  3693. onmouseover="this.style.color='#337AB7'"
  3694. onmouseout="this.style.color='#aaa'"></i>
  3695. <?php echo "{{$kId}} {$vLabel}"; ?>
  3696. </a>
  3697. <?php
  3698. }
  3699. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  3700. $vLabel = $pInitList[$vGotoId];
  3701. $kId = $vGotoId;
  3702. // TODO:?: prevent to execute procedure
  3703. ?>
  3704. <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}"); ?>">
  3705. <span style="padding:10px;"></span>
  3706. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3707. <i class="glyphicon glyphicon-info-sign"
  3708. 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;"
  3709. style="color:#aaa;"
  3710. onmouseover="this.style.color='#337AB7'"
  3711. onmouseout="this.style.color='#aaa'"></i>
  3712. <?php echo "{{$kId}} {$vLabel}"; ?>
  3713. </a>
  3714. <?php
  3715. }
  3716. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  3717. $vLabel = $pInitList[$vGotoLvl2Id];
  3718. $kId = $vGotoLvl2Id;
  3719. // TODO:?: prevent to execute procedure
  3720. ?>
  3721. <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}"); ?>">
  3722. <span style="padding:20px;"></span>
  3723. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3724. <i class="glyphicon glyphicon-info-sign"
  3725. 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;"
  3726. style="color:#aaa;"
  3727. onmouseover="this.style.color='#337AB7'"
  3728. onmouseout="this.style.color='#aaa'"></i>
  3729. <?php echo "{{$kId}} {$vLabel}"; ?>
  3730. </a>
  3731. <?php
  3732. }
  3733. public function hasAdditionalLayers() {
  3734. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  3735. return !empty($layers);
  3736. }
  3737. public function ajaxTask($task) {
  3738. switch ($task) {
  3739. case 'EDIT_INLINE': {
  3740. $this->sendAjaxResponseJson('ajaxInlineEdit', $_REQUEST);
  3741. break;
  3742. }
  3743. case 'EDIT_INLINE_SAVE': {
  3744. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  3745. break;
  3746. }
  3747. case 'COPY': {
  3748. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  3749. break;
  3750. }
  3751. case 'CREATE': {
  3752. $this->sendAjaxCreate($_REQUEST);
  3753. break;
  3754. }
  3755. case 'CREATE_SAVE': {
  3756. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  3757. break;
  3758. }
  3759. case 'HIST': {
  3760. $this->sendAjaxResponseJson('ajaxHist', $_REQUEST);
  3761. break;
  3762. }
  3763. case 'FILES': {
  3764. try {
  3765. $id = V::get('ID', 0, $_REQUEST, 'int');
  3766. if ($id <= 0) throw new HttpException("404", 404);
  3767. $this->sendAjaxFiles($id, $_REQUEST);
  3768. } catch (HttpException $e) {
  3769. Http::sendHeaderByCode($e->getCode());
  3770. echo $e->getMessage();
  3771. //UI::alert('danger', $e->getMessage());
  3772. } catch (Exception $e) {
  3773. echo '<div class="container">';
  3774. UI::alert('danger', $e->getMessage());
  3775. echo '</div>';
  3776. }
  3777. break;
  3778. }
  3779. case 'FILES_UPLOAD': {
  3780. $this->sendAjaxResponseJson('ajaxFileUpload', $_REQUEST);
  3781. break;
  3782. }
  3783. case 'FILES_LIST': {
  3784. $this->sendAjaxResponseJson('ajaxFileList', $_REQUEST);
  3785. break;
  3786. }
  3787. case 'FILE_REMOVE': {
  3788. $args = array();
  3789. $args['ID'] = V::get('ID', '', $_REQUEST);
  3790. $args['filename'] = V::get('filename', '', $_POST);
  3791. $this->sendAjaxResponseJson('ajaxFileRemove', $args);
  3792. break;
  3793. }
  3794. case 'filePermsRefresh': {
  3795. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  3796. break;
  3797. }
  3798. case 'FILES_CONN_TBL_LIST': {
  3799. $id = V::get('ID', 0, $_REQUEST, 'int');
  3800. if ($id > 0) {
  3801. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  3802. } else {
  3803. echo '404';
  3804. }
  3805. break;
  3806. }
  3807. case 'TYPESPECIAL': {
  3808. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  3809. if ($fldID > 0) {
  3810. $this->sendTypeSpecial($fldID, $_REQUEST);
  3811. } else {
  3812. echo '404';
  3813. }
  3814. break;
  3815. }
  3816. case 'HIDDEN_COLS_SAVE': {
  3817. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  3818. break;
  3819. }
  3820. case 'PAGE_SIZE_SAVE': {
  3821. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  3822. break;
  3823. }
  3824. case 'THE_GEOM_SAVE': {
  3825. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  3826. break;
  3827. }
  3828. case 'PROCES_INIT_FILTR': {
  3829. $this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
  3830. break;
  3831. }
  3832. default:
  3833. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  3834. }
  3835. }
  3836. /**
  3837. * ajax url: &_task=EDIT_INLINE
  3838. * @param $rowID - $_GET['ID']
  3839. * @param $fieldName - $_GET['col']
  3840. */
  3841. private function ajaxInlineEdit() {
  3842. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3843. $args = $_REQUEST;
  3844. $rowID = V::get('ID', 0, $_REQUEST, 'int');
  3845. $fieldName = V::get('col', '', $_REQUEST);
  3846. if ($rowID <= 0 || empty($fieldName)) throw new HttpException("404", 404);
  3847. $response = array();
  3848. ob_start();
  3849. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3850. if (!$fieldID) {
  3851. echo "404: No field by name ({$fieldName})";
  3852. exit;
  3853. }
  3854. $response['idZasob'] = $fieldID;
  3855. $response['htmlFieldName'] = "f{$fieldID}";
  3856. if ($DBG) echo "fieldID: {$fieldID}\n";
  3857. $row = $this->_acl->getItem($rowID);
  3858. if (!$row) {
  3859. echo "404: No item ID({$rowID})";
  3860. exit;
  3861. }
  3862. if (!$this->_acl->canReadObjectField($fieldName, $row)) {
  3863. if ($DBG) echo " R not allowed\n";
  3864. } else {
  3865. if ($DBG) echo " R allowed\n";
  3866. }
  3867. if (!$this->_acl->canWriteObjectField($fieldName, $row)) {
  3868. if ($DBG) echo " W not allowed\n";
  3869. } else {
  3870. if ($DBG) echo " W allowed\n";
  3871. }
  3872. $fieldVal = '';
  3873. if ($this->_acl->canReadObjectField($fieldName, $row)) {
  3874. $fieldVal = V::get($fieldName, $fieldVal, $row);
  3875. } else {
  3876. $fieldVal = '*****';
  3877. }
  3878. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  3879. $vCol = $this->_acl->getField($fieldID);
  3880. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3881. $response['fieldLabel'] = $vCol['label'];
  3882. $tsValues = array();
  3883. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  3884. if ($typeSpecial) {
  3885. 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>';}
  3886. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  3887. 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>';}
  3888. if (!empty($specialValues)) {
  3889. $tsValues[$row->ID] = implode('<br>', $specialValues);
  3890. }
  3891. }
  3892. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  3893. if (!empty($tsValues[$row->ID])) $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  3894. if (!empty($tsValues[$row->ID])) $response['typespecialValue'] = $tsValues[$row->ID];
  3895. $vDefault = $this->_acl->getColDefault($fieldName);
  3896. if (!empty($vDefault)) $fieldParams['default'] = $vDefault;
  3897. if (!empty($vDefault)) $response['defaultValue'] = $vDefault;
  3898. {
  3899. try {
  3900. $item = $this->_acl->getFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  3901. $response['formItem'] = $item;
  3902. if (!empty($item['rawColType']['simpleType'])) $response['simpleType'] = $item['rawColType']['simpleType'];
  3903. if (!empty($item['rawColType']['restrictions'])) $response['restrictions'] = $item['rawColType']['restrictions'];
  3904. echo '<div style="display:none">';
  3905. DBG::_(true, true, "item", $item, __CLASS__, __FUNCTION__, __LINE__);
  3906. echo '</div>';
  3907. } catch (Exception $e) {
  3908. echo '<div style="display:none">';
  3909. UI::alert('danger', $e->getMessage());
  3910. echo '</div>';
  3911. }
  3912. }
  3913. ?>
  3914. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  3915. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  3916. <?php if (!empty($vCol['opis'])) : ?>
  3917. <em><?php echo $vCol['opis']; ?></em>
  3918. <?php endif; ?>
  3919. </label>
  3920. <?php
  3921. if (!$this->_acl->canWriteObjectField($fieldName, $row)) {
  3922. // TODO: hide Zapisz btn on frontend side
  3923. if (!$this->_acl->canReadObjectField($fieldName, $row)) {
  3924. UI::alert('warning', "Brak uprawnień do odczytu i zapisu");
  3925. } else {
  3926. echo '<p style="margin-top:16px">' . $fieldVal . '</p>';
  3927. UI::alert('warning', "Brak uprawnień do zapisu");
  3928. }
  3929. } else {
  3930. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  3931. if ($typeSpecial
  3932. || $this->_acl->isDateField($fieldName)
  3933. || $this->_acl->isDateTimeField($fieldName)
  3934. ) {
  3935. echo '<p style="padding:120px 0;"></p>';
  3936. }
  3937. }
  3938. $response['legacy_html'] = ob_get_clean();
  3939. //$response['legacy_html'] = utf8_encode($response['legacy_html']);// pl chars bug
  3940. return $response;
  3941. }
  3942. private function ajaxEditInlineSave($args) {
  3943. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3944. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3945. $fieldName = V::get('col', '', $_REQUEST);
  3946. if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
  3947. if (empty($fieldName)) throw new HttpException("Wrong param col!", 400);
  3948. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3949. if (!$fieldID) throw new HttpException("Field not exists!", 404);
  3950. $item = $this->_acl->getItem($primaryKey);
  3951. if (!$item) throw new HttpException("Item not exists!", 404);
  3952. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3953. if (!isset($itemFromUser[$fieldName])) throw new HttpException("Field not set!", 400);
  3954. $itemPatch = array();
  3955. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  3956. $itemPatch[$primaryKeyField] = $primaryKey;
  3957. $response = new stdClass();
  3958. try {
  3959. $affected = $this->_acl->updateItem($itemPatch);
  3960. if ($affected > 0) {
  3961. $response->type = 'success';
  3962. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3963. } else if ($affected == 0) {
  3964. $response->type = 'info';
  3965. $response->msg = "Nie wprowadzono żadnych zmian";
  3966. }
  3967. $response->record = $this->_acl->getItem($primaryKey);
  3968. }
  3969. catch (Exception $e) {
  3970. $response->type = 'error';
  3971. $response->msg = $e->getMessage();
  3972. }
  3973. return $response;
  3974. }
  3975. public function sendAjaxEdit($id, $args) {
  3976. header("Content-type: text/plain");
  3977. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3978. $acl = $this->_acl;
  3979. $record = (array)$acl->getItem($id);
  3980. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  3981. UI::alert('danger', "Brak dostępu do rekordu");// TODO: more info - reason
  3982. return;
  3983. }
  3984. $fieldsList = array();
  3985. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  3986. if ($fieldName == 'ID') continue;
  3987. $field['name'] = $fieldName;
  3988. $field['opis'] = $acl->getFieldOpis($fieldName);
  3989. $field['label'] = $acl->getFieldLabel($fieldName);
  3990. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  3991. $fieldsList[$kID] = $field;
  3992. }
  3993. $cols = array();
  3994. foreach ($fieldsList as $kID => $field) {
  3995. $cols[$kID] = '';
  3996. if ($this->_acl->canReadObjectField($field['name'], $record)) {
  3997. $cols[$kID] = V::get($field['name'], '', $record);
  3998. } else {
  3999. $cols[$kID] = '*****';
  4000. }
  4001. // if ($acl->canReadObjectField($field['name'])) {
  4002. // $cols[$kID] = V::get($field['name'], '', $record);
  4003. // } else {
  4004. // $cols[$kID] = '*****';
  4005. // }
  4006. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  4007. }
  4008. $tsValues = array();
  4009. 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>';}
  4010. if (!empty($fieldsList)) {
  4011. foreach ($fieldsList as $vColID => $vCol) {
  4012. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  4013. if ($typeSpecial) {
  4014. 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>';}
  4015. $colValue = V::get($vCol['name'], '', $record);
  4016. 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>';}
  4017. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $vCol['name'], $colValue);
  4018. 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>';}
  4019. if (!empty($specialValues)) {
  4020. $tsValues[$vColID] = implode('<br>', $specialValues);
  4021. }
  4022. }
  4023. }
  4024. }
  4025. 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>';}
  4026. $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  4027. ?>
  4028. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  4029. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
  4030. <fieldset>
  4031. <legend>Edycja rekordu Nr <?php echo $record['ID']; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
  4032. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  4033. <?php if ($acl->canWriteObjectField($vCol['name'], $record)) : ?>
  4034. <div class="form-group">
  4035. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  4036. <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>
  4037. </label>
  4038. <div class="col-xs-12 col-sm-9 col-md-10">
  4039. <?php
  4040. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  4041. if (!empty($tsValues[$kID])) {
  4042. $fieldParams['typespecialValue'] = $tsValues[$kID];
  4043. }
  4044. echo $acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  4045. ?>
  4046. </div>
  4047. </div>
  4048. <?php elseif ($acl->canReadObjectField($vCol['name'], $record)) : ?>
  4049. <div class="form-group">
  4050. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  4051. <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>
  4052. </label>
  4053. <div class="col-xs-12 col-sm-9 col-md-10">
  4054. <p style="margin-top:5px;">
  4055. <?php
  4056. //echo $acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  4057. if (!empty($tsValues[$kID])) {
  4058. echo $tsValues[$kID];
  4059. } else if (!empty($record[ $vCol['name'] ])) {
  4060. echo $record[ $vCol['name'] ];
  4061. }
  4062. ?>
  4063. </p>
  4064. </div>
  4065. </div>
  4066. <?php endif; ?>
  4067. <?php endforeach; ?>
  4068. <div class="form-group">
  4069. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  4070. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
  4071. </div>
  4072. </div>
  4073. </fieldset>
  4074. </form>
  4075. <p style="padding:100px 0;"></p>
  4076. </div>
  4077. <script>
  4078. jQuery(document).ready(function(){
  4079. jQuery('textarea').autosize();
  4080. jQuery('.frm-help').popover({trigger:'hover'});
  4081. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  4082. var formData = {};
  4083. jQuery(this).serializeArray().map(function(i) { formData[i.name] = i.value; });// TODO: edit Widget - send only updated fields
  4084. // TODO: change Edit btn to return to edit record with fields -> show form
  4085. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  4086. //taskCont.empty();
  4087. taskCont.children().fadeOut('slow');
  4088. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  4089. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  4090. 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);
  4091. function notifyAjaxCallback(data) {
  4092. var notify = {}, outMsg = '';
  4093. notify.type = (data && data.type)? data.type : '';
  4094. notify.msg = (data && data.msg)? data.msg : '';
  4095. switch (notify.type) {
  4096. case 'success':
  4097. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  4098. break;
  4099. case 'info':
  4100. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  4101. break;
  4102. case 'error':
  4103. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4104. break;
  4105. case 'warning':
  4106. notify.type = 'warn';
  4107. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4108. break;
  4109. default:
  4110. notify.msg = 'Nieznany błąd';
  4111. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4112. notify.type = '';
  4113. }
  4114. jQuery.notify(notify.msg, notify.type);
  4115. var alertType = ('error' == data.type) ? 'danger' : data.type;
  4116. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  4117. return outMsg;
  4118. }
  4119. superagent
  4120. .post('<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editSaveAjax')
  4121. .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
  4122. .send({
  4123. namespace: '<?= $acl->getNamespace(); ?>',
  4124. primaryKey: '<?= $record['ID']; ?>',
  4125. form: formData
  4126. })
  4127. .set('Accept', 'application/json')
  4128. .end(function(err, res) {
  4129. var payload;
  4130. if (err || !res.ok || 'application/json' !== res.type) {
  4131. payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
  4132. } else {
  4133. payload = {type: 'success', msg: res.body.msg || '', body: res.body};
  4134. }
  4135. var data = res.body;
  4136. alertCntWrap.removeClass('AjaxTable-loading');
  4137. alertCnt.empty();
  4138. if (false === ['success', 'info'].indexOf(payload.type)) {
  4139. jQuery(errorTxt).appendTo(alertCnt);
  4140. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  4141. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  4142. 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);
  4143. backToEditBtn.on('click', function(){
  4144. alertCnt.remove();
  4145. taskCont.children().fadeIn('slow');
  4146. return false;
  4147. });
  4148. } else {
  4149. var outMsg = notifyAjaxCallback(payload);
  4150. var out = '';
  4151. out += outMsg;
  4152. out += '<div class="breadcrumb">' +
  4153. ' <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>' +
  4154. ' <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>' +
  4155. '</div>';
  4156. jQuery(out).appendTo(alertCnt);
  4157. // add rowFunctions from response
  4158. if (data && data.rowFunctions && data.primaryKey) {
  4159. var rowFunWrapNode = $('<div class="container"></div>').insertAfter(alertCnt);
  4160. var rowFunListNode = $('<ul></ul>').appendTo(rowFunWrapNode);
  4161. var keys = Object.keys(data.rowFunctions),
  4162. total = keys.length,
  4163. moreFuncBtnNode,
  4164. moreFunctions = [],
  4165. idx
  4166. ;
  4167. moreFunctions = keys.splice(3);
  4168. keys.forEach(function(key) {
  4169. var cellNode = $('<li></li>');
  4170. var funObj = data.rowFunctions[key],
  4171. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, data.primaryKey, {ico: true, label: true})
  4172. ;
  4173. funcNode.appendTo(cellNode);
  4174. cellNode.appendTo(rowFunListNode);
  4175. });
  4176. }
  4177. }
  4178. });
  4179. return false;
  4180. });
  4181. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  4182. var input, btn, btnIco;
  4183. input = jQuery(e.target);
  4184. btn = input.next('.button-appendBack');
  4185. btnIco = btn.find('.glyphicon');
  4186. if (btn.attr('title') != input.val()) {
  4187. btnIco.show();
  4188. } else {
  4189. btnIco.hide();
  4190. }
  4191. });
  4192. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  4193. var input, btn, btnIco;
  4194. btn = jQuery(this);
  4195. btnIco = btn.find('.glyphicon');
  4196. input = btn.prev();
  4197. if (input.is('input')) {
  4198. if (btn.attr('title') != input.val()) {
  4199. input.val(btn.attr('title'));
  4200. btnIco.hide();
  4201. }
  4202. }
  4203. });
  4204. });
  4205. </script>
  4206. <?php
  4207. exit;
  4208. }
  4209. private function sendAjaxCreate($args) {
  4210. $acl = $this->_acl;
  4211. header("Content-type: text/plain");
  4212. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4213. if (!Core_AclHelper::hasCreatePerms($acl)) {
  4214. ?>
  4215. <div class="container">
  4216. <div class="alert alert-danger">
  4217. Brak uprawnień do utworzenia nowego rekordu.
  4218. </div>
  4219. </div>
  4220. <?php
  4221. return;
  4222. }
  4223. $cols = array();
  4224. $forceFilterInit = array();
  4225. $defaultAclGroup = User::getDefaultAclGroup();
  4226. if ($defaultAclGroup) {
  4227. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  4228. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  4229. }
  4230. foreach ($_GET as $k => $v) {
  4231. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  4232. $fldName = substr($k, 3);
  4233. $forceFilterInit[$fldName] = $v;
  4234. }
  4235. }
  4236. $fieldsList = $this->_acl->getFields();
  4237. foreach ($fieldsList as $kID => $vCol) {
  4238. $defaultValue = '';
  4239. if ($vCol['name'] == 'ID') {
  4240. unset($fieldsList[$kID]);
  4241. continue;
  4242. }
  4243. if (!empty($forceFilterInit[$vCol['name']])) {
  4244. $defaultValue = $forceFilterInit[$vCol['name']];
  4245. }
  4246. // TODO: read from session cache
  4247. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  4248. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  4249. }
  4250. ?>
  4251. <div class="container AjaxFrmHorizontalEdit">
  4252. <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  4253. <fieldset>
  4254. <legend>Dodaj nowy rekord</legend>
  4255. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  4256. <?php if ($this->_acl->canCreateField($vCol['name'])) : ?>
  4257. <div class="form-group">
  4258. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  4259. <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>
  4260. </label>
  4261. <div class="col-xs-12 col-sm-9 col-md-10">
  4262. <?php
  4263. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  4264. echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  4265. ?>
  4266. </div>
  4267. </div>
  4268. <?php endif; ?>
  4269. <?php endforeach; ?>
  4270. <div class="form-group">
  4271. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  4272. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  4273. </div>
  4274. </div>
  4275. </fieldset>
  4276. </form>
  4277. </div>
  4278. <script>
  4279. jQuery(document).ready(function(){
  4280. jQuery('textarea').autosize();
  4281. jQuery('.frm-help').popover({trigger:'hover'});
  4282. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  4283. var data = jQuery(this).serialize();
  4284. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  4285. taskCont = taskContLast.parent();
  4286. taskContLast.fadeOut('slow');
  4287. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  4288. 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);
  4289. function notifyAjaxCallback(data) {
  4290. var notify = {};
  4291. notify.type = (data && data.type)? data.type : '';
  4292. notify.msg = (data && data.msg)? data.msg : '';
  4293. switch (notify.type) {
  4294. case 'success':
  4295. if (!notify.msg) notify.msg = 'OK';
  4296. break;
  4297. case 'info':
  4298. if (!notify.msg) notify.msg = '';
  4299. break;
  4300. case 'error':
  4301. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4302. break;
  4303. case 'warning':
  4304. notify.type = 'warn';
  4305. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4306. break;
  4307. default:
  4308. notify.msg = 'Nieznany błąd';
  4309. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4310. notify.type = '';
  4311. }
  4312. jQuery.notify(notify.msg, notify.type);
  4313. }
  4314. $.ajax({
  4315. data: data,
  4316. dataType: 'json',
  4317. type: "POST",
  4318. async: true,
  4319. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  4320. })
  4321. .always(function(dataOrJqXHR){
  4322. var data;
  4323. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  4324. if ('responseJSON' in dataOrJqXHR) {
  4325. data = dataOrJqXHR.responseJSON;
  4326. } else {
  4327. data = {};
  4328. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  4329. if (dataOrJqXHR.status == 404) {
  4330. data.type = 'error';
  4331. } else {
  4332. data.type = 'warning';
  4333. }
  4334. }
  4335. }
  4336. else {
  4337. data = dataOrJqXHR;
  4338. }
  4339. notifyAjaxCallback(data);
  4340. taskCnt.removeClass('AjaxTable-loading');
  4341. taskCnt.empty();
  4342. if (data.type == 'error' || data.type == 'warning') {
  4343. var out = '<div class="container">' +
  4344. '<div class="alert alert-danger">' +
  4345. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  4346. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  4347. '</div>';
  4348. out += '<div class="breadcrumb">' +
  4349. ' <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>' +
  4350. '</div>' +
  4351. '</div>';
  4352. jQuery(out).appendTo(taskCnt);
  4353. var taskContLastNode = taskContLast
  4354. , taskCntNode = taskCnt;
  4355. taskCnt.find('.create-fix').click(function(){
  4356. taskCntNode.remove();
  4357. taskContLastNode.fadeIn('slow');
  4358. return false;
  4359. });
  4360. }
  4361. else if (data.type == 'success') {
  4362. var msg = '';
  4363. if (data.id && data.id > 0) {
  4364. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  4365. } else if (data.msg) {
  4366. msg = data.msg;
  4367. } else {
  4368. msg = 'OK';
  4369. }
  4370. var out = '<div class="container">';
  4371. out += '<div class="alert alert-success">' + msg + '</div>';
  4372. out += '<div class="breadcrumb">' +
  4373. ' <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>' +
  4374. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  4375. ' <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>' +
  4376. '</div>';
  4377. out += '</div>';
  4378. jQuery(out).appendTo(taskCnt);
  4379. }
  4380. });
  4381. return false;
  4382. });
  4383. });
  4384. </script>
  4385. <?php
  4386. exit;
  4387. }
  4388. private function ajaxCreateSave($args) {
  4389. $response = new stdClass();
  4390. $createdId = null;
  4391. try {
  4392. $item = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  4393. $createdId = $this->_acl->addItem($item);
  4394. if ($createdId) {
  4395. $response->type = 'success';
  4396. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  4397. $response->id = $createdId;
  4398. $response->record = $this->_acl->getItem($createdId);
  4399. }
  4400. else {
  4401. $response->type = 'error';
  4402. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  4403. }
  4404. }
  4405. catch (Exception $e) {
  4406. $response->type = 'error';
  4407. $response->msg = $e->getMessage();
  4408. }
  4409. return $response;
  4410. }
  4411. private function ajaxCopy($args) {
  4412. $id = V::get('ID', 0, $_REQUEST, 'int');
  4413. if ($id <= 0) {
  4414. throw new HttpException("Wrong param ID!", 404);
  4415. }
  4416. $item = $this->_acl->getItem($id);
  4417. if (!$item) {
  4418. throw new HttpException("Item '{$id}' not exists!", 404);
  4419. }
  4420. $response = new stdClass();
  4421. $itemCopy = $this->_acl->createItemCopy($item);
  4422. $createdId = null;
  4423. try {
  4424. $createdId = $this->_acl->addItem($itemCopy);
  4425. if ($createdId) {
  4426. $response->type = 'success';
  4427. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  4428. $response->id = $createdId;
  4429. $response->record = $this->_acl->getItem($createdId);
  4430. }
  4431. else {
  4432. $response->type = 'error';
  4433. $response->msg = "Nie udało się skopiować rekordu!";
  4434. }
  4435. }
  4436. catch (Exception $e) {
  4437. $response->type = 'error';
  4438. $response->msg = "Wystąpiły błędy!";
  4439. $response->msg = $e->getMessage();
  4440. }
  4441. return $response;
  4442. }
  4443. private function ajaxHist($args) {
  4444. $jsonResponse = array();
  4445. $id = V::get('ID', 0, $args, 'int');
  4446. $acl = $this->_acl;
  4447. $record = $acl->getItem($id);
  4448. if (!$record) throw new HttpException("404: No item ID({$id})", 404);
  4449. $visibleCols = $acl->getRealFieldList();
  4450. $rowsHist = $acl->getHistItems($id);
  4451. $jsonResponse['row_functions'] = $this->_parseRowFunctions($record->ID, array('hist', 'cp'), $showLabel = true);
  4452. $visibleColsWithIds = array();
  4453. $visibleColsLabels = array();
  4454. foreach ($visibleCols as $vColName) {
  4455. $fldId = $acl->getFieldIdByName($vColName);
  4456. if ($fldId) {
  4457. $visibleColsWithIds[$fldId] = $vColName;
  4458. $label = $acl->getFieldLabel($vColName);
  4459. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  4460. $visibleColsLabels[$fldId] = $label;
  4461. }
  4462. }
  4463. $jsonResponse['label'] = "Historia rekordu Nr {$id}";
  4464. $jsonResponse['fields'] = array_values($visibleColsWithIds);
  4465. $jsonResponse['field_label'] = $visibleColsLabels;
  4466. if (empty($rowsHist)) return $jsonResponse;
  4467. $jsonResponse['rows'] = array();
  4468. foreach ($rowsHist as $row) {
  4469. $histItem = array();
  4470. $histItem['ID'] = $row->ID;
  4471. $histItem['_created'] = $row->_created;
  4472. $histItem['_author'] = $row->_author;
  4473. $histItem['changes'] = array();
  4474. foreach ($visibleColsWithIds as $fldId => $fieldName) {
  4475. // if (in_array($fieldName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue;
  4476. // if ($row->{$fieldName} == 'N/S;') continue;
  4477. $changeItem = array();
  4478. $changeItem['fieldName'] = $fieldName;
  4479. $changeItem['acl_read'] = $acl->canReadObjectField($fieldName, $record);
  4480. if ($changeItem['acl_read']) {
  4481. $changeItem['value'] = $row->{$fieldName};
  4482. }
  4483. if ('the_geom' == $fieldName && $acl->canWriteObjectField($fieldName, $record)) {
  4484. $sourceName = $acl->getSourceName();
  4485. if ('default_db' == $sourceName) {
  4486. $typeName = $acl->getName();
  4487. $changeItem['revert_function_url'] = Request::getPathUri() . "index.php?_route=ViewTableAjax&typeName=p5_{$sourceName}:{$typeName}&_task=revertFromHistAjax&ID={$id}&idHist={$row->ID}&fieldName={$fieldName}";
  4488. $changeItem['revert_function_data'] = "ID={$id}&idHist={$row->ID}&fieldName={$fieldName}";
  4489. }
  4490. }
  4491. $histItem['changes'][$fieldName] = $changeItem;
  4492. }
  4493. $jsonResponse['rows'][] = $histItem;
  4494. }
  4495. return $jsonResponse;
  4496. }
  4497. public function ajaxFileUpload($args) {
  4498. $id = V::get('ID', 0, $args, 'int');
  4499. if ($id <= 0) throw new HttpException("404", 404);
  4500. $dbID = $this->_acl->getDB();
  4501. $db = DB::getDB($dbID);
  4502. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4503. $record = $this->_acl->getItem($id);
  4504. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4505. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4506. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  4507. $tblName = $this->_acl->getName();
  4508. $confTblName = "{$tblName}_COLUMN";
  4509. $folderConfAll = FoldersConfig::getRawData();
  4510. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4511. $folderConf = FoldersConfig::getAll($confTblName);
  4512. $uploader = new FileUploader($confTblName, $record);
  4513. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4514. $uploader->findFolder();
  4515. $errorMsg = '';
  4516. if (!empty($args['SCANS_COLUMN_ADD'])) {
  4517. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  4518. }
  4519. else {
  4520. $uploaded = $uploader->tryUploadAjax($errorMsg);
  4521. }
  4522. $retJson = new stdClass();
  4523. if (!$uploaded) throw new Exception($errorMsg);
  4524. $uploadedFileName = '';
  4525. $uploadedFile = $uploader->getLastUploadedFile();
  4526. if ($uploadedFile) {
  4527. $uploadedFileName = explode('/', $uploadedFile);
  4528. $uploadedFileName = end($uploadedFileName);
  4529. }
  4530. //echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  4531. $retJson->type = 'SUCCESS';
  4532. $retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
  4533. if (!empty($uploadedFileName)) {
  4534. $sqlObj = new stdClass();
  4535. $sqlObj->ID = $record->ID;
  4536. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  4537. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  4538. }
  4539. return $retJson;
  4540. }
  4541. public function ajaxFileRemove($args) {
  4542. $id = V::get('ID', 0, $args, 'int');
  4543. if ($id <= 0) throw new HttpException("404", 404);
  4544. $filename = V::get('filename', '', $args);
  4545. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  4546. $dbID = $this->_acl->getDB();
  4547. $db = DB::getDB($dbID);
  4548. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4549. $record = $this->_acl->getItem($id);
  4550. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4551. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4552. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  4553. $tblName = $this->_acl->getName();
  4554. $confTblName = "{$tblName}_COLUMN";
  4555. $folderConfAll = FoldersConfig::getRawData();
  4556. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4557. $folderConf = FoldersConfig::getAll($confTblName);
  4558. $uploader = new FileUploader($confTblName, $record);
  4559. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4560. $uploader->findFolder();
  4561. $errorMsg = '';
  4562. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  4563. if (!$removed) throw new Exception($errorMsg);
  4564. $retJson = new stdClass();
  4565. $retJson->type = 'SUCCESS';
  4566. $retJson->msg = 'Plik został poprawnie usunięty';
  4567. return $retJson;
  4568. }
  4569. public function ajaxFileList($args) {
  4570. $id = V::get('ID', 0, $args, 'int');
  4571. if ($id <= 0) throw new HttpException("404", 404);
  4572. $dbID = $this->_acl->getDB();
  4573. $db = DB::getDB($dbID);
  4574. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  4575. $record = $this->_acl->getItem($id);
  4576. if (!$record) throw new HttpException("No item ID({$rowID})", 404);
  4577. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4578. $tblName = $this->_acl->getName();
  4579. $confTblName = "{$tblName}_COLUMN";
  4580. $folderConfAll = FoldersConfig::getRawData();
  4581. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  4582. $folderConf = FoldersConfig::getAll($confTblName);
  4583. $uploader = new FileUploader($confTblName, $record);
  4584. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4585. $uploader->findFolder();
  4586. $mainFolder = $uploader->getDestFolder();
  4587. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4588. $localPath = $uploader->getLocalPath();
  4589. $folderWeb = $uploader->getFolderWeb();
  4590. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4591. return $jsonFiles;
  4592. }
  4593. private function ajaxFilePermsRefresh($args) {
  4594. $id = V::get('ID', 0, $args, 'int');
  4595. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  4596. $dbID = $this->_acl->getDB();
  4597. $db = DB::getDB($dbID);
  4598. if (!$db) throw new HttpException("No DB", 406);
  4599. $record = $this->_acl->getItem($id);
  4600. if (!$record) throw new Exception("No item ID({$rowID})", 404);
  4601. $tblName = $this->_acl->getName();
  4602. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  4603. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  4604. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  4605. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  4606. $mainDB = DB::getDB();
  4607. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  4608. $sql = "insert into `_SYNC_FILE_PERMS` (
  4609. `ID_PROJECT`,
  4610. `A_SYNCHRONIZED`
  4611. )
  4612. values (
  4613. '{$record->ID}'
  4614. , 0
  4615. )
  4616. ON DUPLICATE KEY UPDATE
  4617. `A_SYNCHRONIZED`=0
  4618. ";
  4619. }
  4620. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  4621. $sql = "insert into `_SYNC_FILE_PERMS` (
  4622. `ID_PROJECT`,
  4623. `A_SYNCHRONIZED`
  4624. )
  4625. values (
  4626. '{$record->ID_PROJECT}'
  4627. , 0
  4628. )
  4629. ON DUPLICATE KEY UPDATE
  4630. `A_SYNCHRONIZED`=0
  4631. ";
  4632. }
  4633. else {
  4634. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  4635. `TBL_NAME`,
  4636. `TBL_ID`,
  4637. `L_APPOITMENT_USER`,
  4638. `A_ADM_COMPANY`,
  4639. `A_CLASSIFIED`,
  4640. `A_SYNCHRONIZED`
  4641. )
  4642. values (
  4643. '{$tblName}'
  4644. , '{$id}'
  4645. , '{$sql_L_APPOITMENT_USER}'
  4646. , '{$sql_A_ADM_COMPANY}'
  4647. , '{$sql_A_CLASSIFIED}'
  4648. , 0
  4649. )
  4650. ON DUPLICATE KEY UPDATE
  4651. `A_SYNCHRONIZED`=0
  4652. ";
  4653. }
  4654. $res = $mainDB->query($sql);
  4655. if ($mainDB->has_errors()) {
  4656. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  4657. //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>';
  4658. throw new Exception("Nie udało się dodać zadania");
  4659. }
  4660. // TODO: this blocks browser ajax query
  4661. //$limit = 3;
  4662. //while ($limit--) {
  4663. // sleep(10);
  4664. // TODO: check if task is done
  4665. //}
  4666. $confTblName = "{$tblName}_COLUMN";
  4667. $folderConfAll = FoldersConfig::getRawData();
  4668. if (!FoldersConfig::hasConfig($confTblName)) {
  4669. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  4670. }
  4671. $folderConf = FoldersConfig::getAll($confTblName);
  4672. $uploader = new FileUploader($confTblName, $record);
  4673. if (!$uploader->setConfig($folderConf)) {
  4674. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4675. }
  4676. $uploader->findFolder();
  4677. $mainFolder = $uploader->getDestFolder();
  4678. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4679. $localPath = $uploader->getLocalPath();
  4680. $folderWeb = $uploader->getFolderWeb();
  4681. $jsonData = new stdClass();
  4682. $jsonData->msg = 'Zadanie dodane';
  4683. $jsonData->type = 'success';
  4684. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4685. return $jsonData;
  4686. }
  4687. private function sendAjaxFilesConnTblList($id, $args) {
  4688. header("Content-type: application/json");
  4689. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4690. $dbID = $this->_acl->getDB();
  4691. $db = DB::getDB($dbID);
  4692. if (!$db) {
  4693. header('HTTP/1.0 406 Not Acceptable');
  4694. echo 'No DB (' . $dbID . ')';
  4695. exit;
  4696. }
  4697. $record = $this->_acl->getItem($id);
  4698. if (!$record) {
  4699. header('HTTP/1.0 404 Not Found');
  4700. echo 'No item ID(' . $rowID . ')';
  4701. exit;
  4702. }
  4703. $connTblName = '';
  4704. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  4705. if ($connTblID <= 0) {
  4706. header('HTTP/1.0 406 Not Acceptable');
  4707. echo 'No conn Table ID';
  4708. exit;
  4709. }
  4710. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  4711. if (empty($connTblTypespecials)) {
  4712. header('HTTP/1.0 406 Not Acceptable');
  4713. echo "No conn Table (ID={$connTblID})";
  4714. exit;
  4715. }
  4716. 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>';}
  4717. if(1) {
  4718. header('HTTP/1.0 404 Not Found');
  4719. echo 'TODO: ...';
  4720. exit;
  4721. }
  4722. $tblName = $this->_acl->getName();
  4723. $confTblName = "{$tblName}_COLUMN";
  4724. $folderConfAll = FoldersConfig::getRawData();
  4725. if (!FoldersConfig::hasConfig($confTblName)) {
  4726. header('HTTP/1.0 404 Not Found');
  4727. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4728. exit;
  4729. }
  4730. $folderConf = FoldersConfig::getAll($confTblName);
  4731. $uploader = new FileUploader($confTblName, $record);
  4732. if (!$uploader->setConfig($folderConf)) {
  4733. header('HTTP/1.0 404 Not Found');
  4734. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4735. exit;
  4736. }
  4737. $uploader->findFolder();
  4738. $mainFolder = $uploader->getDestFolder();
  4739. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4740. $localPath = $uploader->getLocalPath();
  4741. $folderWeb = $uploader->getFolderWeb();
  4742. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4743. echo json_encode($jsonFiles);
  4744. exit;
  4745. }
  4746. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  4747. $jsonFiles = array();
  4748. if (!is_array($files) || empty($files)) {
  4749. return $jsonFiles;
  4750. }
  4751. sort($files);
  4752. foreach ($files as $vFilePath) {
  4753. $file = new stdClass();
  4754. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  4755. //$file->name = explode('/', $vFilePath);
  4756. //$file->name = end($file->name);
  4757. $file->size = filesize($vFilePath);
  4758. $file->sizeStr = V::humanFileSize($file->size);
  4759. $file->type = '';
  4760. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  4761. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  4762. $jsonFiles[] = $file;
  4763. }
  4764. return $jsonFiles;
  4765. }
  4766. private function getConnectedTables() {
  4767. $connTbls = array();
  4768. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  4769. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  4770. if (!empty($fields)) {
  4771. foreach ($fields as $vColID => $vCol) {
  4772. $typeSpecial = Typespecial::getInstance($vColID);
  4773. if ($typeSpecial) {
  4774. $tsConnTbls = $typeSpecial->getTblAliasList();
  4775. if (!empty($tsConnTbls)) {
  4776. foreach ($tsConnTbls as $kID => $vName) {
  4777. $connTbls[$kID] = $vName;
  4778. }
  4779. }
  4780. }
  4781. }
  4782. }
  4783. return $connTbls;
  4784. }
  4785. private function getConnectedTblTypespecials($connTblID) {
  4786. $connTblTypespecials = array();
  4787. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  4788. if (!empty($fields)) {
  4789. foreach ($fields as $vColID => $vCol) {
  4790. $typeSpecial = Typespecial::getInstance($vColID);
  4791. if ($typeSpecial) {
  4792. $tsConnTbls = $typeSpecial->getTblAliasList();
  4793. if (array_key_exists($connTblID, $tsConnTbls)) {
  4794. $connTblTypespecials[] = $typeSpecial;
  4795. }
  4796. }
  4797. }
  4798. }
  4799. return $connTblTypespecials;
  4800. }
  4801. private function sendAjaxFiles($id, $args) {
  4802. header("Content-type: text/plain");
  4803. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4804. $dbID = $this->_acl->getDB();
  4805. $db = DB::getDB($dbID);
  4806. if (!$db) throw new HttpException("", 406);
  4807. $record = $this->_acl->getItem($id);
  4808. if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
  4809. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  4810. $tblName = $this->_acl->getName();
  4811. $confTblName = "{$tblName}_COLUMN";
  4812. $folderConfAll = FoldersConfig::getRawData();
  4813. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
  4814. $folderConf = FoldersConfig::getAll($confTblName);
  4815. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  4816. $uploader = new FileUploader($confTblName, $record);
  4817. $errMsg = '';
  4818. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})" . '<br>' . "\n" . $errMsg, 404);
  4819. $uploader->findFolder();
  4820. 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>'; }
  4821. $mainFolder = $uploader->getDestFolder();
  4822. 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>'; }
  4823. if (!$mainFolder) {
  4824. $destFolderPath = $uploader->getDestLocalPath(true);
  4825. $folderCreated = $uploader->tryCreateDestFolder($destFolderPath);
  4826. if ($folderCreated) {
  4827. //UI::alert('info', "Utworzono katalog");
  4828. $uploader->findFolder();
  4829. $mainFolder = $uploader->getDestFolder();
  4830. } else {
  4831. UI::alert('warning', "Nie udało się utworzyć katalogu");
  4832. }
  4833. }
  4834. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4835. 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>'; }
  4836. $sharePoint = V::get('share_point', null, $folderConf);
  4837. if ($sharePoint) {
  4838. if ('//' == substr($mainFolder, 0, 2)) {
  4839. $sharePoint = FoldersConfig::getNfsOsPath() . "{$mainFolder}";
  4840. } else {
  4841. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  4842. }
  4843. }
  4844. $localPath = $uploader->getLocalPath();
  4845. $folderWeb = $uploader->getFolderWeb();
  4846. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4847. 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>'; }
  4848. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  4849. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  4850. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  4851. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  4852. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  4853. sort($skanyFiles);
  4854. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  4855. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
  4856. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  4857. $fileIndex = V::get($fileIndexField, $record->ID, $record);
  4858. ?>
  4859. <script src="stuff/jquery.form.js"></script>
  4860. <div class="container">
  4861. <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
  4862. <?php if ($sharePoint) : ?>
  4863. <a href="<?php echo $sharePoint; ?>"><span class="glyphicon glyphicon-folder-open"></span><code><?php echo $mainFolder; ?></code></a>
  4864. <?php else : ?>
  4865. <code><?php echo $mainFolder; ?></code>
  4866. <?php endif; ?>
  4867. <span class="pull-right valign-btns-bottom">
  4868. <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
  4869. <?php echo $rowFunctionsOut; ?>
  4870. </span>
  4871. </h4>
  4872. <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
  4873. <table class="table table-bordered table-hover">
  4874. <colgroup>
  4875. <col style="">
  4876. <col style="width:30px;">
  4877. <?php if ($sharePoint) : ?>
  4878. <col style="width:30px;">
  4879. <?php endif; ?>
  4880. <col style="width:80px;">
  4881. <col style="width:140px;">
  4882. </colgroup>
  4883. <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
  4884. <?php if (empty($mainFolder)) : ?>
  4885. <tr>
  4886. <td colspan="5">
  4887. <div class="alert alert-warning">
  4888. <h4>Brak folderu!</h4>
  4889. Folder dla tego rekordu nie został utworzony.
  4890. </div>
  4891. </td>
  4892. </tr>
  4893. <?php elseif (empty($files)) : ?>
  4894. <tr>
  4895. <td colspan="5">
  4896. <div class="alert alert-info">
  4897. <h4>Brak plików</h4>
  4898. </div>
  4899. </td>
  4900. </tr>
  4901. <?php endif; ?>
  4902. </tbody>
  4903. </table>
  4904. </div>
  4905. <br>
  4906. <br>
  4907. <?php if (!$this->_acl->canWriteRecord($record)) : ?>
  4908. <div class="alert alert-warning">
  4909. Brak uprawnień do dodawania plików
  4910. </div>
  4911. <?php else : ?>
  4912. <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
  4913. <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
  4914. <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
  4915. <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
  4916. <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
  4917. <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
  4918. </ul>
  4919. <div id="myTabContent" class="tab-content">
  4920. <div class="tab-pane fade in active" id="local" style="text-align: center;">
  4921. <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'">
  4922. </div>
  4923. <div class="tab-pane fade" id="scan">
  4924. <?php if (empty($skanyFiles)) : ?>
  4925. <div class="alert alert-info">
  4926. <h4>Brak plików</h4>
  4927. <?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>"; ?>
  4928. </div>
  4929. <?php else : ?>
  4930. <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
  4931. <table class="table table-bordered table-hover">
  4932. <colgroup>
  4933. <col style="width:30px;">
  4934. <col style="">
  4935. <col style="width:30px;">
  4936. <col style="width:80px;">
  4937. <col style="width:140px;">
  4938. </colgroup>
  4939. <tbody>
  4940. <?php foreach ($skanyFiles as $vFilePath) : ?>
  4941. <tr>
  4942. <?php
  4943. $vFileName = explode('/', $vFilePath);
  4944. $vFileName = end($vFileName);
  4945. $vFileSize = filesize($vFilePath);
  4946. $vFileSizeOut = V::humanFileSize($vFileSize);
  4947. ?>
  4948. <td><input style="margin:0" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
  4949. <td><div style="overflow:hidden; white-space:nowrap" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
  4950. <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>
  4951. <td style="white-space:nowrap; text-align:right"><?php echo $vFileSizeOut; ?></td>
  4952. <td style="white-space:nowrap"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
  4953. </tr>
  4954. <?php endforeach; ?>
  4955. </tbody>
  4956. </table>
  4957. </div>
  4958. <?php endif; ?>
  4959. </div>
  4960. </div>
  4961. <br>
  4962. <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
  4963. <?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> ?>
  4964. </h4>
  4965. <table style="width:100%" class="table table-bordered">
  4966. <tr>
  4967. <th>Nr</th>
  4968. <th>Typ</th>
  4969. <th style="width:40%;">Opis <i class="glyphicon glyphicon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
  4970. <th style="width:16%">Data wersji</th>
  4971. <th style="width:12%">Numer wersji</th>
  4972. </tr>
  4973. <tr>
  4974. <td>
  4975. <?php echo $fileIndex; ?>
  4976. </td>
  4977. <td>
  4978. <select class="form-control" name="M_DIST_FILES_TYPE">
  4979. <?php foreach ($fileTypes as $kType => $vLabel) : ?>
  4980. <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
  4981. <?php endforeach; ?>
  4982. </select>
  4983. <br>
  4984. <label class="checkbox">
  4985. <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
  4986. Wykrycie automatyczne typu z wysylanego pliku
  4987. </label>
  4988. <label class="checkbox">
  4989. <input type="checkbox" name="M_DIST_FILES_TEMP">
  4990. Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
  4991. </label>
  4992. </td>
  4993. <td>
  4994. <input class="form-control" style="width:100%" type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
  4995. <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
  4996. </td>
  4997. <td>
  4998. <div class="input-group">
  4999. <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">
  5000. <span class="glyphicon glyphicon-calendar"></span>
  5001. </span>
  5002. </div>
  5003. <!--
  5004. <input class="form-control" type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10">
  5005. -->
  5006. <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
  5007. </td>
  5008. <td>
  5009. <input class="form-control" style="width:100%" type="number" name="M_DIST_FILES_VERSION">
  5010. <br>
  5011. <label class="checkbox">
  5012. <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
  5013. Automatycznie dodaj wersje
  5014. </label>
  5015. </td>
  5016. </tr>
  5017. <tr>
  5018. <td colspan="5">
  5019. <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
  5020. <p>
  5021. <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
  5022. </p>
  5023. <p>
  5024. <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
  5025. <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
  5026. </p>
  5027. </td>
  5028. </tr>
  5029. </table>
  5030. </form>
  5031. </div>
  5032. <?php endif; ?>
  5033. <script>
  5034. function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
  5035. var postData = {};
  5036. jQuery.ajax({
  5037. 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; ?>',
  5038. type: 'POST',
  5039. //dataType: 'json',
  5040. //contentType: "application/json; charset=utf-8",
  5041. data: postData,
  5042. success: function(data) {
  5043. fileListUpdate<?php echo $this->_htmlID; ?>(data);
  5044. },
  5045. error: function(jhr, textStatus, errorThrown) {
  5046. console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
  5047. }
  5048. });
  5049. }
  5050. function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  5051. var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
  5052. fileListNode.empty();
  5053. fileListJson.map(function(file){
  5054. var node = $('<tr></tr>');
  5055. <?php if (!$this->_acl->canWriteRecord($record)) : ?>
  5056. var fFun = null;
  5057. <?php else : ?>
  5058. var fFun = $('<i class="glyphicon glyphicon-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
  5059. <?php endif; ?>
  5060. var fNameCell = $('<td style="overflow: hidden;"></td>');
  5061. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  5062. if (fFun) fName.append(fFun);
  5063. fName.append(file.name);
  5064. fName.appendTo(fNameCell);
  5065. node.append(fNameCell);
  5066. 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>');
  5067. <?php if ($sharePoint) : ?>
  5068. 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>');
  5069. <?php endif; ?>
  5070. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  5071. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  5072. node.appendTo(fileListNode);
  5073. if (fFun) {
  5074. $(fFun).click(function(e){
  5075. var n = $(e.target);
  5076. var fname= n.data('filename');
  5077. if (!fname) {
  5078. return false;
  5079. }
  5080. if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
  5081. var postData = {filename: fname};
  5082. jQuery.ajax({
  5083. 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; ?>',
  5084. type: 'POST',
  5085. //dataType: 'json',
  5086. //contentType: "application/json; charset=utf-8",
  5087. data: postData,
  5088. success: function(data) {
  5089. if (data && data.type) {
  5090. if (data.type == 'SUCCESS') {
  5091. n.parents('tr').remove();
  5092. //console.log('TODO: SUCCESS msg: ', data.msg);
  5093. }
  5094. else if (data.type == 'error') {
  5095. console.log('TODO: ERROR msg: ', data.msg);
  5096. }
  5097. } else {
  5098. console.log('TODO: ??? data: ', data);
  5099. }
  5100. },
  5101. error: function(jhr, textStatus, errorThrown) {
  5102. console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
  5103. }
  5104. });
  5105. }
  5106. });
  5107. }
  5108. });
  5109. }
  5110. function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
  5111. var postData = {};
  5112. // clear current file list
  5113. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
  5114. jQuery.ajax({
  5115. 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,
  5116. type: 'POST',
  5117. //dataType: 'json',
  5118. //contentType: "application/json; charset=utf-8",
  5119. data: postData,
  5120. success: function(data) {
  5121. connTblListUpdate<?php echo $this->_htmlID; ?>(data);
  5122. },
  5123. error: function(jqXHR, textStatus, errorThrown) {
  5124. var txt = jqXHR.responseText || 'Error';
  5125. 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>');
  5126. if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
  5127. }
  5128. });
  5129. }
  5130. function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  5131. var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
  5132. fileListNode.empty();
  5133. fileListJson.map(function(file){
  5134. var node = $('<tr></tr>');
  5135. var fNameCell = $('<td style="overflow: hidden;"></td>');
  5136. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  5137. fName.append(file.name);
  5138. fName.appendTo(fNameCell);
  5139. node.append(fNameCell);
  5140. 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>');
  5141. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  5142. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  5143. node.appendTo(fileListNode);
  5144. });
  5145. }
  5146. function fileListActions<?php echo $this->_htmlID; ?>() {
  5147. var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
  5148. 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>');
  5149. btnReload.on('click', function(e) {
  5150. //console.log('TODO: click reload perms...');
  5151. function notifyAjaxCallback(data) {
  5152. var notify = {};
  5153. notify.type = (data && data.type)? data.type : '';
  5154. notify.msg = (data && data.msg)? data.msg : '';
  5155. switch (notify.type) {
  5156. case 'success':
  5157. if (!notify.msg) notify.msg = 'OK';
  5158. break;
  5159. case 'info':
  5160. if (!notify.msg) notify.msg = '';
  5161. break;
  5162. case 'error':
  5163. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  5164. break;
  5165. case 'warning':
  5166. notify.type = 'warn';
  5167. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  5168. break;
  5169. default:
  5170. notify.msg = 'Nieznany błąd';
  5171. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  5172. notify.type = '';
  5173. }
  5174. jQuery.notify(notify.msg, notify.type);
  5175. }
  5176. var reqData = {};
  5177. jQuery.ajax({
  5178. data: reqData,
  5179. dataType: 'json',
  5180. type: "GET",
  5181. 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; ?>',
  5182. })
  5183. .done(function(data, textStatus, jqXHR){
  5184. notifyAjaxCallback(data);
  5185. if (data && data.files) {
  5186. fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
  5187. }
  5188. })
  5189. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  5190. if (jqXHR.responseJSON) {
  5191. notifyAjaxCallback(jqXHR.responseJSON);
  5192. }
  5193. else {
  5194. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  5195. if (jqXHR.status == 404) {
  5196. jQuery.notify(jqXHR.responseText, 'error');
  5197. } else {
  5198. jQuery.notify(jqXHR.responseText, 'warn');
  5199. }
  5200. }
  5201. });
  5202. });
  5203. filePermsReload.append(btnReload);
  5204. }
  5205. jQuery(document).ready(function(){
  5206. $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function(e) {
  5207. e.preventDefault();
  5208. $(this).tab('show');
  5209. })
  5210. .on('shown.bs.tab', function(e) {
  5211. var fileSource = $(e.target).data('toggle')
  5212. , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
  5213. if (frm['M_DIST_UPLOAD_SOURCE']) {
  5214. frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
  5215. }
  5216. })
  5217. jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
  5218. 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; ?>',
  5219. beforeSubmit: function(args, $form, options) {
  5220. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
  5221. var argsMap = [];
  5222. args.map(function(v, k) {
  5223. argsMap[v.name] = v.value;
  5224. });
  5225. // validate
  5226. if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
  5227. if (!argsMap['M_DIST_FILES_NAME']) {
  5228. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
  5229. return false;
  5230. }
  5231. }
  5232. else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
  5233. if (!argsMap['SCANS_COLUMN_ADD']) {
  5234. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
  5235. return false;
  5236. }
  5237. }
  5238. else {
  5239. return false;
  5240. }
  5241. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  5242. $out.html('Wysyłanie...');
  5243. },
  5244. success: function(data) {
  5245. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->success()...');
  5246. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  5247. var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
  5248. if (typeof data == 'object') {
  5249. if (data.type == 'error') {
  5250. $out.html('<div class="alert alert-danger">' + btnClose + data.msg + '</div>');
  5251. } else if (data.type == 'SUCCESS') {
  5252. $out.html('<div class="alert alert-success">' + btnClose + data.msg + '</div>');
  5253. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  5254. // TODO: scanFileListUpdateAjax...
  5255. }
  5256. } else {
  5257. if (data.substr(0, 7) == 'WARNING') {
  5258. data = data.substr(7);
  5259. $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
  5260. } else if (data.substr(0, 5) == 'error') {
  5261. data = data.substr(5);
  5262. $out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
  5263. } else if (data.substr(0, 7) == 'SUCCESS') {
  5264. data = data.substr(7);
  5265. $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
  5266. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  5267. // TODO: scanFileListUpdateAjax...
  5268. } else if (data.substr(0, 4) == 'INFO') {
  5269. data = data.substr(4);
  5270. $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
  5271. }
  5272. }
  5273. }
  5274. });
  5275. fileListActions<?php echo $this->_htmlID; ?>();
  5276. var fileList = <?php echo json_encode($jsonFiles); ?>;
  5277. fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
  5278. var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
  5279. if (connTbls) {
  5280. var connTblsOut = '';
  5281. for(var key in connTbls) {
  5282. connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
  5283. };
  5284. if (connTblsOut) {
  5285. connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
  5286. connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
  5287. '<table class="table table-bordered table-hover">' +
  5288. '<colgroup>' +
  5289. '<col style="">' +
  5290. '<col style="width:30px;">' +
  5291. <?php if ($sharePoint) : ?>
  5292. '<col style="width:30px;">' +
  5293. <?php endif; ?>
  5294. '<col style="width:80px;">' +
  5295. '<col style="width:140px;">' +
  5296. '</colgroup>' +
  5297. '<tbody class="files-list">' +
  5298. '</tbody>' +
  5299. '</table>' +
  5300. '</div>';
  5301. var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
  5302. _connTblsWrap.css('marginBottom', '26px');
  5303. _connTblsWrap.html(connTblsOut);
  5304. _connTblsWrap.find('.conn-tbl-load').each(function(){
  5305. jQuery(this).click(function(e){
  5306. var tblID = jQuery(e.target).data('zasobid');
  5307. if (tblID) {
  5308. connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
  5309. }// TODO: else show error
  5310. });
  5311. });
  5312. }
  5313. }
  5314. initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
  5315. });
  5316. </script>
  5317. <?php
  5318. exit;
  5319. }
  5320. private function sendTypeSpecial($fldID, $args) {
  5321. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5322. header("Content-type: application/json");
  5323. $fldName = '';
  5324. $fld = $this->_acl->getField($fldID);
  5325. 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>';}
  5326. if (!$fld) {
  5327. // 404
  5328. } else {
  5329. $fldName = $fld['name'];
  5330. }
  5331. $jsonData = array();
  5332. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  5333. if ($typeSpecial) {
  5334. $query = V::get('q', '', $_REQUEST);
  5335. $rawRows = null;
  5336. $rows = $typeSpecial->getValuesWithExports($query);
  5337. 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>';}
  5338. foreach ($rows as $kID => $vItem) {
  5339. $itemJson = new stdClass();
  5340. $itemJson->id = $vItem->id;
  5341. $itemJson->name = $vItem->param_out;
  5342. if (!empty($vItem->exports)) {
  5343. $itemJson->exports = $vItem->exports;
  5344. }
  5345. if (!empty($vItem->{'$order'})) {
  5346. $itemJson->{'$order'} = $vItem->{'$order'};
  5347. }
  5348. $jsonData[] = $itemJson;
  5349. }
  5350. }
  5351. /*
  5352. MENU_INIT:VIEWTABLE_AJAX
  5353. ZASOB_ID:1188
  5354. _task:TYPESPECIAL
  5355. fldID:3866
  5356. Form Dataview sourceview URL encoded
  5357. q:te
  5358. */
  5359. echo json_encode($jsonData);
  5360. exit;
  5361. }
  5362. public function ajaxData($args) {// executed from url: "{$this->syncUrl"&_hash={$this->_htmlID}&_task=loadDataAjax"
  5363. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  5364. $acl = $this->_acl;
  5365. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  5366. $page = V::get('page', 0, $args, 'int');
  5367. $currSortCol = V::get('currSortCol', '', $args);
  5368. $currSortFlip = V::get('currSortFlip', '', $args);
  5369. if ($page > 0) {
  5370. $page -= 1;
  5371. }
  5372. $params = array();
  5373. $params['limit'] = $pageSize;
  5374. $params['limitstart'] = $page * $params['limit'];
  5375. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  5376. $params['order_dir'] = $currSortFlip;
  5377. $filters = new stdClass();
  5378. $filters->currSortCol = $currSortCol;
  5379. $filters->currSortFlip = $currSortFlip;
  5380. foreach ($args as $k => $v) {
  5381. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  5382. $params[$k] = $v;
  5383. $filters->{$k} = $v;
  5384. }
  5385. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  5386. $params[$k] = $v;
  5387. $filters->{$k} = $v;
  5388. }
  5389. }
  5390. $this->setFilters($filters);
  5391. $vCols = $acl->getVirtualFieldListByIdZasob();
  5392. if (!empty($vCols)) {
  5393. 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>';}
  5394. }
  5395. $visibleCols = $acl->getVisibleFieldListByIdZasob();
  5396. 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>';}
  5397. $jsonData = new stdClass();
  5398. $jsonData->page = $page + 1;
  5399. $jsonData->pageSize = $pageSize;
  5400. $jsonData->filters = $filters;
  5401. $jsonData->cols = new stdClass();
  5402. $jsonData->uniqueCol = $acl->getPrimaryKeyField();
  5403. $ind = 0;
  5404. foreach ($visibleCols as $fieldID => $col) {
  5405. $ind++;
  5406. $columnConfig = (object)array('index'=>$ind);
  5407. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  5408. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  5409. }
  5410. else if (in_array($col, array('Status'))) {
  5411. // Ahmes problems Status colors
  5412. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  5413. }
  5414. else if ($acl->isGeomField($col)) {
  5415. $columnConfig->type = 'geom';
  5416. }
  5417. if ('' !== ($label = $acl->getFieldLabel($col))) {
  5418. $columnConfig->friendly = $label;
  5419. }
  5420. $colType = $acl->getFieldType($col);
  5421. if ($colType) {// @see MarkTableAjaxFilterColType
  5422. 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>';}
  5423. if ($colType['type'] == 'date') {
  5424. //$columnConfig->type = 'date';// TODO: require datetimepicker
  5425. }
  5426. if (!empty($colType['simpleType'])) $columnConfig->type = $colType['simpleType'];
  5427. } else {// typespecial - no type
  5428. $columnConfig->type = 'special';
  5429. }
  5430. $columnConfig->xsdType = $acl->getXsdFieldType($col);
  5431. if ($columnConfig->xsdType) {
  5432. $ex = explode(":", $columnConfig->xsdType);
  5433. switch ($ex[0]) {
  5434. case 'ref':
  5435. case 'alias_ref':
  5436. if (3 != count($ex)) throw new HttpException("Schema Error for field({$col}) xsdType({$columnConfig->xsdType})", 500);
  5437. $columnConfig->type = 'ref';
  5438. $columnConfig->xsdRefUri = Api_WfsNs::getNsUri($ex[1]);
  5439. $columnConfig->xsdRefType = $ex[2];
  5440. $columnConfig->xsdRefNsPrefix = $ex[1];
  5441. break;
  5442. case 'xsd':
  5443. switch ($ex[1]) {
  5444. case 'string': $columnConfig->type = 'string'; break;
  5445. case 'ind': $columnConfig->type = 'number'; break;// TODO: bug 'ind'?
  5446. }
  5447. break;
  5448. }
  5449. }
  5450. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  5451. if ($typeSpecial) {
  5452. 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>';}
  5453. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  5454. if ($columnConfig->_tsRetId == 0) {
  5455. $tsParamOut = V::get('param_out', null, $typeSpecial);
  5456. if ($tsParamOut) {
  5457. $tsFormat = V::get('format', null, $tsParamOut);
  5458. $tsValues = V::get('values', null, $tsParamOut);
  5459. $tsAliases = V::get('alias', null, $tsParamOut);
  5460. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  5461. $tsAliasMap = array();
  5462. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  5463. $bugTsColsNotVisible = array();
  5464. foreach ($tsValues as $kVarName => $vIdZasob) {
  5465. if (array_key_exists($vIdZasob, $tsAliases)) {
  5466. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  5467. } else {
  5468. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  5469. }
  5470. if (!array_key_exists($vIdZasob, $visibleCols)) {
  5471. $bugTsColsNotVisible[] = $vIdZasob;
  5472. }
  5473. }
  5474. if (empty($bugTsColsNotVisible)) {
  5475. $tsSimpleLink = new stdClass();
  5476. $tsSimpleLink->format = $tsFormat;
  5477. $tsSimpleLink->aliasMap = $tsAliasMap;
  5478. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  5479. $columnConfig->type = 'simpleLink';
  5480. } else {
  5481. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  5482. }
  5483. }
  5484. }
  5485. }
  5486. }
  5487. if ($columnConfig->xsdType) {// fix fields type p5:typeSpecialSimpleLink (previously defined by Typespecial)
  5488. switch ($columnConfig->xsdType) {
  5489. case 'p5:typeSpecialSimpleLink': {
  5490. $columnConfig->type = 'simpleLink';
  5491. $columnConfig->_tsRetId = 0;
  5492. $columnConfig->_tsSimpleLink = new stdClass();
  5493. $columnConfig->_tsSimpleLink->format = $acl->getXsdFieldParam($col, 'format');
  5494. $columnConfig->_tsSimpleLink->aliasMap = $acl->getXsdFieldParam($col, 'aliasMap');
  5495. } break;
  5496. }
  5497. }
  5498. // @see ajaxHiddenColsSave
  5499. if (UserProfile::isHiddenColumn($acl->getID(), $fieldID)) {
  5500. $columnConfig->hidden = true;
  5501. }
  5502. $columnConfig->description = $acl->getFieldOpis($col);
  5503. $jsonData->cols->{$col} = $columnConfig;
  5504. }
  5505. $jsonData->rows = array();
  5506. $jsonData->total = $acl->getTotal($params);
  5507. 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>';}
  5508. $items = $acl->getItems($params);
  5509. foreach ($items as $idx => $item) $items[$idx] = (array)$item;
  5510. 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>';}
  5511. // TODO: add virtual data by Typespecial
  5512. if (!empty($vCols) && !empty($items)) {
  5513. foreach ($vCols as $vColID => $vCol) {
  5514. $colType = $acl->getFieldTypeById($vColID);
  5515. if ($colType) continue;// pomin Typespecial dla realnych komorek w bazie danych
  5516. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  5517. if ($typeSpecial) {
  5518. $columnConfig = V::get($vCol, null, $jsonData->cols);
  5519. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  5520. // pomin simple link values - mved to js render
  5521. } else {
  5522. 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>';}
  5523. $ids = array_keys($items);
  5524. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  5525. 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>';}
  5526. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  5527. $tsValue = implode('<br>', $vValues);
  5528. 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>';}
  5529. if (!empty($items[$kItemID][$vCol]) && !empty($tsValue)) {
  5530. $items[$kItemID][$vCol] .= ": {$tsValue}";
  5531. } else {
  5532. $items[$kItemID][$vCol] = $tsValue;
  5533. }
  5534. }
  5535. }
  5536. }
  5537. }
  5538. }
  5539. foreach ($items as $item) {
  5540. // TODO: hide items without 'R'
  5541. foreach ($visibleCols as $fieldName) {
  5542. // TODO: ID default 'R'
  5543. if (!$acl->canReadObjectField($fieldName, $item)) $item[$fieldName] = '*****';
  5544. // null => empty string
  5545. if (!isset($item[$fieldName]) || (!$item[$fieldName] && $item[$fieldName] !== '0')) {
  5546. 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>';}
  5547. $item[$fieldName] = '';
  5548. }
  5549. }
  5550. $jsonData->rows[] = $item;
  5551. }
  5552. $jsonData->type = 'success';
  5553. $jsonData->msg = 'pobrano nowe dane';
  5554. return $jsonData;
  5555. }
  5556. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  5557. $value = '';
  5558. $type = $this->_acl->getFieldTypeById($fieldID);
  5559. if ($type) {
  5560. if ($type['type'] == 'date') {
  5561. $value = $type['default'];
  5562. }
  5563. // fix bug when field is unique and is null allowed: change empty string to null
  5564. if ($type['null']) {
  5565. $value = 'NULL';
  5566. }
  5567. // fix bug when field is enum and is set to '0': for php '0' is empty
  5568. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  5569. if (false !== strpos($type['type'], "''")) {
  5570. // enum('', '1','2')
  5571. $value = '';
  5572. } else if (false !== strpos($type['type'], "'0'")) {
  5573. // enum('0', '1','2')
  5574. $value = '0';
  5575. } else {
  5576. $value = $type['default'];
  5577. }
  5578. }
  5579. }
  5580. return $value;
  5581. }
  5582. /**
  5583. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  5584. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  5585. */
  5586. private function ajaxHiddenColsSave($args) {
  5587. $response = new stdClass();
  5588. if (empty($args)) {
  5589. $response->type = 'info';
  5590. return $response;
  5591. }
  5592. UserProfile::load();
  5593. // clean up old, wrong values
  5594. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5595. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5596. }
  5597. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  5598. $fields = $this->_acl->getFieldListByIdZasob();
  5599. foreach ($fields as $idField => $fieldName) {
  5600. if (isset($args[$fieldName])) {
  5601. if ($args[$fieldName] == 'SHOW') {
  5602. $colVis[$idField] = 1;
  5603. } else if ($args[$fieldName] == 'HIDE') {
  5604. $colVis[$idField] = 0;
  5605. }
  5606. }
  5607. }
  5608. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  5609. UserProfile::save();
  5610. $response->type = 'success';
  5611. return $response;
  5612. }
  5613. private function ajaxPageSizeSave($args) {
  5614. $response = new stdClass();
  5615. if (empty($args)) {
  5616. $response->type = 'info';
  5617. return $response;
  5618. }
  5619. $pageSize = V::get('pageSize', 0, $args, 'int');
  5620. UserProfile::load();
  5621. // clean up old, wrong values
  5622. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5623. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5624. }
  5625. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  5626. $tableAjaxSettings['pageSize'] = $pageSize;
  5627. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  5628. UserProfile::save();
  5629. $response->type = 'success';
  5630. return $response;
  5631. }
  5632. private function ajaxTheGeomSave($args) {
  5633. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5634. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5635. $polygon = V::get('polygon', 0, $args);
  5636. $geomFieldName = 'the_geom';
  5637. if ($primaryKey <= 0) {
  5638. throw new HttpException("Wrong param ID", 404);
  5639. }
  5640. // 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)))
  5641. $record = $this->_acl->getItem($primaryKey);
  5642. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5643. throw new HttpException("Brak dostępu do rekordu", 403);
  5644. }
  5645. if (!$this->_acl->canWriteObjectField($geomFieldName, $record)) {
  5646. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5647. }
  5648. $itemPatch = array();
  5649. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  5650. $itemPatch[$primaryKeyField] = $primaryKey;
  5651. $response = new stdClass();
  5652. try {
  5653. $affected = $this->_acl->updateItem($itemPatch);
  5654. if ($affected > 0) {
  5655. $response->type = 'success';
  5656. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5657. } else if ($affected == 0) {
  5658. $response->type = 'info';
  5659. $response->msg = "Nie wprowadzono żadnych zmian";
  5660. }
  5661. $response->record = $this->_acl->getItem($primaryKey);
  5662. }
  5663. catch (Exception $e) {
  5664. $response->type = 'error';
  5665. $response->msg = $e->getMessage();
  5666. }
  5667. return $response;
  5668. }
  5669. private function sendAjaxResponseJson($method, $args) {
  5670. try {
  5671. $response = $this->{$method}($args);
  5672. }
  5673. catch (HttpException $e) {
  5674. $response = new stdClass();
  5675. $response->type = 'error';
  5676. $response->msg = $e->getMessage();
  5677. $response->errorCode = $e->getCode();
  5678. Http::sendHeaderByCode($e->getCode());
  5679. }
  5680. catch (Exception $e) {
  5681. $response = new stdClass();
  5682. $response->type = 'error';
  5683. $response->msg = $e->getMessage();
  5684. $response->errorCode = $e->getCode();
  5685. }
  5686. header('Content-type: application/json');
  5687. if (!$response) $response = new stdClass();
  5688. echo json_encode($response);
  5689. exit;
  5690. }
  5691. private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
  5692. $response = new stdClass();
  5693. $pInitList = array();// [proces_init_id] => label (DESC)
  5694. if (!$this->_showProcesInit) {
  5695. $response->type = 'error';
  5696. return $response;
  5697. }
  5698. $userAcl = User::getAcl();
  5699. $pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
  5700. if (!empty($pInitList)) {
  5701. $procesIds = array_keys($pInitList);
  5702. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  5703. DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
  5704. DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
  5705. $pInitListSelected = $this->getProcesInitSelected();
  5706. $response->pInitData = new stdClass();
  5707. $response->pInitData->pInitList = $pInitList;
  5708. $response->pInitData->mapTree = $mapTree;
  5709. $response->pInitData->pInitListSelected = $pInitListSelected;
  5710. }
  5711. $response->type = 'success';
  5712. return $response;
  5713. }
  5714. }