TableAjax.php 152 KB

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