TableAjax.php 235 KB

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