TableAjax.php 181 KB

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