TableAjax.php 180 KB

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