makegrid.js 95 KB

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