TableAjax.php 182 KB

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