TableAjax.php 231 KB

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