TableAjax.php 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247
  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.loadPage = function(page, pageSize) {
  2107. var skipCols = true, // skipCols = true - prevent columns delete
  2108. resetChecked = false;
  2109. var reqData = {
  2110. page: page,
  2111. pageSize: (pageSize || priv.options.pageSize),
  2112. currSortCol: (_currSortCol || ''),
  2113. currSortFlip: _currSortFlip ? "desc" : "asc"
  2114. };
  2115. if (Object.keys(_filterCols).length > 0) {
  2116. $.each(_filterCols, function (col, colProps) {
  2117. if (colProps.filter && colProps.filter.length > 0) {
  2118. reqData['f_' + col] = colProps.filter;
  2119. }
  2120. });
  2121. skipCols = true;
  2122. }
  2123. // specialFilters
  2124. $.each(_specialFilters, function(groupName, btnValue) {
  2125. if (btnValue.length > 0) {
  2126. reqData['sf_' + groupName] = btnValue;
  2127. }
  2128. });
  2129. if (priv.options.forceFilterInit) {
  2130. $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
  2131. reqData['f_' + fltr] = fltrProps;
  2132. filtersInitSet = true;
  2133. });
  2134. }
  2135. _table.parent().parent().addClass('AjaxTable-loading');
  2136. $.ajax({
  2137. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2138. type: 'GET',
  2139. dataType: 'json',
  2140. contentType: "application/json; charset=utf-8",
  2141. data: reqData,
  2142. async: true,
  2143. success: function (data) {
  2144. if (data.d && data.d.cols)
  2145. priv.setData(data.d, skipCols, resetChecked);
  2146. else
  2147. priv.setData(data, skipCols, resetChecked);
  2148. if (typeof callback == "function")
  2149. callback.call(this);
  2150. _table.parent().parent().removeClass('AjaxTable-loading');
  2151. },
  2152. error: function (err) {
  2153. if (priv.options.debug) console.log('request error: {0}'.f(JSON.stringify(err)));
  2154. }
  2155. });
  2156. };
  2157. publ.getCurrentPage = function() {
  2158. return _currPage;
  2159. };
  2160. publ.popoverCellRemove = function () {
  2161. _popoverCellCurrent.popover('destroy');
  2162. _popoverCell.data('rowid', -1);
  2163. _popoverCell.data('col', -1);
  2164. _popoverCell.html('');
  2165. };
  2166. return publ;
  2167. }
  2168. $.fn.TableAjax = function (options) {
  2169. options = options || {};
  2170. return this.each(function () {
  2171. options.id = this;
  2172. $(this).data('TableAjax', new TableAjax().init(options));
  2173. });
  2174. };
  2175. $.fn.TableAjaxLoadPage = function (page, pageSize) {
  2176. return this.each(function () {
  2177. var tblAjax = jQuery(this).data('TableAjax');
  2178. var curPage = page || tblAjax.getCurrentPage();
  2179. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  2180. });
  2181. };
  2182. String.prototype.format = String.prototype.f = function () {
  2183. var s = this;
  2184. i = arguments.length;
  2185. while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
  2186. return s;
  2187. };
  2188. })(jQuery);
  2189. </script>
  2190. <?php
  2191. $filterInit = $this->_filterInit;
  2192. $forceFilterInit = $this->_forceFilterInit;
  2193. $pageSizes = $this->_pageSizes;
  2194. $rowFunctions = $this->_showRowFunctionsJson();
  2195. $exportFields = $this->_showExportFieldsJson();
  2196. ?>
  2197. <script>
  2198. jQuery(document).ready(function(){
  2199. jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
  2200. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2201. columnPicker: true,
  2202. filter: true,
  2203. filterInit: <?php echo json_encode($filterInit); ?>,
  2204. forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
  2205. debug: true, // TODO: DBG
  2206. height: 400, // TODO: ?
  2207. sorting: true, // TODO: ?
  2208. paging: true, // TODO: ?
  2209. pageSizes: <?php echo json_encode($pageSizes); ?>,
  2210. pageChanged: function(args) {
  2211. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2212. con.TableAjaxLoadPage(args.page);
  2213. },
  2214. pageSizeChanged: function(args) {
  2215. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2216. con.TableAjaxLoadPage(0, args.pageSize);
  2217. },
  2218. tblFunctions: {
  2219. shortdesc: {
  2220. icon: 'align-left',
  2221. title: 'Long desc',
  2222. method: 'longTextChanged'
  2223. },
  2224. <?php if ($hasGeomFlds) : ?>
  2225. mapeditor: {
  2226. icon: 'map-marker',
  2227. title: 'Mapa',
  2228. method: 'mapEditorChanged'
  2229. },
  2230. <?php endif; ?>
  2231. create: {
  2232. href: '#CREATE',
  2233. icon: 'plus',
  2234. title: 'Dodaj nowy rekord'
  2235. },
  2236. refresh: {
  2237. icon: 'refresh',
  2238. title: 'Odśwież dane',
  2239. method: 'refresh'
  2240. }
  2241. },
  2242. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  2243. exportFields: <?php echo json_encode($exportFields); ?>,
  2244. specialFilterFunctions: <?php
  2245. $fltrs = $this->_dataSource->getSpecialFilters();
  2246. if (!empty($fltrs)) {
  2247. echo json_encode($fltrs);
  2248. } else {
  2249. echo 'false';
  2250. }
  2251. echo ',';
  2252. ?>
  2253. router: function () {
  2254. var routes = {
  2255. EDIT: function (args) {
  2256. var recordID = args;
  2257. if (typeof args == 'object') {
  2258. recordID = args.shift();
  2259. recordID = parseInt(recordID);
  2260. }
  2261. if (typeof recordID !== 'number' || recordID <= 0) {
  2262. // TODO: msg
  2263. return false;
  2264. }
  2265. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2266. cont.hide();
  2267. // remove previous task content
  2268. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2269. taskCnt.parent().remove();
  2270. taskCnt.remove();
  2271. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2272. jQuery('<ul class="breadcrumb">' +
  2273. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
  2274. '<li class="active">Edytuj rekord</li>' +
  2275. '</ul>').appendTo(taskCont);
  2276. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2277. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2278. jQuery.ajax({
  2279. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
  2280. type: 'GET',
  2281. dataType: 'text',
  2282. data: '',
  2283. async: true,
  2284. success: function (data) {
  2285. taskCnt.removeClass('AjaxTable-loading');
  2286. jQuery(data).appendTo(taskCnt);
  2287. taskCnt.find('.se_type-date').datepicker({
  2288. format: "yyyy-mm-dd"
  2289. , language: 'pl'
  2290. , todayBtn: "linked"
  2291. });
  2292. taskCnt.find('.se_type-datetime').parent().datetimepicker({
  2293. language: 'pl'
  2294. , format: 'yyyy-MM-dd hh:mm'
  2295. , weekStart: 1
  2296. });
  2297. },
  2298. error: function (err) {
  2299. taskCnt.removeClass('AjaxTable-loading');
  2300. //console.log('request error: {0}'.f(err));
  2301. }
  2302. });
  2303. //return false;
  2304. },
  2305. HIST: function (args) {
  2306. var recordID = args;
  2307. if (typeof args == 'object') {
  2308. recordID = args.shift();
  2309. recordID = parseInt(recordID);
  2310. }
  2311. if (typeof recordID !== 'number' || recordID <= 0) {
  2312. // TODO: msg
  2313. return false;
  2314. }
  2315. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2316. cont.hide();
  2317. // remove previous task content
  2318. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2319. taskCnt.parent().remove();
  2320. taskCnt.remove();
  2321. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2322. jQuery('<ul class="breadcrumb">' +
  2323. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
  2324. '<li class="active">Historia rekordu</li>' +
  2325. '</ul>').appendTo(taskCont);
  2326. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2327. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2328. jQuery.ajax({
  2329. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
  2330. type: 'GET',
  2331. dataType: 'text',
  2332. data: '',
  2333. async: true,
  2334. success: function (data) {
  2335. taskCnt.removeClass('AjaxTable-loading');
  2336. //console.log('request finished L.<?php echo __LINE__; ?>');
  2337. jQuery(data).appendTo(taskCnt);
  2338. },
  2339. error: function (err) {
  2340. taskCnt.removeClass('AjaxTable-loading');
  2341. //console.log('request error: {0}'.f(err));
  2342. }
  2343. });
  2344. //return false;
  2345. },
  2346. FILES: function tableAjaxFiles(args) {
  2347. var recordID = args;
  2348. if (typeof args == 'object') {
  2349. recordID = args.shift();
  2350. recordID = parseInt(recordID);
  2351. }
  2352. if (typeof recordID !== 'number' || recordID <= 0) {
  2353. // TODO: msg
  2354. return false;
  2355. }
  2356. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2357. cont.hide();
  2358. // remove previous task content
  2359. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2360. taskCnt.parent().remove();
  2361. taskCnt.remove();
  2362. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2363. jQuery('<ul class="breadcrumb">' +
  2364. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
  2365. '<li class="active">Pliki</li>' +
  2366. '</ul>').appendTo(taskCont);
  2367. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  2368. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2369. jQuery.ajax({
  2370. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  2371. type: 'GET',
  2372. dataType: 'text',
  2373. data: '',
  2374. async: true,
  2375. success: function (data) {
  2376. taskCnt.removeClass('AjaxTable-loading');
  2377. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  2378. jQuery(data).appendTo(taskCnt);
  2379. },
  2380. error: function (jqXHR, textStatus, errorThrown) {
  2381. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  2382. taskCnt.removeClass('AjaxTable-loading');
  2383. var txt = jqXHR.responseText || 'Error';
  2384. if (jqXHR.status == 404) {
  2385. jQuery('<div class="container"><div class="alert alert-error">' + txt + '</div></div>').appendTo(taskCnt);
  2386. } else {
  2387. jQuery('<div class="container"><div class="alert alert-error">' + txt + '</div></div>').appendTo(taskCnt);
  2388. }
  2389. }
  2390. });
  2391. //return false;
  2392. },
  2393. CREATE: function tableAjaxCreate() {
  2394. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2395. cont.hide();
  2396. // remove previous task content
  2397. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2398. taskCnt.parent().remove();
  2399. taskCnt.remove();
  2400. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2401. jQuery('<ul class="breadcrumb">' +
  2402. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
  2403. '<li class="active">Dodaj nowy rekord</li>' +
  2404. '</ul>').appendTo(taskCont);
  2405. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2406. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2407. var reqData = {};
  2408. var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
  2409. if (forceFilterInit) {
  2410. $.map(forceFilterInit, function (fltrProps, fltr) {
  2411. reqData['ff_' + fltr] = fltrProps;
  2412. });
  2413. }
  2414. jQuery.ajax({
  2415. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
  2416. type: 'GET',
  2417. dataType: 'text',
  2418. data: reqData,
  2419. async: true,
  2420. success: function (data) {
  2421. taskCnt.removeClass('AjaxTable-loading');
  2422. //console.log('request finished L.<?php echo __LINE__; ?>');
  2423. jQuery(data).appendTo(taskCnt);
  2424. taskCnt.find('.se_type-date').datepicker({
  2425. format: "yyyy-mm-dd"
  2426. , language: 'pl'
  2427. , todayBtn: "linked"
  2428. });
  2429. taskCnt.find('.se_type-datetime').parent().datetimepicker({
  2430. language: 'pl'
  2431. , format: 'yyyy-MM-dd hh:mm'
  2432. , weekStart: 1
  2433. });
  2434. },
  2435. error: function (err) {
  2436. taskCnt.removeClass('AjaxTable-loading');
  2437. //console.log('request error: {0}'.f(err));
  2438. }
  2439. });
  2440. //return false;
  2441. }
  2442. };
  2443. var routePath = location.hash;
  2444. //console.log('location.hash: ' + routePath);
  2445. if (location.hash == '' || location.hash == '#') {
  2446. return false;
  2447. }
  2448. if (routePath.charAt(0) == '#') {
  2449. routePath = routePath.substr(1);
  2450. }
  2451. //console.log('routePath: ' + routePath);
  2452. var parts = routePath.split('/');
  2453. var task = parts.shift();
  2454. //console.log('task(' + task + ') parts:');
  2455. //console.log(parts);
  2456. if (task in routes && typeof routes[task] == 'function') {
  2457. routes[task](parts);
  2458. } else {
  2459. return false;
  2460. }
  2461. },
  2462. filtersClean: true,
  2463. longDesc: true
  2464. });
  2465. });
  2466. function tableAjaxBackToTable() {
  2467. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2468. cont.show();
  2469. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  2470. taskCont.remove();
  2471. // reload first page
  2472. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2473. con.TableAjaxLoadPage(0);// TODO: load current page
  2474. }
  2475. function tableAjaxCopy(args) {
  2476. var recordID = args;
  2477. if (typeof args == 'object') {
  2478. recordID = args.shift();
  2479. recordID = parseInt(recordID);
  2480. }
  2481. if (typeof recordID !== 'number' || recordID <= 0) {
  2482. // TODO: msg
  2483. return false;
  2484. }
  2485. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  2486. return false;
  2487. }
  2488. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2489. //cont.hide();
  2490. //var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  2491. //taskCont.remove();
  2492. cont.children('.alert').fadeOut('slow');
  2493. var alert = jQuery('<div class="alert fade in"><strong>Kopiuj rekord</strong> ... </div>').prependTo(cont);
  2494. jQuery.ajax({
  2495. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  2496. type: 'GET',
  2497. dataType: 'text',
  2498. data: '',
  2499. async: true,
  2500. success: function (data) {
  2501. //console.log('data: ', data);
  2502. alert.remove();
  2503. alert = jQuery(data).prependTo(cont);
  2504. alert.alert();
  2505. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2506. con.TableAjaxLoadPage(0);
  2507. },
  2508. error: function (err) {
  2509. alert.remove();
  2510. if (priv.options.debug) console.log(err);
  2511. }
  2512. });
  2513. return false;
  2514. }
  2515. function hidePopover() {
  2516. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2517. if (con) {
  2518. var tblAjax = con.data('TableAjax');
  2519. if (tblAjax) {
  2520. tblAjax.popoverCellRemove();
  2521. }
  2522. }
  2523. return false;
  2524. }
  2525. </script>
  2526. <?php
  2527. $out = ob_get_contents();
  2528. ob_end_clean();
  2529. return $out;
  2530. }
  2531. public function ajaxTask($task) {
  2532. switch ($task) {
  2533. case 'EDIT': {
  2534. $id = V::get('ID', 0, $_REQUEST, 'int');
  2535. if ($id > 0) {
  2536. $this->sendAjaxEdit($id, $_REQUEST);
  2537. } else {
  2538. echo '404';
  2539. }
  2540. break;
  2541. }
  2542. case 'EDIT_SAVE': {
  2543. $id = V::get('ID', 0, $_REQUEST, 'int');
  2544. if ($id > 0) {
  2545. $this->sendAjaxEditSave($id, $_REQUEST);
  2546. } else {
  2547. echo '404';
  2548. }
  2549. break;
  2550. }
  2551. case 'EDIT_INLINE': {
  2552. $id = V::get('ID', 0, $_REQUEST, 'int');
  2553. $col = V::get('col', '', $_REQUEST);
  2554. if ($id > 0 && !empty($col)) {
  2555. $this->sendAjaxEditInline($id, $col, $_REQUEST);
  2556. } else {
  2557. echo '404';
  2558. }
  2559. break;
  2560. }
  2561. case 'EDIT_INLINE_SAVE': {
  2562. $id = V::get('ID', 0, $_REQUEST, 'int');
  2563. $col = V::get('col', '', $_REQUEST);
  2564. if ($id > 0 && !empty($col)) {
  2565. $this->sendAjaxEditInlineSave($id, $col, $_REQUEST);
  2566. } else {
  2567. echo '404';
  2568. }
  2569. break;
  2570. }
  2571. case 'COPY': {
  2572. $id = V::get('ID', 0, $_REQUEST, 'int');
  2573. if ($id > 0) {
  2574. $this->sendAjaxCopy($id, $_REQUEST);
  2575. } else {
  2576. echo '404';
  2577. }
  2578. break;
  2579. }
  2580. case 'CREATE': {
  2581. $this->sendAjaxCreate($_REQUEST);
  2582. break;
  2583. }
  2584. case 'CREATE_SAVE': {
  2585. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  2586. break;
  2587. }
  2588. case 'HIST': {
  2589. $id = V::get('ID', 0, $_REQUEST, 'int');
  2590. if ($id > 0) {
  2591. $this->sendAjaxHistory($id, $_REQUEST);
  2592. } else {
  2593. echo '404';
  2594. }
  2595. break;
  2596. }
  2597. case 'FILES': {
  2598. $id = V::get('ID', 0, $_REQUEST, 'int');
  2599. if ($id > 0) {
  2600. $this->sendAjaxFiles($id, $_REQUEST);
  2601. } else {
  2602. echo '404';
  2603. }
  2604. break;
  2605. }
  2606. case 'FILES_UPLOAD': {
  2607. $id = V::get('ID', 0, $_REQUEST, 'int');
  2608. if ($id > 0) {
  2609. $this->sendAjaxFilesUpload($id, $_REQUEST);
  2610. } else {
  2611. echo '404';
  2612. }
  2613. break;
  2614. }
  2615. case 'FILES_LIST': {
  2616. $id = V::get('ID', 0, $_REQUEST, 'int');
  2617. if ($id > 0) {
  2618. $this->sendAjaxFilesList($id, $_REQUEST);
  2619. } else {
  2620. echo '404';
  2621. }
  2622. break;
  2623. }
  2624. case 'FILE_REMOVE': {
  2625. $id = V::get('ID', 0, $_REQUEST, 'int');
  2626. if ($id > 0) {
  2627. $this->sendAjaxFileRemove($id, $_REQUEST);
  2628. } else {
  2629. echo '404';
  2630. }
  2631. break;
  2632. }
  2633. case 'filePermsRefresh': {
  2634. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  2635. break;
  2636. }
  2637. case 'FILES_CONN_TBL_LIST': {
  2638. $id = V::get('ID', 0, $_REQUEST, 'int');
  2639. if ($id > 0) {
  2640. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  2641. } else {
  2642. echo '404';
  2643. }
  2644. break;
  2645. }
  2646. case 'TYPESPECIAL': {
  2647. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  2648. if ($fldID > 0) {
  2649. $this->sendTypeSpecial($fldID, $_REQUEST);
  2650. } else {
  2651. echo '404';
  2652. }
  2653. break;
  2654. }
  2655. case 'TYPESPECIALL_CELL': {
  2656. $id = V::get('ID', 0, $_REQUEST, 'int');
  2657. $col = V::get('col', '', $_REQUEST);
  2658. if ($id > 0 && !empty($col)) {
  2659. $this->sendTypeSpecialCell($id, $col, $_REQUEST);
  2660. } else {
  2661. echo '404';
  2662. }
  2663. break;
  2664. }
  2665. case 'HIDDEN_COLS_SAVE': {
  2666. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  2667. break;
  2668. }
  2669. case 'THE_GEOM_SAVE': {
  2670. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  2671. break;
  2672. }
  2673. case 'THE_GEOM_REMOVE': {
  2674. $this->sendAjaxResponseJson('ajaxTheGeomRemove', $_REQUEST);
  2675. break;
  2676. }
  2677. default:
  2678. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  2679. }
  2680. }
  2681. /**
  2682. * ajax url: &_task=EDIT_INLINE
  2683. * @param $rowID - $_GET['ID']
  2684. * @param $fieldName - $_GET['col']
  2685. */
  2686. private function sendAjaxEditInline($rowID, $fieldName, $args) {
  2687. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  2688. header("Content-type: text/plain");
  2689. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  2690. if (!$fieldID) {
  2691. echo "404: No field by name ({$fieldName})";
  2692. exit;
  2693. }
  2694. if ($DBG) echo "fieldID: {$fieldID}\n";
  2695. $row = $this->_dataSource->getItem($rowID);
  2696. if (!$row) {
  2697. echo "404: No item ID({$rowID})";
  2698. exit;
  2699. }
  2700. if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
  2701. if ($DBG) echo " R not allowed\n";
  2702. } else {
  2703. if ($DBG) echo " R allowed\n";
  2704. }
  2705. if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
  2706. if ($DBG) echo " W not allowed\n";
  2707. } else {
  2708. if ($DBG) echo " W allowed\n";
  2709. }
  2710. $fieldVal = '';
  2711. if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
  2712. $fieldVal = V::get($fieldName, $fieldVal, $row);
  2713. } else {
  2714. $fieldVal = '*****';
  2715. }
  2716. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  2717. $vCol = $this->_acl->getField($fieldID);
  2718. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  2719. $tsValues = array();
  2720. Lib::loadClass('Typespecial');
  2721. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  2722. if ($typeSpecial) {
  2723. 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>';}
  2724. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  2725. 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>';}
  2726. if (!empty($specialValues)) {
  2727. $tsValues[$row->ID] = implode('<br>', $specialValues);
  2728. }
  2729. }
  2730. Lib::loadClass('SE_Layout');
  2731. ?>
  2732. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  2733. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  2734. <?php if (!empty($vCol['opis'])) : ?>
  2735. <em><?php echo $vCol['opis']; ?></em>
  2736. <?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
  2737. <?php endif; ?>
  2738. </label>
  2739. <?php
  2740. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  2741. if (!empty($tsValues[$row->ID])) {
  2742. $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  2743. }
  2744. $vDefault = $this->_dataSource->getColDefault($fieldName);
  2745. if (!empty($vDefault)) {
  2746. $fieldParams['default'] = $vDefault;
  2747. }
  2748. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  2749. if ($typeSpecial) {
  2750. echo '<p style="padding:100px 0;"></p>';
  2751. }
  2752. exit;
  2753. }
  2754. private function sendAjaxEditInlineSave($rowID, $fieldName, $args) {
  2755. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  2756. sleep(1);// TODO: RMME DBG loading
  2757. 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>';}
  2758. 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>';}
  2759. $dbID = $this->_acl->getDB();
  2760. $db = DB::getDB($dbID);
  2761. if (!$db) {
  2762. header('HTTP/1.0 406 Not Acceptable');
  2763. exit;
  2764. }
  2765. $tblName = $this->_acl->getName();
  2766. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  2767. if (!$fieldID) {
  2768. header('HTTP/1.0 404 Not Found');
  2769. echo "404: No field by name ({$fieldName})";
  2770. exit;
  2771. }
  2772. $row = $this->_dataSource->getItem($rowID);
  2773. if (!$row) {
  2774. header('HTTP/1.0 404 Not Found');
  2775. echo "404: No item ID({$rowID})";
  2776. exit;
  2777. }
  2778. if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
  2779. header('HTTP/1.0 403 Forbidden');
  2780. echo "403: field not allowed to Write ({$fieldName})";
  2781. exit;
  2782. } else {
  2783. if ($DBG) echo " Write allowed\n";
  2784. }
  2785. $sqlObj = new stdClass();
  2786. if (array_key_exists("f{$fieldID}", $args)) {
  2787. if (!$this->_acl->isAllowed($fieldID, 'R', $record) && '*****' == $args["f{$fieldID}"]) {
  2788. // default value for perms 'W' without 'R' is '*****'
  2789. }
  2790. else {
  2791. $sqlObj->{$fieldName} = $args["f{$fieldID}"];
  2792. if (empty($args["f{$fieldID}"]) && strlen($args["f{$fieldID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
  2793. $sqlObj->{$fieldName} = $this->_acl->fixEmptyValueFromUser($fieldID);
  2794. }
  2795. }
  2796. }
  2797. else {
  2798. if ($DBG) echo " TODO: field value not set\n";
  2799. }
  2800. $sqlObj->ID = $rowID;
  2801. 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>';}
  2802. $ret = $db->UPDATE_OBJ($tblName, $sqlObj);
  2803. if ($ret > 0) {
  2804. echo '<div class="alert alert-success">';
  2805. echo "Rekord zapisany pomyślnie";//"Record saved successfully";
  2806. echo '</div>';
  2807. } else if ($ret == 0) {
  2808. echo '<div class="alert alert-info">';
  2809. echo "Nie wprowadzono żadnych zmian";
  2810. if ($db->has_errors()) {
  2811. //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>';
  2812. }
  2813. echo '</div>';
  2814. } else {
  2815. echo '<div class="alert alert-error">';
  2816. echo '<h4>' . "Wystąpiły błędy!" . '</h4>';
  2817. if ($db->has_errors()) {
  2818. $errors = $db->get_errors();
  2819. echo implode('<br>', $errors);
  2820. }
  2821. echo '</div>';
  2822. }
  2823. exit;
  2824. }
  2825. private function sendAjaxEdit($id, $args) {
  2826. header("Content-type: text/plain");
  2827. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  2828. $cols = array();
  2829. $record = $this->_dataSource->getItem($id);
  2830. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  2831. echo '<div class="alert alert-error">';
  2832. echo "Brak dostępu do rekordu";// TODO: more info - reason
  2833. echo '</div>';
  2834. return;
  2835. }
  2836. $fieldsList = $this->_acl->getFields();
  2837. foreach ($fieldsList as $kID => $vCol) {
  2838. if ($vCol['name'] == 'ID') {
  2839. unset($fieldsList[$kID]);
  2840. continue;
  2841. }
  2842. $cols[$kID] = '';
  2843. if ($this->_acl->isAllowed($kID, 'R', $record)) {
  2844. $cols[$kID] = V::get($vCol['name'], '', $record);
  2845. } else {
  2846. $cols[$kID] = '*****';
  2847. }
  2848. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  2849. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
  2850. }
  2851. $tsValues = array();
  2852. 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>';}
  2853. if (!empty($fieldsList)) {
  2854. Lib::loadClass('Typespecial');
  2855. foreach ($fieldsList as $vColID => $vCol) {
  2856. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  2857. if ($typeSpecial) {
  2858. 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>';}
  2859. $colValue = V::get($vCol['name'], '', $record);
  2860. 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>';}
  2861. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
  2862. 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>';}
  2863. if (!empty($specialValues)) {
  2864. $tsValues[$vColID] = implode('<br>', $specialValues);
  2865. }
  2866. }
  2867. }
  2868. }
  2869. 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>';}
  2870. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);
  2871. Lib::loadClass('SE_Layout');
  2872. ?>
  2873. <div class="container AjaxFrmHorizontalEdit">
  2874. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
  2875. <fieldset>
  2876. <legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
  2877. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  2878. <?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
  2879. <div class="control-group">
  2880. <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  2881. <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>
  2882. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  2883. </label>
  2884. <div class="controls">
  2885. <?php
  2886. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  2887. if (!empty($tsValues[$kID])) {
  2888. $fieldParams['typespecialValue'] = $tsValues[$kID];
  2889. }
  2890. echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  2891. ?>
  2892. </div>
  2893. </div>
  2894. <?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
  2895. <div class="control-group">
  2896. <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  2897. <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>
  2898. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  2899. </label>
  2900. <div class="controls">
  2901. <p style="margin-top:5px;">
  2902. <?php
  2903. //echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  2904. if (!empty($tsValues[$kID])) {
  2905. echo $tsValues[$kID];
  2906. } else if (!empty($record->{$vCol['name']})) {
  2907. echo $record->{$vCol['name']};
  2908. }
  2909. ?>
  2910. </p>
  2911. </div>
  2912. </div>
  2913. <?php endif; ?>
  2914. <?php endforeach; ?>
  2915. <div class="control-group">
  2916. <div class="controls">
  2917. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
  2918. </div>
  2919. </div>
  2920. </fieldset>
  2921. </form>
  2922. <p style="padding:100px 0;"></p>
  2923. </div>
  2924. <script>
  2925. jQuery(document).ready(function(){
  2926. jQuery('textarea').autosize();
  2927. jQuery('.frm-help').popover({trigger:'hover'});
  2928. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  2929. var data = jQuery(this).serialize();
  2930. // TODO: change Edit btn to return to edit record with fields -> show form
  2931. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  2932. //taskCont.empty();
  2933. taskCont.children().fadeOut('slow');
  2934. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  2935. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  2936. 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);
  2937. jQuery.ajax({
  2938. 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; ?>',
  2939. type: 'POST',
  2940. dataType: 'text',
  2941. data: data,
  2942. async: true,
  2943. success: function (data) {
  2944. alertCntWrap.removeClass('AjaxTable-loading');
  2945. //console.log('request finished L.<?php echo __LINE__; ?>');
  2946. alertCnt.empty();
  2947. var out = '';
  2948. out += data;
  2949. out += '<div class="breadcrumb">' +
  2950. ' <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>' +
  2951. '<span class="divider">/</span>' +
  2952. ' <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>' +
  2953. '</div>';
  2954. jQuery(out).appendTo(alertCnt);
  2955. },
  2956. error: function (jhr, textStatus, errorThrown) {
  2957. var errorTxt = jhr.responseText || 'Error';
  2958. alertCntWrap.removeClass('AjaxTable-loading');
  2959. //console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
  2960. alertCnt.empty();
  2961. jQuery(errorTxt).appendTo(alertCnt);
  2962. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  2963. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  2964. 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);
  2965. backToEditBtn.on('click', function(){
  2966. alertCnt.remove();
  2967. taskCont.children().fadeIn('slow');
  2968. return false;
  2969. });
  2970. }
  2971. });
  2972. return false;
  2973. });
  2974. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  2975. var input, btn;
  2976. input = jQuery(e.target);
  2977. btn = input.next();
  2978. if (btn.is('button')) {
  2979. if (btn.attr('title') != input.val()) {
  2980. btn.show();
  2981. } else {
  2982. btn.hide();
  2983. }
  2984. }
  2985. });
  2986. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value button.btn-appendBack').on('click', function(e) {
  2987. var input, btn;
  2988. btn = jQuery(e.target);
  2989. input = btn.prev();
  2990. if (input.is('input')) {
  2991. if (btn.attr('title') != input.val()) {
  2992. input.val(btn.attr('title'));
  2993. btn.hide();
  2994. }
  2995. }
  2996. });
  2997. });
  2998. </script>
  2999. <?php
  3000. exit;
  3001. }
  3002. private function sendAjaxEditSave($id, $args) {
  3003. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3004. sleep(1);// TODO: RMME DBG loading
  3005. 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>';}
  3006. 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>';}
  3007. $dbID = $this->_acl->getDB();
  3008. $db = DB::getDB($dbID);
  3009. if (!$db) {
  3010. header('HTTP/1.0 406 Not Acceptable');
  3011. exit;
  3012. }
  3013. $tblName = $this->_acl->getName();
  3014. $record = $db->get_by_id($tblName, $id);
  3015. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  3016. echo '<div class="alert alert-error">';
  3017. echo "Brak dostępu do rekordu";// TODO: more info - reason
  3018. echo '</div>';
  3019. }
  3020. $sqlObj = new stdClass();
  3021. $fields = $this->_acl->getFields();
  3022. 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>';}
  3023. foreach ($fields as $kID => $vField) {
  3024. if (!$this->_acl->isAllowed($kID, 'W', $record)) {
  3025. continue;
  3026. }
  3027. if (array_key_exists("f{$kID}", $args)) {
  3028. if (!$this->_acl->isAllowed($kID, 'R', $record) && '*****' == $args["f{$kID}"]) {
  3029. // default value for perms 'W' without 'R' is '*****'
  3030. }
  3031. else {
  3032. $sqlObj->{$vField['name']} = $args["f{$kID}"];
  3033. if (empty($args["f{$kID}"]) && strlen($args["f{$kID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
  3034. $sqlObj->{$vField['name']} = $this->_acl->fixEmptyValueFromUser($kID);
  3035. }
  3036. }
  3037. }
  3038. }
  3039. $sqlObj->ID = $id;
  3040. 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>';}
  3041. $ret = $db->UPDATE_OBJ($tblName, $sqlObj);
  3042. if ($ret > 0) {
  3043. echo '<div class="alert alert-success">';
  3044. echo "Rekord zapisany pomyślnie";//"Record saved successfully";
  3045. echo '</div>';
  3046. } else if ($ret == 0) {
  3047. echo '<div class="alert alert-info">';
  3048. echo "Nie wprowadzono żadnych zmian";
  3049. echo '</div>';
  3050. } else {
  3051. header('HTTP/1.0 404 Not Found');
  3052. echo '<div class="alert alert-error">';
  3053. echo '<h4>' . "Wystąpiły błędy!" . '</h4>';
  3054. if ($db->has_errors()) {
  3055. $errors = $db->get_errors();
  3056. echo implode('<br>', $errors);
  3057. }
  3058. echo '</div>';
  3059. }
  3060. exit;
  3061. }
  3062. private function sendAjaxCreate($args) {
  3063. header("Content-type: text/plain");
  3064. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3065. $cols = array();
  3066. $forceFilterInit = array();
  3067. $defaultAclGroup = User::getDefaultAclGroup();
  3068. if ($defaultAclGroup) {
  3069. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  3070. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  3071. }
  3072. foreach ($_GET as $k => $v) {
  3073. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  3074. $fldName = substr($k, 3);
  3075. $forceFilterInit[$fldName] = $v;
  3076. }
  3077. }
  3078. $fieldsList = $this->_acl->getFields();
  3079. foreach ($fieldsList as $kID => $vCol) {
  3080. $defaultValue = '';
  3081. if ($vCol['name'] == 'ID') {
  3082. unset($fieldsList[$kID]);
  3083. continue;
  3084. }
  3085. if (!empty($forceFilterInit[$vCol['name']])) {
  3086. $defaultValue = $forceFilterInit[$vCol['name']];
  3087. }
  3088. // TODO: read from session cache
  3089. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  3090. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3091. }
  3092. Lib::loadClass('SE_Layout');
  3093. ?>
  3094. <div class="container AjaxFrmHorizontalEdit">
  3095. <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  3096. <fieldset>
  3097. <legend>Dodaj nowy rekord</legend>
  3098. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3099. <?php if ($this->_acl->isAllowed($kID, 'C')) : ?>
  3100. <div class="control-group">
  3101. <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3102. <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>
  3103. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3104. </label>
  3105. <div class="controls">
  3106. <?php
  3107. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3108. echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  3109. ?>
  3110. </div>
  3111. </div>
  3112. <?php endif; ?>
  3113. <?php endforeach; ?>
  3114. <div class="control-group">
  3115. <div class="controls">
  3116. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  3117. </div>
  3118. </div>
  3119. </fieldset>
  3120. </form>
  3121. </div>
  3122. <script>
  3123. jQuery(document).ready(function(){
  3124. jQuery('textarea').autosize();
  3125. jQuery('.frm-help').popover({trigger:'hover'});
  3126. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3127. var data = jQuery(this).serialize();
  3128. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  3129. taskCont = taskContLast.parent();
  3130. taskContLast.fadeOut('slow');
  3131. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3132. 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);
  3133. function notifyAjaxCallback(data) {
  3134. var notify = {};
  3135. notify.type = (data && data.type)? data.type : '';
  3136. notify.msg = (data && data.msg)? data.msg : '';
  3137. switch (notify.type) {
  3138. case 'success':
  3139. if (!notify.msg) notify.msg = 'OK';
  3140. break;
  3141. case 'info':
  3142. if (!notify.msg) notify.msg = '';
  3143. break;
  3144. case 'error':
  3145. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3146. break;
  3147. case 'warning':
  3148. notify.type = 'warn';
  3149. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3150. break;
  3151. default:
  3152. notify.msg = 'Nieznany błąd';
  3153. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3154. notify.type = '';
  3155. }
  3156. jQuery.notify(notify.msg, notify.type);
  3157. }
  3158. $.ajax({
  3159. data: data,
  3160. dataType: 'json',
  3161. type: "POST",
  3162. async: true,
  3163. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  3164. })
  3165. .always(function(dataOrJqXHR){
  3166. var data;
  3167. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  3168. if ('responseJSON' in dataOrJqXHR) {
  3169. data = dataOrJqXHR.responseJSON;
  3170. } else {
  3171. data = {};
  3172. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  3173. if (dataOrJqXHR.status == 404) {
  3174. data.type = 'error';
  3175. } else {
  3176. data.type = 'warning';
  3177. }
  3178. }
  3179. }
  3180. else {
  3181. data = dataOrJqXHR;
  3182. }
  3183. notifyAjaxCallback(data);
  3184. taskCnt.removeClass('AjaxTable-loading');
  3185. taskCnt.empty();
  3186. if (data.type == 'error' || data.type == 'warning') {
  3187. var out = '<div class="container">' +
  3188. '<div class="alert alert-error">' +
  3189. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  3190. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  3191. '</div>';
  3192. out += '<div class="breadcrumb">' +
  3193. ' <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>' +
  3194. '</div>' +
  3195. '</div>';
  3196. jQuery(out).appendTo(taskCnt);
  3197. var taskContLastNode = taskContLast
  3198. , taskCntNode = taskCnt;
  3199. taskCnt.find('.create-fix').click(function(){
  3200. taskCntNode.remove();
  3201. taskContLastNode.fadeIn('slow');
  3202. return false;
  3203. });
  3204. }
  3205. else if (data.type == 'success') {
  3206. var msg = '';
  3207. if (data.id && data.id > 0) {
  3208. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  3209. } else if (data.msg) {
  3210. msg = data.msg;
  3211. } else {
  3212. msg = 'OK';
  3213. }
  3214. var out = '<div class="container">';
  3215. out += '<div class="alert alert-success">' + msg + '</div>';
  3216. out += '<div class="breadcrumb">' +
  3217. ' <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>' +
  3218. '<span class="divider">/</span>' +
  3219. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  3220. '<span class="divider">/</span>' +
  3221. ' <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>' +
  3222. '</div>';
  3223. out += '</div>';
  3224. jQuery(out).appendTo(taskCnt);
  3225. }
  3226. });
  3227. return false;
  3228. });
  3229. });
  3230. </script>
  3231. <?php
  3232. exit;
  3233. }
  3234. private function ajaxCreateSave($args) {
  3235. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3236. 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>';}
  3237. 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>';}
  3238. $sqlObj = new stdClass();
  3239. $fields = $this->_acl->getFields();
  3240. 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>';}
  3241. foreach ($fields as $kID => $vField) {
  3242. if (!$this->_acl->isAllowed($kID, 'C')) {
  3243. continue;
  3244. }
  3245. if (array_key_exists("f{$kID}", $args)) {
  3246. $sqlObj->{$vField['name']} = $args["f{$kID}"];
  3247. if (empty($args["f{$kID}"]) && strlen($args["f{$kID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
  3248. $sqlObj->{$vField['name']} = $this->_acl->fixEmptyValueFromUser($kID);
  3249. }
  3250. }
  3251. }
  3252. 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>';}
  3253. {// add DefaultAclGroup if no create perms ('C')
  3254. $defaultAclGroup = User::getDefaultAclGroup();
  3255. if ($defaultAclGroup) {
  3256. foreach ($fields as $kID => $vField) {
  3257. if (!$this->_acl->isAllowed($kID, 'C')) {
  3258. if ($vField['name'] == 'A_ADM_COMPANY') {
  3259. $sqlObj->{$vField['name']} = $defaultAclGroup;
  3260. }
  3261. else if ($vField['name'] == 'A_CLASSIFIED') {
  3262. $sqlObj->{$vField['name']} = $defaultAclGroup;
  3263. }
  3264. }
  3265. }
  3266. }
  3267. }
  3268. $retID = $this->_dataSource->addItem($sqlObj);
  3269. $response = new stdClass();
  3270. $response->type = '';
  3271. $response->msg = '';
  3272. if ($retID > 0) {
  3273. $response->type = 'success';
  3274. $response->msg = "Utworzono pomyślnie rekord nr {$retID}";
  3275. $response->id = $retID;
  3276. $response->record = $this->_dataSource->getItem($retID);
  3277. } else {
  3278. $response->type = 'error';
  3279. $response->msg = "Wystąpiły błędy!";
  3280. $response->errors = $this->_dataSource->getDbErrors();
  3281. }
  3282. return $response;
  3283. }
  3284. private function sendAjaxCopy($id, $args) {
  3285. header("Content-type: text/plain");
  3286. sleep(1);// TODO: RMME DBG loading
  3287. $dbID = $this->_acl->getDB();
  3288. $db = DB::getDB($dbID);
  3289. if (!$db) {
  3290. header('HTTP/1.0 406 Not Acceptable');
  3291. exit;
  3292. }
  3293. $row = $this->_dataSource->getItem($id);
  3294. if (!$row) {
  3295. header('HTTP/1.0 404 Not Found');
  3296. echo "404: No item ID({$rowID})";
  3297. exit;
  3298. }
  3299. $tblName = $this->_acl->getName();
  3300. $types = $this->_acl->getTypes();
  3301. $uniqKeys = $this->_acl->getUniqueKeys();
  3302. $sqlObj = new stdClass();
  3303. foreach ($types as $kName => $vType) {
  3304. if ($kName == 'ID') {
  3305. continue;
  3306. } else if (in_array($kName, array('A_RECORD_UPDATE_AUTHOR','A_RECORD_UPDATE_DATE'))) {
  3307. continue;
  3308. }
  3309. $sqlObj->{$kName} = V::get($kName, '', $row);
  3310. if (in_array($kName, $uniqKeys)) {
  3311. $sqlObj->{$kName} .= '?';
  3312. }
  3313. }
  3314. $ret = $db->ADD_NEW_OBJ($tblName, $sqlObj);
  3315. if ($ret > 0) {
  3316. echo '<div class="alert alert-success">';
  3317. echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
  3318. echo "Rekord skopiowany pomyślnie - utworzono rekord nr {$ret}";//"Record saved successfully";
  3319. echo '</div>';
  3320. } else if ($ret == 0) {
  3321. echo '<div class="alert alert-error">';
  3322. echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
  3323. echo "Nie udało się skopiować rekordu";
  3324. if ($db->has_errors()) {
  3325. echo '<br>' . implode("<br>", $db->get_errors());
  3326. }
  3327. echo '</div>';
  3328. } else {
  3329. echo '<div class="alert alert-error">';
  3330. echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
  3331. echo "Błąd bazy danych";
  3332. echo '</div>';
  3333. }
  3334. exit;
  3335. }
  3336. private function sendAjaxHistory($id, $args) {
  3337. header("Content-type: text/plain");
  3338. $record = $this->_dataSource->getItem($id);
  3339. if (!$record) {
  3340. header('HTTP/1.0 404 Not Found');
  3341. echo "404: No item ID({$rowID})";
  3342. exit;
  3343. }
  3344. $visibleCols = $this->_acl->getRealFieldList();
  3345. $rowsHist = $this->_dataSource->getHistItems($id);
  3346. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);
  3347. $visibleColsWithIds = array();
  3348. $visibleColsLabels = array();
  3349. foreach ($visibleCols as $vColName) {
  3350. $fldId = $this->_acl->getFieldIdByName($vColName);
  3351. if ($fldId) {
  3352. $visibleColsWithIds[$fldId] = $vColName;
  3353. $label = $this->_acl->getFieldLabel($fldId);
  3354. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  3355. $visibleColsLabels[$fldId] = $label;
  3356. }
  3357. }
  3358. ?>
  3359. <fieldset>
  3360. <legend>Historia rekordu Nr <?php echo $id; ?>
  3361. <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
  3362. </legend>
  3363. </fieldset>
  3364. <?php if (empty($rowsHist)) : ?>
  3365. <div class="alert alert-info">
  3366. <h4>Brak danych</h4>
  3367. </div>
  3368. <?php else: ?>
  3369. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  3370. <thead>
  3371. <tr>
  3372. <th>Data</th>
  3373. <th>User</th>
  3374. <th>Zmiany</th>
  3375. </tr>
  3376. </thead>
  3377. <tbody>
  3378. <?php foreach ($rowsHist as $row) : ?>
  3379. <tr>
  3380. <td style="white-space:nowrap"><?php echo $row->_created; ?></td>
  3381. <td><?php echo $row->_author; ?></td>
  3382. <td>
  3383. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3384. <?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
  3385. <?php if ($row->$colName == 'N/S;') continue; ?>
  3386. <p><em><?php echo $visibleColsLabels[$fldId]; ?></em>:
  3387. <?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  3388. <?php echo $row->$colName; ?>
  3389. <?php else : ?>
  3390. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  3391. <?php endif; ?>
  3392. </p>
  3393. <?php endforeach; ?>
  3394. </td>
  3395. </tr>
  3396. <?php endforeach; ?>
  3397. </tbody>
  3398. </table>
  3399. <div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
  3400. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  3401. <thead>
  3402. <tr>
  3403. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3404. <th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
  3405. <?php endforeach; ?>
  3406. </tr>
  3407. </thead>
  3408. <tbody>
  3409. <?php foreach ($rowsHist as $row) : ?>
  3410. <tr>
  3411. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3412. <td>
  3413. <?php if ($row->$colName == 'N/S;') : ?>
  3414. <em>N/S;</em>
  3415. <?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  3416. <?php echo $row->$colName; ?>
  3417. <?php else : ?>
  3418. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  3419. <?php endif; ?>
  3420. </td>
  3421. <?php endforeach; ?>
  3422. </tr>
  3423. <?php endforeach; ?>
  3424. </tbody>
  3425. </table>
  3426. </div>
  3427. <?php endif; ?>
  3428. <?php
  3429. exit;
  3430. }
  3431. /**
  3432. * Returns text/plain with type at first line: ERROR, WARNING, INFO, SUCCESS
  3433. */
  3434. private function sendAjaxFilesUpload($id, $args) {
  3435. // http://www.sitepoint.com/html5-ajax-file-upload/
  3436. //$ajaxFileName = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
  3437. //header("Content-type: text/plain");
  3438. header("Content-type: application/json");
  3439. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3440. $dbID = $this->_acl->getDB();
  3441. $db = DB::getDB($dbID);
  3442. if (!$db) {
  3443. header('HTTP/1.0 406 Not Acceptable');
  3444. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3445. exit;
  3446. }
  3447. $record = $this->_dataSource->getItem($id);
  3448. if (!$record) {
  3449. header('HTTP/1.0 404 Not Found');
  3450. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  3451. exit;
  3452. }
  3453. $tblName = $this->_acl->getName();
  3454. $confTblName = "{$tblName}_COLUMN";
  3455. Lib::loadClass('FoldersConfig');
  3456. $folderConfAll = FoldersConfig::getRawData();
  3457. if (!FoldersConfig::hasConfig($confTblName)) {
  3458. header('HTTP/1.0 404 Not Found');
  3459. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych(' . $tblName . ')"}';
  3460. exit;
  3461. }
  3462. $folderConf = FoldersConfig::getAll($confTblName);
  3463. Lib::loadClass('FileUploader');
  3464. $uploader = new FileUploader($confTblName, $record);
  3465. $errMsg = '';
  3466. if (!$uploader->setConfig($folderConf, $errMsg)) {
  3467. header('HTTP/1.0 404 Not Found');
  3468. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych(' . $tblName . ') <br>' . $errMsg . '"}';
  3469. exit;
  3470. }
  3471. $uploader->findFolder();
  3472. $errorMsg = '';
  3473. if (!empty($_POST['SCANS_COLUMN_ADD'])) {
  3474. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  3475. }
  3476. else {
  3477. $uploaded = $uploader->tryUploadAjax($errorMsg);
  3478. }
  3479. if ($uploaded) {
  3480. $uploadedFileName = '';
  3481. $uploadedFile = $uploader->getLastUploadedFile();
  3482. if ($uploadedFile) {
  3483. $uploadedFileName = explode('/', $uploadedFile);
  3484. $uploadedFileName = end($uploadedFileName);
  3485. }
  3486. echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  3487. if (!empty($uploadedFileName)) {
  3488. $sqlObj = new stdClass();
  3489. $sqlObj->ID = $record->ID;
  3490. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  3491. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  3492. }
  3493. } else {
  3494. echo '{"type":"ERROR", "string": "' . $errorMsg . '"}';
  3495. }
  3496. exit;
  3497. }
  3498. private function sendAjaxFileRemove($id, $args) {
  3499. header("Content-type: application/json");
  3500. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3501. if (empty($_POST['filename'])) {
  3502. echo '{"type":"ERROR", "string": "Nie wybrano pliku do usunięcia"}';
  3503. exit;
  3504. }
  3505. $dbID = $this->_acl->getDB();
  3506. $db = DB::getDB($dbID);
  3507. if (!$db) {
  3508. header('HTTP/1.0 406 Not Acceptable');
  3509. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3510. exit;
  3511. }
  3512. $record = $this->_dataSource->getItem($id);
  3513. if (!$record) {
  3514. header('HTTP/1.0 404 Not Found');
  3515. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  3516. exit;
  3517. }
  3518. $tblName = $this->_acl->getName();
  3519. $confTblName = "{$tblName}_COLUMN";
  3520. Lib::loadClass('FoldersConfig');
  3521. $folderConfAll = FoldersConfig::getRawData();
  3522. if (!FoldersConfig::hasConfig($confTblName)) {
  3523. header('HTTP/1.0 404 Not Found');
  3524. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  3525. exit;
  3526. }
  3527. $folderConf = FoldersConfig::getAll($confTblName);
  3528. Lib::loadClass('FileUploader');
  3529. $uploader = new FileUploader($confTblName, $record);
  3530. if (!$uploader->setConfig($folderConf)) {
  3531. header('HTTP/1.0 404 Not Found');
  3532. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  3533. exit;
  3534. }
  3535. $uploader->findFolder();
  3536. $errorMsg = '';
  3537. $removed = $uploader->tryRemoveFromAjax($_POST['filename'], $errorMsg);
  3538. if (!$removed) {
  3539. echo '{"type":"ERROR", "string": "{' . $errorMsg . '}"}';
  3540. } else {
  3541. echo '{"type":"SUCCESS","string":"Plik został poprawnie usunięty"}';
  3542. }
  3543. exit;
  3544. }
  3545. private function sendAjaxFilesList($id, $args) {
  3546. header("Content-type: application/json");
  3547. $dbID = $this->_acl->getDB();
  3548. $db = DB::getDB($dbID);
  3549. if (!$db) {
  3550. header('HTTP/1.0 406 Not Acceptable');
  3551. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3552. exit;
  3553. }
  3554. $record = $this->_dataSource->getItem($id);
  3555. if (!$record) {
  3556. header('HTTP/1.0 404 Not Found');
  3557. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  3558. exit;
  3559. }
  3560. $tblName = $this->_acl->getName();
  3561. $confTblName = "{$tblName}_COLUMN";
  3562. Lib::loadClass('FoldersConfig');
  3563. $folderConfAll = FoldersConfig::getRawData();
  3564. if (!FoldersConfig::hasConfig($confTblName)) {
  3565. header('HTTP/1.0 404 Not Found');
  3566. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  3567. exit;
  3568. }
  3569. $folderConf = FoldersConfig::getAll($confTblName);
  3570. Lib::loadClass('FileUploader');
  3571. $uploader = new FileUploader($confTblName, $record);
  3572. if (!$uploader->setConfig($folderConf)) {
  3573. header('HTTP/1.0 404 Not Found');
  3574. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  3575. exit;
  3576. }
  3577. $uploader->findFolder();
  3578. $mainFolder = $uploader->getDestFolder();
  3579. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  3580. $localPath = $uploader->getLocalPath();
  3581. $folderWeb = $uploader->getFolderWeb();
  3582. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  3583. echo json_encode($jsonFiles);
  3584. exit;
  3585. }
  3586. private function ajaxFilePermsRefresh($args) {
  3587. header("Content-type: application/json");
  3588. $id = V::get('ID', 0, $args, 'int');
  3589. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  3590. $dbID = $this->_acl->getDB();
  3591. $db = DB::getDB($dbID);
  3592. if (!$db) throw new HttpException("No DB", 406);
  3593. $record = $this->_dataSource->getItem($id);
  3594. if (!$record) throw new Exception("No item ID({$rowID})", 404);
  3595. $tblName = $this->_acl->getName();
  3596. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  3597. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  3598. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  3599. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  3600. $mainDB = DB::getDB();
  3601. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  3602. $sql = "insert into `_SYNC_FILE_PERMS` (
  3603. `ID_PROJECT`,
  3604. `A_SYNCHRONIZED`
  3605. )
  3606. values (
  3607. '{$record->ID}'
  3608. , 0
  3609. )
  3610. ON DUPLICATE KEY UPDATE
  3611. `A_SYNCHRONIZED`=0
  3612. ";
  3613. }
  3614. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  3615. $sql = "insert into `_SYNC_FILE_PERMS` (
  3616. `ID_PROJECT`,
  3617. `A_SYNCHRONIZED`
  3618. )
  3619. values (
  3620. '{$record->ID_PROJECT}'
  3621. , 0
  3622. )
  3623. ON DUPLICATE KEY UPDATE
  3624. `A_SYNCHRONIZED`=0
  3625. ";
  3626. }
  3627. else {
  3628. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  3629. `TBL_NAME`,
  3630. `TBL_ID`,
  3631. `L_APPOITMENT_USER`,
  3632. `A_ADM_COMPANY`,
  3633. `A_CLASSIFIED`,
  3634. `A_SYNCHRONIZED`
  3635. )
  3636. values (
  3637. '{$tblName}'
  3638. , '{$id}'
  3639. , '{$sql_L_APPOITMENT_USER}'
  3640. , '{$sql_A_ADM_COMPANY}'
  3641. , '{$sql_A_CLASSIFIED}'
  3642. , 0
  3643. )
  3644. ON DUPLICATE KEY UPDATE
  3645. `A_SYNCHRONIZED`=0
  3646. ";
  3647. }
  3648. $res = $mainDB->query($sql);
  3649. if ($mainDB->has_errors()) {
  3650. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  3651. //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>';
  3652. throw new Exception("Nie udało się dodać zadania");
  3653. }
  3654. // TODO: this blocks browser ajax query
  3655. //$limit = 3;
  3656. //while ($limit--) {
  3657. // sleep(10);
  3658. // TODO: check if task is done
  3659. //}
  3660. $confTblName = "{$tblName}_COLUMN";
  3661. Lib::loadClass('FoldersConfig');
  3662. $folderConfAll = FoldersConfig::getRawData();
  3663. if (!FoldersConfig::hasConfig($confTblName)) {
  3664. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  3665. }
  3666. $folderConf = FoldersConfig::getAll($confTblName);
  3667. Lib::loadClass('FileUploader');
  3668. $uploader = new FileUploader($confTblName, $record);
  3669. if (!$uploader->setConfig($folderConf)) {
  3670. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  3671. }
  3672. $uploader->findFolder();
  3673. $mainFolder = $uploader->getDestFolder();
  3674. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  3675. $localPath = $uploader->getLocalPath();
  3676. $folderWeb = $uploader->getFolderWeb();
  3677. $jsonData = new stdClass();
  3678. $jsonData->msg = 'Zadanie dodane';
  3679. $jsonData->type = 'success';
  3680. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  3681. return $jsonData;
  3682. }
  3683. private function sendAjaxFilesConnTblList($id, $args) {
  3684. header("Content-type: application/json");
  3685. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3686. $dbID = $this->_acl->getDB();
  3687. $db = DB::getDB($dbID);
  3688. if (!$db) {
  3689. header('HTTP/1.0 406 Not Acceptable');
  3690. echo 'No DB (' . $dbID . ')';
  3691. exit;
  3692. }
  3693. $record = $this->_dataSource->getItem($id);
  3694. if (!$record) {
  3695. header('HTTP/1.0 404 Not Found');
  3696. echo 'No item ID(' . $rowID . ')';
  3697. exit;
  3698. }
  3699. $connTblName = '';
  3700. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  3701. if ($connTblID <= 0) {
  3702. header('HTTP/1.0 406 Not Acceptable');
  3703. echo 'No conn Table ID';
  3704. exit;
  3705. }
  3706. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  3707. if (empty($connTblTypespecials)) {
  3708. header('HTTP/1.0 406 Not Acceptable');
  3709. echo "No conn Table (ID={$connTblID})";
  3710. exit;
  3711. }
  3712. 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>';}
  3713. if(1) {
  3714. header('HTTP/1.0 404 Not Found');
  3715. echo 'TODO: ...';
  3716. exit;
  3717. }
  3718. $tblName = $this->_acl->getName();
  3719. $confTblName = "{$tblName}_COLUMN";
  3720. Lib::loadClass('FoldersConfig');
  3721. $folderConfAll = FoldersConfig::getRawData();
  3722. if (!FoldersConfig::hasConfig($confTblName)) {
  3723. header('HTTP/1.0 404 Not Found');
  3724. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  3725. exit;
  3726. }
  3727. $folderConf = FoldersConfig::getAll($confTblName);
  3728. Lib::loadClass('FileUploader');
  3729. $uploader = new FileUploader($confTblName, $record);
  3730. if (!$uploader->setConfig($folderConf)) {
  3731. header('HTTP/1.0 404 Not Found');
  3732. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  3733. exit;
  3734. }
  3735. $uploader->findFolder();
  3736. $mainFolder = $uploader->getDestFolder();
  3737. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  3738. $localPath = $uploader->getLocalPath();
  3739. $folderWeb = $uploader->getFolderWeb();
  3740. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  3741. echo json_encode($jsonFiles);
  3742. exit;
  3743. }
  3744. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  3745. sort($files);
  3746. $jsonFiles = array();
  3747. foreach ($files as $vFilePath) {
  3748. $file = new stdClass();
  3749. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  3750. //$file->name = explode('/', $vFilePath);
  3751. //$file->name = end($file->name);
  3752. $file->size = filesize($vFilePath);
  3753. $file->sizeStr = round($file->size, 2) . "B";
  3754. if ($file->size > 1024 * 1024) {
  3755. $file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
  3756. } else if ($file->size > 1024) {
  3757. $file->sizeStr = round(($file->size / 1024), 2) . "K";
  3758. }
  3759. $file->type = '';
  3760. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  3761. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  3762. $jsonFiles[] = $file;
  3763. }
  3764. return $jsonFiles;
  3765. }
  3766. private function getConnectedTables() {
  3767. $connTbls = array();
  3768. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  3769. $fields = $this->_acl->getVisibleFieldList();
  3770. if (!empty($fields)) {
  3771. Lib::loadClass('Typespecial');
  3772. foreach ($fields as $vColID => $vCol) {
  3773. $typeSpecial = Typespecial::getInstance($vColID);
  3774. if ($typeSpecial) {
  3775. $tsConnTbls = $typeSpecial->getTblAliasList();
  3776. if (!empty($tsConnTbls)) {
  3777. foreach ($tsConnTbls as $kID => $vName) {
  3778. $connTbls[$kID] = $vName;
  3779. }
  3780. }
  3781. }
  3782. }
  3783. }
  3784. return $connTbls;
  3785. }
  3786. private function getConnectedTblTypespecials($connTblID) {
  3787. $connTblTypespecials = array();
  3788. $fields = $this->_acl->getVisibleFieldList();
  3789. if (!empty($fields)) {
  3790. Lib::loadClass('Typespecial');
  3791. foreach ($fields as $vColID => $vCol) {
  3792. $typeSpecial = Typespecial::getInstance($vColID);
  3793. if ($typeSpecial) {
  3794. $tsConnTbls = $typeSpecial->getTblAliasList();
  3795. if (array_key_exists($connTblID, $tsConnTbls)) {
  3796. $connTblTypespecials[] = $typeSpecial;
  3797. }
  3798. }
  3799. }
  3800. }
  3801. return $connTblTypespecials;
  3802. }
  3803. private function sendAjaxFiles($id, $args) {
  3804. header("Content-type: text/plain");
  3805. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3806. $dbID = $this->_acl->getDB();
  3807. $db = DB::getDB($dbID);
  3808. if (!$db) {
  3809. header('HTTP/1.0 406 Not Acceptable');
  3810. exit;
  3811. }
  3812. $record = $this->_dataSource->getItem($id);
  3813. if (!$record) {
  3814. header('HTTP/1.0 404 Not Found');
  3815. echo "404: No item ID({$rowID})";
  3816. exit;
  3817. }
  3818. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  3819. echo '<div class="alert alert-error">';
  3820. echo "Brak dostępu do rekordu";// TODO: more info - reason
  3821. echo '</div>';
  3822. return;
  3823. }
  3824. $tblName = $this->_acl->getName();
  3825. $confTblName = "{$tblName}_COLUMN";
  3826. Lib::loadClass('FoldersConfig');
  3827. $folderConfAll = FoldersConfig::getRawData();
  3828. if (!FoldersConfig::hasConfig($confTblName)) {
  3829. header('HTTP/1.0 404 Not Found');
  3830. echo "Brak danych konfiguracyjnych";
  3831. exit;
  3832. }
  3833. $folderConf = FoldersConfig::getAll($confTblName);
  3834. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  3835. Lib::loadClass('FileUploader');
  3836. $uploader = new FileUploader($confTblName, $record);
  3837. $errMsg = '';
  3838. if (!$uploader->setConfig($folderConf, $errMsg)) {
  3839. header('HTTP/1.0 404 Not Found');
  3840. echo "Błąd danych konfiguracyjnych ({$tblName})";
  3841. echo '<br>' . "\n" . $errMsg;
  3842. exit;
  3843. }
  3844. $uploader->findFolder();
  3845. 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>'; }
  3846. $mainFolder = $uploader->getDestFolder();
  3847. 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>'; }
  3848. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  3849. 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>'; }
  3850. $sharePoint = V::get('share_point', null, $folderConf);
  3851. if ($sharePoint) {
  3852. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  3853. }
  3854. $localPath = $uploader->getLocalPath();
  3855. $folderWeb = $uploader->getFolderWeb();
  3856. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  3857. 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>'; }
  3858. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  3859. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  3860. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  3861. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  3862. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  3863. sort($skanyFiles);
  3864. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  3865. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
  3866. ?>
  3867. <script src="stuff/jquery.form.js"></script>
  3868. <div class="container">
  3869. <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
  3870. <?php if ($sharePoint) : ?>
  3871. <a href="<?php echo $sharePoint; ?>"><code><?php echo $mainFolder; ?></code></a>
  3872. <?php else : ?>
  3873. <code><?php echo $mainFolder; ?></code>
  3874. <?php endif; ?>
  3875. <span class="pull-right valign-btns-bottom">
  3876. <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
  3877. <?php echo $rowFunctionsOut; ?>
  3878. </span>
  3879. </h4>
  3880. <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
  3881. <table class="table table-bordered table-hover">
  3882. <colgroup>
  3883. <col style="">
  3884. <col style="width:30px;">
  3885. <?php if ($sharePoint) : ?>
  3886. <col style="width:30px;">
  3887. <?php endif; ?>
  3888. <col style="width:80px;">
  3889. <col style="width:140px;">
  3890. </colgroup>
  3891. <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
  3892. <?php if (empty($mainFolder)) : ?>
  3893. <tr>
  3894. <td colspan="5">
  3895. <div class="alert alert-warning">
  3896. <h4>Brak folderu!</h4>
  3897. Folder dla tego rekordu nie został utworzony.
  3898. </div>
  3899. </td>
  3900. </tr>
  3901. <?php elseif (empty($files)) : ?>
  3902. <tr>
  3903. <td colspan="5">
  3904. <div class="alert alert-info">
  3905. <h4>Brak plików</h4>
  3906. </div>
  3907. </td>
  3908. </tr>
  3909. <?php endif; ?>
  3910. </tbody>
  3911. </table>
  3912. </div>
  3913. <br>
  3914. <br>
  3915. <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
  3916. <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
  3917. <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
  3918. <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
  3919. <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
  3920. <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
  3921. </ul>
  3922. <div id="myTabContent" class="tab-content">
  3923. <div class="tab-pane fade in active" id="local" style="text-align: center;">
  3924. <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'">
  3925. </div>
  3926. <div class="tab-pane fade" id="scan">
  3927. <?php if (empty($skanyFiles)) : ?>
  3928. <div class="alert alert-info">
  3929. <h4>Brak plików</h4>
  3930. <?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>"; ?>
  3931. </div>
  3932. <?php else : ?>
  3933. <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
  3934. <table class="table table-bordered table-hover">
  3935. <colgroup>
  3936. <col style="width:30px;">
  3937. <col style="">
  3938. <col style="width:30px;">
  3939. <col style="width:80px;">
  3940. <col style="width:140px;">
  3941. </colgroup>
  3942. <tbody>
  3943. <?php foreach ($skanyFiles as $vFilePath) : ?>
  3944. <tr>
  3945. <?php
  3946. $vFileName = explode('/', $vFilePath);
  3947. $vFileName = end($vFileName);
  3948. $vFileSize = filesize($vFilePath);
  3949. $vFileSizeOut = round($vFileSize, 2) . "B";
  3950. if ($vFileSize > 1024 * 1024) {
  3951. $vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
  3952. } else if ($vFileSize > 1024) {
  3953. $vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
  3954. }
  3955. ?>
  3956. <td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
  3957. <td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
  3958. <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>
  3959. <td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
  3960. <td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
  3961. </tr>
  3962. <?php endforeach; ?>
  3963. </tbody>
  3964. </table>
  3965. </div>
  3966. <?php endif; ?>
  3967. </div>
  3968. </div>
  3969. <script>
  3970. $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function (e) {
  3971. e.preventDefault();
  3972. $(this).tab('show');
  3973. })
  3974. .on('shown', function (e) {
  3975. var fileSource = $(e.target).data('toggle')
  3976. , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
  3977. if (frm['M_DIST_UPLOAD_SOURCE']) {
  3978. frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
  3979. }
  3980. })
  3981. </script>
  3982. <br>
  3983. <table style="width:100%" class="table table-noborder">
  3984. <tr>
  3985. <td colspan="5">
  3986. <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
  3987. <?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> ?>
  3988. </h4>
  3989. </td>
  3990. </tr>
  3991. <tr>
  3992. <th style="border-right:1px solid #eee">ID</th>
  3993. <th style="border-right:1px solid #eee">TYP</th>
  3994. <th style="border-right:1px solid #eee">Opis <i class="icon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
  3995. <th style="border-right:1px solid #eee">Data Wersji</th>
  3996. <th>Numer Wersji</th>
  3997. </tr>
  3998. <tr>
  3999. <td style="border-right:1px solid #eee;">
  4000. <?php echo $record->ID; ?>
  4001. </td>
  4002. <td style="border-right:1px solid #eee;">
  4003. <select name="M_DIST_FILES_TYPE">
  4004. <?php foreach ($fileTypes as $kType => $vLabel) : ?>
  4005. <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
  4006. <?php endforeach; ?>
  4007. </select>
  4008. <br>
  4009. <label class="checkbox">
  4010. <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
  4011. Wykrycie automatyczne TYPU z wysylanego pliku
  4012. </label>
  4013. <label class="checkbox">
  4014. <input type="checkbox" name="M_DIST_FILES_TEMP">
  4015. Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
  4016. </label>
  4017. </td>
  4018. <td style="border-right:1px solid #eee;">
  4019. <input type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
  4020. <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
  4021. </td>
  4022. <td style="border-right:1px solid #eee;">
  4023. <input type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10" class="span2">
  4024. <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
  4025. </td>
  4026. <td>
  4027. <input type="number" name="M_DIST_FILES_VERSION" class="span2">
  4028. <br>
  4029. <label class="checkbox">
  4030. <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
  4031. Automatycznie dodaj wersje
  4032. </label>
  4033. </td>
  4034. </tr>
  4035. <tr>
  4036. <td colspan="5">
  4037. <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
  4038. <p>
  4039. <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
  4040. </p>
  4041. <p>
  4042. <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
  4043. <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
  4044. </p>
  4045. </td>
  4046. </tr>
  4047. </table>
  4048. </form>
  4049. </div>
  4050. <script>
  4051. function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
  4052. var postData = {};
  4053. jQuery.ajax({
  4054. 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; ?>',
  4055. type: 'POST',
  4056. //dataType: 'json',
  4057. //contentType: "application/json; charset=utf-8",
  4058. data: postData,
  4059. async: true,
  4060. success: function (data) {
  4061. fileListUpdate<?php echo $this->_htmlID; ?>(data);
  4062. },
  4063. error: function (jhr, textStatus, errorThrown) {
  4064. if (priv.options.debug) console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
  4065. }
  4066. });
  4067. }
  4068. function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4069. var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
  4070. fileListNode.empty();
  4071. fileListJson.map(function(file){
  4072. var node = $('<tr></tr>');
  4073. var fFun = $('<i class="ico-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
  4074. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4075. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4076. fName.append(fFun);
  4077. fName.append(file.name);
  4078. fName.appendTo(fNameCell);
  4079. node.append(fNameCell);
  4080. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="ico-download-alt"></a>' + '</td>');
  4081. <?php if ($sharePoint) : ?>
  4082. 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>');
  4083. <?php endif; ?>
  4084. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4085. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4086. node.appendTo(fileListNode);
  4087. $(fFun).click(function(e){
  4088. var n = $(e.target);
  4089. var fname= n.data('filename');
  4090. if (!fname) {
  4091. return false;
  4092. }
  4093. if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
  4094. var postData = {filename: fname};
  4095. jQuery.ajax({
  4096. 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; ?>',
  4097. type: 'POST',
  4098. //dataType: 'json',
  4099. //contentType: "application/json; charset=utf-8",
  4100. data: postData,
  4101. async: true,
  4102. success: function (data) {
  4103. if (data && data.type) {
  4104. if (data.type == 'SUCCESS') {
  4105. n.parents('tr').remove();
  4106. //console.log('TODO: SUCCESS msg: ', data.string);
  4107. }
  4108. else if (data.type == 'ERROR') {
  4109. //console.log('TODO: ERROR msg: ', data.string);
  4110. }
  4111. } else {
  4112. if (priv.options.debug) console.log('TODO: ??? data: ', data);
  4113. }
  4114. },
  4115. error: function (jhr, textStatus, errorThrown) {
  4116. if (priv.options.debug) console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
  4117. }
  4118. });
  4119. }
  4120. });
  4121. });
  4122. }
  4123. function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
  4124. var postData = {};
  4125. // clear current file list
  4126. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
  4127. jQuery.ajax({
  4128. 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,
  4129. type: 'POST',
  4130. //dataType: 'json',
  4131. //contentType: "application/json; charset=utf-8",
  4132. data: postData,
  4133. async: true,
  4134. success: function (data) {
  4135. connTblListUpdate<?php echo $this->_htmlID; ?>(data);
  4136. },
  4137. error: function (jqXHR, textStatus, errorThrown) {
  4138. var txt = jqXHR.responseText || 'Error';
  4139. 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>');
  4140. if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
  4141. }
  4142. });
  4143. }
  4144. function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4145. var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
  4146. fileListNode.empty();
  4147. fileListJson.map(function(file){
  4148. var node = $('<tr></tr>');
  4149. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4150. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4151. fName.append(file.name);
  4152. fName.appendTo(fNameCell);
  4153. node.append(fNameCell);
  4154. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="ico-download-alt"></a>' + '</td>');
  4155. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4156. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4157. node.appendTo(fileListNode);
  4158. });
  4159. }
  4160. function fileListActions<?php echo $this->_htmlID; ?>() {
  4161. var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
  4162. var btnReload = jQuery('<button class="btn-link btn-small" title="odśwież uprawnienia do plików"><span class="ico-refresh"></span>Odśwież</button>');
  4163. btnReload.on('click', function(e) {
  4164. console.log('TODO: click reload perms...');
  4165. function notifyAjaxCallback(data) {
  4166. var notify = {};
  4167. notify.type = (data && data.type)? data.type : '';
  4168. notify.msg = (data && data.msg)? data.msg : '';
  4169. switch (notify.type) {
  4170. case 'success':
  4171. if (!notify.msg) notify.msg = 'OK';
  4172. break;
  4173. case 'info':
  4174. if (!notify.msg) notify.msg = '';
  4175. break;
  4176. case 'error':
  4177. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4178. break;
  4179. case 'warning':
  4180. notify.type = 'warn';
  4181. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4182. break;
  4183. default:
  4184. notify.msg = 'Nieznany błąd';
  4185. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4186. notify.type = '';
  4187. }
  4188. jQuery.notify(notify.msg, notify.type);
  4189. }
  4190. var reqData = {};
  4191. jQuery.ajax({
  4192. data: reqData,
  4193. dataType: 'json',
  4194. type: "GET",
  4195. 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; ?>',
  4196. })
  4197. .done(function(data, textStatus, jqXHR){
  4198. notifyAjaxCallback(data);
  4199. if (data && data.files) {
  4200. fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
  4201. }
  4202. })
  4203. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  4204. if (jqXHR.responseJSON) {
  4205. notifyAjaxCallback(jqXHR.responseJSON);
  4206. }
  4207. else {
  4208. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  4209. if (jqXHR.status == 404) {
  4210. jQuery.notify(jqXHR.responseText, 'error');
  4211. } else {
  4212. jQuery.notify(jqXHR.responseText, 'warn');
  4213. }
  4214. }
  4215. });
  4216. });
  4217. filePermsReload.append(btnReload);
  4218. }
  4219. jQuery(document).ready(function(){
  4220. jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
  4221. 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; ?>',
  4222. beforeSubmit: function(args, $form, options) {
  4223. var argsMap = [];
  4224. args.map(function(v, k) {
  4225. argsMap[v.name] = v.value;
  4226. });
  4227. // validate
  4228. if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
  4229. if (!argsMap['M_DIST_FILES_NAME']) {
  4230. if (priv.options.debug) console.log('TODO: nie wybrano lokalnego pliku!');
  4231. return false;
  4232. }
  4233. }
  4234. else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
  4235. if (!argsMap['SCANS_COLUMN_ADD']) {
  4236. if (priv.options.debug) console.log('TODO: nie wybrano pliku ze skanów!');
  4237. return false;
  4238. }
  4239. }
  4240. else {
  4241. if (priv.options.debug) console.log('TODO: nie wybrano źródła pliku!');
  4242. return false;
  4243. }
  4244. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4245. $out.html('Wysyłanie...');
  4246. },
  4247. success: function(data) {
  4248. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4249. var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
  4250. if (typeof data == 'object') {
  4251. if (data.type == 'ERROR') {
  4252. $out.html('<div class="alert alert-error">' + btnClose + data.string + '</div>');
  4253. } else if (data.type == 'SUCCESS') {
  4254. $out.html('<div class="alert alert-success">' + btnClose + data.string + '</div>');
  4255. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4256. }
  4257. } else {
  4258. if (data.substr(0, 7) == 'WARNING') {
  4259. data = data.substr(7);
  4260. $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
  4261. } else if (data.substr(0, 5) == 'ERROR') {
  4262. data = data.substr(5);
  4263. $out.html('<div class="alert alert-error">' + btnClose + data + '</div>');
  4264. } else if (data.substr(0, 7) == 'SUCCESS') {
  4265. data = data.substr(7);
  4266. $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
  4267. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4268. } else if (data.substr(0, 4) == 'INFO') {
  4269. data = data.substr(4);
  4270. $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
  4271. }
  4272. }
  4273. }
  4274. });
  4275. fileListActions<?php echo $this->_htmlID; ?>();
  4276. var fileList = <?php echo json_encode($jsonFiles); ?>;
  4277. fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
  4278. var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
  4279. if (connTbls) {
  4280. var connTblsOut = '';
  4281. for(var key in connTbls) {
  4282. connTblsOut += '<button class="btn btn-small conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
  4283. };
  4284. if (connTblsOut) {
  4285. connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
  4286. connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
  4287. '<table class="table table-bordered table-hover">' +
  4288. '<colgroup>' +
  4289. '<col style="">' +
  4290. '<col style="width:30px;">' +
  4291. <?php if ($sharePoint) : ?>
  4292. '<col style="width:30px;">' +
  4293. <?php endif; ?>
  4294. '<col style="width:80px;">' +
  4295. '<col style="width:140px;">' +
  4296. '</colgroup>' +
  4297. '<tbody class="files-list">' +
  4298. '</tbody>' +
  4299. '</table>' +
  4300. '</div>';
  4301. var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
  4302. _connTblsWrap.css('marginBottom', '26px');
  4303. _connTblsWrap.html(connTblsOut);
  4304. _connTblsWrap.find('.conn-tbl-load').each(function(){
  4305. jQuery(this).click(function(e){
  4306. var tblID = jQuery(e.target).data('zasobid');
  4307. if (priv.options.debug) console.log('clicked: ', tblID);
  4308. if (tblID) {
  4309. connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
  4310. }// TODO: else show error
  4311. });
  4312. });
  4313. }
  4314. }
  4315. });
  4316. </script>
  4317. <?php
  4318. exit;
  4319. }
  4320. private function sendTypeSpecial($fldID, $args) {
  4321. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4322. header("Content-type: application/json");
  4323. $fldName = '';
  4324. $fld = $this->_acl->getField($fldID);
  4325. 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>';}
  4326. if (!$fld) {
  4327. // 404
  4328. } else {
  4329. $fldName = $fld['name'];
  4330. }
  4331. $jsonData = array();
  4332. Lib::loadClass('Typespecial');
  4333. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  4334. if ($typeSpecial) {
  4335. $query = V::get('q', '', $_REQUEST);
  4336. $rawRows = null;
  4337. $rows = $typeSpecial->getValuesWithExports($query);
  4338. 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>';}
  4339. foreach ($rows as $kID => $vItem) {
  4340. $itemJson = new stdClass();
  4341. $itemJson->id = $vItem->id;
  4342. $itemJson->name = $vItem->param_out;
  4343. if (!empty($vItem->exports)) {
  4344. $itemJson->exports = $vItem->exports;
  4345. }
  4346. $jsonData[] = $itemJson;
  4347. }
  4348. }
  4349. /*
  4350. MENU_INIT:VIEWTABLE_AJAX
  4351. ZASOB_ID:1188
  4352. _task:TYPESPECIAL
  4353. fldID:3866
  4354. Form Dataview sourceview URL encoded
  4355. q:te
  4356. */
  4357. echo json_encode($jsonData);
  4358. exit;
  4359. }
  4360. private function sendTypeSpecialCell($id, $fldName, $args) {
  4361. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4362. header("Content-type: application/json");
  4363. $jsonData = new stdClass();
  4364. $fldID = $this->_acl->getFieldIdByName($fldName);
  4365. 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>';}
  4366. $item = $this->_dataSource->getItem($id);
  4367. if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
  4368. $jsonData->msg = 'Brak dostępu';
  4369. echo json_encode($jsonData);
  4370. exit;
  4371. }
  4372. if (!$fldID) {
  4373. $jsonData->msg = 'Wrong field';
  4374. echo json_encode($jsonData);
  4375. exit;
  4376. }
  4377. Lib::loadClass('Typespecial');
  4378. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  4379. if ($typeSpecial) {
  4380. $jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
  4381. 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>';}
  4382. }
  4383. echo json_encode($jsonData);
  4384. exit;
  4385. }
  4386. private function ajaxData($args) {
  4387. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4388. $pageSize = V::get('pageSize', 10, $args, 'int');
  4389. $page = V::get('page', 0, $args, 'int');
  4390. $currSortCol = V::get('currSortCol', '', $args);
  4391. $currSortFlip = V::get('currSortFlip', '', $args);
  4392. if ($page > 0) {
  4393. $page -= 1;
  4394. }
  4395. else {
  4396. }
  4397. $params = array();
  4398. $params['limit'] = $pageSize;
  4399. $params['limitstart'] = $page * $params['limit'];
  4400. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  4401. $params['order_dir'] = $currSortFlip;
  4402. $filters = new stdClass();
  4403. $filters->currSortCol = $currSortCol;
  4404. $filters->currSortFlip = $currSortFlip;
  4405. foreach ($args as $k => $v) {
  4406. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  4407. $params[$k] = $v;
  4408. $filters->{$k} = $v;
  4409. }
  4410. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  4411. $params[$k] = $v;
  4412. $filters->{$k} = $v;
  4413. }
  4414. }
  4415. $this->setFilters($filters);
  4416. 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>';}
  4417. $vCols = $this->_acl->getVirtualFieldList();
  4418. if (!empty($vCols)) {
  4419. 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>';}
  4420. }
  4421. Lib::loadClass('Typespecial');
  4422. $total = $this->_dataSource->getTotal($params);
  4423. 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>';}
  4424. $items = $this->_dataSource->getItems($params);
  4425. 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>';}
  4426. // TODO: add virtual data by Typespecial
  4427. if (!empty($vCols) && !empty($items)) {
  4428. foreach ($vCols as $vColID => $vCol) {
  4429. $colType = $this->_acl->getFieldTypeById($vColID);
  4430. if ($colType) {
  4431. continue;// pomin Typespecial dla realnych komorek w bazie danych
  4432. }
  4433. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  4434. if ($typeSpecial) {
  4435. 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>';}
  4436. $ids = array_keys($items);
  4437. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  4438. 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>';}
  4439. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  4440. $tsValue = implode('<br>', $vValues);
  4441. 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>';}
  4442. if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
  4443. $items[$kItemID]->{$vCol} .= ": {$tsValue}";
  4444. } else {
  4445. $items[$kItemID]->{$vCol} = $tsValue;
  4446. }
  4447. }
  4448. }
  4449. }
  4450. }
  4451. $visibleCols = $this->_acl->getVisibleFieldList();
  4452. 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>';}
  4453. $jsonData = new stdClass();
  4454. $jsonData->total = $total;
  4455. $jsonData->cols = new stdClass();
  4456. $ind = 0;
  4457. foreach ($visibleCols as $fieldID => $col) {
  4458. $ind++;
  4459. $columnConfig = (object)array('index'=>$ind);
  4460. if ($col == 'ID') {
  4461. // /SE/se-dev/index.php?MENU_INIT=USERS2_MARKETING_EDIT&ARG1=EDIT&ARG1_VAL=31105
  4462. $columnConfig->format = '<a href="#EDIT/{0}">{0}</a>';
  4463. $columnConfig->unique = true;
  4464. }
  4465. else if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  4466. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  4467. }
  4468. else if (in_array($col, array('Status'))) {
  4469. // Ahmes problems Status colors
  4470. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  4471. }
  4472. else if ($this->_dataSource->isGeomField($col)) {
  4473. $columnConfig->type = 'geom';
  4474. }
  4475. if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
  4476. $columnConfig->friendly = $label;
  4477. }
  4478. $colType = $this->_acl->getFieldType($col);
  4479. if ($colType) {// @see MarkTableAjaxFilterColType
  4480. if ($colType['type'] == 'date') {
  4481. //$columnConfig->type = 'date';// TODO: require datepicker
  4482. }
  4483. } else {// typespecial - no type
  4484. $columnConfig->type = 'special';
  4485. }
  4486. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  4487. if ($typeSpecial) {
  4488. 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>';}
  4489. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  4490. }
  4491. // @see ajaxHiddenColsSave
  4492. // $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  4493. if (isset($_SESSION['USER_PROFILE'][$this->_zasobID])) {
  4494. if (isset($_SESSION['USER_PROFILE'][$this->_zasobID][$fieldID])) {
  4495. if ($_SESSION['USER_PROFILE'][$this->_zasobID][$fieldID] != 1) {
  4496. $columnConfig->hidden = true;
  4497. }
  4498. }
  4499. }
  4500. $columnConfig->description = $this->_acl->getFieldOpis($fieldID);
  4501. $jsonData->cols->{$col} = $columnConfig;
  4502. }
  4503. $jsonData->rows = array();
  4504. foreach ($items as $vItem) {
  4505. // TODO: hide items without 'R'
  4506. foreach ($visibleCols as $kID => $vCol) {
  4507. // TODO: ID default 'R'
  4508. if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
  4509. $vItem->{$vCol} = '*****';
  4510. }
  4511. // null => empty string
  4512. if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
  4513. 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>';}
  4514. $vItem->{$vCol} = '';
  4515. }
  4516. }
  4517. $jsonData->rows[] = $vItem;
  4518. }
  4519. //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>';
  4520. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonData (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData);echo'</pre>';
  4521. return $jsonData;
  4522. }
  4523. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  4524. $value = '';
  4525. $type = $this->_acl->getFieldTypeById($fieldID);
  4526. if ($type) {
  4527. if ($type['type'] == 'date') {
  4528. $value = $type['default'];
  4529. }
  4530. // fix bug when field is unique and is null allowed: change empty string to null
  4531. if ($type['null']) {
  4532. $value = 'NULL';
  4533. }
  4534. // fix bug when field is enum and is set to '0': for php '0' is empty
  4535. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  4536. if (false !== strpos($type['type'], "''")) {
  4537. // enum('', '1','2')
  4538. $value = '';
  4539. } else if (false !== strpos($type['type'], "'0'")) {
  4540. // enum('0', '1','2')
  4541. $value = '0';
  4542. } else {
  4543. $value = $type['default'];
  4544. }
  4545. }
  4546. }
  4547. return $value;
  4548. }
  4549. /**
  4550. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  4551. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  4552. */
  4553. private function ajaxHiddenColsSave($args) {
  4554. $response = new stdClass();
  4555. if (empty($args)) {
  4556. $response->type = 'info';
  4557. return $response;
  4558. }
  4559. Lib::loadClass('UserProfile');
  4560. UserProfile::load();
  4561. // clean up old, wrong values
  4562. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  4563. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  4564. }
  4565. $colVis = array();
  4566. if (array_key_exists($this->_zasobID, $_SESSION['USER_PROFILE'])) {
  4567. $colVis = $_SESSION['USER_PROFILE'][$this->_zasobID];
  4568. }
  4569. $fields = $this->_acl->getFields();
  4570. foreach ($fields as $kFldId => $vFld) {
  4571. $vFldName = $vFld['name'];
  4572. if (isset($args[$vFldName])) {
  4573. if ($args[$vFldName] == 'SHOW') {
  4574. $colVis[$kFldId] = 1;
  4575. } else if ($args[$vFldName] == 'HIDE') {
  4576. $colVis[$kFldId] = 0;
  4577. }
  4578. }
  4579. }
  4580. $_SESSION['USER_PROFILE'][$this->_zasobID] = $colVis;
  4581. UserProfile::save();
  4582. $response->type = 'success';
  4583. return $response;
  4584. }
  4585. private function ajaxTheGeomSave($args) {
  4586. $id = V::get('ID', 0, $args, 'int');
  4587. $polygon = V::get('polygon', 0, $args);
  4588. $geomFieldName = 'the_geom';
  4589. if ($id <= 0) {
  4590. throw new HttpException("Wrong param ID", 404);
  4591. }
  4592. // 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)))
  4593. $record = $this->_dataSource->getItem($id);
  4594. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  4595. throw new HttpException("Brak dostępu do rekordu", 403);
  4596. }
  4597. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  4598. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  4599. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  4600. }
  4601. $itemPath = new stdClass();
  4602. $itemPath->{$geomFieldName} = "GeomFromText('{$polygon}')";
  4603. $itemPath->ID = $id;
  4604. $affected = $this->_dataSource->updateItem($itemPath);
  4605. $response = new stdClass();
  4606. if ($affected > 0) {
  4607. $response->type = 'success';
  4608. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  4609. } else if ($affected == 0) {
  4610. $response->type = 'info';
  4611. $response->msg = "Nie wprowadzono żadnych zmian";
  4612. } else {
  4613. $response->type = 'error';
  4614. $response->msg = "Wystąpiły błędy!";
  4615. $response->errors = $this->_dataSource->getDbErrors();
  4616. }
  4617. $response->record = $this->_dataSource->getItem($id);
  4618. return $response;
  4619. }
  4620. private function sendAjaxResponseJson($method, $args) {
  4621. try {
  4622. $response = $this->{$method}($args);
  4623. }
  4624. catch (HttpException $e) {
  4625. $response = new stdClass();
  4626. $response->type = 'error';
  4627. $response->msg = $e->getMessage();
  4628. $response->errorCode = $e->getCode();
  4629. Http::sendHeaderByCode($e->getCode());
  4630. }
  4631. catch (Exception $e) {
  4632. $response = new stdClass();
  4633. $response->type = 'error';
  4634. $response->msg = $e->getMessage();
  4635. $response->errorCode = $e->getCode();
  4636. }
  4637. header('Content-type: application/json');
  4638. if (!$response) $response = new stdClass();
  4639. echo json_encode($response);
  4640. exit;
  4641. }
  4642. private function ajaxTheGeomRemove($args) {// ajax task 'THE_GEOM_REMOVE'
  4643. $id = V::get('ID', 0, $args, 'int');
  4644. $geomFieldName = 'the_geom';
  4645. $response = new stdClass();
  4646. if ($id <= 0) {
  4647. throw new HttpException("Wrong param ID", 404);
  4648. }
  4649. $tblName = $this->_acl->getName();
  4650. $record = $this->_dataSource->getItem($id);
  4651. if (!$record) {
  4652. throw new HttpException("Nie odnaleziono rekordu nr {$id}", 404);
  4653. }
  4654. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  4655. throw new HttpException("Brak dostępu do rekordu nr {$id}", 403);
  4656. }
  4657. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  4658. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  4659. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  4660. }
  4661. if (empty($record->{$geomFieldName})) {
  4662. $response->type = 'info';
  4663. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  4664. $response->record = $record;
  4665. return $response;
  4666. }
  4667. $itemPath = new stdClass();
  4668. $itemPath->{$geomFieldName} = "NULL";
  4669. $itemPath->ID = $id;
  4670. $affected = $this->_dataSource->updateItem($itemPath);
  4671. $response = new stdClass();
  4672. if ($affected > 0) {
  4673. $response->type = 'success';
  4674. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  4675. } else if ($affected == 0) {
  4676. $response->type = 'info';
  4677. $response->msg = "Nie wprowadzono żadnych zmian";
  4678. } else {
  4679. $response->type = 'error';
  4680. $response->msg = "Wystąpiły błędy!";
  4681. $response->errors = $this->_dataSource->getDbErrors();
  4682. }
  4683. $response->record = $this->_dataSource->getItem($id);
  4684. return $response;
  4685. }
  4686. }