Translated using Weblate (Slovenian)
[phpmyadmin.git] / js / sql.js
blob923303c624f82684ca73d314cdc70700de8b5477
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"]');
216  * @description <p>Ajax scripts for sql and browse pages</p>
218  * Actions ajaxified here:
219  * <ul>
220  * <li>Retrieve results of an SQL query</li>
221  * <li>Paginate the results table</li>
222  * <li>Sort the results table</li>
223  * <li>Change table according to display options</li>
224  * <li>Grid editing of data</li>
225  * <li>Saving a bookmark</li>
226  * </ul>
228  * @name        document.ready
229  * @memberOf    jQuery
230  */
231 AJAX.registerOnload('sql.js', function () {
232     if (codeMirrorEditor || document.sqlform) {
233         Sql.setShowThisQuery();
234     }
235     $(function () {
236         if (codeMirrorEditor) {
237             codeMirrorEditor.on('change', function () {
238                 Sql.autoSave(codeMirrorEditor.getValue());
239             });
240         } else {
241             $('#sqlquery').on('input propertychange', function () {
242                 Sql.autoSave($('#sqlquery').val());
243             });
244             var useLocalStorageValue = isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql_sort !== 'undefined';
245             // Save sql query with sort
246             if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
247                 $('select[name="sql_query"]').on('change', function () {
248                     Sql.autoSaveWithSort($(this).val());
249                 });
250                 $('.sortlink').on('click', function () {
251                     Sql.clearAutoSavedSort();
252                 });
253             } else {
254                 Sql.clearAutoSavedSort();
255             }
256             // If sql query with sort for current table is stored, change sort by key select value
257             var sortStoredQuery = useLocalStorageValue ? window.localStorage.auto_saved_sql_sort : Cookies.get('auto_saved_sql_sort');
258             if (typeof sortStoredQuery !== 'undefined' && sortStoredQuery !== $('select[name="sql_query"]').val() && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0) {
259                 $('select[name="sql_query"]').val(sortStoredQuery).trigger('change');
260             }
261         }
262     });
264     // Delete row from SQL results
265     $(document).on('click', 'a.delete_row.ajax', function (e) {
266         e.preventDefault();
267         var question =  Functions.sprintf(Messages.strDoYouReally, Functions.escapeHtml($(this).closest('td').find('div').text()));
268         var $link = $(this);
269         $link.confirm(question, $link.attr('href'), function (url) {
270             Functions.ajaxShowMessage();
271             var argsep = CommonParams.get('arg_separator');
272             var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
273             var postData = $link.getPostData();
274             if (postData) {
275                 params += argsep + postData;
276             }
277             $.post(url, params, function (data) {
278                 if (data.success) {
279                     Functions.ajaxShowMessage(data.message);
280                     $link.closest('tr').remove();
281                 } else {
282                     Functions.ajaxShowMessage(data.error, false);
283                 }
284             });
285         });
286     });
288     // Ajaxification for 'Bookmark this SQL query'
289     $(document).on('submit', '.bookmarkQueryForm', function (e) {
290         e.preventDefault();
291         Functions.ajaxShowMessage();
292         var argsep = CommonParams.get('arg_separator');
293         $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
294             if (data.success) {
295                 Functions.ajaxShowMessage(data.message);
296             } else {
297                 Functions.ajaxShowMessage(data.error, false);
298             }
299         });
300     });
302     /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
303     $('input#bkm_label').on('input', function () {
304         $('input#id_bkm_all_users, input#id_bkm_replace')
305             .parent()
306             .toggle($(this).val().length > 0);
307     }).trigger('input');
309     /**
310      * Attach Event Handler for 'Copy to clipbpard
311      */
312     $(document).on('click', '#copyToClipBoard', function (event) {
313         event.preventDefault();
315         var textArea = document.createElement('textarea');
317         //
318         // *** This styling is an extra step which is likely not required. ***
319         //
320         // Why is it here? To ensure:
321         // 1. the element is able to have focus and selection.
322         // 2. if element was to flash render it has minimal visual impact.
323         // 3. less flakyness with selection and copying which **might** occur if
324         //    the textarea element is not visible.
325         //
326         // The likelihood is the element won't even render, not even a flash,
327         // so some of these are just precautions. However in IE the element
328         // is visible whilst the popup box asking the user for permission for
329         // the web page to copy to the clipboard.
330         //
332         // Place in top-left corner of screen regardless of scroll position.
333         textArea.style.position = 'fixed';
334         textArea.style.top = 0;
335         textArea.style.left = 0;
337         // Ensure it has a small width and height. Setting to 1px / 1em
338         // doesn't work as this gives a negative w/h on some browsers.
339         textArea.style.width = '2em';
340         textArea.style.height = '2em';
342         // We don't need padding, reducing the size if it does flash render.
343         textArea.style.padding = 0;
345         // Clean up any borders.
346         textArea.style.border = 'none';
347         textArea.style.outline = 'none';
348         textArea.style.boxShadow = 'none';
350         // Avoid flash of white box if rendered for any reason.
351         textArea.style.background = 'transparent';
353         textArea.value = '';
355         $('#server-breadcrumb a').each(function () {
356             textArea.value += $(this).text().split(':')[1].trim() + '/';
357         });
358         textArea.value += '\t\t' + window.location.href;
359         textArea.value += '\n';
360         $('.alert-success').each(function () {
361             textArea.value += $(this).text() + '\n\n';
362         });
364         $('.sql pre').each(function () {
365             textArea.value += $(this).text() + '\n\n';
366         });
368         $('.table_results .column_heading a').each(function () {
369             // Don't copy ordering number text within <small> tag
370             textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
371         });
373         textArea.value += '\n';
374         $('.table_results tbody tr').each(function () {
375             $(this).find('.data span').each(function () {
376                 textArea.value += $(this).text() + '\t';
377             });
378             textArea.value += '\n';
379         });
381         document.body.appendChild(textArea);
383         textArea.select();
385         try {
386             document.execCommand('copy');
387         } catch (err) {
388             alert('Sorry! Unable to copy');
389         }
391         document.body.removeChild(textArea);
392     }); // end of Copy to Clipboard action
394     /**
395      * Attach Event Handler for 'Print' link
396      */
397     $(document).on('click', '#printView', function (event) {
398         event.preventDefault();
400         // Take to preview mode
401         Functions.printPreview();
402     }); // end of 'Print' action
404     /**
405      * Attach the {@link makegrid} function to a custom event, which will be
406      * triggered manually everytime the table of results is reloaded
407      * @memberOf    jQuery
408      */
409     $(document).on('makegrid', '.sqlqueryresults', function () {
410         $('.table_results').each(function () {
411             makeGrid(this);
412         });
413     });
415     /*
416      * Attach a custom event for sticky column headings which will be
417      * triggered manually everytime the table of results is reloaded
418      * @memberOf    jQuery
419      */
420     $(document).on('stickycolumns', '.sqlqueryresults', function () {
421         $('.sticky_columns').remove();
422         $('.table_results').each(function () {
423             var $tableResults = $(this);
424             // add sticky columns div
425             var $stickColumns = Sql.initStickyColumns($tableResults);
426             Sql.rearrangeStickyColumns($stickColumns, $tableResults);
427             // adjust sticky columns on scroll
428             $(document).on('scroll', window, function () {
429                 Sql.handleStickyColumns($stickColumns, $tableResults);
430             });
431         });
432     });
434     /**
435      * Append the "Show/Hide query box" message to the query input form
436      *
437      * @memberOf jQuery
438      * @name    appendToggleSpan
439      */
440     // do not add this link more than once
441     if (! $('#sqlqueryform').find('button').is('#togglequerybox')) {
442         $('<button class="btn btn-secondary" id="togglequerybox"></button>')
443             .html(Messages.strHideQueryBox)
444             .appendTo('#sqlqueryform')
445         // initially hidden because at this point, nothing else
446         // appears under the link
447             .hide();
449         // Attach the toggling of the query box visibility to a click
450         $('#togglequerybox').on('click', function () {
451             var $link = $(this);
452             $link.siblings().slideToggle('fast');
453             if ($link.text() === Messages.strHideQueryBox) {
454                 $link.text(Messages.strShowQueryBox);
455                 // cheap trick to add a spacer between the menu tabs
456                 // and "Show query box"; feel free to improve!
457                 $('#togglequerybox_spacer').remove();
458                 $link.before('<br id="togglequerybox_spacer">');
459             } else {
460                 $link.text(Messages.strHideQueryBox);
461             }
462             // avoid default click action
463             return false;
464         });
465     }
468     /**
469      * Event handler for sqlqueryform.ajax button_submit_query
470      *
471      * @memberOf    jQuery
472      */
473     $(document).on('click', '#button_submit_query', function () {
474         $('.alert-success,.alert-danger').hide();
475         // hide already existing error or success message
476         var $form = $(this).closest('form');
477         // the Go button related to query submission was clicked,
478         // instead of the one related to Bookmarks, so empty the
479         // id_bookmark selector to avoid misinterpretation in
480         // /import about what needs to be done
481         $form.find('select[name=id_bookmark]').val('');
482         // let normal event propagation happen
483         if (isStorageSupported('localStorage')) {
484             window.localStorage.removeItem('autoSavedSql');
485         } else {
486             Cookies.set('autoSavedSql', '');
487         }
488         var isShowQuery =  $('input[name="show_query"]').is(':checked');
489         if (isShowQuery) {
490             window.localStorage.showThisQuery = '1';
491             var db = $('input[name="db"]').val();
492             var table = $('input[name="table"]').val();
493             var query;
494             if (codeMirrorEditor) {
495                 query = codeMirrorEditor.getValue();
496             } else {
497                 query = $('#sqlquery').val();
498             }
499             Sql.showThisQuery(db, table, query);
500         } else {
501             window.localStorage.showThisQuery = '0';
502         }
503     });
505     /**
506      * Event handler to show appropiate number of variable boxes
507      * based on the bookmarked query
508      */
509     $(document).on('change', '#id_bookmark', function () {
510         var varCount = $(this).find('option:selected').data('varcount');
511         if (typeof varCount === 'undefined') {
512             varCount = 0;
513         }
515         var $varDiv = $('#bookmarkVariables');
516         $varDiv.empty();
517         for (var i = 1; i <= varCount; i++) {
518             $varDiv.append($('<div class="form-group">'));
519             $varDiv.append($('<label for="bookmarkVariable' + i + '">' + Functions.sprintf(Messages.strBookmarkVariable, i) + '</label>'));
520             $varDiv.append($('<input class="form-control" type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmarkVariable' + i + '">'));
521             $varDiv.append($('</div>'));
522         }
524         if (varCount === 0) {
525             $varDiv.parent().hide();
526         } else {
527             $varDiv.parent().show();
528         }
529     });
531     /**
532      * Event handler for hitting enter on sqlqueryform bookmark_variable
533      * (the Variable textfield in Bookmarked SQL query section)
534      *
535      * @memberOf    jQuery
536      */
537     $('input[name=bookmark_variable]').on('keypress', function (event) {
538         // force the 'Enter Key' to implicitly click the #button_submit_bookmark
539         var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
540         if (keycode === 13) { // keycode for enter key
541             // When you press enter in the sqlqueryform, which
542             // has 2 submit buttons, the default is to run the
543             // #button_submit_query, because of the tabindex
544             // attribute.
545             // This submits #button_submit_bookmark instead,
546             // because when you are in the Bookmarked SQL query
547             // section and hit enter, you expect it to do the
548             // same action as the Go button in that section.
549             $('#button_submit_bookmark').trigger('click');
550             return false;
551         } else  {
552             return true;
553         }
554     });
556     /**
557      * Ajax Event handler for 'SQL Query Submit'
558      *
559      * @see         Functions.ajaxShowMessage()
560      * @memberOf    jQuery
561      * @name        sqlqueryform_submit
562      */
563     $(document).on('submit', '#sqlqueryform.ajax', function (event) {
564         event.preventDefault();
566         var $form = $(this);
567         if (codeMirrorEditor) {
568             $form[0].elements.sql_query.value = codeMirrorEditor.getValue();
569         }
570         if (! Functions.checkSqlQuery($form[0])) {
571             return false;
572         }
574         // remove any div containing a previous error message
575         $('.alert-danger').remove();
577         var $msgbox = Functions.ajaxShowMessage();
578         var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
580         Functions.prepareForAjaxRequest($form);
582         var argsep = CommonParams.get('arg_separator');
583         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
584             if (typeof data !== 'undefined' && data.success === true) {
585                 // success happens if the query returns rows or not
587                 // show a message that stays on screen
588                 if (typeof data.action_bookmark !== 'undefined') {
589                     // view only
590                     if ('1' === data.action_bookmark) {
591                         $('#sqlquery').text(data.sql_query);
592                         // send to codemirror if possible
593                         Functions.setQuery(data.sql_query);
594                     }
595                     // delete
596                     if ('2' === data.action_bookmark) {
597                         $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
598                         // if there are no bookmarked queries now (only the empty option),
599                         // remove the bookmark section
600                         if ($('#id_bookmark option').length === 1) {
601                             $('#fieldsetBookmarkOptions').hide();
602                             $('#fieldsetBookmarkOptionsFooter').hide();
603                         }
604                     }
605                 }
606                 $sqlqueryresultsouter
607                     .show()
608                     .html(data.message);
609                 Functions.highlightSql($sqlqueryresultsouter);
611                 if (data.menu) {
612                     if (history && history.pushState) {
613                         history.replaceState({
614                             menu : data.menu
615                         },
616                         null
617                         );
618                         AJAX.handleMenu.replace(data.menu);
619                     } else {
620                         MicroHistory.menus.replace(data.menu);
621                         MicroHistory.menus.add(data.menuHash, data.menu);
622                     }
623                 } else if (data.menuHash) {
624                     if (! (history && history.pushState)) {
625                         MicroHistory.menus.replace(MicroHistory.menus.get(data.menuHash));
626                     }
627                 }
629                 if (data.params) {
630                     CommonParams.setAll(data.params);
631                 }
633                 if (typeof data.ajax_reload !== 'undefined') {
634                     if (data.ajax_reload.reload) {
635                         if (data.ajax_reload.table_name) {
636                             CommonParams.set('table', data.ajax_reload.table_name);
637                             CommonActions.refreshMain();
638                         } else {
639                             Navigation.reload();
640                         }
641                     }
642                 } else if (typeof data.reload !== 'undefined') {
643                     // this happens if a USE or DROP command was typed
644                     CommonActions.setDb(data.db);
645                     var url;
646                     if (data.db) {
647                         if (data.table) {
648                             url = 'index.php?route=/table/sql';
649                         } else {
650                             url = 'index.php?route=/database/sql';
651                         }
652                     } else {
653                         url = 'index.php?route=/server/sql';
654                     }
655                     CommonActions.refreshMain(url, function () {
656                         $('#sqlqueryresultsouter')
657                             .show()
658                             .html(data.message);
659                         Functions.highlightSql($('#sqlqueryresultsouter'));
660                     });
661                 }
663                 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
664                 $('#togglequerybox').show();
665                 Functions.initSlider();
667                 if (typeof data.action_bookmark === 'undefined') {
668                     if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
669                         if ($('#togglequerybox').siblings(':visible').length > 0) {
670                             $('#togglequerybox').trigger('click');
671                         }
672                     }
673                 }
674             } else if (typeof data !== 'undefined' && data.success === false) {
675                 // show an error message that stays on screen
676                 $sqlqueryresultsouter
677                     .show()
678                     .html(data.error);
679                 $('html, body').animate({ scrollTop: $(document).height() }, 200);
680             }
681             Functions.ajaxRemoveMessage($msgbox);
682         }); // end $.post()
683     }); // end SQL Query submit
685     /**
686      * Ajax Event handler for the display options
687      * @memberOf    jQuery
688      * @name        displayOptionsForm_submit
689      */
690     $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
691         event.preventDefault();
693         var $form = $(this);
695         var $msgbox = Functions.ajaxShowMessage();
696         var argsep = CommonParams.get('arg_separator');
697         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
698             Functions.ajaxRemoveMessage($msgbox);
699             var $sqlqueryresults = $form.parents('.sqlqueryresults');
700             $sqlqueryresults
701                 .html(data.message)
702                 .trigger('makegrid')
703                 .trigger('stickycolumns');
704             Functions.initSlider();
705             Functions.highlightSql($sqlqueryresults);
706         }); // end $.post()
707     }); // end displayOptionsForm handler
709     // Filter row handling. --STARTS--
710     $(document).on('keyup', '.filter_rows', function () {
711         var uniqueId = $(this).data('for');
712         var $targetTable = $('.table_results[data-uniqueId=\'' + uniqueId + '\']');
713         var $headerCells = $targetTable.find('th[data-column]');
714         var targetColumns = [];
715         // To handle colspan=4, in case of edit,copy etc options.
716         var dummyTh = ($('.edit_row_anchor').length !== 0 ?
717             '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
718             : '');
719         // Selecting columns that will be considered for filtering and searching.
720         $headerCells.each(function () {
721             targetColumns.push($.trim($(this).text()));
722         });
724         var phrase = $(this).val();
725         // Set same value to both Filter rows fields.
726         $('.filter_rows[data-for=\'' + uniqueId + '\']').not(this).val(phrase);
727         // Handle colspan.
728         $targetTable.find('thead > tr').prepend(dummyTh);
729         $.uiTableFilter($targetTable, phrase, targetColumns);
730         $targetTable.find('th.dummy_th').remove();
731     });
732     // Filter row handling. --ENDS--
734     // Prompt to confirm on Show All
735     $('body').on('click', '.navigation .showAllRows', function (e) {
736         e.preventDefault();
737         var $form = $(this).parents('form');
739         if (! $(this).is(':checked')) { // already showing all rows
740             Sql.submitShowAllForm();
741         } else {
742             $form.confirm(Messages.strShowAllRowsWarning, $form.attr('action'), function () {
743                 Sql.submitShowAllForm();
744             });
745         }
747         Sql.submitShowAllForm = function () {
748             var argsep = CommonParams.get('arg_separator');
749             var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
750             Functions.ajaxShowMessage();
751             AJAX.source = $form;
752             $.post($form.attr('action'), submitData, AJAX.responseHandler);
753         };
754     });
756     $('body').on('keyup', '#sqlqueryform', function () {
757         Functions.handleSimulateQueryButton();
758     });
760     /**
761      * Ajax event handler for 'Simulate DML'.
762      */
763     $('body').on('click', '#simulate_dml', function () {
764         var $form = $('#sqlqueryform');
765         var query = '';
766         var delimiter = $('#id_sql_delimiter').val();
767         var dbName = $form.find('input[name="db"]').val();
769         if (codeMirrorEditor) {
770             query = codeMirrorEditor.getValue();
771         } else {
772             query = $('#sqlquery').val();
773         }
775         if (query.length === 0) {
776             alert(Messages.strFormEmpty);
777             $('#sqlquery').trigger('focus');
778             return false;
779         }
781         var $msgbox = Functions.ajaxShowMessage();
782         $.ajax({
783             type: 'POST',
784             url: $form.attr('action'),
785             data: {
786                 'server': CommonParams.get('server'),
787                 'db': dbName,
788                 'ajax_request': '1',
789                 'simulate_dml': '1',
790                 'sql_query': query,
791                 'sql_delimiter': delimiter
792             },
793             success: function (response) {
794                 Functions.ajaxRemoveMessage($msgbox);
795                 if (response.success) {
796                     var dialogContent = '<div class="preview_sql">';
797                     if (response.sql_data) {
798                         var len = response.sql_data.length;
799                         for (var i = 0; i < len; i++) {
800                             dialogContent += '<strong>' + Messages.strSQLQuery +
801                                 '</strong>' + response.sql_data[i].sql_query +
802                                 Messages.strMatchedRows +
803                                 ' <a href="' + response.sql_data[i].matched_rows_url +
804                                 '">' + response.sql_data[i].matched_rows + '</a><br>';
805                             if (i < len - 1) {
806                                 dialogContent += '<hr>';
807                             }
808                         }
809                     } else {
810                         dialogContent += response.message;
811                     }
812                     dialogContent += '</div>';
813                     var $dialogContent = $(dialogContent);
814                     var buttonOptions = {};
815                     buttonOptions[Messages.strClose] = function () {
816                         $(this).dialog('close');
817                     };
818                     $('<div></div>').append($dialogContent).dialog({
819                         minWidth: 540,
820                         maxHeight: 400,
821                         modal: true,
822                         buttons: buttonOptions,
823                         title: Messages.strSimulateDML,
824                         open: function () {
825                             Functions.highlightSql($(this));
826                         },
827                         close: function () {
828                             $(this).remove();
829                         }
830                     });
831                 } else {
832                     Functions.ajaxShowMessage(response.error);
833                 }
834             },
835             error: function () {
836                 Functions.ajaxShowMessage(Messages.strErrorProcessingRequest);
837             }
838         });
839     });
841     /**
842      * Handles multi submits of results browsing page such as edit, delete and export
843      */
844     $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
845         e.preventDefault();
846         var $button = $(this);
847         var $form = $button.closest('form');
848         var argsep = CommonParams.get('arg_separator');
849         var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val();
850         Functions.ajaxShowMessage();
851         AJAX.source = $form;
852         $.post($form.attr('action'), submitData, AJAX.responseHandler);
853     });
854 }); // end $()
857  * Starting from some th, change the class of all td under it.
858  * If isAddClass is specified, it will be used to determine whether to add or remove the class.
859  */
860 Sql.changeClassForColumn = function ($thisTh, newClass, isAddClass) {
861     // index 0 is the th containing the big T
862     var thIndex = $thisTh.index();
863     var hasBigT = $thisTh.closest('tr').children().first().hasClass('column_action');
864     // .eq() is zero-based
865     if (hasBigT) {
866         thIndex--;
867     }
868     var $table = $thisTh.parents('.table_results');
869     if (! $table.length) {
870         $table = $thisTh.parents('table').siblings('.table_results');
871     }
872     var $tds = $table.find('tbody tr').find('td.data').eq(thIndex);
873     if (isAddClass === undefined) {
874         $tds.toggleClass(newClass);
875     } else {
876         $tds.toggleClass(newClass, isAddClass);
877     }
881  * Handles browse foreign values modal dialog
883  * @param object $this_a reference to the browse foreign value link
884  */
885 Sql.browseForeignDialog = function ($thisA) {
886     var formId = '#browse_foreign_form';
887     var showAllId = '#foreign_showAll';
888     var tableId = '#browse_foreign_table';
889     var filterId = '#input_foreign_filter';
890     var $dialog = null;
891     var argSep = CommonParams.get('arg_separator');
892     var params = $thisA.getPostData();
893     params += argSep + 'ajax_request=true';
894     $.post($thisA.attr('href'), params, function (data) {
895         // Creates browse foreign value dialog
896         $dialog = $('<div>').append(data.message).dialog({
897             title: Messages.strBrowseForeignValues,
898             width: Math.min($(window).width() - 100, 700),
899             maxHeight: $(window).height() - 100,
900             dialogClass: 'browse_foreign_modal',
901             close: function () {
902                 // remove event handlers attached to elements related to dialog
903                 $(tableId).off('click', 'td a.foreign_value');
904                 $(formId).off('click', showAllId);
905                 $(formId).off('submit');
906                 // remove dialog itself
907                 $(this).remove();
908             },
909             modal: true
910         });
911     }).done(function () {
912         var showAll = false;
913         $(tableId).on('click', 'td a.foreign_value', function (e) {
914             e.preventDefault();
915             var $input = $thisA.prev('input[type=text]');
916             // Check if input exists or get CEdit edit_box
917             if ($input.length === 0) {
918                 $input = $thisA.closest('.edit_area').prev('.edit_box');
919             }
920             // Set selected value as input value
921             $input.val($(this).data('key'));
922             $dialog.dialog('close');
923         });
924         $(formId).on('click', showAllId, function () {
925             showAll = true;
926         });
927         $(formId).on('submit', function (e) {
928             e.preventDefault();
929             // if filter value is not equal to old value
930             // then reset page number to 1
931             if ($(filterId).val() !== $(filterId).data('old')) {
932                 $(formId).find('select[name=pos]').val('0');
933             }
934             var postParams = $(this).serializeArray();
935             // if showAll button was clicked to submit form then
936             // add showAll button parameter to form
937             if (showAll) {
938                 postParams.push({
939                     name: $(showAllId).attr('name'),
940                     value: $(showAllId).val()
941                 });
942             }
943             // updates values in dialog
944             $.post($(this).attr('action') + '&ajax_request=1', postParams, function (data) {
945                 var $obj = $('<div>').html(data.message);
946                 $(formId).html($obj.find(formId).html());
947                 $(tableId).html($obj.find(tableId).html());
948             });
949             showAll = false;
950         });
951     });
954 Sql.checkSavedQuery = function () {
955     if (isStorageSupported('localStorage') && window.localStorage.autoSavedSql !== undefined) {
956         Functions.ajaxShowMessage(Messages.strPreviousSaveQuery);
957     }
960 AJAX.registerOnload('sql.js', function () {
961     $('body').on('click', 'a.browse_foreign', function (e) {
962         e.preventDefault();
963         Sql.browseForeignDialog($(this));
964     });
966     /**
967      * vertical column highlighting in horizontal mode when hovering over the column header
968      */
969     $(document).on('mouseenter', 'th.column_heading.pointer', function () {
970         Sql.changeClassForColumn($(this), 'hover', true);
971     });
972     $(document).on('mouseleave', 'th.column_heading.pointer', function () {
973         Sql.changeClassForColumn($(this), 'hover', false);
974     });
976     /**
977      * vertical column marking in horizontal mode when clicking the column header
978      */
979     $(document).on('click', 'th.column_heading.marker', function () {
980         Sql.changeClassForColumn($(this), 'marked');
981     });
983     /**
984      * create resizable table
985      */
986     $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
988     /**
989      * Check if there is any saved query
990      */
991     if (codeMirrorEditor || document.sqlform) {
992         Sql.checkSavedQuery();
993     }
997  * Profiling Chart
998  */
999 Sql.makeProfilingChart = function () {
1000     if ($('#profilingchart').length === 0 ||
1001         $('#profilingchart').html().length !== 0 ||
1002         !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
1003     ) {
1004         return;
1005     }
1007     var data = [];
1008     $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
1009         data.push([key, parseFloat(value)]);
1010     });
1012     // Remove chart and data divs contents
1013     $('#profilingchart').html('').show();
1014     $('#profilingChartData').html('');
1016     Functions.createProfilingChart('profilingchart', data);
1020  * initialize profiling data tables
1021  */
1022 Sql.initProfilingTables = function () {
1023     if (!$.tablesorter) {
1024         return;
1025     }
1026     // Added to allow two direction sorting
1027     $('#profiletable')
1028         .find('thead th')
1029         .off('click mousedown');
1031     $('#profiletable').tablesorter({
1032         widgets: ['zebra'],
1033         sortList: [[0, 0]],
1034         textExtraction: function (node) {
1035             if (node.children.length > 0) {
1036                 return node.children[0].innerHTML;
1037             } else {
1038                 return node.innerHTML;
1039             }
1040         }
1041     });
1042     // Added to allow two direction sorting
1043     $('#profilesummarytable')
1044         .find('thead th')
1045         .off('click mousedown');
1047     $('#profilesummarytable').tablesorter({
1048         widgets: ['zebra'],
1049         sortList: [[1, 1]],
1050         textExtraction: function (node) {
1051             if (node.children.length > 0) {
1052                 return node.children[0].innerHTML;
1053             } else {
1054                 return node.innerHTML;
1055             }
1056         }
1057     });
1061  * Set position, left, top, width of sticky_columns div
1062  */
1063 Sql.setStickyColumnsPosition = function ($stickyColumns, $tableResults, position, top, left, marginLeft) {
1064     $stickyColumns
1065         .css('position', position)
1066         .css('top', top)
1067         .css('left', left ? left : 'auto')
1068         .css('margin-left', marginLeft ? marginLeft : '0px')
1069         .css('width', $tableResults.width());
1073  * Initialize sticky columns
1074  */
1075 Sql.initStickyColumns = function ($tableResults) {
1076     return $('<table class="sticky_columns"></table>')
1077         .insertBefore($tableResults)
1078         .css('position', 'fixed')
1079         .css('z-index', '98')
1080         .css('width', $tableResults.width())
1081         .css('margin-left', $('#page_content').css('margin-left'))
1082         .css('top', $('#floating_menubar').height())
1083         .css('display', 'none');
1087  * Arrange/Rearrange columns in sticky header
1088  */
1089 Sql.rearrangeStickyColumns = function ($stickyColumns, $tableResults) {
1090     var $originalHeader = $tableResults.find('thead');
1091     var $originalColumns = $originalHeader.find('tr').first().children();
1092     var $clonedHeader = $originalHeader.clone();
1093     var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
1094     var isSafari = navigator.userAgent.indexOf('Safari') > -1;
1095     // clone width per cell
1096     $clonedHeader.find('tr').first().children().each(function (i) {
1097         var width = $originalColumns.eq(i).width();
1098         if (! isFirefox && ! isSafari) {
1099             width += 1;
1100         }
1101         $(this).width(width);
1102         if (isSafari) {
1103             $(this).css('min-width', width).css('max-width', width);
1104         }
1105     });
1106     $stickyColumns.empty().append($clonedHeader);
1110  * Adjust sticky columns on horizontal/vertical scroll for all tables
1111  */
1112 Sql.handleAllStickyColumns = function () {
1113     $('.sticky_columns').each(function () {
1114         Sql.handleStickyColumns($(this), $(this).next('.table_results'));
1115     });
1119  * Adjust sticky columns on horizontal/vertical scroll
1120  */
1121 Sql.handleStickyColumns = function ($stickyColumns, $tableResults) {
1122     var currentScrollX = $(window).scrollLeft();
1123     var windowOffset = $(window).scrollTop();
1124     var tableStartOffset = $tableResults.offset().top;
1125     var tableEndOffset = tableStartOffset + $tableResults.height();
1126     if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
1127         // for horizontal scrolling
1128         if (prevScrollX !== currentScrollX) {
1129             prevScrollX = currentScrollX;
1130             Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'absolute', $('#floating_menubar').height() + windowOffset - tableStartOffset);
1131         // for vertical scrolling
1132         } else {
1133             Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'fixed', $('#floating_menubar').height(), $('#pma_navigation').width() - currentScrollX, $('#page_content').css('margin-left'));
1134         }
1135         $stickyColumns.show();
1136     } else {
1137         $stickyColumns.hide();
1138     }
1141 AJAX.registerOnload('sql.js', function () {
1142     Sql.makeProfilingChart();
1143     Sql.initProfilingTables();