TableAjax.php 199 KB

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