TableAjax.php 197 KB

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