TableAjax.php 242 KB

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