TableAjax.php 181 KB

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