makegrid.js 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219
  1. /* global firstDayOfCalendar */ // templates/javascript/variables.twig
  2. /**
  3. * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
  4. * This function is designed mainly for table DOM generated from browsing a table in the database.
  5. * For using this function in other table DOM, you may need to:
  6. * - add "draggable" class in the table header <th>, in order to make it resizable, sortable or hidable
  7. * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
  8. * - pass the value "false" for the parameter "enableGridEdit"
  9. * - adjust other parameter value, to select which features that will be enabled
  10. *
  11. * @param t the table DOM element
  12. * @param enableResize Optional, if false, column resizing feature will be disabled
  13. * @param enableReorder Optional, if false, column reordering feature will be disabled
  14. * @param enableVisib Optional, if false, show/hide column feature will be disabled
  15. * @param enableGridEdit Optional, if false, grid editing feature will be disabled
  16. */
  17. // eslint-disable-next-line no-unused-vars
  18. var makeGrid = function (t, enableResize, enableReorder, enableVisib, enableGridEdit) {
  19. var isResizeEnabled = enableResize === undefined ? true : enableResize;
  20. var isReorderEnabled = enableReorder === undefined ? true : enableReorder;
  21. var isVisibEnabled = enableVisib === undefined ? true : enableVisib;
  22. var isGridEditEnabled = enableGridEdit === undefined ? true : enableGridEdit;
  23. var g = {
  24. /** *********
  25. * Constant
  26. ***********/
  27. minColWidth: 15,
  28. /** *********
  29. * Variables, assigned with default value, changed later
  30. ***********/
  31. actionSpan: 5,
  32. // number of colspan in Actions header in a table
  33. tableCreateTime: null,
  34. // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
  35. // Column reordering variables
  36. colOrder: [],
  37. // array of column order
  38. // Column visibility variables
  39. colVisib: [],
  40. // array of column visibility
  41. showAllColText: '',
  42. // string, text for "show all" button under column visibility list
  43. visibleHeadersCount: 0,
  44. // number of visible data headers
  45. // Table hint variables
  46. reorderHint: '',
  47. // string, hint for column reordering
  48. sortHint: '',
  49. // string, hint for column sorting
  50. markHint: '',
  51. // string, hint for column marking
  52. copyHint: '',
  53. // string, hint for copy column name
  54. showReorderHint: false,
  55. showSortHint: false,
  56. showMarkHint: false,
  57. // Grid editing
  58. isCellEditActive: false,
  59. // true if current focus is in edit cell
  60. isEditCellTextEditable: false,
  61. // true if current edit cell is editable in the text input box (not textarea)
  62. currentEditCell: null,
  63. // reference to <td> that currently being edited
  64. cellEditHint: '',
  65. // hint shown when doing grid edit
  66. gotoLinkText: '',
  67. // "Go to link" text
  68. wasEditedCellNull: false,
  69. // true if last value of the edited cell was NULL
  70. maxTruncatedLen: 0,
  71. // number of characters that can be displayed in a cell
  72. saveCellsAtOnce: false,
  73. // $cfg[saveCellsAtOnce]
  74. isCellEdited: false,
  75. // true if at least one cell has been edited
  76. saveCellWarning: '',
  77. // string, warning text when user want to leave a page with unsaved edited data
  78. lastXHR: null,
  79. // last XHR object used in AJAX request
  80. isSaving: false,
  81. // true when currently saving edited data, used to handle double posting caused by pressing ENTER in grid edit text box in Chrome browser
  82. alertNonUnique: '',
  83. // string, alert shown when saving edited nonunique table
  84. // Common hidden inputs
  85. token: null,
  86. server: null,
  87. db: null,
  88. table: null,
  89. /** **********
  90. * Functions
  91. ************/
  92. /**
  93. * Start to resize column. Called when clicking on column separator.
  94. *
  95. * @param e event
  96. * @param obj dragged div object
  97. */
  98. dragStartRsz: function (e, obj) {
  99. var n = $(g.cRsz).find('div').index(obj); // get the index of separator (i.e., column index)
  100. $(obj).addClass('colborder_active');
  101. g.colRsz = {
  102. x0: e.pageX,
  103. n: n,
  104. obj: obj,
  105. objLeft: $(obj).position().left,
  106. objWidth: $(g.t).find('th.draggable:visible').eq(n).find('span').outerWidth()
  107. };
  108. // eslint-disable-next-line compat/compat
  109. $(document.body).css('cursor', 'col-resize').noSelect();
  110. if (g.isCellEditActive) {
  111. g.hideEditCell();
  112. }
  113. },
  114. /**
  115. * Start to reorder column. Called when clicking on table header.
  116. *
  117. * @param e event
  118. * @param obj table header object
  119. */
  120. dragStartReorder: function (e, obj) {
  121. // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
  122. $(g.cCpy).text($(obj).text());
  123. var objPos = $(obj).position();
  124. $(g.cCpy).css({
  125. top: objPos.top + 20,
  126. left: objPos.left,
  127. height: $(obj).height(),
  128. width: $(obj).width()
  129. });
  130. $(g.cPointer).css({
  131. top: objPos.top
  132. });
  133. // get the column index, zero-based
  134. var n = g.getHeaderIdx(obj);
  135. g.colReorder = {
  136. x0: e.pageX,
  137. y0: e.pageY,
  138. n: n,
  139. newn: n,
  140. obj: obj,
  141. objTop: objPos.top,
  142. objLeft: objPos.left
  143. };
  144. // eslint-disable-next-line compat/compat
  145. $(document.body).css('cursor', 'move').noSelect();
  146. if (g.isCellEditActive) {
  147. g.hideEditCell();
  148. }
  149. },
  150. /**
  151. * Handle mousemove event when dragging.
  152. *
  153. * @param e event
  154. */
  155. dragMove: function (e) {
  156. var dx;
  157. if (g.colRsz) {
  158. dx = e.pageX - g.colRsz.x0;
  159. if (g.colRsz.objWidth + dx > g.minColWidth) {
  160. $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
  161. }
  162. } else if (g.colReorder) {
  163. // dragged column animation
  164. dx = e.pageX - g.colReorder.x0;
  165. $(g.cCpy).css('left', g.colReorder.objLeft + dx).show();
  166. // pointer animation
  167. var hoveredCol = g.getHoveredCol(e);
  168. if (hoveredCol) {
  169. var newn = g.getHeaderIdx(hoveredCol);
  170. g.colReorder.newn = newn;
  171. if (newn !== g.colReorder.n) {
  172. // show the column pointer in the right place
  173. var colPos = $(hoveredCol).position();
  174. var newleft = newn < g.colReorder.n ? colPos.left : colPos.left + $(hoveredCol).outerWidth();
  175. $(g.cPointer).css({
  176. left: newleft,
  177. visibility: 'visible'
  178. });
  179. } else {
  180. // no movement to other column, hide the column pointer
  181. $(g.cPointer).css('visibility', 'hidden');
  182. }
  183. }
  184. }
  185. },
  186. /**
  187. * Stop the dragging action.
  188. *
  189. * @param e event
  190. */
  191. dragEnd: function (e) {
  192. if (g.colRsz) {
  193. var dx = e.pageX - g.colRsz.x0;
  194. var nw = g.colRsz.objWidth + dx;
  195. if (nw < g.minColWidth) {
  196. nw = g.minColWidth;
  197. }
  198. var n = g.colRsz.n;
  199. // do the resizing
  200. g.resize(n, nw);
  201. g.reposRsz();
  202. g.reposDrop();
  203. g.colRsz = false;
  204. $(g.cRsz).find('div').removeClass('colborder_active');
  205. } else if (g.colReorder) {
  206. // shift columns
  207. if (g.colReorder.newn !== g.colReorder.n) {
  208. g.shiftCol(g.colReorder.n, g.colReorder.newn);
  209. // assign new position
  210. var objPos = $(g.colReorder.obj).position();
  211. g.colReorder.objTop = objPos.top;
  212. g.colReorder.objLeft = objPos.left;
  213. g.colReorder.n = g.colReorder.newn;
  214. // send request to server to remember the column order
  215. if (g.tableCreateTime) {
  216. g.sendColPrefs();
  217. }
  218. g.refreshRestoreButton();
  219. }
  220. // animate new column position
  221. $(g.cCpy).stop(true, true).animate({
  222. top: g.colReorder.objTop,
  223. left: g.colReorder.objLeft
  224. }, 'fast').fadeOut();
  225. $(g.cPointer).css('visibility', 'hidden');
  226. g.colReorder = false;
  227. }
  228. // eslint-disable-next-line compat/compat
  229. $(document.body).css('cursor', 'inherit').noSelect(false);
  230. },
  231. /**
  232. * Resize column n to new width "nw"
  233. *
  234. * @param n zero-based column index
  235. * @param nw new width of the column in pixel
  236. */
  237. resize: function (n, nw) {
  238. $(g.t).find('tr').each(function () {
  239. $(this).find('th.draggable:visible').eq(n).find('span').add($(this).find('td:visible').eq(g.actionSpan + n).find('span')).css('width', nw);
  240. });
  241. },
  242. /**
  243. * Reposition column resize bars.
  244. */
  245. reposRsz: function () {
  246. $(g.cRsz).find('div').hide();
  247. var $firstRowCols = $(g.t).find('tr').first().find('th.draggable:visible');
  248. var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
  249. $(g.t).find('table.pma_table').find('thead th').first().removeClass('before-condition');
  250. for (var n = 0, l = $firstRowCols.length; n < l; n++) {
  251. var $col = $($firstRowCols[n]);
  252. var colWidth;
  253. if (navigator.userAgent.toLowerCase().indexOf('safari') !== -1) {
  254. colWidth = $col.outerWidth();
  255. } else {
  256. colWidth = $col.outerWidth(true);
  257. }
  258. $($resizeHandles[n]).css('left', $col.position().left + colWidth).show();
  259. if ($col.hasClass('condition')) {
  260. $($resizeHandles[n]).addClass('condition');
  261. if (n > 0) {
  262. $($resizeHandles[n - 1]).addClass('condition');
  263. }
  264. }
  265. }
  266. if ($($resizeHandles[0]).hasClass('condition')) {
  267. $(g.t).find('thead th').first().addClass('before-condition');
  268. }
  269. $(g.cRsz).css('height', $(g.t).height());
  270. },
  271. /**
  272. * Shift column from index oldn to newn.
  273. *
  274. * @param oldn old zero-based column index
  275. * @param newn new zero-based column index
  276. */
  277. shiftCol: function (oldn, newn) {
  278. $(g.t).find('tr').each(function () {
  279. if (newn < oldn) {
  280. $(this).find('th.draggable').eq(newn).add($(this).find('td').eq(g.actionSpan + newn)).before($(this).find('th.draggable').eq(oldn).add($(this).find('td').eq(g.actionSpan + oldn)));
  281. } else {
  282. $(this).find('th.draggable').eq(newn).add($(this).find('td').eq(g.actionSpan + newn)).after($(this).find('th.draggable').eq(oldn).add($(this).find('td').eq(g.actionSpan + oldn)));
  283. }
  284. });
  285. // reposition the column resize bars
  286. g.reposRsz();
  287. // adjust the column visibility list
  288. if (newn < oldn) {
  289. $(g.cList).find('.lDiv div').eq(newn).before($(g.cList).find('.lDiv div').eq(oldn));
  290. } else {
  291. $(g.cList).find('.lDiv div').eq(newn).after($(g.cList).find('.lDiv div').eq(oldn));
  292. }
  293. // adjust the colOrder
  294. var tmp = g.colOrder[oldn];
  295. g.colOrder.splice(oldn, 1);
  296. g.colOrder.splice(newn, 0, tmp);
  297. // adjust the colVisib
  298. if (g.colVisib.length > 0) {
  299. tmp = g.colVisib[oldn];
  300. g.colVisib.splice(oldn, 1);
  301. g.colVisib.splice(newn, 0, tmp);
  302. }
  303. },
  304. /**
  305. * Find currently hovered table column's header (excluding actions column).
  306. *
  307. * @param e event
  308. * @return {object|undefined} the hovered column's th object or undefined if no hovered column found.
  309. */
  310. getHoveredCol: function (e) {
  311. var hoveredCol;
  312. var $headers = $(g.t).find('th.draggable:visible');
  313. $headers.each(function () {
  314. var left = $(this).offset().left;
  315. var right = left + $(this).outerWidth();
  316. if (left <= e.pageX && e.pageX <= right) {
  317. hoveredCol = this;
  318. }
  319. });
  320. return hoveredCol;
  321. },
  322. /**
  323. * Get a zero-based index from a <th class="draggable"> tag in a table.
  324. *
  325. * @param obj table header <th> object
  326. * @return {number} zero-based index of the specified table header in the set of table headers (visible or not)
  327. */
  328. getHeaderIdx: function (obj) {
  329. return $(obj).parents('tr').find('th.draggable').index(obj);
  330. },
  331. /**
  332. * Reposition the columns back to normal order.
  333. */
  334. restoreColOrder: function () {
  335. // use insertion sort, since we already have shiftCol function
  336. for (var i = 1; i < g.colOrder.length; i++) {
  337. var x = g.colOrder[i];
  338. var j = i - 1;
  339. while (j >= 0 && x < g.colOrder[j]) {
  340. j--;
  341. }
  342. if (j !== i - 1) {
  343. g.shiftCol(i, j + 1);
  344. }
  345. }
  346. if (g.tableCreateTime) {
  347. // send request to server to remember the column order
  348. g.sendColPrefs();
  349. }
  350. g.refreshRestoreButton();
  351. },
  352. /**
  353. * Send column preferences (column order and visibility) to the server.
  354. */
  355. sendColPrefs: function () {
  356. if ($(g.t).is('.ajax')) {
  357. // only send preferences if ajax class
  358. if (typeof g.db !== 'string' && typeof g.table !== 'string') {
  359. // The server has nothing to do with it
  360. // Issue: https://github.com/phpmyadmin/phpmyadmin/issues/15658
  361. return;
  362. }
  363. var postParams = {
  364. 'ajax_request': true,
  365. 'db': g.db,
  366. 'table': g.table,
  367. 'token': g.token,
  368. 'server': g.server,
  369. 'table_create_time': g.tableCreateTime
  370. };
  371. if (g.colOrder.length > 0) {
  372. $.extend(postParams, {
  373. 'col_order': g.colOrder.toString()
  374. });
  375. }
  376. if (g.colVisib.length > 0) {
  377. $.extend(postParams, {
  378. 'col_visib': g.colVisib.toString()
  379. });
  380. }
  381. $.post('index.php?route=/sql/set-column-preferences', postParams, function (data) {
  382. if (data.success !== true) {
  383. var $tempDiv = $(document.createElement('div'));
  384. $tempDiv.html(data.error);
  385. $tempDiv.addClass('alert alert-danger');
  386. Functions.ajaxShowMessage($tempDiv, false);
  387. }
  388. });
  389. }
  390. },
  391. /**
  392. * Refresh restore button state.
  393. * Make restore button disabled if the table is similar with initial state.
  394. */
  395. refreshRestoreButton: function () {
  396. // check if table state is as initial state
  397. var isInitial = true;
  398. for (var i = 0; i < g.colOrder.length; i++) {
  399. if (g.colOrder[i] !== i) {
  400. isInitial = false;
  401. break;
  402. }
  403. }
  404. // check if only one visible column left
  405. var isOneColumn = g.visibleHeadersCount === 1;
  406. // enable or disable restore button
  407. if (isInitial || isOneColumn) {
  408. $(g.o).find('div.restore_column').hide();
  409. } else {
  410. $(g.o).find('div.restore_column').show();
  411. }
  412. },
  413. /**
  414. * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
  415. *
  416. * @return {string}
  417. *
  418. */
  419. updateHint: function () {
  420. var text = '';
  421. if (!g.colRsz && !g.colReorder) {
  422. // if not resizing or dragging
  423. if (g.visibleHeadersCount > 1) {
  424. g.showReorderHint = true;
  425. }
  426. if ($(t).find('th.marker').length > 0) {
  427. g.showMarkHint = true;
  428. }
  429. if (g.showSortHint && g.sortHint) {
  430. text += text.length > 0 ? '<br>' : '';
  431. text += '- ' + g.sortHint;
  432. }
  433. if (g.showMultiSortHint && g.strMultiSortHint) {
  434. text += text.length > 0 ? '<br>' : '';
  435. text += '- ' + g.strMultiSortHint;
  436. }
  437. if (g.showMarkHint && g.markHint && !g.showSortHint &&
  438. // we do not show mark hint, when sort hint is shown
  439. g.showReorderHint && g.reorderHint) {
  440. text += text.length > 0 ? '<br>' : '';
  441. text += '- ' + g.reorderHint;
  442. text += text.length > 0 ? '<br>' : '';
  443. text += '- ' + g.markHint;
  444. text += text.length > 0 ? '<br>' : '';
  445. text += '- ' + g.copyHint;
  446. }
  447. }
  448. return text;
  449. },
  450. /**
  451. * Toggle column's visibility.
  452. * After calling this function and it returns true, afterToggleCol() must be called.
  453. *
  454. * @param {number} n
  455. *
  456. * @return {boolean} True if the column is toggled successfully.
  457. */
  458. toggleCol: function (n) {
  459. if (g.colVisib[n]) {
  460. // can hide if more than one column is visible
  461. if (g.visibleHeadersCount > 1) {
  462. $(g.t).find('tr').each(function () {
  463. $(this).find('th.draggable').eq(n).add($(this).find('td').eq(g.actionSpan + n)).hide();
  464. });
  465. g.colVisib[n] = 0;
  466. $(g.cList).find('.lDiv div').eq(n).find('input').prop('checked', false);
  467. } else {
  468. // cannot hide, force the checkbox to stay checked
  469. $(g.cList).find('.lDiv div').eq(n).find('input').prop('checked', true);
  470. return false;
  471. }
  472. } else {
  473. // column n is not visible
  474. $(g.t).find('tr').each(function () {
  475. $(this).find('th.draggable').eq(n).add($(this).find('td').eq(g.actionSpan + n)).show();
  476. });
  477. g.colVisib[n] = 1;
  478. $(g.cList).find('.lDiv div').eq(n).find('input').prop('checked', true);
  479. }
  480. return true;
  481. },
  482. /**
  483. * This must be called if toggleCol() returns is true.
  484. *
  485. * This function is separated from toggleCol because, sometimes, we want to toggle
  486. * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
  487. */
  488. afterToggleCol: function () {
  489. // some adjustments after hiding column
  490. g.reposRsz();
  491. g.reposDrop();
  492. g.sendColPrefs();
  493. // check visible first row headers count
  494. g.visibleHeadersCount = $(g.t).find('tr').first().find('th.draggable:visible').length;
  495. g.refreshRestoreButton();
  496. // Display minimum of one column - disable checkbox for hiding last column
  497. if (g.visibleHeadersCount <= 1) {
  498. $(g.cList).find('.lDiv div').each(function () {
  499. $(this).find('input:checkbox:checked').prop('disabled', true);
  500. });
  501. } else {
  502. // Remove disabled property if showing more than one column
  503. $(g.cList).find('.lDiv div').each(function () {
  504. $(this).find('input:checkbox:disabled').prop('disabled', false);
  505. });
  506. }
  507. },
  508. /**
  509. * Show columns' visibility list.
  510. *
  511. * @param obj The drop down arrow of column visibility list
  512. */
  513. showColList: function (obj) {
  514. // only show when not resizing or reordering
  515. if (!g.colRsz && !g.colReorder) {
  516. var pos = $(obj).position();
  517. $(g.cList).css({
  518. top: pos.top + $(obj).outerHeight(true)
  519. }).show();
  520. $(obj).addClass('coldrop-hover');
  521. }
  522. },
  523. /**
  524. * Hide columns' visibility list.
  525. */
  526. hideColList: function () {
  527. $(g.cList).hide();
  528. $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
  529. },
  530. /**
  531. * Reposition the column visibility drop-down arrow.
  532. */
  533. reposDrop: function () {
  534. var $th = $(t).find('th:not(.draggable)');
  535. for (var i = 0; i < $th.length; i++) {
  536. var $cd = $(g.cDrop).find('div').eq(i); // column drop-down arrow
  537. var pos = $($th[i]).position();
  538. $cd.css({
  539. left: pos.left + $($th[i]).width() - $cd.width(),
  540. top: pos.top
  541. });
  542. }
  543. },
  544. /**
  545. * Show all hidden columns.
  546. */
  547. showAllColumns: function () {
  548. for (var i = 0; i < g.colVisib.length; i++) {
  549. if (!g.colVisib[i]) {
  550. g.toggleCol(i);
  551. }
  552. }
  553. g.afterToggleCol();
  554. },
  555. /**
  556. * Show edit cell, if it can be shown
  557. *
  558. * @param cell <td> element to be edited
  559. */
  560. showEditCell: function (cell) {
  561. // destroy the date picker instance left if any, see: #17703
  562. var $datePickerInstance = $(g.cEdit).find('.hasDatepicker');
  563. if ($datePickerInstance.length > 0) {
  564. $datePickerInstance.datepicker('destroy');
  565. }
  566. if ($(cell).is('.grid_edit') && !g.colRsz && !g.colReorder) {
  567. if (!g.isCellEditActive) {
  568. var $cell = $(cell);
  569. if ('string' === $cell.attr('data-type') || 'blob' === $cell.attr('data-type') || 'json' === $cell.attr('data-type')) {
  570. g.cEdit = g.cEditTextarea;
  571. } else {
  572. g.cEdit = g.cEditStd;
  573. }
  574. // remove all edit area and hide it
  575. $(g.cEdit).find('.edit_area').empty().hide();
  576. // reposition the cEdit element
  577. $(g.cEdit).css({
  578. top: $cell.position().top,
  579. left: $cell.position().left
  580. }).show().find('.edit_box').css({
  581. width: $cell.outerWidth(),
  582. height: $cell.outerHeight()
  583. });
  584. // fill the cell edit with text from <td>
  585. var value = Functions.getCellValue(cell);
  586. if ($cell.attr('data-type') === 'json' && $cell.is('.truncated') === false) {
  587. value = Functions.stringifyJSON(value, null, 4);
  588. }
  589. $(g.cEdit).find('.edit_box').val(value);
  590. g.currentEditCell = cell;
  591. $(g.cEdit).find('.edit_box').trigger('focus');
  592. moveCursorToEnd($(g.cEdit).find('.edit_box'));
  593. $(g.cEdit).find('*').prop('disabled', false);
  594. }
  595. }
  596. function moveCursorToEnd(input) {
  597. var originalValue = input.val();
  598. var originallength = originalValue.length;
  599. input.val('');
  600. input.trigger('blur').trigger('focus').val(originalValue);
  601. input[0].setSelectionRange(originallength, originallength);
  602. }
  603. },
  604. /**
  605. * Remove edit cell and the edit area, if it is shown.
  606. *
  607. * @param force Optional, force to hide edit cell without saving edited field.
  608. * @param data Optional, data from the POST AJAX request to save the edited field
  609. * or just specify "true", if we want to replace the edited field with the new value.
  610. * @param field Optional, the edited <td>. If not specified, the function will
  611. * use currently edited <td> from g.currentEditCell.
  612. * @param options Optional, this object contains a boolean named move (true, if called from move* functions)
  613. * and a <td> to which the grid_edit should move
  614. */
  615. hideEditCell: function (force, data, field, options) {
  616. if (g.isCellEditActive && !force) {
  617. // cell is being edited, save or post the edited data
  618. if (options !== undefined) {
  619. g.saveOrPostEditedCell(options);
  620. } else {
  621. g.saveOrPostEditedCell();
  622. }
  623. return;
  624. }
  625. // cancel any previous request
  626. if (g.lastXHR !== null) {
  627. g.lastXHR.abort();
  628. g.lastXHR = null;
  629. }
  630. if (data) {
  631. if (g.currentEditCell) {
  632. // save value of currently edited cell
  633. // replace current edited field with the new value
  634. var $thisField = $(g.currentEditCell);
  635. var isNull = $thisField.data('value') === null;
  636. if (isNull) {
  637. $thisField.find('span').html('NULL');
  638. $thisField.addClass('null');
  639. } else {
  640. $thisField.removeClass('null');
  641. var value = data.isNeedToRecheck ? data.truncatableFieldValue : $thisField.data('value');
  642. // Truncates the text.
  643. $thisField.removeClass('truncated');
  644. if (CommonParams.get('pftext') === 'P' && value.length > g.maxTruncatedLen) {
  645. $thisField.addClass('truncated');
  646. value = value.substring(0, g.maxTruncatedLen) + '...';
  647. }
  648. // Add <br> before carriage return.
  649. var newHtml = Functions.escapeHtml(value);
  650. newHtml = newHtml.replace(/\n/g, '<br>\n');
  651. var decimals = parseInt($thisField.attr('data-decimals'));
  652. // remove decimal places if column type not supported
  653. if (decimals === 0 && $thisField.attr('data-type').indexOf('time') !== -1) {
  654. newHtml = newHtml.substring(0, newHtml.indexOf('.'));
  655. }
  656. // remove additional decimal places
  657. if (decimals > 0 && $thisField.attr('data-type').indexOf('time') !== -1) {
  658. newHtml = newHtml.substring(0, newHtml.length - (6 - decimals));
  659. }
  660. var selector = 'span';
  661. if ($thisField.hasClass('hex') && $thisField.find('a').length) {
  662. selector = 'a';
  663. }
  664. // Updates the code keeping highlighting (if any).
  665. var $target = $thisField.find(selector);
  666. if (!Functions.updateCode($target, newHtml, value)) {
  667. $target.html(newHtml);
  668. }
  669. }
  670. if ($thisField.is('.bit')) {
  671. $thisField.find('span').text($thisField.data('value'));
  672. }
  673. }
  674. if (data.transformations !== undefined) {
  675. $.each(data.transformations, function (cellIndex, value) {
  676. var $thisField = $(g.t).find('.to_be_saved').eq(cellIndex);
  677. $thisField.find('span').html(value);
  678. });
  679. }
  680. if (data.relations !== undefined) {
  681. $.each(data.relations, function (cellIndex, value) {
  682. var $thisField = $(g.t).find('.to_be_saved').eq(cellIndex);
  683. $thisField.find('span').html(value);
  684. });
  685. }
  686. // refresh the grid
  687. g.reposRsz();
  688. g.reposDrop();
  689. }
  690. // hide the cell editing area
  691. $(g.cEdit).hide();
  692. $(g.cEdit).find('.edit_box').trigger('blur');
  693. g.isCellEditActive = false;
  694. g.currentEditCell = null;
  695. // destroy datepicker in edit area, if exist
  696. var $dp = $(g.cEdit).find('.hasDatepicker');
  697. if ($dp.length > 0) {
  698. // eslint-disable-next-line no-underscore-dangle
  699. $(document).on('mousedown', $.datepicker._checkExternalClick);
  700. $dp.datepicker('refresh');
  701. // change the cursor in edit box back to normal
  702. // (the cursor become a hand pointer when we add datepicker)
  703. $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
  704. }
  705. },
  706. /**
  707. * Show drop-down edit area when edit cell is focused.
  708. */
  709. showEditArea: function () {
  710. if (!g.isCellEditActive) {
  711. // make sure the edit area has not been shown
  712. g.isCellEditActive = true;
  713. g.isEditCellTextEditable = false;
  714. /**
  715. * @var $td current edited cell
  716. */
  717. var $td = $(g.currentEditCell);
  718. /**
  719. * @var $editArea the editing area
  720. */
  721. var $editArea = $(g.cEdit).find('.edit_area');
  722. /**
  723. * @var whereClause WHERE clause for the edited cell
  724. */
  725. var whereClause = $td.parent('tr').find('.where_clause').val();
  726. /**
  727. * @var fieldName String containing the name of this field.
  728. * @see Sql.getFieldName()
  729. */
  730. var fieldName = Sql.getFieldName($(t), $td);
  731. /**
  732. * @var relationCurrValue String current value of the field (for fields that are foreign keyed).
  733. */
  734. var relationCurrValue = $td.text();
  735. /**
  736. * @var relationKeyOrDisplayColumn String relational key if in 'Relational display column' mode,
  737. * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
  738. */
  739. var relationKeyOrDisplayColumn = $td.find('a').attr('title');
  740. /**
  741. * @var currValue String current value of the field (for fields that are of type enum or set).
  742. */
  743. var currValue = $td.find('span').text();
  744. // empty all edit area, then rebuild it based on $td classes
  745. $editArea.empty();
  746. // remember this instead of testing more than once
  747. var isNull = $td.is('.null');
  748. // add goto link, if this cell contains a link
  749. if ($td.find('a').length > 0) {
  750. var gotoLink = document.createElement('div');
  751. gotoLink.className = 'goto_link';
  752. $(gotoLink).append(g.gotoLinkText + ' ').append($td.find('a').clone());
  753. $editArea.append(gotoLink);
  754. }
  755. g.wasEditedCellNull = false;
  756. if ($td.is(':not(.not_null)')) {
  757. // append a null checkbox
  758. $editArea.append('<div class="null_div"><label>NULL:<input type="checkbox"></label></div>');
  759. var $checkbox = $editArea.find('.null_div input');
  760. // check if current <td> is NULL
  761. if (isNull) {
  762. $checkbox.prop('checked', true);
  763. g.wasEditedCellNull = true;
  764. }
  765. // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
  766. if ($td.is('.enum, .set')) {
  767. $editArea.on('change', 'select', function () {
  768. $checkbox.prop('checked', false);
  769. });
  770. } else if ($td.is('.relation')) {
  771. $editArea.on('change', 'select', function () {
  772. $checkbox.prop('checked', false);
  773. });
  774. $editArea.on('click', '.browse_foreign', function () {
  775. $checkbox.prop('checked', false);
  776. });
  777. } else {
  778. $(g.cEdit).on('keypress change paste', '.edit_box', function () {
  779. if ($(this).val() !== '') {
  780. $checkbox.prop('checked', false);
  781. }
  782. });
  783. // Capture ctrl+v (on IE and Chrome)
  784. $(g.cEdit).on('keydown', '.edit_box', function (e) {
  785. if (e.ctrlKey && e.which === 86) {
  786. $checkbox.prop('checked', false);
  787. }
  788. });
  789. $editArea.on('keydown', 'textarea', function () {
  790. $checkbox.prop('checked', false);
  791. });
  792. }
  793. // if some text is written in textbox automatically unmark the null checkbox and if it is emptied again mark the checkbox.
  794. $(g.cEdit).find('.edit_box').on('input', function () {
  795. if ($(g.cEdit).find('.edit_box').val() !== '') {
  796. $checkbox.prop('checked', false);
  797. } else {
  798. $checkbox.prop('checked', true);
  799. }
  800. });
  801. // if null checkbox is clicked empty the corresponding select/editor.
  802. $checkbox.on('click', function () {
  803. if ($td.is('.enum')) {
  804. $editArea.find('select').val('');
  805. } else if ($td.is('.set')) {
  806. $editArea.find('select').find('option').each(function () {
  807. var $option = $(this);
  808. $option.prop('selected', false);
  809. });
  810. } else if ($td.is('.relation')) {
  811. // if the dropdown is there to select the foreign value
  812. if ($editArea.find('select').length > 0) {
  813. $editArea.find('select').val('');
  814. }
  815. } else if ($td.is('.datefield')) {
  816. $('.ui-datepicker-trigger').trigger('click');
  817. } else {
  818. $editArea.find('textarea').val('');
  819. }
  820. $(g.cEdit).find('.edit_box').val('');
  821. });
  822. }
  823. // reset the position of the edit_area div after closing datetime picker
  824. $(g.cEdit).find('.edit_area').css({
  825. 'top': '0',
  826. 'position': ''
  827. });
  828. var postParams;
  829. if ($td.is('.relation')) {
  830. // handle relations
  831. $editArea.addClass('edit_area_loading');
  832. // initialize the original data
  833. $td.data('original_data', null);
  834. /**
  835. * @var postParams Object containing parameters for the POST request
  836. */
  837. postParams = {
  838. 'ajax_request': true,
  839. 'server': g.server,
  840. 'db': g.db,
  841. 'table': g.table,
  842. 'column': fieldName,
  843. 'curr_value': relationCurrValue,
  844. 'relation_key_or_display_column': relationKeyOrDisplayColumn
  845. };
  846. g.lastXHR = $.post('index.php?route=/sql/get-relational-values', postParams, function (data) {
  847. g.lastXHR = null;
  848. $editArea.removeClass('edit_area_loading');
  849. if ($(data.dropdown).is('select')) {
  850. // save original_data
  851. var value = $(data.dropdown).val();
  852. $td.data('original_data', value);
  853. // update the text input field, in case where the "Relational display column" is checked
  854. $(g.cEdit).find('.edit_box').val(value);
  855. }
  856. $editArea.append(data.dropdown);
  857. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  858. // for 'Browse foreign values' options,
  859. // hide the value next to 'Browse foreign values' link
  860. $editArea.find('span.curr_value').hide();
  861. // handle update for new values selected from new window
  862. $editArea.find('span.curr_value').on('change', function () {
  863. $(g.cEdit).find('.edit_box').val($(this).text());
  864. });
  865. }); // end $.post()
  866. $editArea.show();
  867. $editArea.on('change', 'select', function () {
  868. $(g.cEdit).find('.edit_box').val($(this).val());
  869. });
  870. g.isEditCellTextEditable = true;
  871. } else if ($td.is('.enum')) {
  872. // handle enum fields
  873. $editArea.addClass('edit_area_loading');
  874. /**
  875. * @var postParams Object containing parameters for the POST request
  876. */
  877. postParams = {
  878. 'ajax_request': true,
  879. 'server': g.server,
  880. 'db': g.db,
  881. 'table': g.table,
  882. 'column': fieldName,
  883. 'curr_value': currValue
  884. };
  885. g.lastXHR = $.post('index.php?route=/sql/get-enum-values', postParams, function (data) {
  886. g.lastXHR = null;
  887. if (typeof data === 'object' && data.success === false) {
  888. Functions.ajaxShowMessage(data.error, undefined, 'error');
  889. return;
  890. }
  891. $editArea.removeClass('edit_area_loading');
  892. $editArea.append(data.dropdown);
  893. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  894. }); // end $.post()
  895. $editArea.show();
  896. $editArea.on('change', 'select', function () {
  897. $(g.cEdit).find('.edit_box').val($(this).val());
  898. });
  899. } else if ($td.is('.set')) {
  900. // handle set fields
  901. $editArea.addClass('edit_area_loading');
  902. // if the data is truncated, get the full data
  903. if ($td.is('.truncated')) {
  904. postParams = {
  905. 'ajax_request': true,
  906. 'server': g.server,
  907. 'db': g.db,
  908. 'table': g.table,
  909. 'column': fieldName,
  910. 'curr_value': currValue,
  911. 'get_full_values': true,
  912. 'where_clause': whereClause
  913. };
  914. } else {
  915. postParams = {
  916. 'ajax_request': true,
  917. 'server': g.server,
  918. 'db': g.db,
  919. 'table': g.table,
  920. 'column': fieldName,
  921. 'curr_value': currValue
  922. };
  923. }
  924. g.lastXHR = $.post('index.php?route=/sql/get-set-values', postParams, function (data) {
  925. g.lastXHR = null;
  926. if (typeof data === 'object' && data.success === false) {
  927. Functions.ajaxShowMessage(data.error, undefined, 'error');
  928. return;
  929. }
  930. $editArea.removeClass('edit_area_loading');
  931. $editArea.append(data.select);
  932. $td.data('original_data', $(data.select).val().join());
  933. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  934. }); // end $.post()
  935. $editArea.show();
  936. $editArea.on('change', 'select', function () {
  937. $(g.cEdit).find('.edit_box').val($(this).val());
  938. });
  939. } else if ($td.is('.truncated, .transformed')) {
  940. if ($td.is('.to_be_saved')) {
  941. // cell has been edited
  942. var value = $td.data('value');
  943. $(g.cEdit).find('.edit_box').val(value);
  944. $editArea.append('<textarea></textarea>');
  945. $editArea.find('textarea').val(value);
  946. $editArea.on('keyup', 'textarea', function () {
  947. $(g.cEdit).find('.edit_box').val($(this).val());
  948. });
  949. $(g.cEdit).on('keyup', '.edit_box', function () {
  950. $editArea.find('textarea').val($(this).val());
  951. });
  952. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  953. } else {
  954. // handle truncated/transformed values values
  955. $editArea.addClass('edit_area_loading');
  956. // initialize the original data
  957. $td.data('original_data', null);
  958. /**
  959. * @var sqlQuery String containing the SQL query used to retrieve value of truncated/transformed data
  960. */
  961. var sqlQuery = 'SELECT `' + fieldName + '` FROM `' + g.table + '` WHERE ' + whereClause;
  962. // Make the Ajax call and get the data, wrap it and insert it
  963. g.lastXHR = $.post('index.php?route=/sql', {
  964. 'server': g.server,
  965. 'db': g.db,
  966. 'ajax_request': true,
  967. 'sql_query': sqlQuery,
  968. 'grid_edit': true
  969. }, function (data) {
  970. g.lastXHR = null;
  971. $editArea.removeClass('edit_area_loading');
  972. if (typeof data !== 'undefined' && data.success === true) {
  973. if ($td.attr('data-type') === 'json') {
  974. data.value = Functions.stringifyJSON(data.value, null, 4);
  975. }
  976. $td.data('original_data', data.value);
  977. $(g.cEdit).find('.edit_box').val(data.value);
  978. } else {
  979. Functions.ajaxShowMessage(data.error, false);
  980. }
  981. }); // end $.post()
  982. }
  983. g.isEditCellTextEditable = true;
  984. } else if ($td.is('.timefield, .datefield, .datetimefield, .timestampfield')) {
  985. var $inputField = $(g.cEdit).find('.edit_box');
  986. // remember current datetime value in $input_field, if it is not null
  987. var datetimeValue = !isNull ? $inputField.val() : '';
  988. var showMillisec = false;
  989. var showMicrosec = false;
  990. var timeFormat = 'HH:mm:ss';
  991. // check for decimal places of seconds
  992. if ($td.attr('data-decimals') > 0 && $td.attr('data-type').indexOf('time') !== -1) {
  993. if (datetimeValue && datetimeValue.indexOf('.') === false) {
  994. datetimeValue += '.';
  995. }
  996. if ($td.attr('data-decimals') > 3) {
  997. showMillisec = true;
  998. showMicrosec = true;
  999. timeFormat = 'HH:mm:ss.lc';
  1000. if (datetimeValue) {
  1001. datetimeValue += '000000';
  1002. datetimeValue = datetimeValue.substring(0, datetimeValue.indexOf('.') + 7);
  1003. $inputField.val(datetimeValue);
  1004. }
  1005. } else {
  1006. showMillisec = true;
  1007. timeFormat = 'HH:mm:ss.l';
  1008. if (datetimeValue) {
  1009. datetimeValue += '000';
  1010. datetimeValue = datetimeValue.substring(0, datetimeValue.indexOf('.') + 4);
  1011. $inputField.val(datetimeValue);
  1012. }
  1013. }
  1014. }
  1015. // add datetime picker
  1016. Functions.addDatepicker($inputField, $td.attr('data-type'), {
  1017. showMillisec: showMillisec,
  1018. showMicrosec: showMicrosec,
  1019. timeFormat: timeFormat,
  1020. firstDay: firstDayOfCalendar
  1021. });
  1022. $inputField.on('keyup', function (e) {
  1023. if (e.which === 13) {
  1024. // post on pressing "Enter"
  1025. e.preventDefault();
  1026. e.stopPropagation();
  1027. g.saveOrPostEditedCell();
  1028. } else if (e.which !== 27) {
  1029. Functions.toggleDatepickerIfInvalid($td, $inputField);
  1030. }
  1031. });
  1032. $inputField.datepicker('show');
  1033. Functions.toggleDatepickerIfInvalid($td, $inputField);
  1034. // unbind the mousedown event to prevent the problem of
  1035. // datepicker getting closed, needs to be checked for any
  1036. // change in names when updating
  1037. // eslint-disable-next-line no-underscore-dangle
  1038. $(document).off('mousedown', $.datepicker._checkExternalClick);
  1039. // move ui-datepicker-div inside cEdit div
  1040. var datepickerDiv = $('#ui-datepicker-div');
  1041. datepickerDiv.css({
  1042. 'top': 0,
  1043. 'left': 0,
  1044. 'position': 'relative'
  1045. });
  1046. $(g.cEdit).append(datepickerDiv);
  1047. // cancel any click on the datepicker element
  1048. $editArea.find('> *').on('click', function (e) {
  1049. e.stopPropagation();
  1050. });
  1051. g.isEditCellTextEditable = true;
  1052. } else {
  1053. g.isEditCellTextEditable = true;
  1054. // only append edit area hint if there is a null checkbox
  1055. if ($editArea.children().length > 0) {
  1056. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  1057. }
  1058. }
  1059. if ($editArea.children().length > 0) {
  1060. $editArea.show();
  1061. }
  1062. }
  1063. },
  1064. /**
  1065. * Post the content of edited cell.
  1066. *
  1067. * @param options Optional, this object contains a boolean named move (true, if called from move* functions)
  1068. * and a <td> to which the grid_edit should move
  1069. */
  1070. postEditedCell: function (options) {
  1071. if (g.isSaving) {
  1072. return;
  1073. }
  1074. g.isSaving = true;
  1075. /**
  1076. * @var relationFields Array containing the name/value pairs of relational fields
  1077. */
  1078. var relationFields = {};
  1079. /**
  1080. * @var relationalDisplay string 'K' if relational key, 'D' if relational display column
  1081. */
  1082. var relationalDisplay = $(g.o).find('input[name=relational_display]:checked').val();
  1083. /**
  1084. * @var transformFields Array containing the name/value pairs for transformed fields
  1085. */
  1086. var transformFields = {};
  1087. /**
  1088. * @var transformationFields Boolean, if there are any transformed fields in the edited cells
  1089. */
  1090. var transformationFields = false;
  1091. /**
  1092. * @var fullSqlQuery String containing the complete SQL query to update this table
  1093. */
  1094. var fullSqlQuery = '';
  1095. /**
  1096. * @var relFieldsList String, url encoded representation of {@link relations_fields}
  1097. */
  1098. var relFieldsList = '';
  1099. /**
  1100. * @var transformFieldsList String, url encoded representation of {@link transformFields}
  1101. */
  1102. var transformFieldsList = '';
  1103. /**
  1104. * @var fullWhereClause Array containing where clause for updated fields
  1105. */
  1106. var fullWhereClause = [];
  1107. /**
  1108. * @var isUnique Boolean, whether the rows in this table is unique or not
  1109. */
  1110. var isUnique = $(g.t).find('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
  1111. /**
  1112. * multi edit variables
  1113. */
  1114. var multiEditFieldsName = [];
  1115. var multiEditFieldsType = [];
  1116. var multiEditFields = [];
  1117. var multiEditFieldsNull = [];
  1118. // alert user if edited table is not unique
  1119. if (!isUnique) {
  1120. alert(g.alertNonUnique);
  1121. }
  1122. // loop each edited row
  1123. $(g.t).find('td.to_be_saved').parents('tr').each(function () {
  1124. var $tr = $(this);
  1125. var whereClause = $tr.find('.where_clause').val();
  1126. if (typeof whereClause === 'undefined') {
  1127. whereClause = '';
  1128. }
  1129. fullWhereClause.push(whereClause);
  1130. var conditionArrayContent = $tr.find('.condition_array').val();
  1131. if (typeof conditionArrayContent === 'undefined') {
  1132. conditionArrayContent = '{}';
  1133. }
  1134. var conditionArray = JSON.parse(conditionArrayContent);
  1135. /**
  1136. * multi edit variables, for current row
  1137. * @TODO array indices are still not correct, they should be md5 of field's name
  1138. */
  1139. var fieldsName = [];
  1140. var fieldsType = [];
  1141. var fields = [];
  1142. var fieldsNull = [];
  1143. // loop each edited cell in a row
  1144. $tr.find('.to_be_saved').each(function () {
  1145. /**
  1146. * @var $thisField Object referring to the td that is being edited
  1147. */
  1148. var $thisField = $(this);
  1149. /**
  1150. * @var fieldName String containing the name of this field.
  1151. * @see Sql.getFieldName()
  1152. */
  1153. var fieldName = Sql.getFieldName($(g.t), $thisField);
  1154. /**
  1155. * @var thisFieldParams Array temporary storage for the name/value of current field
  1156. */
  1157. var thisFieldParams = {};
  1158. if ($thisField.is('.transformed')) {
  1159. transformationFields = true;
  1160. }
  1161. thisFieldParams[fieldName] = $thisField.data('value');
  1162. /**
  1163. * @var isNull String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
  1164. */
  1165. var isNull = thisFieldParams[fieldName] === null;
  1166. fieldsName.push(fieldName);
  1167. if (isNull) {
  1168. fieldsNull.push('on');
  1169. fields.push('');
  1170. } else {
  1171. if ($thisField.is('.bit')) {
  1172. fieldsType.push('bit');
  1173. } else if ($thisField.hasClass('hex')) {
  1174. fieldsType.push('hex');
  1175. }
  1176. fieldsNull.push('');
  1177. if ($thisField.attr('data-type') !== 'json') {
  1178. fields.push($thisField.data('value'));
  1179. } else {
  1180. const JSONString = Functions.stringifyJSON($thisField.data('value'));
  1181. fields.push(JSONString);
  1182. }
  1183. var cellIndex = $thisField.index('.to_be_saved');
  1184. if ($thisField.is(':not(.relation, .enum, .set, .bit)')) {
  1185. if ($thisField.is('.transformed')) {
  1186. transformFields[cellIndex] = {};
  1187. $.extend(transformFields[cellIndex], thisFieldParams);
  1188. }
  1189. } else if ($thisField.is('.relation')) {
  1190. relationFields[cellIndex] = {};
  1191. $.extend(relationFields[cellIndex], thisFieldParams);
  1192. }
  1193. }
  1194. // check if edited field appears in WHERE clause
  1195. if (whereClause.indexOf(Sql.urlEncode(fieldName)) > -1) {
  1196. var fieldStr = '`' + g.table + '`.' + '`' + fieldName + '`';
  1197. for (var field in conditionArray) {
  1198. if (field.indexOf(fieldStr) > -1) {
  1199. conditionArray[field] = isNull ? 'IS NULL' : '= \'' + thisFieldParams[fieldName].replace(/'/g, '\'\'') + '\'';
  1200. break;
  1201. }
  1202. }
  1203. }
  1204. }); // end of loop for every edited cells in a row
  1205. // save new_clause
  1206. var newClause = '';
  1207. for (var field in conditionArray) {
  1208. newClause += field + ' ' + conditionArray[field] + ' AND ';
  1209. }
  1210. newClause = newClause.substring(0, newClause.length - 5); // remove the last AND
  1211. $tr.data('new_clause', newClause);
  1212. // save condition_array
  1213. $tr.find('.condition_array').val(JSON.stringify(conditionArray));
  1214. multiEditFieldsName.push(fieldsName);
  1215. multiEditFieldsType.push(fieldsType);
  1216. multiEditFields.push(fields);
  1217. multiEditFieldsNull.push(fieldsNull);
  1218. }); // end of loop for every edited rows
  1219. relFieldsList = $.param(relationFields);
  1220. transformFieldsList = $.param(transformFields);
  1221. // Make the Ajax post after setting all parameters
  1222. /**
  1223. * @var postParams Object containing parameters for the POST request
  1224. */
  1225. var postParams = {
  1226. 'ajax_request': true,
  1227. 'sql_query': fullSqlQuery,
  1228. 'server': g.server,
  1229. 'db': g.db,
  1230. 'table': g.table,
  1231. 'clause_is_unique': isUnique,
  1232. 'where_clause': fullWhereClause,
  1233. 'fields[multi_edit]': multiEditFields,
  1234. 'fields_name[multi_edit]': multiEditFieldsName,
  1235. 'fields_type[multi_edit]': multiEditFieldsType,
  1236. 'fields_null[multi_edit]': multiEditFieldsNull,
  1237. 'rel_fields_list': relFieldsList,
  1238. 'do_transformations': transformationFields,
  1239. 'transform_fields_list': transformFieldsList,
  1240. 'relational_display': relationalDisplay,
  1241. 'goto': encodeURIComponent('index.php?route=/sql'),
  1242. 'submit_type': 'save'
  1243. };
  1244. if (!g.saveCellsAtOnce) {
  1245. $(g.cEdit).find('*').prop('disabled', true);
  1246. $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
  1247. } else {
  1248. $(g.o).find('div.save_edited').addClass('saving_edited_data').find('input').prop('disabled', true); // disable the save button
  1249. }
  1250. $.ajax({
  1251. type: 'POST',
  1252. url: 'index.php?route=/table/replace',
  1253. data: postParams,
  1254. success: function (data) {
  1255. g.isSaving = false;
  1256. if (!g.saveCellsAtOnce) {
  1257. $(g.cEdit).find('*').prop('disabled', false);
  1258. $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
  1259. } else {
  1260. $(g.o).find('div.save_edited').removeClass('saving_edited_data').find('input').prop('disabled', false); // enable the save button back
  1261. }
  1262. if (typeof data !== 'undefined' && data.success === true) {
  1263. if (typeof options === 'undefined' || !options.move) {
  1264. Functions.ajaxShowMessage(data.message);
  1265. }
  1266. // update where_clause related data in each edited row
  1267. $(g.t).find('td.to_be_saved').parents('tr').each(function () {
  1268. var newClause = $(this).data('new_clause');
  1269. var $whereClause = $(this).find('.where_clause');
  1270. var oldClause = $whereClause.val();
  1271. var decodedOldClause = oldClause;
  1272. var decodedNewClause = newClause;
  1273. $whereClause.val(newClause);
  1274. // update Edit, Copy, and Delete links also
  1275. $(this).find('a').each(function () {
  1276. $(this).attr('href', $(this).attr('href').replace(oldClause, newClause));
  1277. // update delete confirmation in Delete link
  1278. if ($(this).attr('href').indexOf('DELETE') > -1) {
  1279. $(this).removeAttr('onclick').off('click').on('click', function () {
  1280. return Functions.confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' + decodedNewClause + (isUnique ? '' : ' LIMIT 1'));
  1281. });
  1282. }
  1283. });
  1284. // update the multi edit checkboxes
  1285. $(this).find('input[type=checkbox]').each(function () {
  1286. var $checkbox = $(this);
  1287. var checkboxName = $checkbox.attr('name');
  1288. var checkboxValue = $checkbox.val();
  1289. $checkbox.attr('name', checkboxName.replace(oldClause, newClause));
  1290. $checkbox.val(checkboxValue.replace(decodedOldClause, decodedNewClause));
  1291. });
  1292. });
  1293. // update the display of executed SQL query command
  1294. if (typeof data.sql_query !== 'undefined') {
  1295. // extract query box
  1296. var $resultQuery = $($.parseHTML(data.sql_query));
  1297. var sqlOuter = $resultQuery.find('.sqlOuter').wrap('<p>').parent().html();
  1298. var tools = $resultQuery.find('.tools').wrap('<p>').parent().html();
  1299. // sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
  1300. if (typeof sqlOuter !== 'undefined' && typeof tools !== 'undefined') {
  1301. $(g.o).find('.result_query').not($(g.o).find('.result_query').last()).remove();
  1302. var $existingQuery = $(g.o).find('.result_query');
  1303. // If two query box exists update query in second else add a second box
  1304. if ($existingQuery.find('div.sqlOuter').length > 1) {
  1305. $existingQuery.children().eq(3).remove();
  1306. $existingQuery.children().eq(3).remove();
  1307. $existingQuery.append(sqlOuter + tools);
  1308. } else {
  1309. $existingQuery.append(sqlOuter + tools);
  1310. }
  1311. Functions.highlightSql($existingQuery);
  1312. }
  1313. }
  1314. // hide and/or update the successfully saved cells
  1315. g.hideEditCell(true, data);
  1316. // remove the "Save edited cells" button
  1317. $(g.o).find('div.save_edited').hide();
  1318. // update saved fields
  1319. $(g.t).find('.to_be_saved').removeClass('to_be_saved').data('value', null).data('original_data', null);
  1320. g.isCellEdited = false;
  1321. } else {
  1322. Functions.ajaxShowMessage(data.error, false);
  1323. if (!g.saveCellsAtOnce) {
  1324. $(g.t).find('.to_be_saved').removeClass('to_be_saved');
  1325. }
  1326. }
  1327. }
  1328. }).done(function () {
  1329. if (options !== undefined && options.move) {
  1330. g.showEditCell(options.cell);
  1331. }
  1332. }); // end $.ajax()
  1333. },
  1334. /**
  1335. * Save edited cell, so it can be posted later.
  1336. *
  1337. * @return {bool}
  1338. */
  1339. saveEditedCell: function () {
  1340. /**
  1341. * @var $thisField Object referring to the td that is being edited
  1342. */
  1343. var $thisField = $(g.currentEditCell);
  1344. var $testElement = ''; // to test the presence of a element
  1345. var needToPost = false;
  1346. /**
  1347. * @var fieldName String containing the name of this field.
  1348. * @see Sql.getFieldName()
  1349. */
  1350. var fieldName = Sql.getFieldName($(g.t), $thisField);
  1351. /**
  1352. * @var thisFieldParams Array temporary storage for the name/value of current field
  1353. */
  1354. var thisFieldParams = {};
  1355. /**
  1356. * @var isNull String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
  1357. */
  1358. var isNull = $(g.cEdit).find('input:checkbox').is(':checked');
  1359. if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
  1360. // the edit area is still loading (retrieving cell data), no need to post
  1361. needToPost = false;
  1362. } else if (isNull) {
  1363. if (!g.wasEditedCellNull) {
  1364. thisFieldParams[fieldName] = null;
  1365. needToPost = true;
  1366. }
  1367. } else {
  1368. if ($thisField.is('.bit')) {
  1369. thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
  1370. } else if ($thisField.is('.set')) {
  1371. $testElement = $(g.cEdit).find('select');
  1372. thisFieldParams[fieldName] = $testElement.map(function () {
  1373. return $(this).val();
  1374. }).get().join(',');
  1375. } else if ($thisField.is('.relation, .enum')) {
  1376. // for relation and enumeration, take the results from edit box value,
  1377. // because selected value from drop-down, new window or multiple
  1378. // selection list will always be updated to the edit box
  1379. thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
  1380. } else if ($thisField.hasClass('hex')) {
  1381. if ($(g.cEdit).find('.edit_box').val().match(/^(0x)?[a-f0-9]*$/i) !== null) {
  1382. thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
  1383. } else {
  1384. var hexError = '<div class="alert alert-danger" role="alert">' + Messages.strEnterValidHex + '</div>';
  1385. Functions.ajaxShowMessage(hexError, false);
  1386. thisFieldParams[fieldName] = Functions.getCellValue(g.currentEditCell);
  1387. }
  1388. } else {
  1389. thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
  1390. }
  1391. let isValueUpdated;
  1392. if ($thisField.attr('data-type') !== 'json') {
  1393. isValueUpdated = thisFieldParams[fieldName] !== Functions.getCellValue(g.currentEditCell);
  1394. } else {
  1395. const JSONString = Functions.stringifyJSON(thisFieldParams[fieldName]);
  1396. isValueUpdated = JSONString !== Functions.stringifyJSON(Functions.getCellValue(g.currentEditCell));
  1397. }
  1398. if (g.wasEditedCellNull || isValueUpdated) {
  1399. needToPost = true;
  1400. }
  1401. }
  1402. if (needToPost) {
  1403. $(g.currentEditCell).addClass('to_be_saved').data('value', thisFieldParams[fieldName]);
  1404. if (g.saveCellsAtOnce) {
  1405. $(g.o).find('div.save_edited').show();
  1406. }
  1407. g.isCellEdited = true;
  1408. }
  1409. return needToPost;
  1410. },
  1411. /**
  1412. * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
  1413. *
  1414. * @param options Optional, this object contains a boolean named move (true, if called from move* functions)
  1415. * and a <td> to which the grid_edit should move
  1416. */
  1417. saveOrPostEditedCell: function (options) {
  1418. var saved = g.saveEditedCell();
  1419. // Check if $cfg['SaveCellsAtOnce'] is false
  1420. if (!g.saveCellsAtOnce) {
  1421. // Check if need_to_post is true
  1422. if (saved) {
  1423. // Check if this function called from 'move' functions
  1424. if (options !== undefined && options.move) {
  1425. g.postEditedCell(options);
  1426. } else {
  1427. g.postEditedCell();
  1428. }
  1429. // need_to_post is false
  1430. } else {
  1431. // Check if this function called from 'move' functions
  1432. if (options !== undefined && options.move) {
  1433. g.hideEditCell(true);
  1434. g.showEditCell(options.cell);
  1435. // NOT called from 'move' functions
  1436. } else {
  1437. g.hideEditCell(true);
  1438. }
  1439. }
  1440. // $cfg['SaveCellsAtOnce'] is true
  1441. } else {
  1442. // If need_to_post
  1443. if (saved) {
  1444. // If this function called from 'move' functions
  1445. if (options !== undefined && options.move) {
  1446. g.hideEditCell(true, true, false, options);
  1447. g.showEditCell(options.cell);
  1448. // NOT called from 'move' functions
  1449. } else {
  1450. g.hideEditCell(true, true);
  1451. }
  1452. } else {
  1453. // If this function called from 'move' functions
  1454. if (options !== undefined && options.move) {
  1455. g.hideEditCell(true, false, false, options);
  1456. g.showEditCell(options.cell);
  1457. // NOT called from 'move' functions
  1458. } else {
  1459. g.hideEditCell(true);
  1460. }
  1461. }
  1462. }
  1463. },
  1464. /**
  1465. * Initialize column resize feature.
  1466. */
  1467. initColResize: function () {
  1468. // create column resizer div
  1469. g.cRsz = document.createElement('div');
  1470. g.cRsz.className = 'cRsz';
  1471. // get data columns in the first row of the table
  1472. var $firstRowCols = $(g.t).find('tr').first().find('th.draggable');
  1473. // create column borders
  1474. $firstRowCols.each(function () {
  1475. var cb = document.createElement('div'); // column border
  1476. $(cb).addClass('colborder').on('mousedown', function (e) {
  1477. g.dragStartRsz(e, this);
  1478. });
  1479. $(g.cRsz).append(cb);
  1480. });
  1481. g.reposRsz();
  1482. // attach to global div
  1483. $(g.gDiv).prepend(g.cRsz);
  1484. },
  1485. /**
  1486. * Initialize column reordering feature.
  1487. */
  1488. initColReorder: function () {
  1489. g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
  1490. g.cPointer = document.createElement('div'); // column pointer, used when reordering column
  1491. // adjust g.cCpy
  1492. g.cCpy.className = 'cCpy';
  1493. $(g.cCpy).hide();
  1494. // adjust g.cPointer
  1495. g.cPointer.className = 'cPointer';
  1496. $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
  1497. // assign column reordering hint
  1498. g.reorderHint = Messages.strColOrderHint;
  1499. // get data columns in the first row of the table
  1500. var $firstRowCols = $(g.t).find('tr').first().find('th.draggable');
  1501. // initialize column order
  1502. var $colOrder = $(g.o).find('.col_order'); // check if column order is passed from PHP
  1503. var i;
  1504. if ($colOrder.length > 0) {
  1505. g.colOrder = $colOrder.val().split(',');
  1506. for (i = 0; i < g.colOrder.length; i++) {
  1507. g.colOrder[i] = parseInt(g.colOrder[i], 10);
  1508. }
  1509. } else {
  1510. g.colOrder = [];
  1511. for (i = 0; i < $firstRowCols.length; i++) {
  1512. g.colOrder.push(i);
  1513. }
  1514. }
  1515. // register events
  1516. $(g.t).find('th.draggable').on('mousedown', function (e) {
  1517. $(g.o).addClass('turnOffSelect');
  1518. if (g.visibleHeadersCount > 1) {
  1519. g.dragStartReorder(e, this);
  1520. }
  1521. }).on('mouseenter', function () {
  1522. if (g.visibleHeadersCount > 1) {
  1523. $(this).css('cursor', 'move');
  1524. } else {
  1525. $(this).css('cursor', 'inherit');
  1526. }
  1527. }).on('mouseleave', function () {
  1528. g.showReorderHint = false;
  1529. $(this).uiTooltip('option', {
  1530. content: g.updateHint()
  1531. });
  1532. }).on('dblclick', function (e) {
  1533. e.preventDefault();
  1534. var res = Functions.copyToClipboard($(this).data('column'));
  1535. if (res) {
  1536. Functions.ajaxShowMessage(Messages.strCopyColumnSuccess, false, 'success');
  1537. } else {
  1538. Functions.ajaxShowMessage(Messages.strCopyColumnFailure, false, 'error');
  1539. }
  1540. });
  1541. $(g.t).find('th.draggable a').on('dblclick', function (e) {
  1542. e.stopPropagation();
  1543. });
  1544. // restore column order when the restore button is clicked
  1545. $(g.o).find('div.restore_column').on('click', function () {
  1546. g.restoreColOrder();
  1547. });
  1548. // attach to global div
  1549. $(g.gDiv).append(g.cPointer);
  1550. $(g.gDiv).append(g.cCpy);
  1551. // prevent default "dragstart" event when dragging a link
  1552. $(g.t).find('th a').on('dragstart', function () {
  1553. return false;
  1554. });
  1555. // refresh the restore column button state
  1556. g.refreshRestoreButton();
  1557. },
  1558. /**
  1559. * Initialize column visibility feature.
  1560. */
  1561. initColVisib: function () {
  1562. g.cDrop = document.createElement('div'); // column drop-down arrows
  1563. g.cList = document.createElement('div'); // column visibility list
  1564. // adjust g.cDrop
  1565. g.cDrop.className = 'cDrop';
  1566. // adjust g.cList
  1567. g.cList.className = 'cList';
  1568. $(g.cList).hide();
  1569. // assign column visibility related hints
  1570. g.showAllColText = Messages.strShowAllCol;
  1571. // get data columns in the first row of the table
  1572. var $firstRowCols = $(g.t).find('tr').first().find('th.draggable');
  1573. var i;
  1574. // initialize column visibility
  1575. var $colVisib = $(g.o).find('.col_visib'); // check if column visibility is passed from PHP
  1576. if ($colVisib.length > 0) {
  1577. g.colVisib = $colVisib.val().split(',');
  1578. for (i = 0; i < g.colVisib.length; i++) {
  1579. g.colVisib[i] = parseInt(g.colVisib[i], 10);
  1580. }
  1581. } else {
  1582. g.colVisib = [];
  1583. for (i = 0; i < $firstRowCols.length; i++) {
  1584. g.colVisib.push(1);
  1585. }
  1586. }
  1587. // make sure we have more than one column
  1588. if ($firstRowCols.length > 1) {
  1589. var $colVisibTh = $(g.t).find('th:not(.draggable)').slice(0, 1);
  1590. Functions.tooltip($colVisibTh, 'th', Messages.strColVisibHint);
  1591. // create column visibility drop-down arrow(s)
  1592. $colVisibTh.each(function () {
  1593. var cd = document.createElement('div'); // column drop-down arrow
  1594. $(cd).addClass('coldrop').on('click', function () {
  1595. if (g.cList.style.display === 'none') {
  1596. g.showColList(this);
  1597. } else {
  1598. g.hideColList();
  1599. }
  1600. });
  1601. $(g.cDrop).append(cd);
  1602. });
  1603. // add column visibility control
  1604. g.cList.innerHTML = '<div class="lDiv"></div>';
  1605. var $listDiv = $(g.cList).find('div');
  1606. var tempClick = function () {
  1607. if (g.toggleCol($(this).index())) {
  1608. g.afterToggleCol();
  1609. }
  1610. };
  1611. for (i = 0; i < $firstRowCols.length; i++) {
  1612. var currHeader = $firstRowCols[i];
  1613. var listElmt = document.createElement('div');
  1614. $(listElmt).text($(currHeader).text()).prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '>');
  1615. $listDiv.append(listElmt);
  1616. // add event on click
  1617. $(listElmt).on('click', tempClick);
  1618. }
  1619. // add "show all column" button
  1620. var showAll = document.createElement('div');
  1621. $(showAll).addClass('showAllColBtn').text(g.showAllColText);
  1622. $(g.cList).append(showAll);
  1623. $(showAll).on('click', function () {
  1624. g.showAllColumns();
  1625. });
  1626. // prepend "show all column" button at top if the list is too long
  1627. if ($firstRowCols.length > 10) {
  1628. var clone = showAll.cloneNode(true);
  1629. $(g.cList).prepend(clone);
  1630. $(clone).on('click', function () {
  1631. g.showAllColumns();
  1632. });
  1633. }
  1634. }
  1635. // hide column visibility list if we move outside the list
  1636. $(g.t).find('td, th.draggable').on('mouseenter', function () {
  1637. g.hideColList();
  1638. });
  1639. // attach to first row first col of the grid
  1640. var thFirst = $(g.t).find('th.d-print-none');
  1641. $(thFirst).append(g.cDrop);
  1642. $(thFirst).append(g.cList);
  1643. // some adjustment
  1644. g.reposDrop();
  1645. },
  1646. /**
  1647. * Move currently Editing Cell to Up
  1648. *
  1649. * @param e
  1650. *
  1651. */
  1652. moveUp: function (e) {
  1653. e.preventDefault();
  1654. var $thisField = $(g.currentEditCell);
  1655. var fieldName = Sql.getFieldName($(g.t), $thisField);
  1656. var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
  1657. if (typeof whereClause === 'undefined') {
  1658. whereClause = '';
  1659. }
  1660. var found = false;
  1661. var $prevRow;
  1662. $thisField.parents('tr').first().parents('tbody').children().each(function () {
  1663. if ($(this).find('.where_clause').val() === whereClause) {
  1664. found = true;
  1665. }
  1666. if (!found) {
  1667. $prevRow = $(this);
  1668. }
  1669. });
  1670. var newCell;
  1671. if (found && $prevRow) {
  1672. $prevRow.children('td').each(function () {
  1673. if (Sql.getFieldName($(g.t), $(this)) === fieldName) {
  1674. newCell = this;
  1675. }
  1676. });
  1677. }
  1678. if (newCell) {
  1679. g.hideEditCell(false, false, false, {
  1680. move: true,
  1681. cell: newCell
  1682. });
  1683. }
  1684. },
  1685. /**
  1686. * Move currently Editing Cell to Down
  1687. *
  1688. * @param e
  1689. *
  1690. */
  1691. moveDown: function (e) {
  1692. e.preventDefault();
  1693. var $thisField = $(g.currentEditCell);
  1694. var fieldName = Sql.getFieldName($(g.t), $thisField);
  1695. var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
  1696. if (typeof whereClause === 'undefined') {
  1697. whereClause = '';
  1698. }
  1699. var found = false;
  1700. var $nextRow;
  1701. var j = 0;
  1702. var nextRowFound = false;
  1703. $thisField.parents('tr').first().parents('tbody').children().each(function () {
  1704. if ($(this).find('.where_clause').val() === whereClause) {
  1705. found = true;
  1706. }
  1707. if (found) {
  1708. if (j >= 1 && !nextRowFound) {
  1709. $nextRow = $(this);
  1710. nextRowFound = true;
  1711. } else {
  1712. j++;
  1713. }
  1714. }
  1715. });
  1716. var newCell;
  1717. if (found && $nextRow) {
  1718. $nextRow.children('td').each(function () {
  1719. if (Sql.getFieldName($(g.t), $(this)) === fieldName) {
  1720. newCell = this;
  1721. }
  1722. });
  1723. }
  1724. if (newCell) {
  1725. g.hideEditCell(false, false, false, {
  1726. move: true,
  1727. cell: newCell
  1728. });
  1729. }
  1730. },
  1731. /**
  1732. * Move currently Editing Cell to Left
  1733. *
  1734. * @param e
  1735. *
  1736. */
  1737. moveLeft: function (e) {
  1738. e.preventDefault();
  1739. var $thisField = $(g.currentEditCell);
  1740. var fieldName = Sql.getFieldName($(g.t), $thisField);
  1741. var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
  1742. if (typeof whereClause === 'undefined') {
  1743. whereClause = '';
  1744. }
  1745. var found = false;
  1746. var $foundRow;
  1747. $thisField.parents('tr').first().parents('tbody').children().each(function () {
  1748. if ($(this).find('.where_clause').val() === whereClause) {
  1749. found = true;
  1750. $foundRow = $(this);
  1751. }
  1752. });
  1753. var leftCell;
  1754. var cellFound = false;
  1755. if (found) {
  1756. $foundRow.children('td.grid_edit').each(function () {
  1757. if (Sql.getFieldName($(g.t), $(this)) === fieldName) {
  1758. cellFound = true;
  1759. }
  1760. if (!cellFound) {
  1761. leftCell = this;
  1762. }
  1763. });
  1764. }
  1765. if (leftCell) {
  1766. g.hideEditCell(false, false, false, {
  1767. move: true,
  1768. cell: leftCell
  1769. });
  1770. }
  1771. },
  1772. /**
  1773. * Move currently Editing Cell to Right
  1774. *
  1775. * @param e
  1776. *
  1777. */
  1778. moveRight: function (e) {
  1779. e.preventDefault();
  1780. var $thisField = $(g.currentEditCell);
  1781. var fieldName = Sql.getFieldName($(g.t), $thisField);
  1782. var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
  1783. if (typeof whereClause === 'undefined') {
  1784. whereClause = '';
  1785. }
  1786. var found = false;
  1787. var $foundRow;
  1788. var j = 0;
  1789. $thisField.parents('tr').first().parents('tbody').children().each(function () {
  1790. if ($(this).find('.where_clause').val() === whereClause) {
  1791. found = true;
  1792. $foundRow = $(this);
  1793. }
  1794. });
  1795. var rightCell;
  1796. var cellFound = false;
  1797. var nextCellFound = false;
  1798. if (found) {
  1799. $foundRow.children('td.grid_edit').each(function () {
  1800. if (Sql.getFieldName($(g.t), $(this)) === fieldName) {
  1801. cellFound = true;
  1802. }
  1803. if (cellFound) {
  1804. if (j >= 1 && !nextCellFound) {
  1805. rightCell = this;
  1806. nextCellFound = true;
  1807. } else {
  1808. j++;
  1809. }
  1810. }
  1811. });
  1812. }
  1813. if (rightCell) {
  1814. g.hideEditCell(false, false, false, {
  1815. move: true,
  1816. cell: rightCell
  1817. });
  1818. }
  1819. },
  1820. /**
  1821. * Initialize grid editing feature.
  1822. */
  1823. initGridEdit: function () {
  1824. function startGridEditing(e, cell) {
  1825. if (g.isCellEditActive) {
  1826. g.saveOrPostEditedCell();
  1827. } else {
  1828. g.showEditCell(cell);
  1829. }
  1830. e.stopPropagation();
  1831. }
  1832. function handleCtrlNavigation(e) {
  1833. if (e.ctrlKey && e.which === 38 || e.altKey && e.which === 38) {
  1834. g.moveUp(e);
  1835. } else if (e.ctrlKey && e.which === 40 || e.altKey && e.which === 40) {
  1836. g.moveDown(e);
  1837. } else if (e.ctrlKey && e.which === 37 || e.altKey && e.which === 37) {
  1838. g.moveLeft(e);
  1839. } else if (e.ctrlKey && e.which === 39 || e.altKey && e.which === 39) {
  1840. g.moveRight(e);
  1841. }
  1842. }
  1843. // create cell edit wrapper element
  1844. g.cEditStd = document.createElement('div');
  1845. g.cEdit = g.cEditStd;
  1846. g.cEditTextarea = document.createElement('div');
  1847. // adjust g.cEditStd
  1848. g.cEditStd.className = 'cEdit';
  1849. $(g.cEditStd).html('<input class="edit_box" rows="1"><div class="edit_area"></div>');
  1850. $(g.cEditStd).hide();
  1851. // adjust g.cEdit
  1852. g.cEditTextarea.className = 'cEdit';
  1853. $(g.cEditTextarea).html('<textarea class="edit_box" rows="1"></textarea><div class="edit_area"></div>');
  1854. $(g.cEditTextarea).hide();
  1855. // assign cell editing hint
  1856. g.cellEditHint = Messages.strCellEditHint;
  1857. g.saveCellWarning = Messages.strSaveCellWarning;
  1858. g.alertNonUnique = Messages.strAlertNonUnique;
  1859. g.gotoLinkText = Messages.strGoToLink;
  1860. // initialize cell editing configuration
  1861. g.saveCellsAtOnce = $(g.o).find('.save_cells_at_once').val();
  1862. g.maxTruncatedLen = CommonParams.get('LimitChars');
  1863. // register events
  1864. $(g.t).find('td.data.click1').on('click', function (e) {
  1865. startGridEditing(e, this);
  1866. // prevent default action when clicking on "link" in a table
  1867. if ($(e.target).is('.grid_edit a')) {
  1868. e.preventDefault();
  1869. }
  1870. });
  1871. $(g.t).on('click', 'td.data.click2', function (e) {
  1872. var $cell = $(this);
  1873. // In the case of relational link, We want single click on the link
  1874. // to goto the link and double click to start grid-editing.
  1875. var $link = $(e.target);
  1876. if ($link.is('.grid_edit.relation a')) {
  1877. e.preventDefault();
  1878. // get the click count and increase
  1879. var clicks = $cell.data('clicks');
  1880. clicks = typeof clicks === 'undefined' ? 1 : clicks + 1;
  1881. if (clicks === 1) {
  1882. // if there are no previous clicks,
  1883. // start the single click timer
  1884. var timer = setTimeout(function () {
  1885. // temporarily remove ajax class so the page loader will not handle it,
  1886. // submit and then add it back
  1887. $link.removeClass('ajax');
  1888. AJAX.requestHandler.call($link[0]);
  1889. $link.addClass('ajax');
  1890. $cell.data('clicks', 0);
  1891. }, 700);
  1892. $cell.data('clicks', clicks);
  1893. $cell.data('timer', timer);
  1894. } else {
  1895. // When double clicking a link, switch to edit mode
  1896. // this is a double click, cancel the single click timer
  1897. // and make the click count 0
  1898. clearTimeout($cell.data('timer'));
  1899. $cell.data('clicks', 0);
  1900. // start grid-editing
  1901. startGridEditing(e, this);
  1902. }
  1903. }
  1904. }).on('dblclick', 'td.data.click2', function (e) {
  1905. if ($(e.target).is('.grid_edit a')) {
  1906. e.preventDefault();
  1907. } else {
  1908. startGridEditing(e, this);
  1909. }
  1910. });
  1911. $(g.cEditStd).on('keydown', 'input.edit_box, select', handleCtrlNavigation);
  1912. $(g.cEditStd).find('.edit_box').on('focus', function () {
  1913. g.showEditArea();
  1914. });
  1915. $(g.cEditStd).on('keydown', '.edit_box, select', function (e) {
  1916. if (e.which === 13) {
  1917. // post on pressing "Enter"
  1918. e.preventDefault();
  1919. g.saveOrPostEditedCell();
  1920. }
  1921. });
  1922. $(g.cEditStd).on('keydown', function (e) {
  1923. if (!g.isEditCellTextEditable) {
  1924. // prevent text editing
  1925. e.preventDefault();
  1926. }
  1927. });
  1928. $(g.cEditTextarea).on('keydown', 'textarea.edit_box, select', handleCtrlNavigation);
  1929. $(g.cEditTextarea).find('.edit_box').on('focus', function () {
  1930. g.showEditArea();
  1931. });
  1932. $(g.cEditTextarea).on('keydown', '.edit_box, select', function (e) {
  1933. if (e.which === 13 && !e.shiftKey) {
  1934. // post on pressing "Enter"
  1935. e.preventDefault();
  1936. g.saveOrPostEditedCell();
  1937. }
  1938. });
  1939. $(g.cEditTextarea).on('keydown', function (e) {
  1940. if (!g.isEditCellTextEditable) {
  1941. // prevent text editing
  1942. e.preventDefault();
  1943. }
  1944. });
  1945. $('html').on('click', function (e) {
  1946. // hide edit cell if the click is not fromDat edit area
  1947. if ($(e.target).parents().index($(g.cEdit)) === -1 && !$(e.target).parents('.ui-datepicker-header').length && !$('.browse_foreign_modal.ui-dialog:visible').length && !$(e.target).closest('.dismissable').length) {
  1948. g.hideEditCell();
  1949. }
  1950. }).on('keydown', function (e) {
  1951. if (e.which === 27 && g.isCellEditActive) {
  1952. // cancel on pressing "Esc"
  1953. g.hideEditCell(true);
  1954. }
  1955. });
  1956. $(g.o).find('div.save_edited').on('click', function () {
  1957. g.hideEditCell();
  1958. g.postEditedCell();
  1959. });
  1960. $(window).on('beforeunload', function () {
  1961. if (g.isCellEdited) {
  1962. return g.saveCellWarning;
  1963. }
  1964. });
  1965. // attach to global div
  1966. $(g.gDiv).append(g.cEditStd);
  1967. $(g.gDiv).append(g.cEditTextarea);
  1968. // add hint for grid editing feature when hovering "Edit" link in each table row
  1969. if (Messages.strGridEditFeatureHint !== undefined) {
  1970. Functions.tooltip($(g.t).find('.edit_row_anchor a'), 'a', Messages.strGridEditFeatureHint);
  1971. }
  1972. }
  1973. };
  1974. /** ****************
  1975. * Initialize grid
  1976. ******************/
  1977. // wrap all truncated data cells with span indicating the original length
  1978. // todo update the original length after a grid edit
  1979. $(t).find('td.data.truncated:not(:has(>span))').filter(function () {
  1980. return $(this).data('originallength') !== undefined;
  1981. }).wrapInner(function () {
  1982. return '<span title="' + Messages.strOriginalLength + ' ' + $(this).data('originallength') + '"></span>';
  1983. });
  1984. // wrap remaining cells, except actions cell, with span
  1985. $(t).find('th, td:not(:has(>span))').wrapInner('<span></span>');
  1986. // create grid elements
  1987. g.gDiv = document.createElement('div'); // create global div
  1988. // initialize the table variable
  1989. g.t = t;
  1990. // enclosing .sqlqueryresults div
  1991. g.o = $(t).parents('.sqlqueryresults');
  1992. // get data columns in the first row of the table
  1993. var $firstRowCols = $(t).find('tr').first().find('th.draggable');
  1994. // initialize visible headers count
  1995. g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
  1996. // assign first column (actions) span
  1997. if (!$(t).find('tr').first().find('th').first().hasClass('draggable')) {
  1998. // action header exist
  1999. g.actionSpan = $(t).find('tr').first().find('th').first().prop('colspan');
  2000. } else {
  2001. g.actionSpan = 0;
  2002. }
  2003. // assign table create time
  2004. // table_create_time will only available if we are in "Browse" tab
  2005. g.tableCreateTime = $(g.o).find('.table_create_time').val();
  2006. // assign the hints
  2007. g.sortHint = Messages.strSortHint;
  2008. g.strMultiSortHint = Messages.strMultiSortHint;
  2009. g.markHint = Messages.strColMarkHint;
  2010. g.copyHint = Messages.strColNameCopyHint;
  2011. // assign common hidden inputs
  2012. var $commonHiddenInputs = $(g.o).find('div.common_hidden_inputs');
  2013. g.server = $commonHiddenInputs.find('input[name=server]').val();
  2014. g.db = $commonHiddenInputs.find('input[name=db]').val();
  2015. g.table = $commonHiddenInputs.find('input[name=table]').val();
  2016. // add table class
  2017. $(t).addClass('pma_table');
  2018. // add relative position to global div so that resize handlers are correctly positioned
  2019. $(g.gDiv).css('position', 'relative');
  2020. // link the global div
  2021. $(t).before(g.gDiv);
  2022. $(g.gDiv).append(t);
  2023. // FEATURES
  2024. if (isResizeEnabled) {
  2025. g.initColResize();
  2026. }
  2027. // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
  2028. if (isReorderEnabled && $(g.o).find('table.navigation').length > 0) {
  2029. g.initColReorder();
  2030. }
  2031. if (isVisibEnabled) {
  2032. g.initColVisib();
  2033. }
  2034. // make sure we have the ajax class
  2035. if (isGridEditEnabled && $(t).is('.ajax')) {
  2036. g.initGridEdit();
  2037. }
  2038. // create tooltip for each <th> with draggable class
  2039. Functions.tooltip($(t).find('th.draggable'), 'th', g.updateHint());
  2040. // register events for hint tooltip (anchors inside draggable th)
  2041. $(t).find('th.draggable a').on('mouseenter', function () {
  2042. g.showSortHint = true;
  2043. g.showMultiSortHint = true;
  2044. $(t).find('th.draggable').uiTooltip('option', {
  2045. content: g.updateHint()
  2046. });
  2047. }).on('mouseleave', function () {
  2048. g.showSortHint = false;
  2049. g.showMultiSortHint = false;
  2050. $(t).find('th.draggable').uiTooltip('option', {
  2051. content: g.updateHint()
  2052. });
  2053. });
  2054. // register events for dragging-related feature
  2055. if (isResizeEnabled || isReorderEnabled) {
  2056. $(document).on('mousemove', function (e) {
  2057. g.dragMove(e);
  2058. });
  2059. $(document).on('mouseup', function (e) {
  2060. $(g.o).removeClass('turnOffSelect');
  2061. g.dragEnd(e);
  2062. });
  2063. }
  2064. // some adjustment
  2065. $(t).removeClass('data');
  2066. $(g.gDiv).addClass('data');
  2067. };
  2068. /**
  2069. * jQuery plugin to cancel selection in HTML code.
  2070. */
  2071. (function ($) {
  2072. $.fn.noSelect = function (p) {
  2073. // no select plugin by Paulo P.Marinas
  2074. var prevent = p === null ? true : p;
  2075. /* eslint-disable compat/compat */
  2076. var isMsie = navigator.userAgent.indexOf('MSIE') > -1 || !!window.navigator.userAgent.match(/Trident.*rv:11\./);
  2077. var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
  2078. var isSafari = navigator.userAgent.indexOf('Safari') > -1;
  2079. var isOpera = navigator.userAgent.indexOf('Presto') > -1;
  2080. /* eslint-enable compat/compat */
  2081. if (prevent) {
  2082. return this.each(function () {
  2083. if (isMsie || isSafari) {
  2084. $(this).on('selectstart', false);
  2085. } else if (isFirefox) {
  2086. $(this).css('MozUserSelect', 'none');
  2087. $('body').trigger('focus');
  2088. } else if (isOpera) {
  2089. $(this).on('mousedown', false);
  2090. } else {
  2091. $(this).attr('unselectable', 'on');
  2092. }
  2093. });
  2094. } else {
  2095. return this.each(function () {
  2096. if (isMsie || isSafari) {
  2097. $(this).off('selectstart');
  2098. } else if (isFirefox) {
  2099. $(this).css('MozUserSelect', 'inherit');
  2100. } else if (isOpera) {
  2101. $(this).off('mousedown');
  2102. } else {
  2103. $(this).removeAttr('unselectable');
  2104. }
  2105. });
  2106. }
  2107. }; // end noSelect
  2108. })(jQuery);