TableAjax.php 151 KB

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