Translated using Weblate (German)
[phpmyadmin.git] / js / console.js
blob57539fca4883ecee8d06eefef57b8f74cc73c548
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * Used in or for console
4  *
5  * @package phpMyAdmin-Console
6  */
8 /**
9  * Console object
10  */
11 var PMA_console = {
12     /**
13      * @var object, jQuery object, selector is '#pma_console>.content'
14      * @access private
15      */
16     $consoleContent: null,
17     /**
18      * @var object, jQuery object, selector is '#pma_console .content',
19      *  used for resizer
20      * @access private
21      */
22     $consoleAllContents: null,
23     /**
24      * @var object, jQuery object, selector is '#pma_console .toolbar'
25      * @access private
26      */
27     $consoleToolbar: null,
28     /**
29      * @var object, jQuery object, selector is '#pma_console .template'
30      * @access private
31      */
32     $consoleTemplates: null,
33     /**
34      * @var object, jQuery object, form for submit
35      * @access private
36      */
37     $requestForm: null,
38     /**
39      * @var object, contain console config
40      * @access private
41      */
42     config: null,
43     /**
44      * @var bool, if console element exist, it'll be true
45      * @access public
46      */
47     isEnabled: false,
48     /**
49      * @var bool, make sure console events bind only once
50      * @access private
51      */
52     isInitialized: false,
53     /**
54      * Used for console initialize, reinit is ok, just some variable assignment
55      *
56      * @return void
57      */
58     initialize: function() {
60         if ($('#pma_console').length === 0) {
61             return;
62         }
64         PMA_console.isEnabled = true;
66         // Cookie var checks and init
67         if (! Cookies.get('pma_console_height')) {
68             Cookies.set('pma_console_height', 92);
69         }
70         if (! Cookies.get('pma_console_mode')) {
71             Cookies.set('pma_console_mode', 'info');
72         }
74         // Vars init
75         PMA_console.$consoleToolbar = $("#pma_console").find(">.toolbar");
76         PMA_console.$consoleContent = $("#pma_console").find(">.content");
77         PMA_console.$consoleAllContents = $('#pma_console').find('.content');
78         PMA_console.$consoleTemplates = $('#pma_console').find('>.templates');
80         // Generate a from for post
81         PMA_console.$requestForm = $('<form method="post" action="import.php">' +
82             '<input name="is_js_confirmed" value="0">' +
83             '<textarea name="sql_query"></textarea>' +
84             '<input name="console_message_id" value="0">' +
85             '<input name="server" value="">' +
86             '<input name="db" value="">' +
87             '<input name="table" value="">' +
88             '<input name="token" value="">' +
89             '</form>'
90         );
91         PMA_console.$requestForm.children('[name=token]').val(PMA_commonParams.get('token'));
92         PMA_console.$requestForm.on('submit', AJAX.requestHandler);
94         // Event binds shouldn't run again
95         if (PMA_console.isInitialized === false) {
97             // Load config first
98             var tempConfig = Cookies.getJSON('pma_console_config');
99             if (tempConfig) {
100                 if (tempConfig.alwaysExpand === true) {
101                     $('#pma_console_options input[name=always_expand]').prop('checked', true);
102                 }
103                 if (tempConfig.startHistory === true) {
104                     $('#pma_console_options').find('input[name=start_history]').prop('checked', true);
105                 }
106                 if (tempConfig.currentQuery === true) {
107                     $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
108                 }
109                 if (ConsoleEnterExecutes === true) {
110                     $('#pma_console_options').find('input[name=enter_executes]').prop('checked', true);
111                 }
112                 if (tempConfig.darkTheme === true) {
113                     $('#pma_console_options').find('input[name=dark_theme]').prop('checked', true);
114                     $('#pma_console').find('>.content').addClass('console_dark_theme');
115                 }
116             } else {
117                 $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
118             }
120             PMA_console.updateConfig();
122             PMA_consoleResizer.initialize();
123             PMA_consoleInput.initialize();
124             PMA_consoleMessages.initialize();
125             PMA_consoleBookmarks.initialize();
126             PMA_consoleDebug.initialize();
128             PMA_console.$consoleToolbar.children('.console_switch').click(PMA_console.toggle);
130             $('#pma_console').find('.toolbar').children().mousedown(function(event) {
131                 event.preventDefault();
132                 event.stopImmediatePropagation();
133             });
135             $('#pma_console').find('.button.clear').click(function() {
136                 PMA_consoleMessages.clear();
137             });
139             $('#pma_console').find('.button.history').click(function() {
140                 PMA_consoleMessages.showHistory();
141             });
143             $('#pma_console').find('.button.options').click(function() {
144                 PMA_console.showCard('#pma_console_options');
145             });
147             $('#pma_console').find('.button.debug').click(function() {
148                 PMA_console.showCard('#debug_console');
149             });
151             PMA_console.$consoleContent.click(function(event) {
152                 if (event.target == this) {
153                     PMA_consoleInput.focus();
154                 }
155             });
157             $('#pma_console').find('.mid_layer').click(function() {
158                 PMA_console.hideCard($(this).parent().children('.card'));
159             });
160             $('#debug_console').find('.switch_button').click(function() {
161                 PMA_console.hideCard($(this).closest('.card'));
162             });
163             $('#pma_bookmarks').find('.switch_button').click(function() {
164                 PMA_console.hideCard($(this).closest('.card'));
165             });
166             $('#pma_console_options').find('.switch_button').click(function() {
167                 PMA_console.hideCard($(this).closest('.card'));
168             });
170             $('#pma_console_options').find('input[type=checkbox]').change(function() {
171                 PMA_console.updateConfig();
172             });
174             $('#pma_console_options').find('.button.default').click(function() {
175                 $('#pma_console_options input[name=always_expand]').prop('checked', false);
176                 $('#pma_console_options').find('input[name=start_history]').prop('checked', false);
177                 $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
178                 $('#pma_console_options').find('input[name=enter_executes]').prop('checked', false);
179                 $('#pma_console_options').find('input[name=dark_theme]').prop('checked', false);
180                 PMA_console.updateConfig();
181             });
183             $('#pma_console_options').find('input[name=enter_executes]').change(function() {
184                 PMA_consoleMessages.showInstructions(PMA_console.config.enterExecutes);
185             });
187             $(document).ajaxComplete(function (event, xhr, ajaxOptions) {
188                 if (ajaxOptions.dataType && ajaxOptions.dataType.indexOf('json') != -1) {
189                     return;
190                 }
191                 if (xhr.status !== 200) {
192                     return;
193                 }
194                 try {
195                     var data = JSON.parse(xhr.responseText);
196                     PMA_console.ajaxCallback(data);
197                 } catch (e) {
198                     console.trace();
199                     console.log("Failed to parse JSON: " + e.message);
200                 }
201             });
203             PMA_console.isInitialized = true;
204         }
206         // Change console mode from cookie
207         switch(Cookies.get('pma_console_mode')) {
208             case 'collapse':
209                 PMA_console.collapse();
210                 break;
211             /* jshint -W086 */// no break needed in default section
212             default:
213                 Cookies.set('pma_console_mode', 'info');
214             case 'info':
215             /* jshint +W086 */
216                 PMA_console.info();
217                 break;
218             case 'show':
219                 PMA_console.show(true);
220                 PMA_console.scrollBottom();
221                 break;
222         }
223     },
224     /**
225      * Execute query and show results in console
226      *
227      * @return void
228      */
229     execute: function(queryString, options) {
230         if (typeof(queryString) != 'string' || ! /[a-z]|[A-Z]/.test(queryString)) {
231             return;
232         }
233         PMA_console.$requestForm.children('textarea').val(queryString);
234         PMA_console.$requestForm.children('[name=server]').attr('value', PMA_commonParams.get('server'));
235         if (options && options.db) {
236             PMA_console.$requestForm.children('[name=db]').val(options.db);
237             if (options.table) {
238                 PMA_console.$requestForm.children('[name=table]').val(options.table);
239             } else {
240                 PMA_console.$requestForm.children('[name=table]').val('');
241             }
242         } else {
243             PMA_console.$requestForm.children('[name=db]').val(
244                 (PMA_commonParams.get('db').length > 0 ? PMA_commonParams.get('db') : ''));
245         }
246         PMA_console.$requestForm.find('[name=profiling]').remove();
247         if (options && options.profiling === true) {
248             PMA_console.$requestForm.append('<input name="profiling" value="on">');
249         }
250         if (! confirmQuery(PMA_console.$requestForm[0], PMA_console.$requestForm.children('textarea')[0].value)) {
251             return;
252         }
253         PMA_console.$requestForm.children('[name=console_message_id]')
254             .val(PMA_consoleMessages.appendQuery({sql_query: queryString}).message_id);
255         PMA_console.$requestForm.trigger('submit');
256         PMA_consoleInput.clear();
257         PMA_reloadNavigation();
258     },
259     ajaxCallback: function(data) {
260         if (data && data.console_message_id) {
261             PMA_consoleMessages.updateQuery(data.console_message_id, data.success,
262                 (data._reloadQuerywindow ? data._reloadQuerywindow : false));
263         } else if ( data && data._reloadQuerywindow) {
264             if (data._reloadQuerywindow.sql_query.length > 0) {
265                 PMA_consoleMessages.appendQuery(data._reloadQuerywindow, 'successed')
266                     .$message.addClass(PMA_console.config.currentQuery ? '' : 'hide');
267             }
268         }
269     },
270     /**
271      * Change console to collapse mode
272      *
273      * @return void
274      */
275     collapse: function() {
276         Cookies.set('pma_console_mode', 'collapse');
277         var pmaConsoleHeight = Cookies.get('pma_console_height');
279         if (pmaConsoleHeight < 32) {
280             Cookies.set('pma_console_height', 92);
281         }
282         PMA_console.$consoleToolbar.addClass('collapsed');
283         PMA_console.$consoleAllContents.height(pmaConsoleHeight);
284         PMA_console.$consoleContent.stop();
285         PMA_console.$consoleContent.animate({'margin-bottom': -1 * PMA_console.$consoleContent.outerHeight() + 'px'},
286             'fast', 'easeOutQuart', function() {
287                 PMA_console.$consoleContent.css({display:'none'});
288                 $(window).trigger('resize');
289             });
290         PMA_console.hideCard();
291     },
292     /**
293      * Show console
294      *
295      * @param bool inputFocus If true, focus the input line after show()
296      * @return void
297      */
298     show: function(inputFocus) {
299         Cookies.set('pma_console_mode', 'show');
301         var pmaConsoleHeight = Cookies.get('pma_console_height');
303         if (pmaConsoleHeight < 32) {
304             Cookies.set('pma_console_height', 32);
305             PMA_console.collapse();
306             return;
307         }
308         PMA_console.$consoleContent.css({display:'block'});
309         if (PMA_console.$consoleToolbar.hasClass('collapsed')) {
310             PMA_console.$consoleToolbar.removeClass('collapsed');
311         }
312         PMA_console.$consoleAllContents.height(pmaConsoleHeight);
313         PMA_console.$consoleContent.stop();
314         PMA_console.$consoleContent.animate({'margin-bottom': 0},
315             'fast', 'easeOutQuart', function() {
316                 $(window).trigger('resize');
317                 if (inputFocus) {
318                     PMA_consoleInput.focus();
319                 }
320             });
321     },
322     /**
323      * Change console to SQL information mode
324      * this mode shows current SQL query
325      * This mode is the default mode
326      *
327      * @return void
328      */
329     info: function() {
330         // Under construction
331         PMA_console.collapse();
332     },
333     /**
334      * Toggle console mode between collapse/show
335      * Used for toggle buttons and shortcuts
336      *
337      * @return void
338      */
339     toggle: function() {
340         switch(Cookies.get('pma_console_mode')) {
341             case 'collapse':
342             case 'info':
343                 PMA_console.show(true);
344                 break;
345             case 'show':
346                 PMA_console.collapse();
347                 break;
348             default:
349                 PMA_consoleInitialize();
350         }
351     },
352     /**
353      * Scroll console to bottom
354      *
355      * @return void
356      */
357     scrollBottom: function() {
358         PMA_console.$consoleContent.scrollTop(PMA_console.$consoleContent.prop("scrollHeight"));
359     },
360     /**
361      * Show card
362      *
363      * @param string cardSelector Selector, select string will be "#pma_console " + cardSelector
364      * this param also can be JQuery object, if you need.
365      *
366      * @return void
367      */
368     showCard: function(cardSelector) {
369         var $card = null;
370         if (typeof(cardSelector) !== 'string') {
371             if (cardSelector.length > 0) {
372                 $card = cardSelector;
373             } else {
374                 return;
375             }
376         } else {
377             $card = $("#pma_console " + cardSelector);
378         }
379         if ($card.length === 0) {
380             return;
381         }
382         $card.parent().children('.mid_layer').show().fadeTo(0, 0.15);
383         $card.addClass('show');
384         PMA_consoleInput.blur();
385         if ($card.parents('.card').length > 0) {
386             PMA_console.showCard($card.parents('.card'));
387         }
388     },
389     /**
390      * Scroll console to bottom
391      *
392      * @param object $targetCard Target card JQuery object, if it's empty, function will hide all cards
393      * @return void
394      */
395     hideCard: function($targetCard) {
396         if (! $targetCard) {
397             $('#pma_console').find('.mid_layer').fadeOut(140);
398             $('#pma_console').find('.card').removeClass('show');
399         } else if ($targetCard.length > 0) {
400             $targetCard.parent().find('.mid_layer').fadeOut(140);
401             $targetCard.find('.card').removeClass('show');
402             $targetCard.removeClass('show');
403         }
404     },
405     /**
406      * Used for update console config
407      *
408      * @return void
409      */
410     updateConfig: function() {
411         PMA_console.config = {
412             alwaysExpand: $('#pma_console_options input[name=always_expand]').prop('checked'),
413             startHistory: $('#pma_console_options').find('input[name=start_history]').prop('checked'),
414             currentQuery: $('#pma_console_options').find('input[name=current_query]').prop('checked'),
415             enterExecutes: $('#pma_console_options').find('input[name=enter_executes]').prop('checked'),
416             darkTheme: $('#pma_console_options').find('input[name=dark_theme]').prop('checked')
417         };
418         Cookies.set('pma_console_config', PMA_console.config);
419         /*Setting the dark theme of the console*/
420         if (PMA_console.config.darkTheme) {
421             $('#pma_console').find('>.content').addClass('console_dark_theme');
422         } else {
423             $('#pma_console').find('>.content').removeClass('console_dark_theme');
424         }
425     },
426     isSelect: function (queryString) {
427         var reg_exp = /^SELECT\s+/i;
428         return reg_exp.test(queryString);
429     }
433  * Resizer object
434  * Careful: this object UI logics highly related with functions under PMA_console
435  * Resizing min-height is 32, if small than it, console will collapse
436  */
437 var PMA_consoleResizer = {
438     _posY: 0,
439     _height: 0,
440     _resultHeight: 0,
441     /**
442      * Mousedown event handler for bind to resizer
443      *
444      * @return void
445      */
446     _mousedown: function(event) {
447         if (Cookies.get('pma_console_mode') !== 'show') {
448             return;
449         }
450         PMA_consoleResizer._posY = event.pageY;
451         PMA_consoleResizer._height = PMA_console.$consoleContent.height();
452         $(document).mousemove(PMA_consoleResizer._mousemove);
453         $(document).mouseup(PMA_consoleResizer._mouseup);
454         // Disable text selection while resizing
455         $(document).on('selectstart', function() { return false; });
456     },
457     /**
458      * Mousemove event handler for bind to resizer
459      *
460      * @return void
461      */
462     _mousemove: function(event) {
463         if (event.pageY < 35) {
464             event.pageY = 35
465         }
466         PMA_consoleResizer._resultHeight = PMA_consoleResizer._height + (PMA_consoleResizer._posY -event.pageY);
467         // Content min-height is 32, if adjusting height small than it we'll move it out of the page
468         if (PMA_consoleResizer._resultHeight <= 32) {
469             PMA_console.$consoleAllContents.height(32);
470             PMA_console.$consoleContent.css('margin-bottom', PMA_consoleResizer._resultHeight - 32);
471         }
472         else {
473             // Logic below makes viewable area always at bottom when adjusting height and content already at bottom
474             if (PMA_console.$consoleContent.scrollTop() + PMA_console.$consoleContent.innerHeight() + 16
475                 >= PMA_console.$consoleContent.prop('scrollHeight')) {
476                 PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);
477                 PMA_console.scrollBottom();
478             } else {
479                 PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);
480             }
481         }
482     },
483     /**
484      * Mouseup event handler for bind to resizer
485      *
486      * @return void
487      */
488     _mouseup: function() {
489         Cookies.set('pma_console_height', PMA_consoleResizer._resultHeight);
490         PMA_console.show();
491         $(document).off('mousemove');
492         $(document).off('mouseup');
493         $(document).off('selectstart');
494     },
495     /**
496      * Used for console resizer initialize
497      *
498      * @return void
499      */
500     initialize: function() {
501         $('#pma_console').find('.toolbar').off('mousedown');
502         $('#pma_console').find('.toolbar').mousedown(PMA_consoleResizer._mousedown);
503     }
508  * Console input object
509  */
510 var PMA_consoleInput = {
511     /**
512      * @var array, contains Codemirror objects or input jQuery objects
513      * @access private
514      */
515     _inputs: null,
516     /**
517      * @var bool, if codemirror enabled
518      * @access private
519      */
520     _codemirror: false,
521     /**
522      * @var int, count for history navigation, 0 for current input
523      * @access private
524      */
525     _historyCount: 0,
526     /**
527      * @var string, current input when navigating through history
528      * @access private
529      */
530     _historyPreserveCurrent: null,
531     /**
532      * Used for console input initialize
533      *
534      * @return void
535      */
536     initialize: function() {
537         // _cm object can't be reinitialize
538         if (PMA_consoleInput._inputs !== null) {
539             return;
540         }
541         if (typeof CodeMirror !== 'undefined') {
542             PMA_consoleInput._codemirror = true;
543         }
544         PMA_consoleInput._inputs = [];
545         if (PMA_consoleInput._codemirror) {
546             PMA_consoleInput._inputs.console = CodeMirror($('#pma_console').find('.console_query_input')[0], {
547                 theme: 'pma',
548                 mode: 'text/x-sql',
549                 lineWrapping: true,
550                 extraKeys: {"Ctrl-Space": "autocomplete"},
551                 hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
552                 gutters: ["CodeMirror-lint-markers"],
553                 lint: {
554                     "getAnnotations": CodeMirror.sqlLint,
555                     "async": true,
556                 }
557             });
558             PMA_consoleInput._inputs.console.on("inputRead", codemirrorAutocompleteOnInputRead);
559             PMA_consoleInput._inputs.console.on("keydown", function(instance, event) {
560                 PMA_consoleInput._historyNavigate(event);
561             });
562             if ($('#pma_bookmarks').length !== 0) {
563                 PMA_consoleInput._inputs.bookmark = CodeMirror($('#pma_console').find('.bookmark_add_input')[0], {
564                     theme: 'pma',
565                     mode: 'text/x-sql',
566                     lineWrapping: true,
567                     extraKeys: {"Ctrl-Space": "autocomplete"},
568                     hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
569                     gutters: ["CodeMirror-lint-markers"],
570                     lint: {
571                         "getAnnotations": CodeMirror.sqlLint,
572                         "async": true,
573                     }
574                 });
575                 PMA_consoleInput._inputs.bookmark.on("inputRead", codemirrorAutocompleteOnInputRead);
576             }
577         } else {
578             PMA_consoleInput._inputs.console =
579                 $('<textarea>').appendTo('#pma_console .console_query_input')
580                     .on('keydown', PMA_consoleInput._historyNavigate);
581             if ($('#pma_bookmarks').length !== 0) {
582                 PMA_consoleInput._inputs.bookmark =
583                     $('<textarea>').appendTo('#pma_console .bookmark_add_input');
584             }
585         }
586         $('#pma_console').find('.console_query_input').keydown(PMA_consoleInput._keydown);
587     },
588     _historyNavigate: function(event) {
589         if (event.keyCode == 38 || event.keyCode == 40) {
590             var upPermitted = false;
591             var downPermitted = false;
592             var editor = PMA_consoleInput._inputs.console;
593             var cursorLine;
594             var totalLine;
595             if (PMA_consoleInput._codemirror) {
596                 cursorLine = editor.getCursor().line;
597                 totalLine = editor.lineCount();
598             } else {
599                 // Get cursor position from textarea
600                 var text = PMA_consoleInput.getText();
601                 cursorLine = text.substr(0, editor.prop("selectionStart")).split("\n").length - 1;
602                 totalLine = text.split(/\r*\n/).length;
603             }
604             if (cursorLine === 0) {
605                 upPermitted = true;
606             }
607             if (cursorLine == totalLine - 1) {
608                 downPermitted = true;
609             }
610             var nextCount;
611             var queryString = false;
612             if (upPermitted && event.keyCode == 38) {
613                 // Navigate up in history
614                 if (PMA_consoleInput._historyCount === 0) {
615                     PMA_consoleInput._historyPreserveCurrent = PMA_consoleInput.getText();
616                 }
617                 nextCount = PMA_consoleInput._historyCount + 1;
618                 queryString = PMA_consoleMessages.getHistory(nextCount);
619             } else if (downPermitted && event.keyCode == 40) {
620                 // Navigate down in history
621                 if (PMA_consoleInput._historyCount === 0) {
622                     return;
623                 }
624                 nextCount = PMA_consoleInput._historyCount - 1;
625                 if (nextCount === 0) {
626                     queryString = PMA_consoleInput._historyPreserveCurrent;
627                 } else {
628                     queryString = PMA_consoleMessages.getHistory(nextCount);
629                 }
630             }
631             if (queryString !== false) {
632                 PMA_consoleInput._historyCount = nextCount;
633                 PMA_consoleInput.setText(queryString, 'console');
634                 if (PMA_consoleInput._codemirror) {
635                     editor.setCursor(editor.lineCount(), 0);
636                 }
637                 event.preventDefault();
638             }
639         }
640     },
641     /**
642      * Mousedown event handler for bind to input
643      * Shortcut is Ctrl+Enter key or just ENTER, depending on console's
644      * configuration.
645      *
646      * @return void
647      */
648     _keydown: function(event) {
649         if (PMA_console.config.enterExecutes) {
650             // Enter, but not in combination with Shift (which writes a new line).
651             if (!event.shiftKey && event.keyCode === 13) {
652                 PMA_consoleInput.execute();
653             }
654         } else {
655             // Ctrl+Enter
656             if (event.ctrlKey && event.keyCode === 13) {
657                 PMA_consoleInput.execute();
658             }
659         }
660     },
661     /**
662      * Used for send text to PMA_console.execute()
663      *
664      * @return void
665      */
666     execute: function() {
667         if (PMA_consoleInput._codemirror) {
668             PMA_console.execute(PMA_consoleInput._inputs.console.getValue());
669         } else {
670             PMA_console.execute(PMA_consoleInput._inputs.console.val());
671         }
672     },
673     /**
674      * Used for clear the input
675      *
676      * @param string target, default target is console input
677      * @return void
678      */
679     clear: function(target) {
680         PMA_consoleInput.setText('', target);
681     },
682     /**
683      * Used for set focus to input
684      *
685      * @return void
686      */
687     focus: function() {
688         PMA_consoleInput._inputs.console.focus();
689     },
690     /**
691      * Used for blur input
692      *
693      * @return void
694      */
695     blur: function() {
696         if (PMA_consoleInput._codemirror) {
697             PMA_consoleInput._inputs.console.getInputField().blur();
698         } else {
699             PMA_consoleInput._inputs.console.blur();
700         }
701     },
702     /**
703      * Used for set text in input
704      *
705      * @param string text
706      * @param string target
707      * @return void
708      */
709     setText: function(text, target) {
710         if (PMA_consoleInput._codemirror) {
711             switch(target) {
712                 case 'bookmark':
713                     PMA_console.execute(PMA_consoleInput._inputs.bookmark.setValue(text));
714                     break;
715                 default:
716                 case 'console':
717                     PMA_console.execute(PMA_consoleInput._inputs.console.setValue(text));
718             }
719         } else {
720             switch(target) {
721                 case 'bookmark':
722                     PMA_console.execute(PMA_consoleInput._inputs.bookmark.val(text));
723                     break;
724                 default:
725                 case 'console':
726                     PMA_console.execute(PMA_consoleInput._inputs.console.val(text));
727             }
728         }
729     },
730     getText: function(target) {
731         if (PMA_consoleInput._codemirror) {
732             switch(target) {
733                 case 'bookmark':
734                     return PMA_consoleInput._inputs.bookmark.getValue();
735                 default:
736                 case 'console':
737                     return PMA_consoleInput._inputs.console.getValue();
738             }
739         } else {
740             switch(target) {
741                 case 'bookmark':
742                     return PMA_consoleInput._inputs.bookmark.val();
743                 default:
744                 case 'console':
745                     return PMA_consoleInput._inputs.console.val();
746             }
747         }
748     }
754  * Console messages, and message items management object
755  */
756 var PMA_consoleMessages = {
757     /**
758      * Used for clear the messages
759      *
760      * @return void
761      */
762     clear: function() {
763         $('#pma_console').find('.content .console_message_container .message:not(.welcome)').addClass('hide');
764         $('#pma_console').find('.content .console_message_container .message.failed').remove();
765         $('#pma_console').find('.content .console_message_container .message.expanded').find('.action.collapse').click();
766     },
767     /**
768      * Used for show history messages
769      *
770      * @return void
771      */
772     showHistory: function() {
773         $('#pma_console').find('.content .console_message_container .message.hide').removeClass('hide');
774     },
775     /**
776      * Used for getting a perticular history query
777      *
778      * @param int nthLast get nth query message from latest, i.e 1st is last
779      * @return string message
780      */
781     getHistory: function(nthLast) {
782         var $queries = $('#pma_console').find('.content .console_message_container .query');
783         var length = $queries.length;
784         var $query = $queries.eq(length - nthLast);
785         if (!$query || (length - nthLast) < 0) {
786             return false;
787         } else {
788             return $query.text();
789         }
790     },
791     /**
792      * Used to show the correct message depending on which key
793      * combination executes the query (Ctrl+Enter or Enter).
794      *
795      * @param bool enterExecutes Only Enter has to be pressed to execute query.
796      * @return void
797      */
798     showInstructions: function(enterExecutes) {
799         enterExecutes = +enterExecutes || 0; // conversion to int
800         var $welcomeMsg = $('#pma_console').find('.content .console_message_container .message.welcome span');
801         $welcomeMsg.children('[id^=instructions]').hide();
802         $welcomeMsg.children('#instructions-' + enterExecutes).show();
803     },
804     /**
805      * Used for log new message
806      *
807      * @param string msgString Message to show
808      * @param string msgType Message type
809      * @return object, {message_id, $message}
810      */
811     append: function(msgString, msgType) {
812         if (typeof(msgString) !== 'string') {
813             return false;
814         }
815         // Generate an ID for each message, we can find them later
816         var msgId = Math.round(Math.random()*(899999999999)+100000000000);
817         var now = new Date();
818         var $newMessage =
819             $('<div class="message ' +
820                 (PMA_console.config.alwaysExpand ? 'expanded' : 'collapsed') +
821                 '" msgid="' + msgId + '"><div class="action_content"></div></div>');
822         switch(msgType) {
823             case 'query':
824                 $newMessage.append('<div class="query highlighted"></div>');
825                 if (PMA_consoleInput._codemirror) {
826                     CodeMirror.runMode(msgString,
827                         'text/x-sql', $newMessage.children('.query')[0]);
828                 } else {
829                     $newMessage.children('.query').text(msgString);
830                 }
831                 $newMessage.children('.action_content')
832                     .append(PMA_console.$consoleTemplates.children('.query_actions').html());
833                 break;
834             default:
835             case 'normal':
836                 $newMessage.append('<div>' + msgString + '</div>');
837         }
838         PMA_consoleMessages._msgEventBinds($newMessage);
839         $newMessage.find('span.text.query_time span')
840             .text(now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds())
841             .parent().attr('title', now);
842         return {message_id: msgId,
843                 $message: $newMessage.appendTo('#pma_console .content .console_message_container')};
844     },
845     /**
846      * Used for log new query
847      *
848      * @param string queryData Struct should be
849      * {sql_query: "Query string", db: "Target DB", table: "Target Table"}
850      * @param string state Message state
851      * @return object, {message_id: string message id, $message: JQuery object}
852      */
853     appendQuery: function(queryData, state) {
854         var targetMessage = PMA_consoleMessages.append(queryData.sql_query, 'query');
855         if (! targetMessage) {
856             return false;
857         }
858         if (queryData.db && queryData.table) {
859             targetMessage.$message.attr('targetdb', queryData.db);
860             targetMessage.$message.attr('targettable', queryData.table);
861             targetMessage.$message.find('.text.targetdb span').text(queryData.db);
862         }
863         if (PMA_console.isSelect(queryData.sql_query)) {
864             targetMessage.$message.addClass('select');
865         }
866         switch(state) {
867             case 'failed':
868                 targetMessage.$message.addClass('failed');
869                 break;
870             case 'successed':
871                 targetMessage.$message.addClass('successed');
872                 break;
873             default:
874             case 'pending':
875                 targetMessage.$message.addClass('pending');
876         }
877         return targetMessage;
878     },
879     _msgEventBinds: function($targetMessage) {
880         // Leave unbinded elements, remove binded.
881         $targetMessage = $targetMessage.filter(':not(.binded)');
882         if ($targetMessage.length === 0) {
883             return;
884         }
885         $targetMessage.addClass('binded');
887         $targetMessage.find('.action.expand').click(function () {
888             $(this).closest('.message').removeClass('collapsed');
889             $(this).closest('.message').addClass('expanded');
890         });
891         $targetMessage.find('.action.collapse').click(function () {
892             $(this).closest('.message').addClass('collapsed');
893             $(this).closest('.message').removeClass('expanded');
894         });
895         $targetMessage.find('.action.edit').click(function () {
896             PMA_consoleInput.setText($(this).parent().siblings('.query').text());
897             PMA_consoleInput.focus();
898         });
899         $targetMessage.find('.action.requery').click(function () {
900             var query = $(this).parent().siblings('.query').text();
901             var $message = $(this).closest('.message');
902             if (confirm(PMA_messages.strConsoleRequeryConfirm + '\n' +
903                 (query.length<100 ? query : query.slice(0, 100) + '...'))
904             ) {
905                 PMA_console.execute(query, {db: $message.attr('targetdb'), table: $message.attr('targettable')});
906             }
907         });
908         $targetMessage.find('.action.bookmark').click(function () {
909             var query = $(this).parent().siblings('.query').text();
910             var $message = $(this).closest('.message');
911             PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'));
912             PMA_console.showCard('#pma_bookmarks .card.add');
913         });
914         $targetMessage.find('.action.edit_bookmark').click(function () {
915             var query = $(this).parent().siblings('.query').text();
916             var $message = $(this).closest('.message');
917             var isShared = $message.find('span.bookmark_label').hasClass('shared');
918             var label = $message.find('span.bookmark_label').text();
919             PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'), label, isShared);
920             PMA_console.showCard('#pma_bookmarks .card.add');
921         });
922         $targetMessage.find('.action.delete_bookmark').click(function () {
923             var $message = $(this).closest('.message');
924             if (confirm(PMA_messages.strConsoleDeleteBookmarkConfirm + '\n' + $message.find('.bookmark_label').text())) {
925                 $.post('import.php',
926                     {
927                     server: PMA_commonParams.get('server'),
928                     action_bookmark: 2,
929                     ajax_request: true,
930                     id_bookmark: $message.attr('bookmarkid')},
931                     function () {
932                         PMA_consoleBookmarks.refresh();
933                     });
934             }
935         });
936         $targetMessage.find('.action.profiling').click(function () {
937             var $message = $(this).closest('.message');
938             PMA_console.execute($(this).parent().siblings('.query').text(),
939                 {db: $message.attr('targetdb'),
940                 table: $message.attr('targettable'),
941                 profiling: true});
942         });
943         $targetMessage.find('.action.explain').click(function () {
944             var $message = $(this).closest('.message');
945             PMA_console.execute('EXPLAIN ' + $(this).parent().siblings('.query').text(),
946                 {db: $message.attr('targetdb'),
947                 table: $message.attr('targettable')});
948         });
949         $targetMessage.find('.action.dbg_show_trace').click(function () {
950             var $message = $(this).closest('.message');
951             if (!$message.find('.trace').length) {
952                 PMA_consoleDebug.getQueryDetails(
953                     $message.data('queryInfo'),
954                     $message.data('totalTime'),
955                     $message
956                 );
957                 PMA_consoleMessages._msgEventBinds($message.find('.message:not(.binded)'));
958             }
959             $message.addClass('show_trace');
960             $message.removeClass('hide_trace');
961         });
962         $targetMessage.find('.action.dbg_hide_trace').click(function () {
963             var $message = $(this).closest('.message');
964             $message.addClass('hide_trace');
965             $message.removeClass('show_trace');
966         });
967         $targetMessage.find('.action.dbg_show_args').click(function () {
968             var $message = $(this).closest('.message');
969             $message.addClass('show_args expanded');
970             $message.removeClass('hide_args collapsed');
971         });
972         $targetMessage.find('.action.dbg_hide_args').click(function () {
973             var $message = $(this).closest('.message');
974             $message.addClass('hide_args collapsed');
975             $message.removeClass('show_args expanded');
976         });
977         if (PMA_consoleInput._codemirror) {
978             $targetMessage.find('.query:not(.highlighted)').each(function(index, elem) {
979                     CodeMirror.runMode($(elem).text(),
980                         'text/x-sql', elem);
981                     $(this).addClass('highlighted');
982                 });
983         }
984     },
985     msgAppend: function(msgId, msgString, msgType) {
986         var $targetMessage = $('#pma_console').find('.content .console_message_container .message[msgid=' + msgId +']');
987         if ($targetMessage.length === 0 || isNaN(parseInt(msgId)) || typeof(msgString) !== 'string') {
988             return false;
989         }
990         $targetMessage.append('<div>' + msgString + '</div>');
991     },
992     updateQuery: function(msgId, isSuccessed, queryData) {
993         var $targetMessage = $('#pma_console').find('.console_message_container .message[msgid=' + parseInt(msgId) +']');
994         if ($targetMessage.length === 0 || isNaN(parseInt(msgId))) {
995             return false;
996         }
997         $targetMessage.removeClass('pending failed successed');
998         if (isSuccessed) {
999             $targetMessage.addClass('successed');
1000             if (queryData) {
1001                 $targetMessage.children('.query').text('');
1002                 $targetMessage.removeClass('select');
1003                 if (PMA_console.isSelect(queryData.sql_query)) {
1004                     $targetMessage.addClass('select');
1005                 }
1006                 if (PMA_consoleInput._codemirror) {
1007                     CodeMirror.runMode(queryData.sql_query, 'text/x-sql', $targetMessage.children('.query')[0]);
1008                 } else {
1009                     $targetMessage.children('.query').text(queryData.sql_query);
1010                 }
1011                 $targetMessage.attr('targetdb', queryData.db);
1012                 $targetMessage.attr('targettable', queryData.table);
1013                 $targetMessage.find('.text.targetdb span').text(queryData.db);
1014             }
1015         } else {
1016             $targetMessage.addClass('failed');
1017         }
1018     },
1019     /**
1020      * Used for console messages initialize
1021      *
1022      * @return void
1023      */
1024     initialize: function() {
1025         PMA_consoleMessages._msgEventBinds($('#pma_console').find('.message:not(.binded)'));
1026         if (PMA_console.config.startHistory) {
1027             PMA_consoleMessages.showHistory();
1028         }
1029         PMA_consoleMessages.showInstructions(PMA_console.config.enterExecutes);
1030     }
1035  * Console bookmarks card, and bookmarks items management object
1036  */
1037 var PMA_consoleBookmarks = {
1038     _bookmarks: [],
1039     addBookmark: function (queryString, targetDb, label, isShared, id) {
1040         $('#pma_bookmarks').find('.add [name=shared]').prop('checked', false);
1041         $('#pma_bookmarks').find('.add [name=label]').val('');
1042         $('#pma_bookmarks').find('.add [name=targetdb]').val('');
1043         $('#pma_bookmarks').find('.add [name=id_bookmark]').val('');
1044         PMA_consoleInput.setText('', 'bookmark');
1046         switch(arguments.length) {
1047             case 4:
1048                 $('#pma_bookmarks').find('.add [name=shared]').prop('checked', isShared);
1049             case 3:
1050                 $('#pma_bookmarks').find('.add [name=label]').val(label);
1051             case 2:
1052                 $('#pma_bookmarks').find('.add [name=targetdb]').val(targetDb);
1053             case 1:
1054                 PMA_consoleInput.setText(queryString, 'bookmark');
1055             default:
1056                 break;
1057         }
1058     },
1059     refresh: function () {
1060         $.get('import.php',
1061             {ajax_request: true,
1062             server: PMA_commonParams.get('server'),
1063             console_bookmark_refresh: 'refresh'},
1064             function(data) {
1065                 if (data.console_message_bookmark) {
1066                     $('#pma_bookmarks').find('.content.bookmark').html(data.console_message_bookmark);
1067                     PMA_consoleMessages._msgEventBinds($('#pma_bookmarks').find('.message:not(.binded)'));
1068                 }
1069             });
1070     },
1071     /**
1072      * Used for console bookmarks initialize
1073      * message events are already binded by PMA_consoleMsg._msgEventBinds
1074      *
1075      * @return void
1076      */
1077     initialize: function() {
1078         if ($('#pma_bookmarks').length === 0) {
1079             return;
1080         }
1081         $('#pma_console').find('.button.bookmarks').click(function() {
1082             PMA_console.showCard('#pma_bookmarks');
1083         });
1084         $('#pma_bookmarks').find('.button.add').click(function() {
1085             PMA_console.showCard('#pma_bookmarks .card.add');
1086         });
1087         $('#pma_bookmarks').find('.card.add [name=submit]').click(function () {
1088             if ($('#pma_bookmarks').find('.card.add [name=label]').val().length === 0
1089                 || PMA_consoleInput.getText('bookmark').length === 0)
1090             {
1091                 alert(PMA_messages.strFormEmpty);
1092                 return;
1093             }
1094             $(this).prop('disabled', true);
1095             $.post('import.php',
1096                 {
1097                 ajax_request: true,
1098                 console_bookmark_add: 'true',
1099                 label: $('#pma_bookmarks').find('.card.add [name=label]').val(),
1100                 server: PMA_commonParams.get('server'),
1101                 db: $('#pma_bookmarks').find('.card.add [name=targetdb]').val(),
1102                 bookmark_query: PMA_consoleInput.getText('bookmark'),
1103                 shared: $('#pma_bookmarks').find('.card.add [name=shared]').prop('checked')},
1104                 function () {
1105                     PMA_consoleBookmarks.refresh();
1106                     $('#pma_bookmarks').find('.card.add [name=submit]').prop('disabled', false);
1107                     PMA_console.hideCard($('#pma_bookmarks').find('.card.add'));
1108                 });
1109         });
1110         $('#pma_console').find('.button.refresh').click(function() {
1111             PMA_consoleBookmarks.refresh();
1112         });
1113     }
1116 var PMA_consoleDebug;
1117 PMA_consoleDebug = {
1118     _config: {
1119         groupQueries: false,
1120         orderBy: 'exec', // Possible 'exec' => Execution order, 'time' => Time taken, 'count'
1121         order: 'asc' // Possible 'asc', 'desc'
1122     },
1123     _lastDebugInfo: {
1124         debugInfo: null,
1125         url: null
1126     },
1127     initialize: function () {
1128         // Try to get debug info after every AJAX request
1129         $(document).ajaxSuccess(function (event, xhr, settings, data) {
1130             if (data._debug) {
1131                 PMA_consoleDebug.showLog(data._debug, settings.url);
1132             }
1133         });
1135         // Initialize config
1136         this._initConfig();
1138         if (this.configParam('groupQueries')) {
1139             $('#debug_console').addClass('grouped');
1140         } else {
1141             $('#debug_console').addClass('ungrouped');
1142             if (PMA_consoleDebug.configParam('orderBy') == 'count') {
1143                 $('#debug_console').find('.button.order_by.sort_exec').addClass('active');
1144             }
1145         }
1146         var orderBy = this.configParam('orderBy');
1147         var order = this.configParam('order');
1148         $('#debug_console').find('.button.order_by.sort_' + orderBy).addClass('active');
1149         $('#debug_console').find('.button.order.order_' + order).addClass('active');
1151         // Initialize actions in toolbar
1152         $('#debug_console').find('.button.group_queries').click(function () {
1153             $('#debug_console').addClass('grouped');
1154             $('#debug_console').removeClass('ungrouped');
1155             PMA_consoleDebug.configParam('groupQueries', true);
1156             PMA_consoleDebug.refresh();
1157             if (PMA_consoleDebug.configParam('orderBy') == 'count') {
1158                 $('#debug_console').find('.button.order_by.sort_exec').removeClass('active');
1159             }
1160         });
1161         $('#debug_console').find('.button.ungroup_queries').click(function () {
1162             $('#debug_console').addClass('ungrouped');
1163             $('#debug_console').removeClass('grouped');
1164             PMA_consoleDebug.configParam('groupQueries', false);
1165             PMA_consoleDebug.refresh();
1166             if (PMA_consoleDebug.configParam('orderBy') == 'count') {
1167                 $('#debug_console').find('.button.order_by.sort_exec').addClass('active');
1168             }
1169         });
1170         $('#debug_console').find('.button.order_by').click(function () {
1171             var $this = $(this);
1172             $('#debug_console').find('.button.order_by').removeClass('active');
1173             $this.addClass('active');
1174             if ($this.hasClass('sort_time')) {
1175                 PMA_consoleDebug.configParam('orderBy', 'time');
1176             } else if ($this.hasClass('sort_exec')) {
1177                 PMA_consoleDebug.configParam('orderBy', 'exec');
1178             } else if ($this.hasClass('sort_count')) {
1179                 PMA_consoleDebug.configParam('orderBy', 'count');
1180             }
1181             PMA_consoleDebug.refresh();
1182         });
1183         $('#debug_console').find('.button.order').click(function () {
1184             var $this = $(this);
1185             $('#debug_console').find('.button.order').removeClass('active');
1186             $this.addClass('active');
1187             if ($this.hasClass('order_asc')) {
1188                 PMA_consoleDebug.configParam('order', 'asc');
1189             } else if ($this.hasClass('order_desc')) {
1190                 PMA_consoleDebug.configParam('order', 'desc');
1191             }
1192             PMA_consoleDebug.refresh();
1193         });
1195         // Show SQL debug info for first page load
1196         if (typeof debugSQLInfo !== 'undefined' && debugSQLInfo !== 'null') {
1197             $('#pma_console').find('.button.debug').removeClass('hide');
1198         }
1199         else {
1200             return;
1201         }
1202         PMA_consoleDebug.showLog(debugSQLInfo);
1203     },
1204     _initConfig: function () {
1205         var config = Cookies.getJSON('pma_console_dbg_config');
1206         if (config) {
1207             for (var name in config) {
1208                 if (config.hasOwnProperty(name)) {
1209                     this._config[name] = config[name];
1210                 }
1211             }
1212         }
1213     },
1214     configParam: function (name, value) {
1215         if (typeof value === 'undefined') {
1216             return this._config[name];
1217         }
1218         this._config[name] = value;
1219         Cookies.set('pma_console_dbg_config', this._config);
1220         return value;
1221     },
1222     _formatFunctionCall: function (dbgStep) {
1223         var functionName = '';
1224         if ('class' in dbgStep) {
1225             functionName += dbgStep.class;
1226             functionName += dbgStep.type;
1227         }
1228         functionName += dbgStep.function;
1229         if (dbgStep.args && dbgStep.args.length) {
1230             functionName += '(...)';
1231         } else {
1232             functionName += '()';
1233         }
1234         return functionName;
1235     },
1236     _formatFunctionArgs: function (dbgStep) {
1237         var $args = $('<div>');
1238         if (dbgStep.args.length) {
1239             $args.append('<div class="message welcome">')
1240                 .append(
1241                 $('<div class="message welcome">')
1242                     .text(
1243                     PMA_sprintf(
1244                         PMA_messages.strConsoleDebugArgsSummary,
1245                         dbgStep.args.length
1246                     )
1247                 )
1248             );
1249             for (var i = 0; i < dbgStep.args.length; i++) {
1250                 $args.append(
1251                     $('<div class="message">')
1252                         .html(
1253                         '<pre>' +
1254                         escapeHtml(JSON.stringify(dbgStep.args[i], null, "  ")) +
1255                         '</pre>'
1256                     )
1257                 );
1258             }
1259         }
1260         return $args;
1261     },
1262     _formatFileName: function (dbgStep) {
1263         var fileName = '';
1264         if ('file' in dbgStep) {
1265             fileName += dbgStep.file;
1266             fileName += '#' + dbgStep.line;
1267         }
1268         return fileName;
1269     },
1270     _formatBackTrace: function (dbgTrace) {
1271         var $traceElem = $('<div class="trace">');
1272         $traceElem.append(
1273             $('<div class="message welcome">')
1274         );
1275         var step, $stepElem;
1276         for (var stepId in dbgTrace) {
1277             if (dbgTrace.hasOwnProperty(stepId)) {
1278                 step = dbgTrace[stepId];
1279                 if (!Array.isArray(step) && typeof step !== 'object') {
1280                     $stepElem =
1281                         $('<div class="message traceStep collapsed hide_args">')
1282                             .append(
1283                             $('<span>').text(step)
1284                         );
1285                 } else {
1286                     if (typeof step.args === 'string' && step.args) {
1287                         step.args = [step.args];
1288                     }
1289                     $stepElem =
1290                         $('<div class="message traceStep collapsed hide_args">')
1291                             .append(
1292                             $('<span class="function">').text(this._formatFunctionCall(step))
1293                         )
1294                             .append(
1295                             $('<span class="file">').text(this._formatFileName(step))
1296                         );
1297                     if (step.args && step.args.length) {
1298                         $stepElem
1299                             .append(
1300                             $('<span class="args">').html(this._formatFunctionArgs(step))
1301                         )
1302                             .prepend(
1303                             $('<div class="action_content">')
1304                                 .append(
1305                                 '<span class="action dbg_show_args">' +
1306                                 PMA_messages.strConsoleDebugShowArgs +
1307                                 '</span> '
1308                             )
1309                                 .append(
1310                                 '<span class="action dbg_hide_args">' +
1311                                 PMA_messages.strConsoleDebugHideArgs +
1312                                 '</span> '
1313                             )
1314                         );
1315                     }
1316                 }
1317                 $traceElem.append($stepElem);
1318             }
1319         }
1320         return $traceElem;
1321     },
1322     _formatQueryOrGroup: function (queryInfo, totalTime) {
1323         var grouped, queryText, queryTime, count, i;
1324         if (Array.isArray(queryInfo)) {
1325             // It is grouped
1326             grouped = true;
1328             queryText = queryInfo[0].query;
1330             queryTime = 0;
1331             for (i in queryInfo) {
1332                 queryTime += queryInfo[i].time;
1333             }
1335             count = queryInfo.length;
1336         } else {
1337             queryText = queryInfo.query;
1338             queryTime = queryInfo.time;
1339         }
1341         var $query = $('<div class="message collapsed hide_trace">')
1342             .append(
1343             $('#debug_console').find('.templates .debug_query').clone()
1344         )
1345             .append(
1346             $('<div class="query">')
1347                 .text(queryText)
1348         )
1349             .data('queryInfo', queryInfo)
1350             .data('totalTime', totalTime);
1351         if (grouped) {
1352             $query.find('.text.count').removeClass('hide');
1353             $query.find('.text.count span').text(count);
1354         }
1355         $query.find('.text.time span').text(queryTime + 's (' + ((queryTime * 100) / totalTime).toFixed(3) + '%)');
1357         return $query;
1358     },
1359     _appendQueryExtraInfo: function (query, $elem) {
1360         if ('error' in query) {
1361             $elem.append(
1362                 $('<div>').html(query.error)
1363             );
1364         }
1365         $elem.append(this._formatBackTrace(query.trace));
1366     },
1367     getQueryDetails: function (queryInfo, totalTime, $query) {
1368         if (Array.isArray(queryInfo)) {
1369             var $singleQuery;
1370             for (var i in queryInfo) {
1371                 $singleQuery = $('<div class="message welcome trace">')
1372                     .text((parseInt(i) + 1) + '.')
1373                     .append(
1374                     $('<span class="time">').text(
1375                         PMA_messages.strConsoleDebugTimeTaken +
1376                         ' ' + queryInfo[i].time + 's' +
1377                         ' (' + ((queryInfo[i].time * 100) / totalTime).toFixed(3) + '%)'
1378                     )
1379                 );
1380                 this._appendQueryExtraInfo(queryInfo[i], $singleQuery);
1381                 $query
1382                     .append('<div class="message welcome trace">')
1383                     .append($singleQuery);
1384             }
1385         } else {
1386             this._appendQueryExtraInfo(queryInfo, $query);
1387         }
1388     },
1389     showLog: function (debugInfo, url) {
1390         this._lastDebugInfo.debugInfo = debugInfo;
1391         this._lastDebugInfo.url = url;
1393         $('#debug_console').find('.debugLog').empty();
1394         $("#debug_console").find(".debug>.welcome").empty();
1396         var debugJson = false, i;
1397         if (typeof debugInfo === "object" && 'queries' in debugInfo) {
1398             // Copy it to debugJson, so that it doesn't get changed
1399             if (!('queries' in debugInfo)) {
1400                 debugJson = false;
1401             } else {
1402                 debugJson = {queries: []};
1403                 for (i in debugInfo.queries) {
1404                     debugJson.queries[i] = debugInfo.queries[i];
1405                 }
1406             }
1407         } else if (typeof debugInfo === "string") {
1408             try {
1409                 debugJson = JSON.parse(debugInfo);
1410             } catch (e) {
1411                 debugJson = false;
1412             }
1413             if (debugJson && !('queries' in debugJson)) {
1414                 debugJson = false;
1415             }
1416         }
1417         if (debugJson === false) {
1418             $("#debug_console").find(".debug>.welcome").text(
1419                 PMA_messages.strConsoleDebugError
1420             );
1421             return;
1422         }
1423         var allQueries = debugJson.queries;
1424         var uniqueQueries = {};
1426         var totalExec = allQueries.length;
1428         // Calculate total time and make unique query array
1429         var totalTime = 0;
1430         for (i = 0; i < totalExec; ++i) {
1431             totalTime += allQueries[i].time;
1432             if (!(allQueries[i].hash in uniqueQueries)) {
1433                 uniqueQueries[allQueries[i].hash] = [];
1434             }
1435             uniqueQueries[allQueries[i].hash].push(allQueries[i]);
1436         }
1437         // Count total unique queries, convert uniqueQueries to Array
1438         var totalUnique = 0, uniqueArray = [];
1439         for (var hash in uniqueQueries) {
1440             if (uniqueQueries.hasOwnProperty(hash)) {
1441                 ++totalUnique;
1442                 uniqueArray.push(uniqueQueries[hash]);
1443             }
1444         }
1445         uniqueQueries = uniqueArray;
1446         // Show summary
1447         $("#debug_console").find(".debug>.welcome").append(
1448             $('<span class="debug_summary">').text(
1449                 PMA_sprintf(
1450                     PMA_messages.strConsoleDebugSummary,
1451                     totalUnique,
1452                     totalExec,
1453                     totalTime
1454                 )
1455             )
1456         );
1457         if (url) {
1458             $("#debug_console").find(".debug>.welcome").append(
1459                 $('<span class="script_name">').text(url.split('?')[0])
1460             );
1461         }
1463         // For sorting queries
1464         function sortByTime(a, b) {
1465             var order = ((PMA_consoleDebug.configParam('order') == 'asc') ? 1 : -1);
1466             if (Array.isArray(a) && Array.isArray(b)) {
1467                 // It is grouped
1468                 var timeA = 0, timeB = 0, i;
1469                 for (i in a) {
1470                     timeA += a[i].time;
1471                 }
1472                 for (i in b) {
1473                     timeB += b[i].time;
1474                 }
1475                 return (timeA - timeB) * order;
1476             } else {
1477                 return (a.time - b.time) * order;
1478             }
1479         }
1481         function sortByCount(a, b) {
1482             var order = ((PMA_consoleDebug.configParam('order') == 'asc') ? 1 : -1);
1483             return (a.length - b.length) * order;
1484         }
1486         var orderBy = this.configParam('orderBy');
1487         var order = PMA_consoleDebug.configParam('order');
1489         if (this.configParam('groupQueries')) {
1490             // Sort queries
1491             if (orderBy == 'time') {
1492                 uniqueQueries.sort(sortByTime);
1493             } else if (orderBy == 'count') {
1494                 uniqueQueries.sort(sortByCount);
1495             } else if (orderBy == 'exec' && order == 'desc') {
1496                 uniqueQueries.reverse();
1497             }
1498             for (i in uniqueQueries) {
1499                 if (orderBy == 'time') {
1500                     uniqueQueries[i].sort(sortByTime);
1501                 } else if (orderBy == 'exec' && order == 'desc') {
1502                     uniqueQueries[i].reverse();
1503                 }
1504                 $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(uniqueQueries[i], totalTime));
1505             }
1506         } else {
1507             if (orderBy == 'time') {
1508                 allQueries.sort(sortByTime);
1509             } else if (order == 'desc') {
1510                 allQueries.reverse();
1511             }
1512             for (i = 0; i < totalExec; ++i) {
1513                 $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(allQueries[i], totalTime));
1514             }
1515         }
1517         PMA_consoleMessages._msgEventBinds($('#debug_console').find('.message:not(.binded)'));
1518     },
1519     refresh: function () {
1520         var last = this._lastDebugInfo;
1521         PMA_consoleDebug.showLog(last.debugInfo, last.url);
1522     }
1525 /**s
1526  * Executed on page load
1527  */
1528 $(function () {
1529     PMA_console.initialize();