1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * Used in or for console
5 * @package phpMyAdmin-Console
13 * @var object, jQuery object, selector is '#pma_console>.content'
16 $consoleContent: null,
18 * @var object, jQuery object, selector is '#pma_console .content',
22 $consoleAllContents: null,
24 * @var object, jQuery object, selector is '#pma_console .toolbar'
27 $consoleToolbar: null,
29 * @var object, jQuery object, selector is '#pma_console .template'
32 $consoleTemplates: null,
34 * @var object, jQuery object, form for submit
39 * @var object, contain console config
44 * @var bool, if console element exist, it'll be true
49 * @var bool, make sure console events bind only once
54 * Used for console initialize, reinit is ok, just some variable assignment
58 initialize: function() {
60 if ($('#pma_console').length === 0) {
64 PMA_console.isEnabled = true;
66 // Cookie var checks and init
67 if (! $.cookie('pma_console_height')) {
68 $.cookie('pma_console_height', 92);
70 if (! $.cookie('pma_console_mode')) {
71 $.cookie('pma_console_mode', 'info');
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') +
93 PMA_console.$requestForm.bind('submit', AJAX.requestHandler);
95 // Event binds shouldn't run again
96 if (PMA_console.isInitialized === false) {
99 var tempConfig = JSON.parse($.cookie('pma_console_config'));
101 if (tempConfig.alwaysExpand === true) {
102 $('#pma_console_options input[name=always_expand]').prop('checked', true);
104 if (tempConfig.startHistory === true) {
105 $('#pma_console_options').find('input[name=start_history]').prop('checked', true);
107 if (tempConfig.currentQuery === true) {
108 $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
110 if (ConsoleEnterExecutes === true) {
111 $('#pma_console_options').find('input[name=enter_executes]').prop('checked', true);
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');
118 $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
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();
136 $('#pma_console').find('.button.clear').click(function() {
137 PMA_consoleMessages.clear();
140 $('#pma_console').find('.button.history').click(function() {
141 PMA_consoleMessages.showHistory();
144 $('#pma_console').find('.button.options').click(function() {
145 PMA_console.showCard('#pma_console_options');
148 $('#pma_console').find('.button.debug').click(function() {
149 PMA_console.showCard('#debug_console');
152 PMA_console.$consoleContent.click(function(event) {
153 if (event.target == this) {
154 PMA_consoleInput.focus();
158 $('#pma_console').find('.mid_layer').click(function() {
159 PMA_console.hideCard($(this).parent().children('.card'));
161 $('#debug_console').find('.switch_button').click(function() {
162 PMA_console.hideCard($(this).closest('.card'));
164 $('#pma_bookmarks').find('.switch_button').click(function() {
165 PMA_console.hideCard($(this).closest('.card'));
167 $('#pma_console_options').find('.switch_button').click(function() {
168 PMA_console.hideCard($(this).closest('.card'));
171 $('#pma_console_options').find('input[type=checkbox]').change(function() {
172 PMA_console.updateConfig();
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();
184 $('#pma_console_options').find('input[name=enter_executes]').change(function() {
185 PMA_consoleMessages.showInstructions(PMA_console.config.enterExecutes);
188 $(document).ajaxComplete(function (event, xhr, ajaxOptions) {
189 if (ajaxOptions.dataType && ajaxOptions.dataType.indexOf('json') != -1) {
192 if (xhr.status !== 200) {
196 var data = JSON.parse(xhr.responseText);
197 PMA_console.ajaxCallback(data);
200 console.log("Failed to parse JSON: " + e.message);
204 PMA_console.isInitialized = true;
207 // Change console mode from cookie
208 switch($.cookie('pma_console_mode')) {
210 PMA_console.collapse();
212 /* jshint -W086 */// no break needed in default section
214 $.cookie('pma_console_mode', 'info');
220 PMA_console.show(true);
221 PMA_console.scrollBottom();
226 * Execute query and show results in console
230 execute: function(queryString, options) {
231 if (typeof(queryString) != 'string' || ! /[a-z]|[A-Z]/.test(queryString)) {
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);
239 PMA_console.$requestForm.children('[name=table]').val(options.table);
241 PMA_console.$requestForm.children('[name=table]').val('');
244 PMA_console.$requestForm.children('[name=db]').val(
245 (PMA_commonParams.get('db').length > 0 ? PMA_commonParams.get('db') : ''));
247 PMA_console.$requestForm.find('[name=profiling]').remove();
248 if (options && options.profiling === true) {
249 PMA_console.$requestForm.append('<input name="profiling" value="on">');
251 if (! confirmQuery(PMA_console.$requestForm[0], PMA_console.$requestForm.children('textarea')[0].value)) {
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();
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');
272 * Change console to collapse mode
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);
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');
291 PMA_console.hideCard();
296 * @param bool inputFocus If true, focus the input line after show()
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();
309 PMA_console.$consoleContent.css({display:'block'});
310 if (PMA_console.$consoleToolbar.hasClass('collapsed')) {
311 PMA_console.$consoleToolbar.removeClass('collapsed');
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');
319 PMA_consoleInput.focus();
324 * Change console to SQL information mode
325 * this mode shows current SQL query
326 * This mode is the default mode
331 // Under construction
332 PMA_console.collapse();
335 * Toggle console mode between collapse/show
336 * Used for toggle buttons and shortcuts
341 switch($.cookie('pma_console_mode')) {
344 PMA_console.show(true);
347 PMA_console.collapse();
350 PMA_consoleInitialize();
354 * Scroll console to bottom
358 scrollBottom: function() {
359 PMA_console.$consoleContent.scrollTop(PMA_console.$consoleContent.prop("scrollHeight"));
364 * @param string cardSelector Selector, select string will be "#pma_console " + cardSelector
365 * this param also can be JQuery object, if you need.
369 showCard: function(cardSelector) {
371 if (typeof(cardSelector) !== 'string') {
372 if (cardSelector.length > 0) {
373 $card = cardSelector;
378 $card = $("#pma_console " + cardSelector);
380 if ($card.length === 0) {
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'));
391 * Scroll console to bottom
393 * @param object $targetCard Target card JQuery object, if it's empty, function will hide all cards
396 hideCard: function($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');
407 * Used for update console config
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')
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');
424 $('#pma_console').find('>.content').removeClass('console_dark_theme');
427 isSelect: function (queryString) {
428 var reg_exp = /^SELECT\s+/i;
429 return reg_exp.test(queryString);
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
438 var PMA_consoleResizer = {
443 * Mousedown event handler for bind to resizer
447 _mousedown: function(event) {
448 if ($.cookie('pma_console_mode') !== 'show') {
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; });
459 * Mousemove event handler for bind to resizer
463 _mousemove: function(event) {
464 if (event.pageY < 35) {
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);
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();
480 PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);
485 * Mouseup event handler for bind to resizer
489 _mouseup: function() {
490 $.cookie('pma_console_height', PMA_consoleResizer._resultHeight);
492 $(document).unbind('mousemove');
493 $(document).unbind('mouseup');
494 $(document).unbind('selectstart');
497 * Used for console resizer initialize
501 initialize: function() {
502 $('#pma_console').find('.toolbar').unbind('mousedown');
503 $('#pma_console').find('.toolbar').mousedown(PMA_consoleResizer._mousedown);
509 * Console input object
511 var PMA_consoleInput = {
513 * @var array, contains Codemirror objects or input jQuery objects
518 * @var bool, if codemirror enabled
523 * @var int, count for history navigation, 0 for current input
528 * @var string, current input when navigating through history
531 _historyPreserveCurrent: null,
533 * Used for console input initialize
537 initialize: function() {
538 // _cm object can't be reinitialize
539 if (PMA_consoleInput._inputs !== null) {
542 if (typeof CodeMirror !== 'undefined') {
543 PMA_consoleInput._codemirror = true;
545 PMA_consoleInput._inputs = [];
546 if (PMA_consoleInput._codemirror) {
547 PMA_consoleInput._inputs.console = CodeMirror($('#pma_console').find('.console_query_input')[0], {
551 extraKeys: {"Ctrl-Space": "autocomplete"},
552 hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
553 gutters: ["CodeMirror-lint-markers"],
555 "getAnnotations": CodeMirror.sqlLint,
559 PMA_consoleInput._inputs.console.on("inputRead", codemirrorAutocompleteOnInputRead);
560 PMA_consoleInput._inputs.console.on("keydown", function(instance, event) {
561 PMA_consoleInput._historyNavigate(event);
563 if ($('#pma_bookmarks').length !== 0) {
564 PMA_consoleInput._inputs.bookmark = CodeMirror($('#pma_console').find('.bookmark_add_input')[0], {
568 extraKeys: {"Ctrl-Space": "autocomplete"},
569 hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
570 gutters: ["CodeMirror-lint-markers"],
572 "getAnnotations": CodeMirror.sqlLint,
576 PMA_consoleInput._inputs.bookmark.on("inputRead", codemirrorAutocompleteOnInputRead);
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');
587 $('#pma_console').find('.console_query_input').keydown(PMA_consoleInput._keydown);
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;
596 if (PMA_consoleInput._codemirror) {
597 cursorLine = editor.getCursor().line;
598 totalLine = editor.lineCount();
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;
605 if (cursorLine === 0) {
608 if (cursorLine == totalLine - 1) {
609 downPermitted = true;
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();
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) {
625 nextCount = PMA_consoleInput._historyCount - 1;
626 if (nextCount === 0) {
627 queryString = PMA_consoleInput._historyPreserveCurrent;
629 queryString = PMA_consoleMessages.getHistory(nextCount);
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);
638 event.preventDefault();
643 * Mousedown event handler for bind to input
644 * Shortcut is Ctrl+Enter key or just ENTER, depending on console's
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();
657 if (event.ctrlKey && event.keyCode === 13) {
658 PMA_consoleInput.execute();
663 * Used for send text to PMA_console.execute()
667 execute: function() {
668 if (PMA_consoleInput._codemirror) {
669 PMA_console.execute(PMA_consoleInput._inputs.console.getValue());
671 PMA_console.execute(PMA_consoleInput._inputs.console.val());
675 * Used for clear the input
677 * @param string target, default target is console input
680 clear: function(target) {
681 PMA_consoleInput.setText('', target);
684 * Used for set focus to input
689 PMA_consoleInput._inputs.console.focus();
692 * Used for blur input
697 if (PMA_consoleInput._codemirror) {
698 PMA_consoleInput._inputs.console.getInputField().blur();
700 PMA_consoleInput._inputs.console.blur();
704 * Used for set text in input
707 * @param string target
710 setText: function(text, target) {
711 if (PMA_consoleInput._codemirror) {
714 PMA_console.execute(PMA_consoleInput._inputs.bookmark.setValue(text));
718 PMA_console.execute(PMA_consoleInput._inputs.console.setValue(text));
723 PMA_console.execute(PMA_consoleInput._inputs.bookmark.val(text));
727 PMA_console.execute(PMA_consoleInput._inputs.console.val(text));
731 getText: function(target) {
732 if (PMA_consoleInput._codemirror) {
735 return PMA_consoleInput._inputs.bookmark.getValue();
738 return PMA_consoleInput._inputs.console.getValue();
743 return PMA_consoleInput._inputs.bookmark.val();
746 return PMA_consoleInput._inputs.console.val();
755 * Console messages, and message items management object
757 var PMA_consoleMessages = {
759 * Used for clear the messages
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();
769 * Used for show history messages
773 showHistory: function() {
774 $('#pma_console').find('.content .console_message_container .message.hide').removeClass('hide');
777 * Used for getting a perticular history query
779 * @param int nthLast get nth query message from latest, i.e 1st is last
780 * @return string message
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) {
789 return $query.text();
793 * Used to show the correct message depending on which key
794 * combination executes the query (Ctrl+Enter or Enter).
796 * @param bool enterExecutes Only Enter has to be pressed to execute query.
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();
806 * Used for log new message
808 * @param string msgString Message to show
809 * @param string msgType Message type
810 * @return object, {message_id, $message}
812 append: function(msgString, msgType) {
813 if (typeof(msgString) !== 'string') {
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();
820 $('<div class="message ' +
821 (PMA_console.config.alwaysExpand ? 'expanded' : 'collapsed') +
822 '" msgid="' + msgId + '"><div class="action_content"></div></div>');
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]);
830 $newMessage.children('.query').text(msgString);
832 $newMessage.children('.action_content')
833 .append(PMA_console.$consoleTemplates.children('.query_actions').html());
837 $newMessage.append('<div>' + msgString + '</div>');
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')};
847 * Used for log new query
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}
854 appendQuery: function(queryData, state) {
855 var targetMessage = PMA_consoleMessages.append(queryData.sql_query, 'query');
856 if (! targetMessage) {
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);
864 if (PMA_console.isSelect(queryData.sql_query)) {
865 targetMessage.$message.addClass('select');
869 targetMessage.$message.addClass('failed');
872 targetMessage.$message.addClass('successed');
876 targetMessage.$message.addClass('pending');
878 return targetMessage;
880 _msgEventBinds: function($targetMessage) {
881 // Leave unbinded elements, remove binded.
882 $targetMessage = $targetMessage.filter(':not(.binded)');
883 if ($targetMessage.length === 0) {
886 $targetMessage.addClass('binded');
888 $targetMessage.find('.action.expand').click(function () {
889 $(this).closest('.message').removeClass('collapsed');
890 $(this).closest('.message').addClass('expanded');
892 $targetMessage.find('.action.collapse').click(function () {
893 $(this).closest('.message').addClass('collapsed');
894 $(this).closest('.message').removeClass('expanded');
896 $targetMessage.find('.action.edit').click(function () {
897 PMA_consoleInput.setText($(this).parent().siblings('.query').text());
898 PMA_consoleInput.focus();
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) + '...'))
906 PMA_console.execute(query, {db: $message.attr('targetdb'), table: $message.attr('targettable')});
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');
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');
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())) {
927 {token: PMA_commonParams.get('token'),
928 server: PMA_commonParams.get('server'),
931 id_bookmark: $message.attr('bookmarkid')},
933 PMA_consoleBookmarks.refresh();
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'),
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')});
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'),
958 PMA_consoleMessages._msgEventBinds($message.find('.message:not(.binded)'));
960 $message.addClass('show_trace');
961 $message.removeClass('hide_trace');
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');
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');
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');
978 if (PMA_consoleInput._codemirror) {
979 $targetMessage.find('.query:not(.highlighted)').each(function(index, elem) {
980 CodeMirror.runMode($(elem).text(),
982 $(this).addClass('highlighted');
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') {
991 $targetMessage.append('<div>' + msgString + '</div>');
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))) {
998 $targetMessage.removeClass('pending failed successed');
1000 $targetMessage.addClass('successed');
1002 $targetMessage.children('.query').text('');
1003 $targetMessage.removeClass('select');
1004 if (PMA_console.isSelect(queryData.sql_query)) {
1005 $targetMessage.addClass('select');
1007 if (PMA_consoleInput._codemirror) {
1008 CodeMirror.runMode(queryData.sql_query, 'text/x-sql', $targetMessage.children('.query')[0]);
1010 $targetMessage.children('.query').text(queryData.sql_query);
1012 $targetMessage.attr('targetdb', queryData.db);
1013 $targetMessage.attr('targettable', queryData.table);
1014 $targetMessage.find('.text.targetdb span').text(queryData.db);
1017 $targetMessage.addClass('failed');
1021 * Used for console messages initialize
1025 initialize: function() {
1026 PMA_consoleMessages._msgEventBinds($('#pma_console').find('.message:not(.binded)'));
1027 if (PMA_console.config.startHistory) {
1028 PMA_consoleMessages.showHistory();
1030 PMA_consoleMessages.showInstructions(PMA_console.config.enterExecutes);
1036 * Console bookmarks card, and bookmarks items management object
1038 var PMA_consoleBookmarks = {
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) {
1049 $('#pma_bookmarks').find('.add [name=shared]').prop('checked', isShared);
1051 $('#pma_bookmarks').find('.add [name=label]').val(label);
1053 $('#pma_bookmarks').find('.add [name=targetdb]').val(targetDb);
1055 PMA_consoleInput.setText(queryString, 'bookmark');
1060 refresh: function () {
1062 {ajax_request: true,
1063 token: PMA_commonParams.get('token'),
1064 server: PMA_commonParams.get('server'),
1065 console_bookmark_refresh: 'refresh'},
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)'));
1074 * Used for console bookmarks initialize
1075 * message events are already binded by PMA_consoleMsg._msgEventBinds
1079 initialize: function() {
1080 if ($('#pma_bookmarks').length === 0) {
1083 $('#pma_console').find('.button.bookmarks').click(function() {
1084 PMA_console.showCard('#pma_bookmarks');
1086 $('#pma_bookmarks').find('.button.add').click(function() {
1087 PMA_console.showCard('#pma_bookmarks .card.add');
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)
1093 alert(PMA_messages.strFormEmpty);
1096 $(this).prop('disabled', true);
1097 $.post('import.php',
1098 {token: PMA_commonParams.get('token'),
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')},
1107 PMA_consoleBookmarks.refresh();
1108 $('#pma_bookmarks').find('.card.add [name=submit]').prop('disabled', false);
1109 PMA_console.hideCard($('#pma_bookmarks').find('.card.add'));
1112 $('#pma_console').find('.button.refresh').click(function() {
1113 PMA_consoleBookmarks.refresh();
1118 var PMA_consoleDebug;
1119 PMA_consoleDebug = {
1121 groupQueries: false,
1122 orderBy: 'exec', // Possible 'exec' => Execution order, 'time' => Time taken, 'count'
1123 order: 'asc' // Possible 'asc', 'desc'
1129 initialize: function () {
1130 // Try to get debug info after every AJAX request
1131 $(document).ajaxSuccess(function (event, xhr, settings, data) {
1133 PMA_consoleDebug.showLog(data._debug, settings.url);
1137 // Initialize config
1140 if (this.configParam('groupQueries')) {
1141 $('#debug_console').addClass('grouped');
1143 $('#debug_console').addClass('ungrouped');
1144 if (PMA_consoleDebug.configParam('orderBy') == 'count') {
1145 $('#debug_console').find('.button.order_by.sort_exec').addClass('active');
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');
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');
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');
1183 PMA_consoleDebug.refresh();
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');
1194 PMA_consoleDebug.refresh();
1197 // Show SQL debug info for first page load
1198 if (typeof debugSQLInfo !== 'undefined' && debugSQLInfo !== 'null') {
1199 $('#pma_console').find('.button.debug').removeClass('hide');
1204 PMA_consoleDebug.showLog(debugSQLInfo);
1206 _initConfig: function () {
1207 var config = JSON.parse($.cookie('pma_console_dbg_config'));
1209 for (var name in config) {
1210 if (config.hasOwnProperty(name)) {
1211 this._config[name] = config[name];
1216 configParam: function (name, value) {
1217 if (typeof value === 'undefined') {
1218 return this._config[name];
1220 this._config[name] = value;
1221 $.cookie('pma_console_dbg_config', JSON.stringify(this._config));
1224 _formatFunctionCall: function (dbgStep) {
1225 var functionName = '';
1226 if ('class' in dbgStep) {
1227 functionName += dbgStep.class;
1228 functionName += dbgStep.type;
1230 functionName += dbgStep.function;
1231 if (dbgStep.args && dbgStep.args.length) {
1232 functionName += '(...)';
1234 functionName += '()';
1236 return functionName;
1238 _formatFunctionArgs: function (dbgStep) {
1239 var $args = $('<div>');
1240 if (dbgStep.args.length) {
1241 $args.append('<div class="message welcome">')
1243 $('<div class="message welcome">')
1246 PMA_messages.strConsoleDebugArgsSummary,
1251 for (var i = 0; i < dbgStep.args.length; i++) {
1253 $('<div class="message">')
1256 escapeHtml(JSON.stringify(dbgStep.args[i], null, " ")) +
1264 _formatFileName: function (dbgStep) {
1266 if ('file' in dbgStep) {
1267 fileName += dbgStep.file;
1268 fileName += '#' + dbgStep.line;
1272 _formatBackTrace: function (dbgTrace) {
1273 var $traceElem = $('<div class="trace">');
1275 $('<div class="message welcome">')
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') {
1283 $('<div class="message traceStep collapsed hide_args">')
1285 $('<span>').text(step)
1288 if (typeof step.args === 'string' && step.args) {
1289 step.args = [step.args];
1292 $('<div class="message traceStep collapsed hide_args">')
1294 $('<span class="function">').text(this._formatFunctionCall(step))
1297 $('<span class="file">').text(this._formatFileName(step))
1299 if (step.args && step.args.length) {
1302 $('<span class="args">').html(this._formatFunctionArgs(step))
1305 $('<div class="action_content">')
1307 '<span class="action dbg_show_args">' +
1308 PMA_messages.strConsoleDebugShowArgs +
1312 '<span class="action dbg_hide_args">' +
1313 PMA_messages.strConsoleDebugHideArgs +
1319 $traceElem.append($stepElem);
1324 _formatQueryOrGroup: function (queryInfo, totalTime) {
1325 var grouped, queryText, queryTime, count, i;
1326 if (Array.isArray(queryInfo)) {
1330 queryText = queryInfo[0].query;
1333 for (i in queryInfo) {
1334 queryTime += queryInfo[i].time;
1337 count = queryInfo.length;
1339 queryText = queryInfo.query;
1340 queryTime = queryInfo.time;
1343 var $query = $('<div class="message collapsed hide_trace">')
1345 $('#debug_console').find('.templates .debug_query').clone()
1348 $('<div class="query">')
1351 .data('queryInfo', queryInfo)
1352 .data('totalTime', totalTime);
1354 $query.find('.text.count').removeClass('hide');
1355 $query.find('.text.count span').text(count);
1357 $query.find('.text.time span').text(queryTime + 's (' + ((queryTime * 100) / totalTime).toFixed(3) + '%)');
1361 _appendQueryExtraInfo: function (query, $elem) {
1362 if ('error' in query) {
1364 $('<div>').html(query.error)
1367 $elem.append(this._formatBackTrace(query.trace));
1369 getQueryDetails: function (queryInfo, totalTime, $query) {
1370 if (Array.isArray(queryInfo)) {
1372 for (var i in queryInfo) {
1373 $singleQuery = $('<div class="message welcome trace">')
1374 .text((parseInt(i) + 1) + '.')
1376 $('<span class="time">').text(
1377 PMA_messages.strConsoleDebugTimeTaken +
1378 ' ' + queryInfo[i].time + 's' +
1379 ' (' + ((queryInfo[i].time * 100) / totalTime).toFixed(3) + '%)'
1382 this._appendQueryExtraInfo(queryInfo[i], $singleQuery);
1384 .append('<div class="message welcome trace">')
1385 .append($singleQuery);
1388 this._appendQueryExtraInfo(queryInfo, $query);
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)) {
1404 debugJson = {queries: []};
1405 for (i in debugInfo.queries) {
1406 debugJson.queries[i] = debugInfo.queries[i];
1409 } else if (typeof debugInfo === "string") {
1411 debugJson = JSON.parse(debugInfo);
1415 if (debugJson && !('queries' in debugJson)) {
1419 if (debugJson === false) {
1420 $("#debug_console").find(".debug>.welcome").text(
1421 PMA_messages.strConsoleDebugError
1425 var allQueries = debugJson.queries;
1426 var uniqueQueries = {};
1428 var totalExec = allQueries.length;
1430 // Calculate total time and make unique query array
1432 for (i = 0; i < totalExec; ++i) {
1433 totalTime += allQueries[i].time;
1434 if (!(allQueries[i].hash in uniqueQueries)) {
1435 uniqueQueries[allQueries[i].hash] = [];
1437 uniqueQueries[allQueries[i].hash].push(allQueries[i]);
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)) {
1444 uniqueArray.push(uniqueQueries[hash]);
1447 uniqueQueries = uniqueArray;
1449 $("#debug_console").find(".debug>.welcome").append(
1450 $('<span class="debug_summary">').text(
1452 PMA_messages.strConsoleDebugSummary,
1460 $("#debug_console").find(".debug>.welcome").append(
1461 $('<span class="script_name">').text(url.split('?')[0])
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)) {
1470 var timeA = 0, timeB = 0, i;
1477 return (timeA - timeB) * order;
1479 return (a.time - b.time) * order;
1483 function sortByCount(a, b) {
1484 var order = ((PMA_consoleDebug.configParam('order') == 'asc') ? 1 : -1);
1485 return (a.length - b.length) * order;
1488 var orderBy = this.configParam('orderBy');
1489 var order = PMA_consoleDebug.configParam('order');
1491 if (this.configParam('groupQueries')) {
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();
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();
1506 $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(uniqueQueries[i], totalTime));
1509 if (orderBy == 'time') {
1510 allQueries.sort(sortByTime);
1511 } else if (order == 'desc') {
1512 allQueries.reverse();
1514 for (i = 0; i < totalExec; ++i) {
1515 $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(allQueries[i], totalTime));
1519 PMA_consoleMessages._msgEventBinds($('#debug_console').find('.message:not(.binded)'));
1521 refresh: function () {
1522 var last = this._lastDebugInfo;
1523 PMA_consoleDebug.showLog(last.debugInfo, last.url);
1528 * Executed on page load
1531 PMA_console.initialize();