TableAjax.php 207 KB

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