Extract add-key action from table structure index method
[phpmyadmin.git] / js / sql.js
blob211c16ed38a20d3c04380c67a4d6b6152bb6049d
1 /**
2  * @fileoverview    functions used wherever an sql query form is used
3  *
4  * @requires    jQuery
5  * @requires    js/functions.js
6  *
7  */
9 /* global isStorageSupported */ // js/config.js
10 /* global codeMirrorEditor */ // js/functions.js
11 /* global MicroHistory */ // js/microhistory.js
12 /* global makeGrid */ // js/makegrid.js
14 var Sql = {};
16 var prevScrollX = 0;
18 /**
19  * decode a string URL_encoded
20  *
21  * @param string str
22  * @return string the URL-decoded string
23  */
24 Sql.urlDecode = function (str) {
25     if (typeof str !== 'undefined') {
26         return decodeURIComponent(str.replace(/\+/g, '%20'));
27     }
30 /**
31  * endecode a string URL_decoded
32  *
33  * @param string str
34  * @return string the URL-encoded string
35  */
36 Sql.urlEncode = function (str) {
37     if (typeof str !== 'undefined') {
38         return encodeURIComponent(str).replace(/%20/g, '+');
39     }
42 /**
43  * Saves SQL query in local storage or cookie
44  *
45  * @param string SQL query
46  * @return void
47  */
48 Sql.autoSave = function (query) {
49     if (isStorageSupported('localStorage')) {
50         window.localStorage.autoSavedSql = query;
51     } else {
52         Cookies.set('autoSavedSql', query);
53     }
56 /**
57  * Saves SQL query in local storage or cookie
58  *
59  * @param string database name
60  * @param string table name
61  * @param string SQL query
62  * @return void
63  */
64 Sql.showThisQuery = function (db, table, query) {
65     var showThisQueryObject = {
66         'db': db,
67         'table': table,
68         'query': query
69     };
70     if (isStorageSupported('localStorage')) {
71         window.localStorage.showThisQuery = 1;
72         window.localStorage.showThisQueryObject = JSON.stringify(showThisQueryObject);
73     } else {
74         Cookies.set('showThisQuery', 1);
75         Cookies.set('showThisQueryObject', JSON.stringify(showThisQueryObject));
76     }
79 /**
80  * Set query to codemirror if show this query is
81  * checked and query for the db and table pair exists
82  */
83 Sql.setShowThisQuery = function () {
84     var db = $('input[name="db"]').val();
85     var table = $('input[name="table"]').val();
86     if (isStorageSupported('localStorage')) {
87         if (window.localStorage.showThisQueryObject !== undefined) {
88             var storedDb = JSON.parse(window.localStorage.showThisQueryObject).db;
89             var storedTable = JSON.parse(window.localStorage.showThisQueryObject).table;
90             var storedQuery = JSON.parse(window.localStorage.showThisQueryObject).query;
91         }
92         if (window.localStorage.showThisQuery !== undefined
93             && window.localStorage.showThisQuery === '1') {
94             $('input[name="show_query"]').prop('checked', true);
95             if (db === storedDb && table === storedTable) {
96                 if (codeMirrorEditor) {
97                     codeMirrorEditor.setValue(storedQuery);
98                 } else if (document.sqlform) {
99                     document.sqlform.sql_query.value = storedQuery;
100                 }
101             }
102         } else {
103             $('input[name="show_query"]').prop('checked', false);
104         }
105     }
109  * Saves SQL query with sort in local storage or cookie
111  * @param string SQL query
112  * @return void
113  */
114 Sql.autoSaveWithSort = function (query) {
115     if (query) {
116         if (isStorageSupported('localStorage')) {
117             window.localStorage.autoSavedSqlSort = query;
118         } else {
119             Cookies.set('autoSavedSqlSort', query);
120         }
121     }
125  * Clear saved SQL query with sort in local storage or cookie
127  * @return void
128  */
129 Sql.clearAutoSavedSort = function () {
130     if (isStorageSupported('localStorage')) {
131         window.localStorage.removeItem('auto_saved_sql_sort');
132     } else {
133         Cookies.set('auto_saved_sql_sort', '');
134     }
138  * Get the field name for the current field.  Required to construct the query
139  * for grid editing
141  * @param $tableResults enclosing results table
142  * @param $thisField    jQuery object that points to the current field's tr
143  */
144 Sql.getFieldName = function ($tableResults, $thisField) {
145     var thisFieldIndex = $thisField.index();
146     // ltr or rtl direction does not impact how the DOM was generated
147     // check if the action column in the left exist
148     var leftActionExist = !$tableResults.find('th').first().hasClass('draggable');
149     // number of column span for checkbox and Actions
150     var leftActionSkip = leftActionExist ? $tableResults.find('th').first().attr('colspan') - 1 : 0;
152     // If this column was sorted, the text of the a element contains something
153     // like <small>1</small> that is useful to indicate the order in case
154     // of a sort on multiple columns; however, we dont want this as part
155     // of the column name so we strip it ( .clone() to .end() )
156     var fieldName = $tableResults
157         .find('thead')
158         .find('th')
159         .eq(thisFieldIndex - leftActionSkip)
160         .find('a')
161         .clone()    // clone the element
162         .children() // select all the children
163         .remove()   // remove all of them
164         .end()      // go back to the selected element
165         .text();    // grab the text
166     // happens when just one row (headings contain no a)
167     if (fieldName === '') {
168         var $heading = $tableResults.find('thead').find('th').eq(thisFieldIndex - leftActionSkip).children('span');
169         // may contain column comment enclosed in a span - detach it temporarily to read the column name
170         var $tempColComment = $heading.children().detach();
171         fieldName = $heading.text();
172         // re-attach the column comment
173         $heading.append($tempColComment);
174     }
176     fieldName = $.trim(fieldName);
178     return fieldName;
182  * Unbind all event handlers before tearing down a page
183  */
184 AJAX.registerTeardown('sql.js', function () {
185     $(document).off('click', 'a.delete_row.ajax');
186     $(document).off('submit', '.bookmarkQueryForm');
187     $('input#bkm_label').off('input');
188     $(document).off('makegrid', '.sqlqueryresults');
189     $(document).off('stickycolumns', '.sqlqueryresults');
190     $('#togglequerybox').off('click');
191     $(document).off('click', '#button_submit_query');
192     $(document).off('change', '#id_bookmark');
193     $('input[name=\'bookmark_variable\']').off('keypress');
194     $(document).off('submit', '#sqlqueryform.ajax');
195     $(document).off('click', 'input[name=navig].ajax');
196     $(document).off('submit', 'form[name=\'displayOptionsForm\'].ajax');
197     $(document).off('mouseenter', 'th.column_heading.pointer');
198     $(document).off('mouseleave', 'th.column_heading.pointer');
199     $(document).off('click', 'th.column_heading.marker');
200     $(document).off('scroll', window);
201     $(document).off('keyup', '.filter_rows');
202     $(document).off('click', '#printView');
203     if (codeMirrorEditor) {
204         codeMirrorEditor.off('change');
205     } else {
206         $('#sqlquery').off('input propertychange');
207     }
208     $('body').off('click', '.navigation .showAllRows');
209     $('body').off('click', 'a.browse_foreign');
210     $('body').off('click', '#simulate_dml');
211     $('body').off('keyup', '#sqlqueryform');
212     $('body').off('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]');
213     $(document).off('submit', '#maxRowsForm');
217  * @description <p>Ajax scripts for sql and browse pages</p>
219  * Actions ajaxified here:
220  * <ul>
221  * <li>Retrieve results of an SQL query</li>
222  * <li>Paginate the results table</li>
223  * <li>Sort the results table</li>
224  * <li>Change table according to display options</li>
225  * <li>Grid editing of data</li>
226  * <li>Saving a bookmark</li>
227  * </ul>
229  * @name        document.ready
230  * @memberOf    jQuery
231  */
232 AJAX.registerOnload('sql.js', function () {
233     if (codeMirrorEditor || document.sqlform) {
234         Sql.setShowThisQuery();
235     }
236     $(function () {
237         if (codeMirrorEditor) {
238             codeMirrorEditor.on('change', function () {
239                 Sql.autoSave(codeMirrorEditor.getValue());
240             });
241         } else {
242             $('#sqlquery').on('input propertychange', function () {
243                 Sql.autoSave($('#sqlquery').val());
244             });
245             var useLocalStorageValue = isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql_sort !== 'undefined';
246             // Save sql query with sort
247             if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
248                 $('select[name="sql_query"]').on('change', function () {
249                     Sql.autoSaveWithSort($(this).val());
250                 });
251                 $('.sortlink').on('click', function () {
252                     Sql.clearAutoSavedSort();
253                 });
254             } else {
255                 Sql.clearAutoSavedSort();
256             }
257             // If sql query with sort for current table is stored, change sort by key select value
258             var sortStoredQuery = useLocalStorageValue ? window.localStorage.auto_saved_sql_sort : Cookies.get('auto_saved_sql_sort');
259             if (typeof sortStoredQuery !== 'undefined' && sortStoredQuery !== $('select[name="sql_query"]').val() && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0) {
260                 $('select[name="sql_query"]').val(sortStoredQuery).trigger('change');
261             }
262         }
263     });
265     // Delete row from SQL results
266     $(document).on('click', 'a.delete_row.ajax', function (e) {
267         e.preventDefault();
268         var question =  Functions.sprintf(Messages.strDoYouReally, Functions.escapeHtml($(this).closest('td').find('div').text()));
269         var $link = $(this);
270         $link.confirm(question, $link.attr('href'), function (url) {
271             Functions.ajaxShowMessage();
272             var argsep = CommonParams.get('arg_separator');
273             var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
274             var postData = $link.getPostData();
275             if (postData) {
276                 params += argsep + postData;
277             }
278             $.post(url, params, function (data) {
279                 if (data.success) {
280                     Functions.ajaxShowMessage(data.message);
281                     $link.closest('tr').remove();
282                 } else {
283                     Functions.ajaxShowMessage(data.error, false);
284                 }
285             });
286         });
287     });
289     // Ajaxification for 'Bookmark this SQL query'
290     $(document).on('submit', '.bookmarkQueryForm', function (e) {
291         e.preventDefault();
292         Functions.ajaxShowMessage();
293         var argsep = CommonParams.get('arg_separator');
294         $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
295             if (data.success) {
296                 Functions.ajaxShowMessage(data.message);
297             } else {
298                 Functions.ajaxShowMessage(data.error, false);
299             }
300         });
301     });
303     /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
304     $('input#bkm_label').on('input', function () {
305         $('input#id_bkm_all_users, input#id_bkm_replace')
306             .parent()
307             .toggle($(this).val().length > 0);
308     }).trigger('input');
310     /**
311      * Attach Event Handler for 'Copy to clipbpard
312      */
313     $(document).on('click', '#copyToClipBoard', function (event) {
314         event.preventDefault();
316         var textArea = document.createElement('textarea');
318         //
319         // *** This styling is an extra step which is likely not required. ***
320         //
321         // Why is it here? To ensure:
322         // 1. the element is able to have focus and selection.
323         // 2. if element was to flash render it has minimal visual impact.
324         // 3. less flakyness with selection and copying which **might** occur if
325         //    the textarea element is not visible.
326         //
327         // The likelihood is the element won't even render, not even a flash,
328         // so some of these are just precautions. However in IE the element
329         // is visible whilst the popup box asking the user for permission for
330         // the web page to copy to the clipboard.
331         //
333         // Place in top-left corner of screen regardless of scroll position.
334         textArea.style.position = 'fixed';
335         textArea.style.top = 0;
336         textArea.style.left = 0;
338         // Ensure it has a small width and height. Setting to 1px / 1em
339         // doesn't work as this gives a negative w/h on some browsers.
340         textArea.style.width = '2em';
341         textArea.style.height = '2em';
343         // We don't need padding, reducing the size if it does flash render.
344         textArea.style.padding = 0;
346         // Clean up any borders.
347         textArea.style.border = 'none';
348         textArea.style.outline = 'none';
349         textArea.style.boxShadow = 'none';
351         // Avoid flash of white box if rendered for any reason.
352         textArea.style.background = 'transparent';
354         textArea.value = '';
356         $('#server-breadcrumb a').each(function () {
357             textArea.value += $(this).text().split(':')[1].trim() + '/';
358         });
359         textArea.value += '\t\t' + window.location.href;
360         textArea.value += '\n';
361         $('.alert-success').each(function () {
362             textArea.value += $(this).text() + '\n\n';
363         });
365         $('.sql pre').each(function () {
366             textArea.value += $(this).text() + '\n\n';
367         });
369         $('.table_results .column_heading a').each(function () {
370             // Don't copy ordering number text within <small> tag
371             textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
372         });
374         textArea.value += '\n';
375         $('.table_results tbody tr').each(function () {
376             $(this).find('.data span').each(function () {
377                 textArea.value += $(this).text() + '\t';
378             });
379             textArea.value += '\n';
380         });
382         document.body.appendChild(textArea);
384         textArea.select();
386         try {
387             document.execCommand('copy');
388         } catch (err) {
389             alert('Sorry! Unable to copy');
390         }
392         document.body.removeChild(textArea);
393     }); // end of Copy to Clipboard action
395     /**
396      * Attach Event Handler for 'Print' link
397      */
398     $(document).on('click', '#printView', function (event) {
399         event.preventDefault();
401         // Take to preview mode
402         Functions.printPreview();
403     }); // end of 'Print' action
405     /**
406      * Attach the {@link makegrid} function to a custom event, which will be
407      * triggered manually everytime the table of results is reloaded
408      * @memberOf    jQuery
409      */
410     $(document).on('makegrid', '.sqlqueryresults', function () {
411         $('.table_results').each(function () {
412             makeGrid(this);
413         });
414     });
416     /*
417      * Attach a custom event for sticky column headings which will be
418      * triggered manually everytime the table of results is reloaded
419      * @memberOf    jQuery
420      */
421     $(document).on('stickycolumns', '.sqlqueryresults', function () {
422         $('.sticky_columns').remove();
423         $('.table_results').each(function () {
424             var $tableResults = $(this);
425             // add sticky columns div
426             var $stickColumns = Sql.initStickyColumns($tableResults);
427             Sql.rearrangeStickyColumns($stickColumns, $tableResults);
428             // adjust sticky columns on scroll
429             $(document).on('scroll', window, function () {
430                 Sql.handleStickyColumns($stickColumns, $tableResults);
431             });
432         });
433     });
435     /**
436      * Append the "Show/Hide query box" message to the query input form
437      *
438      * @memberOf jQuery
439      * @name    appendToggleSpan
440      */
441     // do not add this link more than once
442     if (! $('#sqlqueryform').find('button').is('#togglequerybox')) {
443         $('<button class="btn btn-secondary" id="togglequerybox"></button>')
444             .html(Messages.strHideQueryBox)
445             .appendTo('#sqlqueryform')
446         // initially hidden because at this point, nothing else
447         // appears under the link
448             .hide();
450         // Attach the toggling of the query box visibility to a click
451         $('#togglequerybox').on('click', function () {
452             var $link = $(this);
453             $link.siblings().slideToggle('fast');
454             if ($link.text() === Messages.strHideQueryBox) {
455                 $link.text(Messages.strShowQueryBox);
456                 // cheap trick to add a spacer between the menu tabs
457                 // and "Show query box"; feel free to improve!
458                 $('#togglequerybox_spacer').remove();
459                 $link.before('<br id="togglequerybox_spacer">');
460             } else {
461                 $link.text(Messages.strHideQueryBox);
462             }
463             // avoid default click action
464             return false;
465         });
466     }
469     /**
470      * Event handler for sqlqueryform.ajax button_submit_query
471      *
472      * @memberOf    jQuery
473      */
474     $(document).on('click', '#button_submit_query', function () {
475         $('.alert-success,.alert-danger').hide();
476         // hide already existing error or success message
477         var $form = $(this).closest('form');
478         // the Go button related to query submission was clicked,
479         // instead of the one related to Bookmarks, so empty the
480         // id_bookmark selector to avoid misinterpretation in
481         // /import about what needs to be done
482         $form.find('select[name=id_bookmark]').val('');
483         // let normal event propagation happen
484         if (isStorageSupported('localStorage')) {
485             window.localStorage.removeItem('autoSavedSql');
486         } else {
487             Cookies.set('autoSavedSql', '');
488         }
489         var isShowQuery =  $('input[name="show_query"]').is(':checked');
490         if (isShowQuery) {
491             window.localStorage.showThisQuery = '1';
492             var db = $('input[name="db"]').val();
493             var table = $('input[name="table"]').val();
494             var query;
495             if (codeMirrorEditor) {
496                 query = codeMirrorEditor.getValue();
497             } else {
498                 query = $('#sqlquery').val();
499             }
500             Sql.showThisQuery(db, table, query);
501         } else {
502             window.localStorage.showThisQuery = '0';
503         }
504     });
506     /**
507      * Event handler to show appropiate number of variable boxes
508      * based on the bookmarked query
509      */
510     $(document).on('change', '#id_bookmark', function () {
511         var varCount = $(this).find('option:selected').data('varcount');
512         if (typeof varCount === 'undefined') {
513             varCount = 0;
514         }
516         var $varDiv = $('#bookmarkVariables');
517         $varDiv.empty();
518         for (var i = 1; i <= varCount; i++) {
519             $varDiv.append($('<div class="form-group">'));
520             $varDiv.append($('<label for="bookmarkVariable' + i + '">' + Functions.sprintf(Messages.strBookmarkVariable, i) + '</label>'));
521             $varDiv.append($('<input class="form-control" type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmarkVariable' + i + '">'));
522             $varDiv.append($('</div>'));
523         }
525         if (varCount === 0) {
526             $varDiv.parent().hide();
527         } else {
528             $varDiv.parent().show();
529         }
530     });
532     /**
533      * Event handler for hitting enter on sqlqueryform bookmark_variable
534      * (the Variable textfield in Bookmarked SQL query section)
535      *
536      * @memberOf    jQuery
537      */
538     $('input[name=bookmark_variable]').on('keypress', function (event) {
539         // force the 'Enter Key' to implicitly click the #button_submit_bookmark
540         var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
541         if (keycode === 13) { // keycode for enter key
542             // When you press enter in the sqlqueryform, which
543             // has 2 submit buttons, the default is to run the
544             // #button_submit_query, because of the tabindex
545             // attribute.
546             // This submits #button_submit_bookmark instead,
547             // because when you are in the Bookmarked SQL query
548             // section and hit enter, you expect it to do the
549             // same action as the Go button in that section.
550             $('#button_submit_bookmark').trigger('click');
551             return false;
552         } else  {
553             return true;
554         }
555     });
557     /**
558      * Ajax Event handler for 'SQL Query Submit'
559      *
560      * @see         Functions.ajaxShowMessage()
561      * @memberOf    jQuery
562      * @name        sqlqueryform_submit
563      */
564     $(document).on('submit', '#sqlqueryform.ajax', function (event) {
565         event.preventDefault();
567         var $form = $(this);
568         if (codeMirrorEditor) {
569             $form[0].elements.sql_query.value = codeMirrorEditor.getValue();
570         }
571         if (! Functions.checkSqlQuery($form[0])) {
572             return false;
573         }
575         // remove any div containing a previous error message
576         $('.alert-danger').remove();
578         var $msgbox = Functions.ajaxShowMessage();
579         var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
581         Functions.prepareForAjaxRequest($form);
583         var argsep = CommonParams.get('arg_separator');
584         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
585             if (typeof data !== 'undefined' && data.success === true) {
586                 // success happens if the query returns rows or not
588                 // show a message that stays on screen
589                 if (typeof data.action_bookmark !== 'undefined') {
590                     // view only
591                     if ('1' === data.action_bookmark) {
592                         $('#sqlquery').text(data.sql_query);
593                         // send to codemirror if possible
594                         Functions.setQuery(data.sql_query);
595                     }
596                     // delete
597                     if ('2' === data.action_bookmark) {
598                         $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
599                         // if there are no bookmarked queries now (only the empty option),
600                         // remove the bookmark section
601                         if ($('#id_bookmark option').length === 1) {
602                             $('#fieldsetBookmarkOptions').hide();
603                             $('#fieldsetBookmarkOptionsFooter').hide();
604                         }
605                     }
606                 }
607                 $sqlqueryresultsouter
608                     .show()
609                     .html(data.message);
610                 Functions.highlightSql($sqlqueryresultsouter);
612                 if (data.menu) {
613                     if (history && history.pushState) {
614                         history.replaceState({
615                             menu : data.menu
616                         },
617                         null
618                         );
619                         AJAX.handleMenu.replace(data.menu);
620                     } else {
621                         MicroHistory.menus.replace(data.menu);
622                         MicroHistory.menus.add(data.menuHash, data.menu);
623                     }
624                 } else if (data.menuHash) {
625                     if (! (history && history.pushState)) {
626                         MicroHistory.menus.replace(MicroHistory.menus.get(data.menuHash));
627                     }
628                 }
630                 if (data.params) {
631                     CommonParams.setAll(data.params);
632                 }
634                 if (typeof data.ajax_reload !== 'undefined') {
635                     if (data.ajax_reload.reload) {
636                         if (data.ajax_reload.table_name) {
637                             CommonParams.set('table', data.ajax_reload.table_name);
638                             CommonActions.refreshMain();
639                         } else {
640                             Navigation.reload();
641                         }
642                     }
643                 } else if (typeof data.reload !== 'undefined') {
644                     // this happens if a USE or DROP command was typed
645                     CommonActions.setDb(data.db);
646                     var url;
647                     if (data.db) {
648                         if (data.table) {
649                             url = 'index.php?route=/table/sql';
650                         } else {
651                             url = 'index.php?route=/database/sql';
652                         }
653                     } else {
654                         url = 'index.php?route=/server/sql';
655                     }
656                     CommonActions.refreshMain(url, function () {
657                         $('#sqlqueryresultsouter')
658                             .show()
659                             .html(data.message);
660                         Functions.highlightSql($('#sqlqueryresultsouter'));
661                     });
662                 }
664                 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
665                 $('#togglequerybox').show();
666                 Functions.initSlider();
668                 if (typeof data.action_bookmark === 'undefined') {
669                     if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
670                         if ($('#togglequerybox').siblings(':visible').length > 0) {
671                             $('#togglequerybox').trigger('click');
672                         }
673                     }
674                 }
675             } else if (typeof data !== 'undefined' && data.success === false) {
676                 // show an error message that stays on screen
677                 $sqlqueryresultsouter
678                     .show()
679                     .html(data.error);
680                 $('html, body').animate({ scrollTop: $(document).height() }, 200);
681             }
682             Functions.ajaxRemoveMessage($msgbox);
683         }); // end $.post()
684     }); // end SQL Query submit
686     /**
687      * Ajax Event handler for the display options
688      * @memberOf    jQuery
689      * @name        displayOptionsForm_submit
690      */
691     $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
692         event.preventDefault();
694         var $form = $(this);
696         var $msgbox = Functions.ajaxShowMessage();
697         var argsep = CommonParams.get('arg_separator');
698         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
699             Functions.ajaxRemoveMessage($msgbox);
700             var $sqlqueryresults = $form.parents('.sqlqueryresults');
701             $sqlqueryresults
702                 .html(data.message)
703                 .trigger('makegrid')
704                 .trigger('stickycolumns');
705             Functions.initSlider();
706             Functions.highlightSql($sqlqueryresults);
707         }); // end $.post()
708     }); // end displayOptionsForm handler
710     // Filter row handling. --STARTS--
711     $(document).on('keyup', '.filter_rows', function () {
712         var uniqueId = $(this).data('for');
713         var $targetTable = $('.table_results[data-uniqueId=\'' + uniqueId + '\']');
714         var $headerCells = $targetTable.find('th[data-column]');
715         var targetColumns = [];
716         // To handle colspan=4, in case of edit,copy etc options.
717         var dummyTh = ($('.edit_row_anchor').length !== 0 ?
718             '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
719             : '');
720         // Selecting columns that will be considered for filtering and searching.
721         $headerCells.each(function () {
722             targetColumns.push($.trim($(this).text()));
723         });
725         var phrase = $(this).val();
726         // Set same value to both Filter rows fields.
727         $('.filter_rows[data-for=\'' + uniqueId + '\']').not(this).val(phrase);
728         // Handle colspan.
729         $targetTable.find('thead > tr').prepend(dummyTh);
730         $.uiTableFilter($targetTable, phrase, targetColumns);
731         $targetTable.find('th.dummy_th').remove();
732     });
733     // Filter row handling. --ENDS--
735     // Prompt to confirm on Show All
736     $('body').on('click', '.navigation .showAllRows', function (e) {
737         e.preventDefault();
738         var $form = $(this).parents('form');
740         if (! $(this).is(':checked')) { // already showing all rows
741             Sql.submitShowAllForm();
742         } else {
743             $form.confirm(Messages.strShowAllRowsWarning, $form.attr('action'), function () {
744                 Sql.submitShowAllForm();
745             });
746         }
748         Sql.submitShowAllForm = function () {
749             var argsep = CommonParams.get('arg_separator');
750             var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
751             Functions.ajaxShowMessage();
752             AJAX.source = $form;
753             $.post($form.attr('action'), submitData, AJAX.responseHandler);
754         };
755     });
757     $('body').on('keyup', '#sqlqueryform', function () {
758         Functions.handleSimulateQueryButton();
759     });
761     /**
762      * Ajax event handler for 'Simulate DML'.
763      */
764     $('body').on('click', '#simulate_dml', function () {
765         var $form = $('#sqlqueryform');
766         var query = '';
767         var delimiter = $('#id_sql_delimiter').val();
768         var dbName = $form.find('input[name="db"]').val();
770         if (codeMirrorEditor) {
771             query = codeMirrorEditor.getValue();
772         } else {
773             query = $('#sqlquery').val();
774         }
776         if (query.length === 0) {
777             alert(Messages.strFormEmpty);
778             $('#sqlquery').trigger('focus');
779             return false;
780         }
782         var $msgbox = Functions.ajaxShowMessage();
783         $.ajax({
784             type: 'POST',
785             url: $form.attr('action'),
786             data: {
787                 'server': CommonParams.get('server'),
788                 'db': dbName,
789                 'ajax_request': '1',
790                 'simulate_dml': '1',
791                 'sql_query': query,
792                 'sql_delimiter': delimiter
793             },
794             success: function (response) {
795                 Functions.ajaxRemoveMessage($msgbox);
796                 if (response.success) {
797                     var dialogContent = '<div class="preview_sql">';
798                     if (response.sql_data) {
799                         var len = response.sql_data.length;
800                         for (var i = 0; i < len; i++) {
801                             dialogContent += '<strong>' + Messages.strSQLQuery +
802                                 '</strong>' + response.sql_data[i].sql_query +
803                                 Messages.strMatchedRows +
804                                 ' <a href="' + response.sql_data[i].matched_rows_url +
805                                 '">' + response.sql_data[i].matched_rows + '</a><br>';
806                             if (i < len - 1) {
807                                 dialogContent += '<hr>';
808                             }
809                         }
810                     } else {
811                         dialogContent += response.message;
812                     }
813                     dialogContent += '</div>';
814                     var $dialogContent = $(dialogContent);
815                     var buttonOptions = {};
816                     buttonOptions[Messages.strClose] = function () {
817                         $(this).dialog('close');
818                     };
819                     $('<div></div>').append($dialogContent).dialog({
820                         minWidth: 540,
821                         maxHeight: 400,
822                         modal: true,
823                         buttons: buttonOptions,
824                         title: Messages.strSimulateDML,
825                         open: function () {
826                             Functions.highlightSql($(this));
827                         },
828                         close: function () {
829                             $(this).remove();
830                         }
831                     });
832                 } else {
833                     Functions.ajaxShowMessage(response.error);
834                 }
835             },
836             error: function () {
837                 Functions.ajaxShowMessage(Messages.strErrorProcessingRequest);
838             }
839         });
840     });
842     /**
843      * Handles multi submits of results browsing page such as edit, delete and export
844      */
845     $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
846         e.preventDefault();
847         var $button = $(this);
848         var action = $button.val();
849         var $form = $button.closest('form');
850         var argsep = CommonParams.get('arg_separator');
851         var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep;
852         Functions.ajaxShowMessage();
853         AJAX.source = $form;
855         var url;
856         if (action === 'edit') {
857             submitData = submitData + argsep + 'default_action=update';
858             url = 'index.php?route=/table/change/rows';
859         } else if (action === 'copy') {
860             submitData = submitData + argsep + 'default_action=insert';
861             url = 'index.php?route=/table/change/rows';
862         } else if (action === 'export') {
863             url = 'index.php?route=/table/export/rows';
864         } else if (action === 'delete') {
865             url = 'index.php?route=/table/delete/confirm';
866         } else {
867             return;
868         }
870         $.post(url, submitData, AJAX.responseHandler);
871     });
873     $(document).on('submit', '#maxRowsForm', function () {
874         var unlimNumRows = $(this).find('input[name="unlim_num_rows"]').val();
876         var maxRowsCheck = Functions.checkFormElementInRange(
877             this,
878             'session_max_rows',
879             Messages.strNotValidRowNumber,
880             1
881         );
882         var posCheck = Functions.checkFormElementInRange(
883             this,
884             'pos',
885             Messages.strNotValidRowNumber,
886             0,
887             unlimNumRows > 0 ? unlimNumRows - 1 : null
888         );
890         return maxRowsCheck && posCheck;
891     });
892 }); // end $()
895  * Starting from some th, change the class of all td under it.
896  * If isAddClass is specified, it will be used to determine whether to add or remove the class.
897  */
898 Sql.changeClassForColumn = function ($thisTh, newClass, isAddClass) {
899     // index 0 is the th containing the big T
900     var thIndex = $thisTh.index();
901     var hasBigT = $thisTh.closest('tr').children().first().hasClass('column_action');
902     // .eq() is zero-based
903     if (hasBigT) {
904         thIndex--;
905     }
906     var $table = $thisTh.parents('.table_results');
907     if (! $table.length) {
908         $table = $thisTh.parents('table').siblings('.table_results');
909     }
910     var $tds = $table.find('tbody tr').find('td.data').eq(thIndex);
911     if (isAddClass === undefined) {
912         $tds.toggleClass(newClass);
913     } else {
914         $tds.toggleClass(newClass, isAddClass);
915     }
919  * Handles browse foreign values modal dialog
921  * @param object $this_a reference to the browse foreign value link
922  */
923 Sql.browseForeignDialog = function ($thisA) {
924     var formId = '#browse_foreign_form';
925     var showAllId = '#foreign_showAll';
926     var tableId = '#browse_foreign_table';
927     var filterId = '#input_foreign_filter';
928     var $dialog = null;
929     var argSep = CommonParams.get('arg_separator');
930     var params = $thisA.getPostData();
931     params += argSep + 'ajax_request=true';
932     $.post($thisA.attr('href'), params, function (data) {
933         // Creates browse foreign value dialog
934         $dialog = $('<div>').append(data.message).dialog({
935             title: Messages.strBrowseForeignValues,
936             width: Math.min($(window).width() - 100, 700),
937             maxHeight: $(window).height() - 100,
938             dialogClass: 'browse_foreign_modal',
939             close: function () {
940                 // remove event handlers attached to elements related to dialog
941                 $(tableId).off('click', 'td a.foreign_value');
942                 $(formId).off('click', showAllId);
943                 $(formId).off('submit');
944                 // remove dialog itself
945                 $(this).remove();
946             },
947             modal: true
948         });
949     }).done(function () {
950         var showAll = false;
951         $(tableId).on('click', 'td a.foreign_value', function (e) {
952             e.preventDefault();
953             var $input = $thisA.prev('input[type=text]');
954             // Check if input exists or get CEdit edit_box
955             if ($input.length === 0) {
956                 $input = $thisA.closest('.edit_area').prev('.edit_box');
957             }
958             // Set selected value as input value
959             $input.val($(this).data('key'));
960             $dialog.dialog('close');
961         });
962         $(formId).on('click', showAllId, function () {
963             showAll = true;
964         });
965         $(formId).on('submit', function (e) {
966             e.preventDefault();
967             // if filter value is not equal to old value
968             // then reset page number to 1
969             if ($(filterId).val() !== $(filterId).data('old')) {
970                 $(formId).find('select[name=pos]').val('0');
971             }
972             var postParams = $(this).serializeArray();
973             // if showAll button was clicked to submit form then
974             // add showAll button parameter to form
975             if (showAll) {
976                 postParams.push({
977                     name: $(showAllId).attr('name'),
978                     value: $(showAllId).val()
979                 });
980             }
981             // updates values in dialog
982             $.post($(this).attr('action') + '&ajax_request=1', postParams, function (data) {
983                 var $obj = $('<div>').html(data.message);
984                 $(formId).html($obj.find(formId).html());
985                 $(tableId).html($obj.find(tableId).html());
986             });
987             showAll = false;
988         });
989     });
992 Sql.checkSavedQuery = function () {
993     if (isStorageSupported('localStorage') && window.localStorage.autoSavedSql !== undefined) {
994         Functions.ajaxShowMessage(Messages.strPreviousSaveQuery);
995     }
998 AJAX.registerOnload('sql.js', function () {
999     $('body').on('click', 'a.browse_foreign', function (e) {
1000         e.preventDefault();
1001         Sql.browseForeignDialog($(this));
1002     });
1004     /**
1005      * vertical column highlighting in horizontal mode when hovering over the column header
1006      */
1007     $(document).on('mouseenter', 'th.column_heading.pointer', function () {
1008         Sql.changeClassForColumn($(this), 'hover', true);
1009     });
1010     $(document).on('mouseleave', 'th.column_heading.pointer', function () {
1011         Sql.changeClassForColumn($(this), 'hover', false);
1012     });
1014     /**
1015      * vertical column marking in horizontal mode when clicking the column header
1016      */
1017     $(document).on('click', 'th.column_heading.marker', function () {
1018         Sql.changeClassForColumn($(this), 'marked');
1019     });
1021     /**
1022      * create resizable table
1023      */
1024     $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
1026     /**
1027      * Check if there is any saved query
1028      */
1029     if (codeMirrorEditor || document.sqlform) {
1030         Sql.checkSavedQuery();
1031     }
1035  * Profiling Chart
1036  */
1037 Sql.makeProfilingChart = function () {
1038     if ($('#profilingchart').length === 0 ||
1039         $('#profilingchart').html().length !== 0 ||
1040         !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
1041     ) {
1042         return;
1043     }
1045     var data = [];
1046     $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
1047         data.push([key, parseFloat(value)]);
1048     });
1050     // Remove chart and data divs contents
1051     $('#profilingchart').html('').show();
1052     $('#profilingChartData').html('');
1054     Functions.createProfilingChart('profilingchart', data);
1058  * initialize profiling data tables
1059  */
1060 Sql.initProfilingTables = function () {
1061     if (!$.tablesorter) {
1062         return;
1063     }
1064     // Added to allow two direction sorting
1065     $('#profiletable')
1066         .find('thead th')
1067         .off('click mousedown');
1069     $('#profiletable').tablesorter({
1070         widgets: ['zebra'],
1071         sortList: [[0, 0]],
1072         textExtraction: function (node) {
1073             if (node.children.length > 0) {
1074                 return node.children[0].innerHTML;
1075             } else {
1076                 return node.innerHTML;
1077             }
1078         }
1079     });
1080     // Added to allow two direction sorting
1081     $('#profilesummarytable')
1082         .find('thead th')
1083         .off('click mousedown');
1085     $('#profilesummarytable').tablesorter({
1086         widgets: ['zebra'],
1087         sortList: [[1, 1]],
1088         textExtraction: function (node) {
1089             if (node.children.length > 0) {
1090                 return node.children[0].innerHTML;
1091             } else {
1092                 return node.innerHTML;
1093             }
1094         }
1095     });
1099  * Set position, left, top, width of sticky_columns div
1100  */
1101 Sql.setStickyColumnsPosition = function ($stickyColumns, $tableResults, position, top, left, marginLeft) {
1102     $stickyColumns
1103         .css('position', position)
1104         .css('top', top)
1105         .css('left', left ? left : 'auto')
1106         .css('margin-left', marginLeft ? marginLeft : '0px')
1107         .css('width', $tableResults.width());
1111  * Initialize sticky columns
1112  */
1113 Sql.initStickyColumns = function ($tableResults) {
1114     return $('<table class="sticky_columns"></table>')
1115         .insertBefore($tableResults)
1116         .css('position', 'fixed')
1117         .css('z-index', '98')
1118         .css('width', $tableResults.width())
1119         .css('margin-left', $('#page_content').css('margin-left'))
1120         .css('top', $('#floating_menubar').height())
1121         .css('display', 'none');
1125  * Arrange/Rearrange columns in sticky header
1126  */
1127 Sql.rearrangeStickyColumns = function ($stickyColumns, $tableResults) {
1128     var $originalHeader = $tableResults.find('thead');
1129     var $originalColumns = $originalHeader.find('tr').first().children();
1130     var $clonedHeader = $originalHeader.clone();
1131     var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
1132     var isSafari = navigator.userAgent.indexOf('Safari') > -1;
1133     // clone width per cell
1134     $clonedHeader.find('tr').first().children().each(function (i) {
1135         var width = $originalColumns.eq(i).width();
1136         if (! isFirefox && ! isSafari) {
1137             width += 1;
1138         }
1139         $(this).width(width);
1140         if (isSafari) {
1141             $(this).css('min-width', width).css('max-width', width);
1142         }
1143     });
1144     $stickyColumns.empty().append($clonedHeader);
1148  * Adjust sticky columns on horizontal/vertical scroll for all tables
1149  */
1150 Sql.handleAllStickyColumns = function () {
1151     $('.sticky_columns').each(function () {
1152         Sql.handleStickyColumns($(this), $(this).next('.table_results'));
1153     });
1157  * Adjust sticky columns on horizontal/vertical scroll
1158  */
1159 Sql.handleStickyColumns = function ($stickyColumns, $tableResults) {
1160     var currentScrollX = $(window).scrollLeft();
1161     var windowOffset = $(window).scrollTop();
1162     var tableStartOffset = $tableResults.offset().top;
1163     var tableEndOffset = tableStartOffset + $tableResults.height();
1164     if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
1165         // for horizontal scrolling
1166         if (prevScrollX !== currentScrollX) {
1167             prevScrollX = currentScrollX;
1168             Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'absolute', $('#floating_menubar').height() + windowOffset - tableStartOffset);
1169         // for vertical scrolling
1170         } else {
1171             Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'fixed', $('#floating_menubar').height(), $('#pma_navigation').width() - currentScrollX, $('#page_content').css('margin-left'));
1172         }
1173         $stickyColumns.show();
1174     } else {
1175         $stickyColumns.hide();
1176     }
1179 AJAX.registerOnload('sql.js', function () {
1180     Sql.makeProfilingChart();
1181     Sql.initProfilingTables();