TableAjax.php 228 KB

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