TableAjax.php 195 KB

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