TableAjax.php 150 KB

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