Improve storing columns on designer and add a translation
[phpmyadmin.git] / js / sql.js
blob3d7f8d79a6684ec57fdd56833c898eede4ee4990
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    functions used wherever an sql query form is used
4  *
5  * @requires    jQuery
6  * @requires    js/functions.js
7  *
8  */
10 var $data_a;
11 var prevScrollX = 0;
13 /**
14  * decode a string URL_encoded
15  *
16  * @param string str
17  * @return string the URL-decoded string
18  */
19 function PMA_urldecode (str) {
20     if (typeof str !== 'undefined') {
21         return decodeURIComponent(str.replace(/\+/g, '%20'));
22     }
25 /**
26  * endecode a string URL_decoded
27  *
28  * @param string str
29  * @return string the URL-encoded string
30  */
31 function PMA_urlencode (str) {
32     if (typeof str !== 'undefined') {
33         return encodeURIComponent(str).replace(/\%20/g, '+');
34     }
37 /**
38  * Saves SQL query in local storage or cookie
39  *
40  * @param string SQL query
41  * @return void
42  */
43 function PMA_autosaveSQL (query) {
44     if (query) {
45         if (isStorageSupported('localStorage')) {
46             window.localStorage.auto_saved_sql = query;
47         } else {
48             Cookies.set('auto_saved_sql', query);
49         }
50     }
53 /**
54  * Saves SQL query with sort in local storage or cookie
55  *
56  * @param string SQL query
57  * @return void
58  */
59 function PMA_autosaveSQLSort (query) {
60     if (query) {
61         if (isStorageSupported('localStorage')) {
62             window.localStorage.auto_saved_sql_sort = query;
63         } else {
64             Cookies.set('auto_saved_sql_sort', query);
65         }
66     }
69 /**
70  * Clear saved SQL query with sort in local storage or cookie
71  *
72  * @return void
73  */
74 function PMA_clearAutoSavedSQLSort () {
75     if (isStorageSupported('localStorage')) {
76         window.localStorage.removeItem('auto_saved_sql_sort');
77     } else {
78         Cookies.set('auto_saved_sql_sort', '');
79     }
82 /**
83  * Get the field name for the current field.  Required to construct the query
84  * for grid editing
85  *
86  * @param $table_results enclosing results table
87  * @param $this_field    jQuery object that points to the current field's tr
88  */
89 function getFieldName ($table_results, $this_field) {
90     var this_field_index = $this_field.index();
91     // ltr or rtl direction does not impact how the DOM was generated
92     // check if the action column in the left exist
93     var left_action_exist = !$table_results.find('th:first').hasClass('draggable');
94     // number of column span for checkbox and Actions
95     var left_action_skip = left_action_exist ? $table_results.find('th:first').attr('colspan') - 1 : 0;
97     // If this column was sorted, the text of the a element contains something
98     // like <small>1</small> that is useful to indicate the order in case
99     // of a sort on multiple columns; however, we dont want this as part
100     // of the column name so we strip it ( .clone() to .end() )
101     var field_name = $table_results
102         .find('thead')
103         .find('th:eq(' + (this_field_index - left_action_skip) + ') a')
104         .clone()    // clone the element
105         .children() // select all the children
106         .remove()   // remove all of them
107         .end()      // go back to the selected element
108         .text();    // grab the text
109     // happens when just one row (headings contain no a)
110     if (field_name === '') {
111         var $heading = $table_results.find('thead').find('th:eq(' + (this_field_index - left_action_skip) + ')').children('span');
112         // may contain column comment enclosed in a span - detach it temporarily to read the column name
113         var $tempColComment = $heading.children().detach();
114         field_name = $heading.text();
115         // re-attach the column comment
116         $heading.append($tempColComment);
117     }
119     field_name = $.trim(field_name);
121     return field_name;
125  * Unbind all event handlers before tearing down a page
126  */
127 AJAX.registerTeardown('sql.js', function () {
128     $(document).off('click', 'a.delete_row.ajax');
129     $(document).off('submit', '.bookmarkQueryForm');
130     $('input#bkm_label').off('input');
131     $(document).off('makegrid', '.sqlqueryresults');
132     $(document).off('stickycolumns', '.sqlqueryresults');
133     $('#togglequerybox').off('click');
134     $(document).off('click', '#button_submit_query');
135     $(document).off('change', '#id_bookmark');
136     $('input[name=\'bookmark_variable\']').off('keypress');
137     $(document).off('submit', '#sqlqueryform.ajax');
138     $(document).off('click', 'input[name=navig].ajax');
139     $(document).off('submit', 'form[name=\'displayOptionsForm\'].ajax');
140     $(document).off('mouseenter', 'th.column_heading.pointer');
141     $(document).off('mouseleave', 'th.column_heading.pointer');
142     $(document).off('click', 'th.column_heading.marker');
143     $(window).off('scroll');
144     $(document).off('keyup', '.filter_rows');
145     $(document).off('click', '#printView');
146     if (codemirror_editor) {
147         codemirror_editor.off('change');
148     } else {
149         $('#sqlquery').off('input propertychange');
150     }
151     $('body').off('click', '.navigation .showAllRows');
152     $('body').off('click', 'a.browse_foreign');
153     $('body').off('click', '#simulate_dml');
154     $('body').off('keyup', '#sqlqueryform');
155     $('body').off('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]');
159  * @description <p>Ajax scripts for sql and browse pages</p>
161  * Actions ajaxified here:
162  * <ul>
163  * <li>Retrieve results of an SQL query</li>
164  * <li>Paginate the results table</li>
165  * <li>Sort the results table</li>
166  * <li>Change table according to display options</li>
167  * <li>Grid editing of data</li>
168  * <li>Saving a bookmark</li>
169  * </ul>
171  * @name        document.ready
172  * @memberOf    jQuery
173  */
174 AJAX.registerOnload('sql.js', function () {
175     $(function () {
176         if (codemirror_editor) {
177             codemirror_editor.on('change', function () {
178                 PMA_autosaveSQL(codemirror_editor.getValue());
179             });
180         } else {
181             $('#sqlquery').on('input propertychange', function () {
182                 PMA_autosaveSQL($('#sqlquery').val());
183             });
184             var useLocalStorageValue = isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql_sort !== 'undefined';
185             // Save sql query with sort
186             if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
187                 $('select[name="sql_query"]').on('change', function () {
188                     PMA_autosaveSQLSort($(this).val());
189                 });
190                 $('.sortlink').on('click', function () {
191                     PMA_clearAutoSavedSQLSort();
192                 });
193             } else {
194                 PMA_clearAutoSavedSQLSort();
195             }
196             // If sql query with sort for current table is stored, change sort by key select value
197             var sortStoredQuery = useLocalStorageValue ? window.localStorage.auto_saved_sql_sort : Cookies.get('auto_saved_sql_sort');
198             if (typeof sortStoredQuery !== 'undefined' && sortStoredQuery !== $('select[name="sql_query"]').val() && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0) {
199                 $('select[name="sql_query"]').val(sortStoredQuery).change();
200             }
201         }
202     });
204     // Delete row from SQL results
205     $(document).on('click', 'a.delete_row.ajax', function (e) {
206         e.preventDefault();
207         var question =  PMA_sprintf(PMA_messages.strDoYouReally, escapeHtml($(this).closest('td').find('div').text()));
208         var $link = $(this);
209         $link.PMA_confirm(question, $link.attr('href'), function (url) {
210             $msgbox = PMA_ajaxShowMessage();
211             var argsep = PMA_commonParams.get('arg_separator');
212             var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
213             var postData = $link.getPostData();
214             if (postData) {
215                 params += argsep + postData;
216             }
217             $.post(url, params, function (data) {
218                 if (data.success) {
219                     PMA_ajaxShowMessage(data.message);
220                     $link.closest('tr').remove();
221                 } else {
222                     PMA_ajaxShowMessage(data.error, false);
223                 }
224             });
225         });
226     });
228     // Ajaxification for 'Bookmark this SQL query'
229     $(document).on('submit', '.bookmarkQueryForm', function (e) {
230         e.preventDefault();
231         PMA_ajaxShowMessage();
232         var argsep = PMA_commonParams.get('arg_separator');
233         $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
234             if (data.success) {
235                 PMA_ajaxShowMessage(data.message);
236             } else {
237                 PMA_ajaxShowMessage(data.error, false);
238             }
239         });
240     });
242     /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
243     $('input#bkm_label').on('input', function () {
244         $('input#id_bkm_all_users, input#id_bkm_replace')
245             .parent()
246             .toggle($(this).val().length > 0);
247     }).trigger('input');
249     /**
250      * Attach Event Handler for 'Copy to clipbpard
251      */
252     $(document).on('click', '#copyToClipBoard', function (event) {
253         event.preventDefault();
255         var textArea = document.createElement('textarea');
257         //
258         // *** This styling is an extra step which is likely not required. ***
259         //
260         // Why is it here? To ensure:
261         // 1. the element is able to have focus and selection.
262         // 2. if element was to flash render it has minimal visual impact.
263         // 3. less flakyness with selection and copying which **might** occur if
264         //    the textarea element is not visible.
265         //
266         // The likelihood is the element won't even render, not even a flash,
267         // so some of these are just precautions. However in IE the element
268         // is visible whilst the popup box asking the user for permission for
269         // the web page to copy to the clipboard.
270         //
272         // Place in top-left corner of screen regardless of scroll position.
273         textArea.style.position = 'fixed';
274         textArea.style.top = 0;
275         textArea.style.left = 0;
277         // Ensure it has a small width and height. Setting to 1px / 1em
278         // doesn't work as this gives a negative w/h on some browsers.
279         textArea.style.width = '2em';
280         textArea.style.height = '2em';
282         // We don't need padding, reducing the size if it does flash render.
283         textArea.style.padding = 0;
285         // Clean up any borders.
286         textArea.style.border = 'none';
287         textArea.style.outline = 'none';
288         textArea.style.boxShadow = 'none';
290         // Avoid flash of white box if rendered for any reason.
291         textArea.style.background = 'transparent';
293         textArea.value = '';
295         $('#serverinfo a').each(function () {
296             textArea.value += $(this).text().split(':')[1].trim() + '/';
297         });
298         textArea.value += '\t\t' + window.location.href;
299         textArea.value += '\n';
300         $('.success').each(function () {
301             textArea.value += $(this).text() + '\n\n';
302         });
304         $('.sql pre').each(function () {
305             textArea.value += $(this).text() + '\n\n';
306         });
308         $('.table_results .column_heading a').each(function () {
309             // Don't copy ordering number text within <small> tag
310             textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
311         });
313         textArea.value += '\n';
314         $('.table_results tbody tr').each(function () {
315             $(this).find('.data span').each(function () {
316                 textArea.value += $(this).text() + '\t';
317             });
318             textArea.value += '\n';
319         });
321         document.body.appendChild(textArea);
323         textArea.select();
325         try {
326             document.execCommand('copy');
327         } catch (err) {
328             alert('Sorry! Unable to copy');
329         }
331         document.body.removeChild(textArea);
332     }); // end of Copy to Clipboard action
334     /**
335      * Attach Event Handler for 'Print' link
336      */
337     $(document).on('click', '#printView', function (event) {
338         event.preventDefault();
340         // Take to preview mode
341         printPreview();
342     }); // end of 'Print' action
344     /**
345      * Attach the {@link makegrid} function to a custom event, which will be
346      * triggered manually everytime the table of results is reloaded
347      * @memberOf    jQuery
348      */
349     $(document).on('makegrid', '.sqlqueryresults', function () {
350         $('.table_results').each(function () {
351             PMA_makegrid(this);
352         });
353     });
355     /*
356      * Attach a custom event for sticky column headings which will be
357      * triggered manually everytime the table of results is reloaded
358      * @memberOf    jQuery
359      */
360     $(document).on('stickycolumns', '.sqlqueryresults', function () {
361         $('.sticky_columns').remove();
362         $('.table_results').each(function () {
363             var $table_results = $(this);
364             // add sticky columns div
365             var $stick_columns = initStickyColumns($table_results);
366             rearrangeStickyColumns($stick_columns, $table_results);
367             // adjust sticky columns on scroll
368             $(window).on('scroll', function () {
369                 handleStickyColumns($stick_columns, $table_results);
370             });
371         });
372     });
374     /**
375      * Append the "Show/Hide query box" message to the query input form
376      *
377      * @memberOf jQuery
378      * @name    appendToggleSpan
379      */
380     // do not add this link more than once
381     if (! $('#sqlqueryform').find('a').is('#togglequerybox')) {
382         $('<a id="togglequerybox"></a>')
383             .html(PMA_messages.strHideQueryBox)
384             .appendTo('#sqlqueryform')
385         // initially hidden because at this point, nothing else
386         // appears under the link
387             .hide();
389         // Attach the toggling of the query box visibility to a click
390         $('#togglequerybox').bind('click', function () {
391             var $link = $(this);
392             $link.siblings().slideToggle('fast');
393             if ($link.text() === PMA_messages.strHideQueryBox) {
394                 $link.text(PMA_messages.strShowQueryBox);
395                 // cheap trick to add a spacer between the menu tabs
396                 // and "Show query box"; feel free to improve!
397                 $('#togglequerybox_spacer').remove();
398                 $link.before('<br id="togglequerybox_spacer" />');
399             } else {
400                 $link.text(PMA_messages.strHideQueryBox);
401             }
402             // avoid default click action
403             return false;
404         });
405     }
408     /**
409      * Event handler for sqlqueryform.ajax button_submit_query
410      *
411      * @memberOf    jQuery
412      */
413     $(document).on('click', '#button_submit_query', function (event) {
414         $('.success,.error').hide();
415         // hide already existing error or success message
416         var $form = $(this).closest('form');
417         // the Go button related to query submission was clicked,
418         // instead of the one related to Bookmarks, so empty the
419         // id_bookmark selector to avoid misinterpretation in
420         // import.php about what needs to be done
421         $form.find('select[name=id_bookmark]').val('');
422         // let normal event propagation happen
423     });
425     /**
426      * Event handler to show appropiate number of variable boxes
427      * based on the bookmarked query
428      */
429     $(document).on('change', '#id_bookmark', function (event) {
430         var varCount = $(this).find('option:selected').data('varcount');
431         if (typeof varCount === 'undefined') {
432             varCount = 0;
433         }
435         var $varDiv = $('#bookmark_variables');
436         $varDiv.empty();
437         for (var i = 1; i <= varCount; i++) {
438             $varDiv.append($('<label for="bookmark_variable_' + i + '">' + PMA_sprintf(PMA_messages.strBookmarkVariable, i) + '</label>'));
439             $varDiv.append($('<input type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmark_variable_' + i + '"/>'));
440         }
442         if (varCount === 0) {
443             $varDiv.parent('.formelement').hide();
444         } else {
445             $varDiv.parent('.formelement').show();
446         }
447     });
449     /**
450      * Event handler for hitting enter on sqlqueryform bookmark_variable
451      * (the Variable textfield in Bookmarked SQL query section)
452      *
453      * @memberOf    jQuery
454      */
455     $('input[name=bookmark_variable]').on('keypress', function (event) {
456         // force the 'Enter Key' to implicitly click the #button_submit_bookmark
457         var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
458         if (keycode === 13) { // keycode for enter key
459             // When you press enter in the sqlqueryform, which
460             // has 2 submit buttons, the default is to run the
461             // #button_submit_query, because of the tabindex
462             // attribute.
463             // This submits #button_submit_bookmark instead,
464             // because when you are in the Bookmarked SQL query
465             // section and hit enter, you expect it to do the
466             // same action as the Go button in that section.
467             $('#button_submit_bookmark').click();
468             return false;
469         } else  {
470             return true;
471         }
472     });
474     /**
475      * Ajax Event handler for 'SQL Query Submit'
476      *
477      * @see         PMA_ajaxShowMessage()
478      * @memberOf    jQuery
479      * @name        sqlqueryform_submit
480      */
481     $(document).on('submit', '#sqlqueryform.ajax', function (event) {
482         event.preventDefault();
484         var $form = $(this);
485         if (codemirror_editor) {
486             $form[0].elements.sql_query.value = codemirror_editor.getValue();
487         }
488         if (! checkSqlQuery($form[0])) {
489             return false;
490         }
492         // remove any div containing a previous error message
493         $('div.error').remove();
495         var $msgbox = PMA_ajaxShowMessage();
496         var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
498         PMA_prepareForAjaxRequest($form);
500         var argsep = PMA_commonParams.get('arg_separator');
501         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
502             if (typeof data !== 'undefined' && data.success === true) {
503                 // success happens if the query returns rows or not
505                 // show a message that stays on screen
506                 if (typeof data.action_bookmark !== 'undefined') {
507                     // view only
508                     if ('1' === data.action_bookmark) {
509                         $('#sqlquery').text(data.sql_query);
510                         // send to codemirror if possible
511                         setQuery(data.sql_query);
512                     }
513                     // delete
514                     if ('2' === data.action_bookmark) {
515                         $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
516                         // if there are no bookmarked queries now (only the empty option),
517                         // remove the bookmark section
518                         if ($('#id_bookmark option').length === 1) {
519                             $('#fieldsetBookmarkOptions').hide();
520                             $('#fieldsetBookmarkOptionsFooter').hide();
521                         }
522                     }
523                 }
524                 $sqlqueryresultsouter
525                     .show()
526                     .html(data.message);
527                 PMA_highlightSQL($sqlqueryresultsouter);
529                 if (data._menu) {
530                     if (history && history.pushState) {
531                         history.replaceState({
532                             menu : data._menu
533                         },
534                         null
535                         );
536                         AJAX.handleMenu.replace(data._menu);
537                     } else {
538                         PMA_MicroHistory.menus.replace(data._menu);
539                         PMA_MicroHistory.menus.add(data._menuHash, data._menu);
540                     }
541                 } else if (data._menuHash) {
542                     if (! (history && history.pushState)) {
543                         PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(data._menuHash));
544                     }
545                 }
547                 if (data._params) {
548                     PMA_commonParams.setAll(data._params);
549                 }
551                 if (typeof data.ajax_reload !== 'undefined') {
552                     if (data.ajax_reload.reload) {
553                         if (data.ajax_reload.table_name) {
554                             PMA_commonParams.set('table', data.ajax_reload.table_name);
555                             PMA_commonActions.refreshMain();
556                         } else {
557                             PMA_reloadNavigation();
558                         }
559                     }
560                 } else if (typeof data.reload !== 'undefined') {
561                     // this happens if a USE or DROP command was typed
562                     PMA_commonActions.setDb(data.db);
563                     var url;
564                     if (data.db) {
565                         if (data.table) {
566                             url = 'table_sql.php';
567                         } else {
568                             url = 'db_sql.php';
569                         }
570                     } else {
571                         url = 'server_sql.php';
572                     }
573                     PMA_commonActions.refreshMain(url, function () {
574                         $('#sqlqueryresultsouter')
575                             .show()
576                             .html(data.message);
577                         PMA_highlightSQL($('#sqlqueryresultsouter'));
578                     });
579                 }
581                 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
582                 $('#togglequerybox').show();
583                 PMA_init_slider();
585                 if (typeof data.action_bookmark === 'undefined') {
586                     if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
587                         if ($('#togglequerybox').siblings(':visible').length > 0) {
588                             $('#togglequerybox').trigger('click');
589                         }
590                     }
591                 }
592             } else if (typeof data !== 'undefined' && data.success === false) {
593                 // show an error message that stays on screen
594                 $sqlqueryresultsouter
595                     .show()
596                     .html(data.error);
597             }
598             PMA_ajaxRemoveMessage($msgbox);
599         }); // end $.post()
600     }); // end SQL Query submit
602     /**
603      * Ajax Event handler for the display options
604      * @memberOf    jQuery
605      * @name        displayOptionsForm_submit
606      */
607     $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
608         event.preventDefault();
610         $form = $(this);
612         var $msgbox = PMA_ajaxShowMessage();
613         var argsep = PMA_commonParams.get('arg_separator');
614         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
615             PMA_ajaxRemoveMessage($msgbox);
616             var $sqlqueryresults = $form.parents('.sqlqueryresults');
617             $sqlqueryresults
618                 .html(data.message)
619                 .trigger('makegrid')
620                 .trigger('stickycolumns');
621             PMA_init_slider();
622             PMA_highlightSQL($sqlqueryresults);
623         }); // end $.post()
624     }); // end displayOptionsForm handler
626     // Filter row handling. --STARTS--
627     $(document).on('keyup', '.filter_rows', function () {
628         var unique_id = $(this).data('for');
629         var $target_table = $('.table_results[data-uniqueId=\'' + unique_id + '\']');
630         var $header_cells = $target_table.find('th[data-column]');
631         var target_columns = Array();
632         // To handle colspan=4, in case of edit,copy etc options.
633         var dummy_th = ($('.edit_row_anchor').length !== 0 ?
634             '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
635             : '');
636         // Selecting columns that will be considered for filtering and searching.
637         $header_cells.each(function () {
638             target_columns.push($.trim($(this).text()));
639         });
641         var phrase = $(this).val();
642         // Set same value to both Filter rows fields.
643         $('.filter_rows[data-for=\'' + unique_id + '\']').not(this).val(phrase);
644         // Handle colspan.
645         $target_table.find('thead > tr').prepend(dummy_th);
646         $.uiTableFilter($target_table, phrase, target_columns);
647         $target_table.find('th.dummy_th').remove();
648     });
649     // Filter row handling. --ENDS--
651     // Prompt to confirm on Show All
652     $('body').on('click', '.navigation .showAllRows', function (e) {
653         e.preventDefault();
654         var $form = $(this).parents('form');
656         if (! $(this).is(':checked')) { // already showing all rows
657             submitShowAllForm();
658         } else {
659             $form.PMA_confirm(PMA_messages.strShowAllRowsWarning, $form.attr('action'), function (url) {
660                 submitShowAllForm();
661             });
662         }
664         function submitShowAllForm () {
665             var argsep = PMA_commonParams.get('arg_separator');
666             var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
667             PMA_ajaxShowMessage();
668             AJAX.source = $form;
669             $.post($form.attr('action'), submitData, AJAX.responseHandler);
670         }
671     });
673     $('body').on('keyup', '#sqlqueryform', function () {
674         PMA_handleSimulateQueryButton();
675     });
677     /**
678      * Ajax event handler for 'Simulate DML'.
679      */
680     $('body').on('click', '#simulate_dml', function () {
681         var $form = $('#sqlqueryform');
682         var query = '';
683         var delimiter = $('#id_sql_delimiter').val();
684         var db_name = $form.find('input[name="db"]').val();
686         if (codemirror_editor) {
687             query = codemirror_editor.getValue();
688         } else {
689             query = $('#sqlquery').val();
690         }
692         if (query.length === 0) {
693             alert(PMA_messages.strFormEmpty);
694             $('#sqlquery').focus();
695             return false;
696         }
698         var $msgbox = PMA_ajaxShowMessage();
699         $.ajax({
700             type: 'POST',
701             url: $form.attr('action'),
702             data: {
703                 server: PMA_commonParams.get('server'),
704                 db: db_name,
705                 ajax_request: '1',
706                 simulate_dml: '1',
707                 sql_query: query,
708                 sql_delimiter: delimiter
709             },
710             success: function (response) {
711                 PMA_ajaxRemoveMessage($msgbox);
712                 if (response.success) {
713                     var dialog_content = '<div class="preview_sql">';
714                     if (response.sql_data) {
715                         var len = response.sql_data.length;
716                         for (var i = 0; i < len; i++) {
717                             dialog_content += '<strong>' + PMA_messages.strSQLQuery +
718                                 '</strong>' + response.sql_data[i].sql_query +
719                                 PMA_messages.strMatchedRows +
720                                 ' <a href="' + response.sql_data[i].matched_rows_url +
721                                 '">' + response.sql_data[i].matched_rows + '</a><br>';
722                             if (i < len - 1) {
723                                 dialog_content += '<hr>';
724                             }
725                         }
726                     } else {
727                         dialog_content += response.message;
728                     }
729                     dialog_content += '</div>';
730                     var $dialog_content = $(dialog_content);
731                     var button_options = {};
732                     button_options[PMA_messages.strClose] = function () {
733                         $(this).dialog('close');
734                     };
735                     var $response_dialog = $('<div />').append($dialog_content).dialog({
736                         minWidth: 540,
737                         maxHeight: 400,
738                         modal: true,
739                         buttons: button_options,
740                         title: PMA_messages.strSimulateDML,
741                         open: function () {
742                             PMA_highlightSQL($(this));
743                         },
744                         close: function () {
745                             $(this).remove();
746                         }
747                     });
748                 } else {
749                     PMA_ajaxShowMessage(response.error);
750                 }
751             },
752             error: function (response) {
753                 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
754             }
755         });
756     });
758     /**
759      * Handles multi submits of results browsing page such as edit, delete and export
760      */
761     $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
762         e.preventDefault();
763         var $button = $(this);
764         var $form = $button.closest('form');
765         var argsep = PMA_commonParams.get('arg_separator');
766         var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val();
767         PMA_ajaxShowMessage();
768         AJAX.source = $form;
769         $.post($form.attr('action'), submitData, AJAX.responseHandler);
770     });
771 }); // end $()
774  * Starting from some th, change the class of all td under it.
775  * If isAddClass is specified, it will be used to determine whether to add or remove the class.
776  */
777 function PMA_changeClassForColumn ($this_th, newclass, isAddClass) {
778     // index 0 is the th containing the big T
779     var th_index = $this_th.index();
780     var has_big_t = $this_th.closest('tr').children(':first').hasClass('column_action');
781     // .eq() is zero-based
782     if (has_big_t) {
783         th_index--;
784     }
785     var $table = $this_th.parents('.table_results');
786     if (! $table.length) {
787         $table = $this_th.parents('table').siblings('.table_results');
788     }
789     var $tds = $table.find('tbody tr').find('td.data:eq(' + th_index + ')');
790     if (isAddClass === undefined) {
791         $tds.toggleClass(newclass);
792     } else {
793         $tds.toggleClass(newclass, isAddClass);
794     }
798  * Handles browse foreign values modal dialog
800  * @param object $this_a reference to the browse foreign value link
801  */
802 function browseForeignDialog ($this_a) {
803     var formId = '#browse_foreign_form';
804     var showAllId = '#foreign_showAll';
805     var tableId = '#browse_foreign_table';
806     var filterId = '#input_foreign_filter';
807     var $dialog = null;
808     var argSep = PMA_commonParams.get('arg_separator');
809     var params = $this_a.getPostData();
810     params += argSep + 'ajax_request=true';
811     $.post($this_a.attr('href'), params, function (data) {
812         // Creates browse foreign value dialog
813         $dialog = $('<div>').append(data.message).dialog({
814             title: PMA_messages.strBrowseForeignValues,
815             width: Math.min($(window).width() - 100, 700),
816             maxHeight: $(window).height() - 100,
817             dialogClass: 'browse_foreign_modal',
818             close: function (ev, ui) {
819                 // remove event handlers attached to elements related to dialog
820                 $(tableId).off('click', 'td a.foreign_value');
821                 $(formId).off('click', showAllId);
822                 $(formId).off('submit');
823                 // remove dialog itself
824                 $(this).remove();
825             },
826             modal: true
827         });
828     }).done(function () {
829         var showAll = false;
830         $(tableId).on('click', 'td a.foreign_value', function (e) {
831             e.preventDefault();
832             var $input = $this_a.prev('input[type=text]');
833             // Check if input exists or get CEdit edit_box
834             if ($input.length === 0) {
835                 $input = $this_a.closest('.edit_area').prev('.edit_box');
836             }
837             // Set selected value as input value
838             $input.val($(this).data('key'));
839             $dialog.dialog('close');
840         });
841         $(formId).on('click', showAllId, function () {
842             showAll = true;
843         });
844         $(formId).on('submit', function (e) {
845             e.preventDefault();
846             // if filter value is not equal to old value
847             // then reset page number to 1
848             if ($(filterId).val() !== $(filterId).data('old')) {
849                 $(formId).find('select[name=pos]').val('0');
850             }
851             var postParams = $(this).serializeArray();
852             // if showAll button was clicked to submit form then
853             // add showAll button parameter to form
854             if (showAll) {
855                 postParams.push({
856                     name: $(showAllId).attr('name'),
857                     value: $(showAllId).val()
858                 });
859             }
860             // updates values in dialog
861             $.post($(this).attr('action') + '?ajax_request=1', postParams, function (data) {
862                 var $obj = $('<div>').html(data.message);
863                 $(formId).html($obj.find(formId).html());
864                 $(tableId).html($obj.find(tableId).html());
865             });
866             showAll = false;
867         });
868     });
871 AJAX.registerOnload('sql.js', function () {
872     $('body').on('click', 'a.browse_foreign', function (e) {
873         e.preventDefault();
874         browseForeignDialog($(this));
875     });
877     /**
878      * vertical column highlighting in horizontal mode when hovering over the column header
879      */
880     $(document).on('mouseenter', 'th.column_heading.pointer', function (e) {
881         PMA_changeClassForColumn($(this), 'hover', true);
882     });
883     $(document).on('mouseleave', 'th.column_heading.pointer', function (e) {
884         PMA_changeClassForColumn($(this), 'hover', false);
885     });
887     /**
888      * vertical column marking in horizontal mode when clicking the column header
889      */
890     $(document).on('click', 'th.column_heading.marker', function () {
891         PMA_changeClassForColumn($(this), 'marked');
892     });
894     /**
895      * create resizable table
896      */
897     $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
901  * Profiling Chart
902  */
903 function makeProfilingChart () {
904     if ($('#profilingchart').length === 0 ||
905         $('#profilingchart').html().length !== 0 ||
906         !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
907     ) {
908         return;
909     }
911     var data = [];
912     $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
913         data.push([key, parseFloat(value)]);
914     });
916     // Remove chart and data divs contents
917     $('#profilingchart').html('').show();
918     $('#profilingChartData').html('');
920     PMA_createProfilingChart('profilingchart', data);
924  * initialize profiling data tables
925  */
926 function initProfilingTables () {
927     if (!$.tablesorter) {
928         return;
929     }
931     $('#profiletable').tablesorter({
932         widgets: ['zebra'],
933         sortList: [[0, 0]],
934         textExtraction: function (node) {
935             if (node.children.length > 0) {
936                 return node.children[0].innerHTML;
937             } else {
938                 return node.innerHTML;
939             }
940         }
941     });
943     $('#profilesummarytable').tablesorter({
944         widgets: ['zebra'],
945         sortList: [[1, 1]],
946         textExtraction: function (node) {
947             if (node.children.length > 0) {
948                 return node.children[0].innerHTML;
949             } else {
950                 return node.innerHTML;
951             }
952         }
953     });
957  * Set position, left, top, width of sticky_columns div
958  */
959 function setStickyColumnsPosition ($sticky_columns, $table_results, position, top, left, margin_left) {
960     $sticky_columns
961         .css('position', position)
962         .css('top', top)
963         .css('left', left ? left : 'auto')
964         .css('margin-left', margin_left ? margin_left : '0px')
965         .css('width', $table_results.width());
969  * Initialize sticky columns
970  */
971 function initStickyColumns ($table_results) {
972     return $('<table class="sticky_columns"></table>')
973         .insertBefore($table_results)
974         .css('position', 'fixed')
975         .css('z-index', '98')
976         .css('width', $table_results.width())
977         .css('margin-left', $('#page_content').css('margin-left'))
978         .css('top', $('#floating_menubar').height())
979         .css('display', 'none');
983  * Arrange/Rearrange columns in sticky header
984  */
985 function rearrangeStickyColumns ($sticky_columns, $table_results) {
986     var $originalHeader = $table_results.find('thead');
987     var $originalColumns = $originalHeader.find('tr:first').children();
988     var $clonedHeader = $originalHeader.clone();
989     // clone width per cell
990     $clonedHeader.find('tr:first').children().width(function (i,val) {
991         var width = $originalColumns.eq(i).width();
992         var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
993         if (! is_firefox) {
994             width += 1;
995         }
996         return width;
997     });
998     $sticky_columns.empty().append($clonedHeader);
1002  * Adjust sticky columns on horizontal/vertical scroll for all tables
1003  */
1004 function handleAllStickyColumns () {
1005     $('.sticky_columns').each(function () {
1006         handleStickyColumns($(this), $(this).next('.table_results'));
1007     });
1011  * Adjust sticky columns on horizontal/vertical scroll
1012  */
1013 function handleStickyColumns ($sticky_columns, $table_results) {
1014     var currentScrollX = $(window).scrollLeft();
1015     var windowOffset = $(window).scrollTop();
1016     var tableStartOffset = $table_results.offset().top;
1017     var tableEndOffset = tableStartOffset + $table_results.height();
1018     if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
1019         // for horizontal scrolling
1020         if (prevScrollX !== currentScrollX) {
1021             prevScrollX = currentScrollX;
1022             setStickyColumnsPosition($sticky_columns, $table_results, 'absolute', $('#floating_menubar').height() + windowOffset - tableStartOffset);
1023         // for vertical scrolling
1024         } else {
1025             setStickyColumnsPosition($sticky_columns, $table_results, 'fixed', $('#floating_menubar').height(), $('#pma_navigation').width() - currentScrollX, $('#page_content').css('margin-left'));
1026         }
1027         $sticky_columns.show();
1028     } else {
1029         $sticky_columns.hide();
1030     }
1033 AJAX.registerOnload('sql.js', function () {
1034     makeProfilingChart();
1035     initProfilingTables();