TableAjax.php 239 KB

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