TableAjax.php 183 KB

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