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