TableAjax.php 170 KB

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