TableAjax.php 183 KB

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