TableAjax.php 241 KB

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