TableAjax.php 225 KB

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