diff options
author | Deven Bansod <devenbansod@users.noreply.github.com> | 2018-08-28 08:00:16 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-08-28 08:00:16 +0300 |
commit | e12e38bd373c72c7f57e9d450c4021096e3e7911 (patch) | |
tree | 526dde3e92e10273d6e2a1a7c641548257d4faa9 | |
parent | d031dec87a1e3f9cc1fceee1195d11acdba80383 (diff) | |
parent | f08db2e8a86db50ce6170e2616fe7e5f065b8f82 (diff) |
Merge pull request #14584 from Piyush3079/Mod_Js_DST_Cleanup
Code cleanup for Server, Database and Table related files
72 files changed, 516 insertions, 11440 deletions
diff --git a/js/console.js b/js/console.js deleted file mode 100644 index 98a4716c6f..0000000000 --- a/js/console.js +++ /dev/null @@ -1,1495 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * Used in or for console - * - * @package phpMyAdmin-Console - */ - -/** - * Console object - */ -var PMA_console = { - /** - * @var object, jQuery object, selector is '#pma_console>.content' - * @access private - */ - $consoleContent: null, - /** - * @var object, jQuery object, selector is '#pma_console .content', - * used for resizer - * @access private - */ - $consoleAllContents: null, - /** - * @var object, jQuery object, selector is '#pma_console .toolbar' - * @access private - */ - $consoleToolbar: null, - /** - * @var object, jQuery object, selector is '#pma_console .template' - * @access private - */ - $consoleTemplates: null, - /** - * @var object, jQuery object, form for submit - * @access private - */ - $requestForm: null, - /** - * @var object, contain console config - * @access private - */ - config: null, - /** - * @var bool, if console element exist, it'll be true - * @access public - */ - isEnabled: false, - /** - * @var bool, make sure console events bind only once - * @access private - */ - isInitialized: false, - /** - * Used for console initialize, reinit is ok, just some variable assignment - * - * @return void - */ - initialize: function () { - if ($('#pma_console').length === 0) { - return; - } - - PMA_console.config = configGet('Console', false); - - PMA_console.isEnabled = true; - - // Vars init - PMA_console.$consoleToolbar = $('#pma_console').find('>.toolbar'); - PMA_console.$consoleContent = $('#pma_console').find('>.content'); - PMA_console.$consoleAllContents = $('#pma_console').find('.content'); - PMA_console.$consoleTemplates = $('#pma_console').find('>.templates'); - - // Generate a from for post - PMA_console.$requestForm = $('<form method="post" action="import.php">' + - '<input name="is_js_confirmed" value="0">' + - '<textarea name="sql_query"></textarea>' + - '<input name="console_message_id" value="0">' + - '<input name="server" value="">' + - '<input name="db" value="">' + - '<input name="table" value="">' + - '<input name="token" value="">' + - '</form>' - ); - PMA_console.$requestForm.children('[name=token]').val(PMA_commonParams.get('token')); - PMA_console.$requestForm.on('submit', AJAX.requestHandler); - - // Event binds shouldn't run again - if (PMA_console.isInitialized === false) { - // Load config first - if (PMA_console.config.AlwaysExpand === true) { - $('#pma_console_options input[name=always_expand]').prop('checked', true); - } - if (PMA_console.config.StartHistory === true) { - $('#pma_console_options').find('input[name=start_history]').prop('checked', true); - } - if (PMA_console.config.CurrentQuery === true) { - $('#pma_console_options').find('input[name=current_query]').prop('checked', true); - } - if (PMA_console.config.EnterExecutes === true) { - $('#pma_console_options').find('input[name=enter_executes]').prop('checked', true); - } - if (PMA_console.config.DarkTheme === true) { - $('#pma_console_options').find('input[name=dark_theme]').prop('checked', true); - $('#pma_console').find('>.content').addClass('console_dark_theme'); - } - - PMA_consoleResizer.initialize(); - PMA_consoleInput.initialize(); - PMA_consoleMessages.initialize(); - PMA_consoleBookmarks.initialize(); - PMA_consoleDebug.initialize(); - - PMA_console.$consoleToolbar.children('.console_switch').on('click', PMA_console.toggle); - - $('#pma_console').find('.toolbar').children().on('mousedown', function (event) { - event.preventDefault(); - event.stopImmediatePropagation(); - }); - - $('#pma_console').find('.button.clear').on('click', function () { - PMA_consoleMessages.clear(); - }); - - $('#pma_console').find('.button.history').on('click', function () { - PMA_consoleMessages.showHistory(); - }); - - $('#pma_console').find('.button.options').on('click', function () { - PMA_console.showCard('#pma_console_options'); - }); - - $('#pma_console').find('.button.debug').on('click', function () { - PMA_console.showCard('#debug_console'); - }); - - PMA_console.$consoleContent.on('click', function (event) { - if (event.target === this) { - PMA_consoleInput.focus(); - } - }); - - $('#pma_console').find('.mid_layer').on('click', function () { - PMA_console.hideCard($(this).parent().children('.card')); - }); - $('#debug_console').find('.switch_button').on('click', function () { - PMA_console.hideCard($(this).closest('.card')); - }); - $('#pma_bookmarks').find('.switch_button').on('click', function () { - PMA_console.hideCard($(this).closest('.card')); - }); - $('#pma_console_options').find('.switch_button').on('click', function () { - PMA_console.hideCard($(this).closest('.card')); - }); - - $('#pma_console_options').find('input[type=checkbox]').on('change', function () { - PMA_console.updateConfig(); - }); - - $('#pma_console_options').find('.button.default').on('click', function () { - $('#pma_console_options input[name=always_expand]').prop('checked', false); - $('#pma_console_options').find('input[name=start_history]').prop('checked', false); - $('#pma_console_options').find('input[name=current_query]').prop('checked', true); - $('#pma_console_options').find('input[name=enter_executes]').prop('checked', false); - $('#pma_console_options').find('input[name=dark_theme]').prop('checked', false); - PMA_console.updateConfig(); - }); - - $('#pma_console_options').find('input[name=enter_executes]').on('change', function () { - PMA_consoleMessages.showInstructions(PMA_console.config.EnterExecutes); - }); - - $(document).ajaxComplete(function (event, xhr, ajaxOptions) { - if (ajaxOptions.dataType && ajaxOptions.dataType.indexOf('json') !== -1) { - return; - } - if (xhr.status !== 200) { - return; - } - try { - var data = JSON.parse(xhr.responseText); - PMA_console.ajaxCallback(data); - } catch (e) { - console.trace(); - console.log('Failed to parse JSON: ' + e.message); - } - }); - - PMA_console.isInitialized = true; - } - - // Change console mode from cookie - switch (PMA_console.config.Mode) { - case 'collapse': - PMA_console.collapse(); - break; - /* jshint -W086 */// no break needed in default section - default: - PMA_console.setConfig('Mode', 'info'); - case 'info': - /* jshint +W086 */ - PMA_console.info(); - break; - case 'show': - PMA_console.show(true); - PMA_console.scrollBottom(); - break; - } - }, - /** - * Execute query and show results in console - * - * @return void - */ - execute: function (queryString, options) { - if (typeof(queryString) !== 'string' || ! /[a-z]|[A-Z]/.test(queryString)) { - return; - } - PMA_console.$requestForm.children('textarea').val(queryString); - PMA_console.$requestForm.children('[name=server]').attr('value', PMA_commonParams.get('server')); - if (options && options.db) { - PMA_console.$requestForm.children('[name=db]').val(options.db); - if (options.table) { - PMA_console.$requestForm.children('[name=table]').val(options.table); - } else { - PMA_console.$requestForm.children('[name=table]').val(''); - } - } else { - PMA_console.$requestForm.children('[name=db]').val( - (PMA_commonParams.get('db').length > 0 ? PMA_commonParams.get('db') : '')); - } - PMA_console.$requestForm.find('[name=profiling]').remove(); - if (options && options.profiling === true) { - PMA_console.$requestForm.append('<input name="profiling" value="on">'); - } - if (! confirmQuery(PMA_console.$requestForm[0], PMA_console.$requestForm.children('textarea')[0].value)) { - return; - } - PMA_console.$requestForm.children('[name=console_message_id]') - .val(PMA_consoleMessages.appendQuery({ sql_query: queryString }).message_id); - PMA_console.$requestForm.trigger('submit'); - PMA_consoleInput.clear(); - PMA_reloadNavigation(); - }, - ajaxCallback: function (data) { - if (data && data.console_message_id) { - PMA_consoleMessages.updateQuery(data.console_message_id, data.success, - (data._reloadQuerywindow ? data._reloadQuerywindow : false)); - } else if (data && data._reloadQuerywindow) { - if (data._reloadQuerywindow.sql_query.length > 0) { - PMA_consoleMessages.appendQuery(data._reloadQuerywindow, 'successed') - .$message.addClass(PMA_console.config.CurrentQuery ? '' : 'hide'); - } - } - }, - /** - * Change console to collapse mode - * - * @return void - */ - collapse: function () { - PMA_console.setConfig('Mode', 'collapse'); - var pmaConsoleHeight = Math.max(92, PMA_console.config.Height); - - PMA_console.$consoleToolbar.addClass('collapsed'); - PMA_console.$consoleAllContents.height(pmaConsoleHeight); - PMA_console.$consoleContent.stop(); - PMA_console.$consoleContent.animate({ 'margin-bottom': -1 * PMA_console.$consoleContent.outerHeight() + 'px' }, - 'fast', 'easeOutQuart', function () { - PMA_console.$consoleContent.css({ display:'none' }); - $(window).trigger('resize'); - }); - PMA_console.hideCard(); - }, - /** - * Show console - * - * @param bool inputFocus If true, focus the input line after show() - * @return void - */ - show: function (inputFocus) { - PMA_console.setConfig('Mode', 'show'); - - var pmaConsoleHeight = Math.max(92, PMA_console.config.Height); - pmaConsoleHeight = Math.min(PMA_console.config.Height, (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - 25); - PMA_console.$consoleContent.css({ display:'block' }); - if (PMA_console.$consoleToolbar.hasClass('collapsed')) { - PMA_console.$consoleToolbar.removeClass('collapsed'); - } - PMA_console.$consoleAllContents.height(pmaConsoleHeight); - PMA_console.$consoleContent.stop(); - PMA_console.$consoleContent.animate({ 'margin-bottom': 0 }, - 'fast', 'easeOutQuart', function () { - $(window).trigger('resize'); - if (inputFocus) { - PMA_consoleInput.focus(); - } - }); - }, - /** - * Change console to SQL information mode - * this mode shows current SQL query - * This mode is the default mode - * - * @return void - */ - info: function () { - // Under construction - PMA_console.collapse(); - }, - /** - * Toggle console mode between collapse/show - * Used for toggle buttons and shortcuts - * - * @return void - */ - toggle: function () { - switch (PMA_console.config.Mode) { - case 'collapse': - case 'info': - PMA_console.show(true); - break; - case 'show': - PMA_console.collapse(); - break; - default: - PMA_consoleInitialize(); - } - }, - /** - * Scroll console to bottom - * - * @return void - */ - scrollBottom: function () { - PMA_console.$consoleContent.scrollTop(PMA_console.$consoleContent.prop('scrollHeight')); - }, - /** - * Show card - * - * @param string cardSelector Selector, select string will be "#pma_console " + cardSelector - * this param also can be JQuery object, if you need. - * - * @return void - */ - showCard: function (cardSelector) { - var $card = null; - if (typeof(cardSelector) !== 'string') { - if (cardSelector.length > 0) { - $card = cardSelector; - } else { - return; - } - } else { - $card = $('#pma_console ' + cardSelector); - } - if ($card.length === 0) { - return; - } - $card.parent().children('.mid_layer').show().fadeTo(0, 0.15); - $card.addClass('show'); - PMA_consoleInput.blur(); - if ($card.parents('.card').length > 0) { - PMA_console.showCard($card.parents('.card')); - } - }, - /** - * Scroll console to bottom - * - * @param object $targetCard Target card JQuery object, if it's empty, function will hide all cards - * @return void - */ - hideCard: function ($targetCard) { - if (! $targetCard) { - $('#pma_console').find('.mid_layer').fadeOut(140); - $('#pma_console').find('.card').removeClass('show'); - } else if ($targetCard.length > 0) { - $targetCard.parent().find('.mid_layer').fadeOut(140); - $targetCard.find('.card').removeClass('show'); - $targetCard.removeClass('show'); - } - }, - /** - * Used for update console config - * - * @return void - */ - updateConfig: function () { - PMA_console.setConfig('AlwaysExpand', $('#pma_console_options input[name=always_expand]').prop('checked')); - PMA_console.setConfig('StartHistory', $('#pma_console_options').find('input[name=start_history]').prop('checked')); - PMA_console.setConfig('CurrentQuery', $('#pma_console_options').find('input[name=current_query]').prop('checked')); - PMA_console.setConfig('EnterExecutes', $('#pma_console_options').find('input[name=enter_executes]').prop('checked')); - PMA_console.setConfig('DarkTheme', $('#pma_console_options').find('input[name=dark_theme]').prop('checked')); - /* Setting the dark theme of the console*/ - if (PMA_console.config.DarkTheme) { - $('#pma_console').find('>.content').addClass('console_dark_theme'); - } else { - $('#pma_console').find('>.content').removeClass('console_dark_theme'); - } - }, - setConfig: function (key, value) { - PMA_console.config[key] = value; - configSet('Console/' + key, value); - }, - isSelect: function (queryString) { - var reg_exp = /^SELECT\s+/i; - return reg_exp.test(queryString); - } -}; - -/** - * Resizer object - * Careful: this object UI logics highly related with functions under PMA_console - * Resizing min-height is 32, if small than it, console will collapse - */ -var PMA_consoleResizer = { - _posY: 0, - _height: 0, - _resultHeight: 0, - /** - * Mousedown event handler for bind to resizer - * - * @return void - */ - _mousedown: function (event) { - if (PMA_console.config.Mode !== 'show') { - return; - } - PMA_consoleResizer._posY = event.pageY; - PMA_consoleResizer._height = PMA_console.$consoleContent.height(); - $(document).mousemove(PMA_consoleResizer._mousemove); - $(document).mouseup(PMA_consoleResizer._mouseup); - // Disable text selection while resizing - $(document).on('selectstart', function () { - return false; - }); - }, - /** - * Mousemove event handler for bind to resizer - * - * @return void - */ - _mousemove: function (event) { - if (event.pageY < 35) { - event.pageY = 35; - } - PMA_consoleResizer._resultHeight = PMA_consoleResizer._height + (PMA_consoleResizer._posY - event.pageY); - // Content min-height is 32, if adjusting height small than it we'll move it out of the page - if (PMA_consoleResizer._resultHeight <= 32) { - PMA_console.$consoleAllContents.height(32); - PMA_console.$consoleContent.css('margin-bottom', PMA_consoleResizer._resultHeight - 32); - } else { - // Logic below makes viewable area always at bottom when adjusting height and content already at bottom - if (PMA_console.$consoleContent.scrollTop() + PMA_console.$consoleContent.innerHeight() + 16 - >= PMA_console.$consoleContent.prop('scrollHeight')) { - PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight); - PMA_console.scrollBottom(); - } else { - PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight); - } - } - }, - /** - * Mouseup event handler for bind to resizer - * - * @return void - */ - _mouseup: function () { - PMA_console.setConfig('Height', PMA_consoleResizer._resultHeight); - PMA_console.show(); - $(document).off('mousemove'); - $(document).off('mouseup'); - $(document).off('selectstart'); - }, - /** - * Used for console resizer initialize - * - * @return void - */ - initialize: function () { - $('#pma_console').find('.toolbar').off('mousedown'); - $('#pma_console').find('.toolbar').on('mousedown', PMA_consoleResizer._mousedown); - } -}; - - -/** - * Console input object - */ -var PMA_consoleInput = { - /** - * @var array, contains Codemirror objects or input jQuery objects - * @access private - */ - _inputs: null, - /** - * @var bool, if codemirror enabled - * @access private - */ - _codemirror: false, - /** - * @var int, count for history navigation, 0 for current input - * @access private - */ - _historyCount: 0, - /** - * @var string, current input when navigating through history - * @access private - */ - _historyPreserveCurrent: null, - /** - * Used for console input initialize - * - * @return void - */ - initialize: function () { - // _cm object can't be reinitialize - if (PMA_consoleInput._inputs !== null) { - return; - } - if (typeof CodeMirror !== 'undefined') { - PMA_consoleInput._codemirror = true; - } - PMA_consoleInput._inputs = []; - if (PMA_consoleInput._codemirror) { - PMA_consoleInput._inputs.console = CodeMirror($('#pma_console').find('.console_query_input')[0], { - theme: 'pma', - mode: 'text/x-sql', - lineWrapping: true, - extraKeys: { 'Ctrl-Space': 'autocomplete' }, - hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true }, - gutters: ['CodeMirror-lint-markers'], - lint: { - 'getAnnotations': CodeMirror.sqlLint, - 'async': true, - } - }); - PMA_consoleInput._inputs.console.on('inputRead', codemirrorAutocompleteOnInputRead); - PMA_consoleInput._inputs.console.on('keydown', function (instance, event) { - PMA_consoleInput._historyNavigate(event); - }); - if ($('#pma_bookmarks').length !== 0) { - PMA_consoleInput._inputs.bookmark = CodeMirror($('#pma_console').find('.bookmark_add_input')[0], { - theme: 'pma', - mode: 'text/x-sql', - lineWrapping: true, - extraKeys: { 'Ctrl-Space': 'autocomplete' }, - hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true }, - gutters: ['CodeMirror-lint-markers'], - lint: { - 'getAnnotations': CodeMirror.sqlLint, - 'async': true, - } - }); - PMA_consoleInput._inputs.bookmark.on('inputRead', codemirrorAutocompleteOnInputRead); - } - } else { - PMA_consoleInput._inputs.console = - $('<textarea>').appendTo('#pma_console .console_query_input') - .on('keydown', PMA_consoleInput._historyNavigate); - if ($('#pma_bookmarks').length !== 0) { - PMA_consoleInput._inputs.bookmark = - $('<textarea>').appendTo('#pma_console .bookmark_add_input'); - } - } - $('#pma_console').find('.console_query_input').on('keydown', PMA_consoleInput._keydown); - }, - _historyNavigate: function (event) { - if (event.keyCode === 38 || event.keyCode === 40) { - var upPermitted = false; - var downPermitted = false; - var editor = PMA_consoleInput._inputs.console; - var cursorLine; - var totalLine; - if (PMA_consoleInput._codemirror) { - cursorLine = editor.getCursor().line; - totalLine = editor.lineCount(); - } else { - // Get cursor position from textarea - var text = PMA_consoleInput.getText(); - cursorLine = text.substr(0, editor.prop('selectionStart')).split('\n').length - 1; - totalLine = text.split(/\r*\n/).length; - } - if (cursorLine === 0) { - upPermitted = true; - } - if (cursorLine === totalLine - 1) { - downPermitted = true; - } - var nextCount; - var queryString = false; - if (upPermitted && event.keyCode === 38) { - // Navigate up in history - if (PMA_consoleInput._historyCount === 0) { - PMA_consoleInput._historyPreserveCurrent = PMA_consoleInput.getText(); - } - nextCount = PMA_consoleInput._historyCount + 1; - queryString = PMA_consoleMessages.getHistory(nextCount); - } else if (downPermitted && event.keyCode === 40) { - // Navigate down in history - if (PMA_consoleInput._historyCount === 0) { - return; - } - nextCount = PMA_consoleInput._historyCount - 1; - if (nextCount === 0) { - queryString = PMA_consoleInput._historyPreserveCurrent; - } else { - queryString = PMA_consoleMessages.getHistory(nextCount); - } - } - if (queryString !== false) { - PMA_consoleInput._historyCount = nextCount; - PMA_consoleInput.setText(queryString, 'console'); - if (PMA_consoleInput._codemirror) { - editor.setCursor(editor.lineCount(), 0); - } - event.preventDefault(); - } - } - }, - /** - * Mousedown event handler for bind to input - * Shortcut is Ctrl+Enter key or just ENTER, depending on console's - * configuration. - * - * @return void - */ - _keydown: function (event) { - if (PMA_console.config.EnterExecutes) { - // Enter, but not in combination with Shift (which writes a new line). - if (!event.shiftKey && event.keyCode === 13) { - PMA_consoleInput.execute(); - } - } else { - // Ctrl+Enter - if (event.ctrlKey && event.keyCode === 13) { - PMA_consoleInput.execute(); - } - } - }, - /** - * Used for send text to PMA_console.execute() - * - * @return void - */ - execute: function () { - if (PMA_consoleInput._codemirror) { - PMA_console.execute(PMA_consoleInput._inputs.console.getValue()); - } else { - PMA_console.execute(PMA_consoleInput._inputs.console.val()); - } - }, - /** - * Used for clear the input - * - * @param string target, default target is console input - * @return void - */ - clear: function (target) { - PMA_consoleInput.setText('', target); - }, - /** - * Used for set focus to input - * - * @return void - */ - focus: function () { - PMA_consoleInput._inputs.console.focus(); - }, - /** - * Used for blur input - * - * @return void - */ - blur: function () { - if (PMA_consoleInput._codemirror) { - PMA_consoleInput._inputs.console.getInputField().blur(); - } else { - PMA_consoleInput._inputs.console.blur(); - } - }, - /** - * Used for set text in input - * - * @param string text - * @param string target - * @return void - */ - setText: function (text, target) { - if (PMA_consoleInput._codemirror) { - switch (target) { - case 'bookmark': - PMA_console.execute(PMA_consoleInput._inputs.bookmark.setValue(text)); - break; - default: - case 'console': - PMA_console.execute(PMA_consoleInput._inputs.console.setValue(text)); - } - } else { - switch (target) { - case 'bookmark': - PMA_console.execute(PMA_consoleInput._inputs.bookmark.val(text)); - break; - default: - case 'console': - PMA_console.execute(PMA_consoleInput._inputs.console.val(text)); - } - } - }, - getText: function (target) { - if (PMA_consoleInput._codemirror) { - switch (target) { - case 'bookmark': - return PMA_consoleInput._inputs.bookmark.getValue(); - default: - case 'console': - return PMA_consoleInput._inputs.console.getValue(); - } - } else { - switch (target) { - case 'bookmark': - return PMA_consoleInput._inputs.bookmark.val(); - default: - case 'console': - return PMA_consoleInput._inputs.console.val(); - } - } - } - -}; - - -/** - * Console messages, and message items management object - */ -var PMA_consoleMessages = { - /** - * Used for clear the messages - * - * @return void - */ - clear: function () { - $('#pma_console').find('.content .console_message_container .message:not(.welcome)').addClass('hide'); - $('#pma_console').find('.content .console_message_container .message.failed').remove(); - $('#pma_console').find('.content .console_message_container .message.expanded').find('.action.collapse').trigger('click'); - }, - /** - * Used for show history messages - * - * @return void - */ - showHistory: function () { - $('#pma_console').find('.content .console_message_container .message.hide').removeClass('hide'); - }, - /** - * Used for getting a perticular history query - * - * @param int nthLast get nth query message from latest, i.e 1st is last - * @return string message - */ - getHistory: function (nthLast) { - var $queries = $('#pma_console').find('.content .console_message_container .query'); - var length = $queries.length; - var $query = $queries.eq(length - nthLast); - if (!$query || (length - nthLast) < 0) { - return false; - } else { - return $query.text(); - } - }, - /** - * Used to show the correct message depending on which key - * combination executes the query (Ctrl+Enter or Enter). - * - * @param bool enterExecutes Only Enter has to be pressed to execute query. - * @return void - */ - showInstructions: function (enterExecutes) { - enterExecutes = +enterExecutes || 0; // conversion to int - var $welcomeMsg = $('#pma_console').find('.content .console_message_container .message.welcome span'); - $welcomeMsg.children('[id^=instructions]').hide(); - $welcomeMsg.children('#instructions-' + enterExecutes).show(); - }, - /** - * Used for log new message - * - * @param string msgString Message to show - * @param string msgType Message type - * @return object, {message_id, $message} - */ - append: function (msgString, msgType) { - if (typeof(msgString) !== 'string') { - return false; - } - // Generate an ID for each message, we can find them later - var msgId = Math.round(Math.random() * (899999999999) + 100000000000); - var now = new Date(); - var $newMessage = - $('<div class="message ' + - (PMA_console.config.AlwaysExpand ? 'expanded' : 'collapsed') + - '" msgid="' + msgId + '"><div class="action_content"></div></div>'); - switch (msgType) { - case 'query': - $newMessage.append('<div class="query highlighted"></div>'); - if (PMA_consoleInput._codemirror) { - CodeMirror.runMode(msgString, - 'text/x-sql', $newMessage.children('.query')[0]); - } else { - $newMessage.children('.query').text(msgString); - } - $newMessage.children('.action_content') - .append(PMA_console.$consoleTemplates.children('.query_actions').html()); - break; - default: - case 'normal': - $newMessage.append('<div>' + msgString + '</div>'); - } - PMA_consoleMessages._msgEventBinds($newMessage); - $newMessage.find('span.text.query_time span') - .text(now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()) - .parent().attr('title', now); - return { message_id: msgId, - $message: $newMessage.appendTo('#pma_console .content .console_message_container') }; - }, - /** - * Used for log new query - * - * @param string queryData Struct should be - * {sql_query: "Query string", db: "Target DB", table: "Target Table"} - * @param string state Message state - * @return object, {message_id: string message id, $message: JQuery object} - */ - appendQuery: function (queryData, state) { - var targetMessage = PMA_consoleMessages.append(queryData.sql_query, 'query'); - if (! targetMessage) { - return false; - } - if (queryData.db && queryData.table) { - targetMessage.$message.attr('targetdb', queryData.db); - targetMessage.$message.attr('targettable', queryData.table); - targetMessage.$message.find('.text.targetdb span').text(queryData.db); - } - if (PMA_console.isSelect(queryData.sql_query)) { - targetMessage.$message.addClass('select'); - } - switch (state) { - case 'failed': - targetMessage.$message.addClass('failed'); - break; - case 'successed': - targetMessage.$message.addClass('successed'); - break; - default: - case 'pending': - targetMessage.$message.addClass('pending'); - } - return targetMessage; - }, - _msgEventBinds: function ($targetMessage) { - // Leave unbinded elements, remove binded. - $targetMessage = $targetMessage.filter(':not(.binded)'); - if ($targetMessage.length === 0) { - return; - } - $targetMessage.addClass('binded'); - - $targetMessage.find('.action.expand').on('click', function () { - $(this).closest('.message').removeClass('collapsed'); - $(this).closest('.message').addClass('expanded'); - }); - $targetMessage.find('.action.collapse').on('click', function () { - $(this).closest('.message').addClass('collapsed'); - $(this).closest('.message').removeClass('expanded'); - }); - $targetMessage.find('.action.edit').on('click', function () { - PMA_consoleInput.setText($(this).parent().siblings('.query').text()); - PMA_consoleInput.focus(); - }); - $targetMessage.find('.action.requery').on('click', function () { - var query = $(this).parent().siblings('.query').text(); - var $message = $(this).closest('.message'); - if (confirm(PMA_messages.strConsoleRequeryConfirm + '\n' + - (query.length < 100 ? query : query.slice(0, 100) + '...')) - ) { - PMA_console.execute(query, { db: $message.attr('targetdb'), table: $message.attr('targettable') }); - } - }); - $targetMessage.find('.action.bookmark').on('click', function () { - var query = $(this).parent().siblings('.query').text(); - var $message = $(this).closest('.message'); - PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb')); - PMA_console.showCard('#pma_bookmarks .card.add'); - }); - $targetMessage.find('.action.edit_bookmark').on('click', function () { - var query = $(this).parent().siblings('.query').text(); - var $message = $(this).closest('.message'); - var isShared = $message.find('span.bookmark_label').hasClass('shared'); - var label = $message.find('span.bookmark_label').text(); - PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'), label, isShared); - PMA_console.showCard('#pma_bookmarks .card.add'); - }); - $targetMessage.find('.action.delete_bookmark').on('click', function () { - var $message = $(this).closest('.message'); - if (confirm(PMA_messages.strConsoleDeleteBookmarkConfirm + '\n' + $message.find('.bookmark_label').text())) { - $.post('import.php', - { - server: PMA_commonParams.get('server'), - action_bookmark: 2, - ajax_request: true, - id_bookmark: $message.attr('bookmarkid') }, - function () { - PMA_consoleBookmarks.refresh(); - }); - } - }); - $targetMessage.find('.action.profiling').on('click', function () { - var $message = $(this).closest('.message'); - PMA_console.execute($(this).parent().siblings('.query').text(), - { db: $message.attr('targetdb'), - table: $message.attr('targettable'), - profiling: true }); - }); - $targetMessage.find('.action.explain').on('click', function () { - var $message = $(this).closest('.message'); - PMA_console.execute('EXPLAIN ' + $(this).parent().siblings('.query').text(), - { db: $message.attr('targetdb'), - table: $message.attr('targettable') }); - }); - $targetMessage.find('.action.dbg_show_trace').on('click', function () { - var $message = $(this).closest('.message'); - if (!$message.find('.trace').length) { - PMA_consoleDebug.getQueryDetails( - $message.data('queryInfo'), - $message.data('totalTime'), - $message - ); - PMA_consoleMessages._msgEventBinds($message.find('.message:not(.binded)')); - } - $message.addClass('show_trace'); - $message.removeClass('hide_trace'); - }); - $targetMessage.find('.action.dbg_hide_trace').on('click', function () { - var $message = $(this).closest('.message'); - $message.addClass('hide_trace'); - $message.removeClass('show_trace'); - }); - $targetMessage.find('.action.dbg_show_args').on('click', function () { - var $message = $(this).closest('.message'); - $message.addClass('show_args expanded'); - $message.removeClass('hide_args collapsed'); - }); - $targetMessage.find('.action.dbg_hide_args').on('click', function () { - var $message = $(this).closest('.message'); - $message.addClass('hide_args collapsed'); - $message.removeClass('show_args expanded'); - }); - if (PMA_consoleInput._codemirror) { - $targetMessage.find('.query:not(.highlighted)').each(function (index, elem) { - CodeMirror.runMode($(elem).text(), - 'text/x-sql', elem); - $(this).addClass('highlighted'); - }); - } - }, - msgAppend: function (msgId, msgString, msgType) { - var $targetMessage = $('#pma_console').find('.content .console_message_container .message[msgid=' + msgId + ']'); - if ($targetMessage.length === 0 || isNaN(parseInt(msgId)) || typeof(msgString) !== 'string') { - return false; - } - $targetMessage.append('<div>' + msgString + '</div>'); - }, - updateQuery: function (msgId, isSuccessed, queryData) { - var $targetMessage = $('#pma_console').find('.console_message_container .message[msgid=' + parseInt(msgId) + ']'); - if ($targetMessage.length === 0 || isNaN(parseInt(msgId))) { - return false; - } - $targetMessage.removeClass('pending failed successed'); - if (isSuccessed) { - $targetMessage.addClass('successed'); - if (queryData) { - $targetMessage.children('.query').text(''); - $targetMessage.removeClass('select'); - if (PMA_console.isSelect(queryData.sql_query)) { - $targetMessage.addClass('select'); - } - if (PMA_consoleInput._codemirror) { - CodeMirror.runMode(queryData.sql_query, 'text/x-sql', $targetMessage.children('.query')[0]); - } else { - $targetMessage.children('.query').text(queryData.sql_query); - } - $targetMessage.attr('targetdb', queryData.db); - $targetMessage.attr('targettable', queryData.table); - $targetMessage.find('.text.targetdb span').text(queryData.db); - } - } else { - $targetMessage.addClass('failed'); - } - }, - /** - * Used for console messages initialize - * - * @return void - */ - initialize: function () { - PMA_consoleMessages._msgEventBinds($('#pma_console').find('.message:not(.binded)')); - if (PMA_console.config.StartHistory) { - PMA_consoleMessages.showHistory(); - } - PMA_consoleMessages.showInstructions(PMA_console.config.EnterExecutes); - } -}; - - -/** - * Console bookmarks card, and bookmarks items management object - */ -var PMA_consoleBookmarks = { - _bookmarks: [], - addBookmark: function (queryString, targetDb, label, isShared, id) { - $('#pma_bookmarks').find('.add [name=shared]').prop('checked', false); - $('#pma_bookmarks').find('.add [name=label]').val(''); - $('#pma_bookmarks').find('.add [name=targetdb]').val(''); - $('#pma_bookmarks').find('.add [name=id_bookmark]').val(''); - PMA_consoleInput.setText('', 'bookmark'); - - switch (arguments.length) { - case 4: - $('#pma_bookmarks').find('.add [name=shared]').prop('checked', isShared); - case 3: - $('#pma_bookmarks').find('.add [name=label]').val(label); - case 2: - $('#pma_bookmarks').find('.add [name=targetdb]').val(targetDb); - case 1: - PMA_consoleInput.setText(queryString, 'bookmark'); - default: - break; - } - }, - refresh: function () { - $.get('import.php', - { ajax_request: true, - server: PMA_commonParams.get('server'), - console_bookmark_refresh: 'refresh' }, - function (data) { - if (data.console_message_bookmark) { - $('#pma_bookmarks').find('.content.bookmark').html(data.console_message_bookmark); - PMA_consoleMessages._msgEventBinds($('#pma_bookmarks').find('.message:not(.binded)')); - } - }); - }, - /** - * Used for console bookmarks initialize - * message events are already binded by PMA_consoleMsg._msgEventBinds - * - * @return void - */ - initialize: function () { - if ($('#pma_bookmarks').length === 0) { - return; - } - $('#pma_console').find('.button.bookmarks').on('click', function () { - PMA_console.showCard('#pma_bookmarks'); - }); - $('#pma_bookmarks').find('.button.add').on('click', function () { - PMA_console.showCard('#pma_bookmarks .card.add'); - }); - $('#pma_bookmarks').find('.card.add [name=submit]').on('click', function () { - if ($('#pma_bookmarks').find('.card.add [name=label]').val().length === 0 - || PMA_consoleInput.getText('bookmark').length === 0) { - alert(PMA_messages.strFormEmpty); - return; - } - $(this).prop('disabled', true); - $.post('import.php', - { - ajax_request: true, - console_bookmark_add: 'true', - label: $('#pma_bookmarks').find('.card.add [name=label]').val(), - server: PMA_commonParams.get('server'), - db: $('#pma_bookmarks').find('.card.add [name=targetdb]').val(), - bookmark_query: PMA_consoleInput.getText('bookmark'), - shared: $('#pma_bookmarks').find('.card.add [name=shared]').prop('checked') }, - function () { - PMA_consoleBookmarks.refresh(); - $('#pma_bookmarks').find('.card.add [name=submit]').prop('disabled', false); - PMA_console.hideCard($('#pma_bookmarks').find('.card.add')); - }); - }); - $('#pma_console').find('.button.refresh').on('click', function () { - PMA_consoleBookmarks.refresh(); - }); - } -}; - -var PMA_consoleDebug; -PMA_consoleDebug = { - _config: { - groupQueries: false, - orderBy: 'exec', // Possible 'exec' => Execution order, 'time' => Time taken, 'count' - order: 'asc' // Possible 'asc', 'desc' - }, - _lastDebugInfo: { - debugInfo: null, - url: null - }, - initialize: function () { - // Try to get debug info after every AJAX request - $(document).ajaxSuccess(function (event, xhr, settings, data) { - if (data._debug) { - PMA_consoleDebug.showLog(data._debug, settings.url); - } - }); - - if (PMA_console.config.GroupQueries) { - $('#debug_console').addClass('grouped'); - } else { - $('#debug_console').addClass('ungrouped'); - if (PMA_console.config.OrderBy === 'count') { - $('#debug_console').find('.button.order_by.sort_exec').addClass('active'); - } - } - var orderBy = PMA_console.config.OrderBy; - var order = PMA_console.config.Order; - $('#debug_console').find('.button.order_by.sort_' + orderBy).addClass('active'); - $('#debug_console').find('.button.order.order_' + order).addClass('active'); - - // Initialize actions in toolbar - $('#debug_console').find('.button.group_queries').on('click', function () { - $('#debug_console').addClass('grouped'); - $('#debug_console').removeClass('ungrouped'); - PMA_console.setConfig('GroupQueries', true); - PMA_consoleDebug.refresh(); - if (PMA_console.config.OrderBy === 'count') { - $('#debug_console').find('.button.order_by.sort_exec').removeClass('active'); - } - }); - $('#debug_console').find('.button.ungroup_queries').on('click', function () { - $('#debug_console').addClass('ungrouped'); - $('#debug_console').removeClass('grouped'); - PMA_console.setConfig('GroupQueries', false); - PMA_consoleDebug.refresh(); - if (PMA_console.config.OrderBy === 'count') { - $('#debug_console').find('.button.order_by.sort_exec').addClass('active'); - } - }); - $('#debug_console').find('.button.order_by').on('click', function () { - var $this = $(this); - $('#debug_console').find('.button.order_by').removeClass('active'); - $this.addClass('active'); - if ($this.hasClass('sort_time')) { - PMA_console.setConfig('OrderBy', 'time'); - } else if ($this.hasClass('sort_exec')) { - PMA_console.setConfig('OrderBy', 'exec'); - } else if ($this.hasClass('sort_count')) { - PMA_console.setConfig('OrderBy', 'count'); - } - PMA_consoleDebug.refresh(); - }); - $('#debug_console').find('.button.order').on('click', function () { - var $this = $(this); - $('#debug_console').find('.button.order').removeClass('active'); - $this.addClass('active'); - if ($this.hasClass('order_asc')) { - PMA_console.setConfig('Order', 'asc'); - } else if ($this.hasClass('order_desc')) { - PMA_console.setConfig('Order', 'desc'); - } - PMA_consoleDebug.refresh(); - }); - - // Show SQL debug info for first page load - if (typeof debugSQLInfo !== 'undefined' && debugSQLInfo !== 'null') { - $('#pma_console').find('.button.debug').removeClass('hide'); - } else { - return; - } - PMA_consoleDebug.showLog(debugSQLInfo); - }, - _formatFunctionCall: function (dbgStep) { - var functionName = ''; - if ('class' in dbgStep) { - functionName += dbgStep.class; - functionName += dbgStep.type; - } - functionName += dbgStep.function; - if (dbgStep.args && dbgStep.args.length) { - functionName += '(...)'; - } else { - functionName += '()'; - } - return functionName; - }, - _formatFunctionArgs: function (dbgStep) { - var $args = $('<div>'); - if (dbgStep.args.length) { - $args.append('<div class="message welcome">') - .append( - $('<div class="message welcome">') - .text( - PMA_sprintf( - PMA_messages.strConsoleDebugArgsSummary, - dbgStep.args.length - ) - ) - ); - for (var i = 0; i < dbgStep.args.length; i++) { - $args.append( - $('<div class="message">') - .html( - '<pre>' + - escapeHtml(JSON.stringify(dbgStep.args[i], null, ' ')) + - '</pre>' - ) - ); - } - } - return $args; - }, - _formatFileName: function (dbgStep) { - var fileName = ''; - if ('file' in dbgStep) { - fileName += dbgStep.file; - fileName += '#' + dbgStep.line; - } - return fileName; - }, - _formatBackTrace: function (dbgTrace) { - var $traceElem = $('<div class="trace">'); - $traceElem.append( - $('<div class="message welcome">') - ); - var step; - var $stepElem; - for (var stepId in dbgTrace) { - if (dbgTrace.hasOwnProperty(stepId)) { - step = dbgTrace[stepId]; - if (!Array.isArray(step) && typeof step !== 'object') { - $stepElem = - $('<div class="message traceStep collapsed hide_args">') - .append( - $('<span>').text(step) - ); - } else { - if (typeof step.args === 'string' && step.args) { - step.args = [step.args]; - } - $stepElem = - $('<div class="message traceStep collapsed hide_args">') - .append( - $('<span class="function">').text(this._formatFunctionCall(step)) - ) - .append( - $('<span class="file">').text(this._formatFileName(step)) - ); - if (step.args && step.args.length) { - $stepElem - .append( - $('<span class="args">').html(this._formatFunctionArgs(step)) - ) - .prepend( - $('<div class="action_content">') - .append( - '<span class="action dbg_show_args">' + - PMA_messages.strConsoleDebugShowArgs + - '</span> ' - ) - .append( - '<span class="action dbg_hide_args">' + - PMA_messages.strConsoleDebugHideArgs + - '</span> ' - ) - ); - } - } - $traceElem.append($stepElem); - } - } - return $traceElem; - }, - _formatQueryOrGroup: function (queryInfo, totalTime) { - var grouped; - var queryText; - var queryTime; - var count; - var i; - if (Array.isArray(queryInfo)) { - // It is grouped - grouped = true; - - queryText = queryInfo[0].query; - - queryTime = 0; - for (i in queryInfo) { - queryTime += queryInfo[i].time; - } - - count = queryInfo.length; - } else { - queryText = queryInfo.query; - queryTime = queryInfo.time; - } - - var $query = $('<div class="message collapsed hide_trace">') - .append( - $('#debug_console').find('.templates .debug_query').clone() - ) - .append( - $('<div class="query">') - .text(queryText) - ) - .data('queryInfo', queryInfo) - .data('totalTime', totalTime); - if (grouped) { - $query.find('.text.count').removeClass('hide'); - $query.find('.text.count span').text(count); - } - $query.find('.text.time span').text(queryTime + 's (' + ((queryTime * 100) / totalTime).toFixed(3) + '%)'); - - return $query; - }, - _appendQueryExtraInfo: function (query, $elem) { - if ('error' in query) { - $elem.append( - $('<div>').html(query.error) - ); - } - $elem.append(this._formatBackTrace(query.trace)); - }, - getQueryDetails: function (queryInfo, totalTime, $query) { - if (Array.isArray(queryInfo)) { - var $singleQuery; - for (var i in queryInfo) { - $singleQuery = $('<div class="message welcome trace">') - .text((parseInt(i) + 1) + '.') - .append( - $('<span class="time">').text( - PMA_messages.strConsoleDebugTimeTaken + - ' ' + queryInfo[i].time + 's' + - ' (' + ((queryInfo[i].time * 100) / totalTime).toFixed(3) + '%)' - ) - ); - this._appendQueryExtraInfo(queryInfo[i], $singleQuery); - $query - .append('<div class="message welcome trace">') - .append($singleQuery); - } - } else { - this._appendQueryExtraInfo(queryInfo, $query); - } - }, - showLog: function (debugInfo, url) { - this._lastDebugInfo.debugInfo = debugInfo; - this._lastDebugInfo.url = url; - - $('#debug_console').find('.debugLog').empty(); - $('#debug_console').find('.debug>.welcome').empty(); - - var debugJson = false; - var i; - if (typeof debugInfo === 'object' && 'queries' in debugInfo) { - // Copy it to debugJson, so that it doesn't get changed - if (!('queries' in debugInfo)) { - debugJson = false; - } else { - debugJson = { queries: [] }; - for (i in debugInfo.queries) { - debugJson.queries[i] = debugInfo.queries[i]; - } - } - } else if (typeof debugInfo === 'string') { - try { - debugJson = JSON.parse(debugInfo); - } catch (e) { - debugJson = false; - } - if (debugJson && !('queries' in debugJson)) { - debugJson = false; - } - } - if (debugJson === false) { - $('#debug_console').find('.debug>.welcome').text( - PMA_messages.strConsoleDebugError - ); - return; - } - var allQueries = debugJson.queries; - var uniqueQueries = {}; - - var totalExec = allQueries.length; - - // Calculate total time and make unique query array - var totalTime = 0; - for (i = 0; i < totalExec; ++i) { - totalTime += allQueries[i].time; - if (!(allQueries[i].hash in uniqueQueries)) { - uniqueQueries[allQueries[i].hash] = []; - } - uniqueQueries[allQueries[i].hash].push(allQueries[i]); - } - // Count total unique queries, convert uniqueQueries to Array - var totalUnique = 0; - var uniqueArray = []; - for (var hash in uniqueQueries) { - if (uniqueQueries.hasOwnProperty(hash)) { - ++totalUnique; - uniqueArray.push(uniqueQueries[hash]); - } - } - uniqueQueries = uniqueArray; - // Show summary - $('#debug_console').find('.debug>.welcome').append( - $('<span class="debug_summary">').text( - PMA_sprintf( - PMA_messages.strConsoleDebugSummary, - totalUnique, - totalExec, - totalTime - ) - ) - ); - if (url) { - $('#debug_console').find('.debug>.welcome').append( - $('<span class="script_name">').text(url.split('?')[0]) - ); - } - - // For sorting queries - function sortByTime (a, b) { - var order = ((PMA_console.config.Order === 'asc') ? 1 : -1); - if (Array.isArray(a) && Array.isArray(b)) { - // It is grouped - var timeA = 0; - var timeB = 0; - var i; - for (i in a) { - timeA += a[i].time; - } - for (i in b) { - timeB += b[i].time; - } - return (timeA - timeB) * order; - } else { - return (a.time - b.time) * order; - } - } - - function sortByCount (a, b) { - var order = ((PMA_console.config.Oorder === 'asc') ? 1 : -1); - return (a.length - b.length) * order; - } - - var orderBy = PMA_console.config.OrderBy; - var order = PMA_console.config.Order; - - if (PMA_console.config.GroupQueries) { - // Sort queries - if (orderBy === 'time') { - uniqueQueries.sort(sortByTime); - } else if (orderBy === 'count') { - uniqueQueries.sort(sortByCount); - } else if (orderBy === 'exec' && order === 'desc') { - uniqueQueries.reverse(); - } - for (i in uniqueQueries) { - if (orderBy === 'time') { - uniqueQueries[i].sort(sortByTime); - } else if (orderBy === 'exec' && order === 'desc') { - uniqueQueries[i].reverse(); - } - $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(uniqueQueries[i], totalTime)); - } - } else { - if (orderBy === 'time') { - allQueries.sort(sortByTime); - } else if (order === 'desc') { - allQueries.reverse(); - } - for (i = 0; i < totalExec; ++i) { - $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(allQueries[i], totalTime)); - } - } - - PMA_consoleMessages._msgEventBinds($('#debug_console').find('.message:not(.binded)')); - }, - refresh: function () { - var last = this._lastDebugInfo; - PMA_consoleDebug.showLog(last.debugInfo, last.url); - } -}; - -/** s - * Executed on page load - */ -$(function () { - PMA_console.initialize(); -}); diff --git a/js/db_central_columns.js b/js/db_central_columns.js deleted file mode 100644 index 1faa8a99db..0000000000 --- a/js/db_central_columns.js +++ /dev/null @@ -1,241 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview events handling from central columns page - * @name Central columns - * - * @requires jQuery - */ - -/** - * AJAX scripts for db_central_columns.php - * - * Actions ajaxified here: - * Inline Edit and save of a result row - * Delete a row - * Multiple edit and delete option - * - */ - -AJAX.registerTeardown('db_central_columns.js', function () { - $('.edit').off('click'); - $('.edit_save_form').off('click'); - $('.edit_cancel_form').off('click'); - $('.del_row').off('click'); - $(document).off('keyup', '.filter_rows'); - $('.edit_cancel_form').off('click'); - $('#table-select').off('change'); - $('#column-select').off('change'); - $('#add_col_div').find('>a').off('click'); - $('#add_new').off('submit'); - $('#multi_edit_central_columns').off('submit'); - $('select.default_type').off('change'); - $('button[name=\'delete_central_columns\']').off('click'); - $('button[name=\'edit_central_columns\']').off('click'); -}); - -AJAX.registerOnload('db_central_columns.js', function () { - $('#tableslistcontainer input,#tableslistcontainer select,#tableslistcontainer .default_value,#tableslistcontainer .open_enum_editor').hide(); - $('#tableslistcontainer').find('.checkall').show(); - $('#tableslistcontainer').find('.checkall_box').show(); - if ($('#table_columns').find('tbody tr').length > 0) { - $('#table_columns').tablesorter({ - headers: { - 0: { sorter: false }, - 1: { sorter: false }, // hidden column - 4: { sorter: 'integer' } - } - }); - } - $('#tableslistcontainer').find('button[name="delete_central_columns"]').on('click', function (event) { - event.preventDefault(); - var multi_delete_columns = $('.checkall:checkbox:checked').serialize(); - if (multi_delete_columns === '') { - PMA_ajaxShowMessage(PMA_messages.strRadioUnchecked); - return false; - } - PMA_ajaxShowMessage(); - $('#del_col_name').val(multi_delete_columns); - $('#del_form').submit(); - }); - $('#tableslistcontainer').find('button[name="edit_central_columns"]').on('click', function (event) { - event.preventDefault(); - var editColumnList = $('.checkall:checkbox:checked').serialize(); - if (editColumnList === '') { - PMA_ajaxShowMessage(PMA_messages.strRadioUnchecked); - return false; - } - var argsep = PMA_commonParams.get('arg_separator'); - var editColumnData = editColumnList + '' + argsep + 'edit_central_columns_page=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + PMA_commonParams.get('db'); - PMA_ajaxShowMessage(); - AJAX.source = $(this); - $.get('db_central_columns.php', editColumnData, AJAX.responseHandler); - }); - $('#multi_edit_central_columns').submit(function (event) { - event.preventDefault(); - event.stopPropagation(); - var argsep = PMA_commonParams.get('arg_separator'); - var multi_column_edit_data = $('#multi_edit_central_columns').serialize() + argsep + 'multi_edit_central_column_save=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + encodeURIComponent(PMA_commonParams.get('db')); - PMA_ajaxShowMessage(); - AJAX.source = $(this); - $.post('db_central_columns.php', multi_column_edit_data, AJAX.responseHandler); - }); - $('#add_new').find('td').each(function () { - if ($(this).attr('name') !== 'undefined') { - $(this).find('input,select:first').attr('name', $(this).attr('name')); - } - }); - $('#field_0_0').attr('required','required'); - $('#add_new input[type="text"], #add_new input[type="number"], #add_new select') - .css({ - 'width' : '10em', - '-moz-box-sizing' : 'border-box' - }); - window.scrollTo(0, 0); - $(document).on('keyup', '.filter_rows', function () { - // get the column names - var cols = $('th.column_heading').map(function () { - return $.trim($(this).text()); - }).get(); - $.uiTableFilter($('#table_columns'), $(this).val(), cols, null, 'td span'); - }); - $('.edit').on('click', function () { - var rownum = $(this).parent().data('rownum'); - $('#save_' + rownum).show(); - $(this).hide(); - $('#f_' + rownum + ' td span').hide(); - $('#f_' + rownum + ' input, #f_' + rownum + ' select, #f_' + rownum + ' .open_enum_editor').show(); - var attribute_val = $('#f_' + rownum + ' td[name=col_attribute] span').html(); - $('#f_' + rownum + ' select[name=field_attribute\\[' + rownum + '\\] ] option[value="' + attribute_val + '"]').attr('selected','selected'); - if ($('#f_' + rownum + ' .default_type').val() === 'USER_DEFINED') { - $('#f_' + rownum + ' .default_type').siblings('.default_value').show(); - } else { - $('#f_' + rownum + ' .default_type').siblings('.default_value').hide(); - } - }); - $('.del_row').on('click', function (event) { - event.preventDefault(); - event.stopPropagation(); - var $td = $(this); - var question = PMA_messages.strDeleteCentralColumnWarning; - $td.PMA_confirm(question, null, function (url) { - var rownum = $td.data('rownum'); - $('#del_col_name').val('selected_fld%5B%5D=' + $('#checkbox_row_' + rownum).val()); - $('#del_form').submit(); - }); - }); - $('.edit_cancel_form').on('click', function (event) { - event.preventDefault(); - event.stopPropagation(); - var rownum = $(this).data('rownum'); - $('#save_' + rownum).hide(); - $('#edit_' + rownum).show(); - $('#f_' + rownum + ' td span').show(); - $('#f_' + rownum + ' input, #f_' + rownum + ' select,#f_' + rownum + ' .default_value, #f_' + rownum + ' .open_enum_editor').hide(); - $('#tableslistcontainer').find('.checkall').show(); - }); - $('.edit_save_form').on('click', function (event) { - event.preventDefault(); - event.stopPropagation(); - var rownum = $(this).data('rownum'); - $('#f_' + rownum + ' td').each(function () { - if ($(this).attr('name') !== 'undefined') { - $(this).find(':input[type!="hidden"],select:first') - .attr('name', $(this).attr('name')); - } - }); - - if ($('#f_' + rownum + ' .default_type').val() === 'USER_DEFINED') { - $('#f_' + rownum + ' .default_type').attr('name','col_default_sel'); - } else { - $('#f_' + rownum + ' .default_value').attr('name','col_default_val'); - } - - var datastring = $('#f_' + rownum + ' :input').serialize(); - $.ajax({ - type: 'POST', - url: 'db_central_columns.php', - data: datastring + PMA_commonParams.get('arg_separator') + 'ajax_request=true', - dataType: 'json', - success: function (data) { - if (data.message !== '1') { - PMA_ajaxShowMessage( - '<div class="error">' + - data.message + - '</div>', - false - ); - } else { - $('#f_' + rownum + ' td input[id=checkbox_row_' + rownum + ']').val($('#f_' + rownum + ' input[name=col_name]').val()).html(); - $('#f_' + rownum + ' td[name=col_name] span').text($('#f_' + rownum + ' input[name=col_name]').val()).html(); - $('#f_' + rownum + ' td[name=col_type] span').text($('#f_' + rownum + ' select[name=col_type]').val()).html(); - $('#f_' + rownum + ' td[name=col_length] span').text($('#f_' + rownum + ' input[name=col_length]').val()).html(); - $('#f_' + rownum + ' td[name=collation] span').text($('#f_' + rownum + ' select[name=collation]').val()).html(); - $('#f_' + rownum + ' td[name=col_attribute] span').text($('#f_' + rownum + ' select[name=col_attribute]').val()).html(); - $('#f_' + rownum + ' td[name=col_isNull] span').text($('#f_' + rownum + ' input[name=col_isNull]').is(':checked') ? 'Yes' : 'No').html(); - $('#f_' + rownum + ' td[name=col_extra] span').text($('#f_' + rownum + ' input[name=col_extra]').is(':checked') ? 'auto_increment' : '').html(); - $('#f_' + rownum + ' td[name=col_default] span').text($('#f_' + rownum + ' :input[name=col_default]').val()).html(); - } - $('#save_' + rownum).hide(); - $('#edit_' + rownum).show(); - $('#f_' + rownum + ' td span').show(); - $('#f_' + rownum + ' input, #f_' + rownum + ' select,#f_' + rownum + ' .default_value, #f_' + rownum + ' .open_enum_editor').hide(); - $('#tableslistcontainer').find('.checkall').show(); - }, - error: function () { - PMA_ajaxShowMessage( - '<div class="error">' + - PMA_messages.strErrorProcessingRequest + - '</div>', - false - ); - } - }); - }); - $('#table-select').on('change', function (e) { - var selectvalue = $(this).val(); - var default_column_select = $('#column-select').find('option:first'); - var href = 'db_central_columns.php'; - var params = { - 'ajax_request' : true, - 'server' : PMA_commonParams.get('server'), - 'db' : PMA_commonParams.get('db'), - 'selectedTable' : selectvalue, - 'populateColumns' : true - }; - $('#column-select').html('<option value="">' + PMA_messages.strLoading + '</option>'); - if (selectvalue !== '') { - $.post(href, params, function (data) { - $('#column-select').empty().append(default_column_select); - $('#column-select').append(data.message); - }); - } - }); - $('#add_column').submit(function (e) { - var selectvalue = $('#column-select').val(); - if (selectvalue === '') { - e.preventDefault(); - e.stopPropagation(); - } - }); - $('#add_col_div').find('>a').on('click', function (event) { - $('#add_new').slideToggle('slow'); - var $addColDivLinkSpan = $('#add_col_div').find('>a span'); - if ($addColDivLinkSpan.html() === '+') { - $addColDivLinkSpan.html('-'); - } else { - $addColDivLinkSpan.html('+'); - } - }); - $('#add_new').submit(function (event) { - $('#add_new').toggle(); - }); - $('#tableslistcontainer').find('select.default_type').on('change', function () { - if ($(this).val() === 'USER_DEFINED') { - $(this).siblings('.default_value').attr('name','col_default'); - $(this).attr('name','col_default_sel'); - } else { - $(this).attr('name','col_default'); - $(this).siblings('.default_value').attr('name','col_default_val'); - } - }); -}); diff --git a/js/db_operations.js b/js/db_operations.js deleted file mode 100644 index 3c408d89ba..0000000000 --- a/js/db_operations.js +++ /dev/null @@ -1,167 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview function used in server privilege pages - * @name Database Operations - * - * @requires jQuery - * @requires jQueryUI - * @requires js/functions.js - * - */ - -/** - * Ajax event handlers here for db_operations.php - * - * Actions Ajaxified here: - * Rename Database - * Copy Database - * Change Charset - * Drop Database - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('db_operations.js', function () { - $(document).off('submit', '#rename_db_form.ajax'); - $(document).off('submit', '#copy_db_form.ajax'); - $(document).off('submit', '#change_db_charset_form.ajax'); - $(document).off('click', '#drop_db_anchor.ajax'); -}); - -AJAX.registerOnload('db_operations.js', function () { - /** - * Ajax event handlers for 'Rename Database' - */ - $(document).on('submit', '#rename_db_form.ajax', function (event) { - event.preventDefault(); - - var old_db_name = PMA_commonParams.get('db'); - var new_db_name = $('#new_db_name').val(); - - if (new_db_name === old_db_name) { - PMA_ajaxShowMessage(PMA_messages.strDatabaseRenameToSameName, false, 'error'); - return false; - } - - var $form = $(this); - - var question = escapeHtml('CREATE DATABASE ' + new_db_name + ' / DROP DATABASE ' + old_db_name); - - PMA_prepareForAjaxRequest($form); - - $form.PMA_confirm(question, $form.attr('action'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strRenamingDatabases, false); - $.post(url, $('#rename_db_form').serialize() + PMA_commonParams.get('arg_separator') + 'is_js_confirmed=1', function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - PMA_commonParams.set('db', data.newname); - - PMA_reloadNavigation(function () { - $('#pma_navigation_tree') - .find('a:not(\'.expander\')') - .each(function (index) { - var $thisAnchor = $(this); - if ($thisAnchor.text() === data.newname) { - // simulate a click on the new db name - // in navigation - $thisAnchor.trigger('click'); - } - }); - }); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }); - }); // end Rename Database - - /** - * Ajax Event Handler for 'Copy Database' - */ - $(document).on('submit', '#copy_db_form.ajax', function (event) { - event.preventDefault(); - PMA_ajaxShowMessage(PMA_messages.strCopyingDatabase, false); - var $form = $(this); - PMA_prepareForAjaxRequest($form); - $.post($form.attr('action'), $form.serialize(), function (data) { - // use messages that stay on screen - $('div.success, div.error').fadeOut(); - if (typeof data !== 'undefined' && data.success === true) { - if ($('#checkbox_switch').is(':checked')) { - PMA_commonParams.set('db', data.newname); - PMA_commonActions.refreshMain(false, function () { - PMA_ajaxShowMessage(data.message); - }); - } else { - PMA_commonParams.set('db', data.db); - PMA_ajaxShowMessage(data.message); - } - PMA_reloadNavigation(); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }); // end copy database - - /** - * Change tables columns visible only if change tables is checked - */ - $('#span_change_all_tables_columns_collations').hide(); - $('#checkbox_change_all_tables_collations').on('click', function () { - $('#span_change_all_tables_columns_collations').toggle(); - }); - - /** - * Ajax Event handler for 'Change Charset' of the database - */ - $(document).on('submit', '#change_db_charset_form.ajax', function (event) { - event.preventDefault(); - var $form = $(this); - PMA_prepareForAjaxRequest($form); - PMA_ajaxShowMessage(PMA_messages.strChangingCharset); - $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'submitcollation=1', function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }); // end change charset - - /** - * Ajax event handlers for Drop Database - */ - $(document).on('click', '#drop_db_anchor.ajax', function (event) { - event.preventDefault(); - var $link = $(this); - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_messages.strDropDatabaseStrongWarning + ' '; - question += PMA_sprintf( - PMA_messages.strDoYouReally, - 'DROP DATABASE `' + escapeHtml(PMA_commonParams.get('db') + '`') - ); - var params = getJSConfirmCommonParam(this, $link.getPostData()); - - $(this).PMA_confirm(question, $(this).attr('href'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success) { - // Database deleted successfully, refresh both the frames - PMA_reloadNavigation(); - PMA_commonParams.set('db', ''); - PMA_commonActions.refreshMain( - 'server_databases.php', - function () { - PMA_ajaxShowMessage(data.message); - } - ); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); - }); - }); -}); diff --git a/js/db_search.js b/js/db_search.js deleted file mode 100644 index 66f7c6287e..0000000000 --- a/js/db_search.js +++ /dev/null @@ -1,246 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * JavaScript functions used on Database Search page - * - * @requires jQuery - * @requires js/functions.js - * - * @package PhpMyAdmin - */ - -/** - * AJAX script for the Database Search page. - * - * Actions ajaxified here: - * Retrieve result of SQL query - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('db_search.js', function () { - $('a.browse_results').off('click'); - $('a.delete_results').off('click'); - $('#buttonGo').off('click'); - $('#togglesearchresultlink').off('click'); - $('#togglequerybox').off('click'); - $('#togglesearchformlink').off('click'); - $(document).off('submit', '#db_search_form.ajax'); -}); - -AJAX.registerOnload('db_search.js', function () { - /** Hide the table link in the initial search result */ - var icon = PMA_getImage('s_tbl', '', { 'id': 'table-image' }).toString(); - $('#table-info').prepend(icon).hide(); - - /** Hide the browse and deleted results in the new search criteria */ - $('#buttonGo').on('click', function () { - $('#table-info').hide(); - $('#browse-results').hide(); - $('#sqlqueryform').hide(); - $('#togglequerybox').hide(); - }); - /** - * Prepare a div containing a link for toggle the search results - */ - $('#togglesearchresultsdiv') - /** don't show it until we have results on-screen */ - .hide(); - - /** - * Changing the displayed text according to - * the hide/show criteria in search result forms - */ - $('#togglesearchresultlink') - .html(PMA_messages.strHideSearchResults) - .on('click', function () { - var $link = $(this); - $('#searchresults').slideToggle(); - if ($link.text() === PMA_messages.strHideSearchResults) { - $link.text(PMA_messages.strShowSearchResults); - } else { - $link.text(PMA_messages.strHideSearchResults); - } - /** avoid default click action */ - return false; - }); - - /** - * Prepare a div containing a link for toggle the search form, - * otherwise it's incorrectly displayed after a couple of clicks - */ - $('#togglesearchformdiv') - .hide(); // don't show it until we have results on-screen - - /** - * Changing the displayed text according to - * the hide/show criteria in search form - */ - $('#togglequerybox') - .hide() - .on('click', function () { - var $link = $(this); - $('#sqlqueryform').slideToggle('medium'); - if ($link.text() === PMA_messages.strHideQueryBox) { - $link.text(PMA_messages.strShowQueryBox); - } else { - $link.text(PMA_messages.strHideQueryBox); - } - /** avoid default click action */ - return false; - }); - - /** don't show it until we have results on-screen */ - - /** - * Changing the displayed text according to - * the hide/show criteria in search criteria form - */ - $('#togglesearchformlink') - .html(PMA_messages.strShowSearchCriteria) - .on('click', function () { - var $link = $(this); - $('#db_search_form').slideToggle(); - if ($link.text() === PMA_messages.strHideSearchCriteria) { - $link.text(PMA_messages.strShowSearchCriteria); - } else { - $link.text(PMA_messages.strHideSearchCriteria); - } - /** avoid default click action */ - return false; - }); - - /* - * Ajax Event handler for retrieving the results from a table - */ - $(document).on('click', 'a.browse_results', function (e) { - e.preventDefault(); - /** Hides the results shown by the delete criteria */ - var $msg = PMA_ajaxShowMessage(PMA_messages.strBrowsing, false); - $('#sqlqueryform').hide(); - $('#togglequerybox').hide(); - /** Load the browse results to the page */ - $('#table-info').show(); - var table_name = $(this).data('table-name'); - $('#table-link').attr({ 'href' : $(this).attr('href') }).text(table_name); - - var url = $(this).attr('href') + '#searchresults'; - var browse_sql = $(this).data('browse-sql'); - var params = { - 'ajax_request': true, - 'is_js_confirmed': true, - 'sql_query' : browse_sql - }; - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success) { - $('#browse-results').html(data.message); - PMA_ajaxRemoveMessage($msg); - $('.table_results').each(function () { - PMA_makegrid(this, true, true, true, true); - }); - $('#browse-results').show(); - PMA_highlightSQL($('#browse-results')); - $('html, body') - .animate({ - scrollTop: $('#browse-results').offset().top - }, 1000); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); - }); - - /* - * Ajax Event handler for deleting the results from a table - */ - $(document).on('click', 'a.delete_results', function (e) { - e.preventDefault(); - /** Hides the results shown by the browse criteria */ - $('#table-info').hide(); - $('#sqlqueryform').hide(); - $('#togglequerybox').hide(); - /** Conformation message for deletion */ - var msg = PMA_sprintf( - PMA_messages.strConfirmDeleteResults, - $(this).data('table-name') - ); - if (confirm(msg)) { - var $msg = PMA_ajaxShowMessage(PMA_messages.strDeleting, false); - /** Load the deleted option to the page*/ - $('#sqlqueryform').html(''); - var params = { - 'ajax_request': true, - 'is_js_confirmed': true, - 'sql_query': $(this).data('delete-sql') - }; - var url = $(this).attr('href'); - - $.post(url, params, function (data) { - if (typeof data === 'undefined' || !data.success) { - PMA_ajaxShowMessage(data.error, false); - return; - } - - $('#sqlqueryform').html(data.sql_query); - /** Refresh the search results after the deletion */ - document.getElementById('buttonGo').trigger('click'); - $('#togglequerybox').html(PMA_messages.strHideQueryBox); - /** Show the results of the deletion option */ - $('#browse-results').hide(); - $('#sqlqueryform').show(); - $('#togglequerybox').show(); - $('html, body') - .animate({ - scrollTop: $('#browse-results').offset().top - }, 1000); - PMA_ajaxRemoveMessage($msg); - }); - } - }); - - /** - * Ajax Event handler for retrieving the result of an SQL Query - */ - $(document).on('submit', '#db_search_form.ajax', function (event) { - event.preventDefault(); - - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strSearching, false); - // jQuery object to reuse - var $form = $(this); - - PMA_prepareForAjaxRequest($form); - - var url = $form.serialize() + PMA_commonParams.get('arg_separator') + 'submit_search=' + $('#buttonGo').val(); - $.post($form.attr('action'), url, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - // found results - $('#searchresults').html(data.message); - - $('#togglesearchresultlink') - // always start with the Show message - .text(PMA_messages.strHideSearchResults); - $('#togglesearchresultsdiv') - // now it's time to show the div containing the link - .show(); - $('#searchresults').show(); - - - $('#db_search_form') - // workaround for Chrome problem (bug #3168569) - .slideToggle() - .hide(); - $('#togglesearchformlink') - // always start with the Show message - .text(PMA_messages.strShowSearchCriteria); - $('#togglesearchformdiv') - // now it's time to show the div containing the link - .show(); - } else { - // error message (zero rows) - $('#searchresults').html(data.error).show(); - } - - PMA_ajaxRemoveMessage($msgbox); - }); - }); -}); // end $() diff --git a/js/db_structure.js b/js/db_structure.js deleted file mode 100644 index 95e72323fe..0000000000 --- a/js/db_structure.js +++ /dev/null @@ -1,427 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview functions used on the database structure page - * @name Database Structure - * - * @requires jQuery - * @requires jQueryUI - * @required js/functions.js - */ - -/** - * AJAX scripts for db_structure.php - * - * Actions ajaxified here: - * Drop Database - * Truncate Table - * Drop Table - * - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('db_structure.js', function () { - $(document).off('click', 'a.truncate_table_anchor.ajax'); - $(document).off('click', 'a.drop_table_anchor.ajax'); - $(document).off('click', '#real_end_input'); - $(document).off('click', 'a.favorite_table_anchor.ajax'); - $(document).off('click', '#printView'); - $('a.real_row_count').off('click'); - $('a.row_count_sum').off('click'); - $('select[name=submit_mult]').off('change'); -}); - -/** - * Adjust number of rows and total size in the summary - * when truncating, creating, dropping or inserting into a table - */ -function PMA_adjustTotals () { - var byteUnits = [ - PMA_messages.strB, - PMA_messages.strKiB, - PMA_messages.strMiB, - PMA_messages.strGiB, - PMA_messages.strTiB, - PMA_messages.strPiB, - PMA_messages.strEiB - ]; - /** - * @var $allTr jQuery object that references all the rows in the list of tables - */ - var $allTr = $('#tablesForm').find('table.data tbody:first tr'); - // New summary values for the table - var tableSum = $allTr.size(); - var rowsSum = 0; - var sizeSum = 0; - var overheadSum = 0; - var rowSumApproximated = false; - - $allTr.each(function () { - var $this = $(this); - var i; - var tmpVal; - // Get the number of rows for this SQL table - var strRows = $this.find('.tbl_rows').text(); - // If the value is approximated - if (strRows.indexOf('~') === 0) { - rowSumApproximated = true; - // The approximated value contains a preceding ~ (Eg 100 --> ~100) - strRows = strRows.substring(1, strRows.length); - } - strRows = strRows.replace(/[,.]/g, ''); - var intRow = parseInt(strRows, 10); - if (! isNaN(intRow)) { - rowsSum += intRow; - } - // Extract the size and overhead - var valSize = 0; - var valOverhead = 0; - var strSize = $.trim($this.find('.tbl_size span:not(.unit)').text()); - var strSizeUnit = $.trim($this.find('.tbl_size span.unit').text()); - var strOverhead = $.trim($this.find('.tbl_overhead span:not(.unit)').text()); - var strOverheadUnit = $.trim($this.find('.tbl_overhead span.unit').text()); - // Given a value and a unit, such as 100 and KiB, for the table size - // and overhead calculate their numeric values in bytes, such as 102400 - for (i = 0; i < byteUnits.length; i++) { - if (strSizeUnit === byteUnits[i]) { - tmpVal = parseFloat(strSize); - valSize = tmpVal * Math.pow(1024, i); - break; - } - } - for (i = 0; i < byteUnits.length; i++) { - if (strOverheadUnit === byteUnits[i]) { - tmpVal = parseFloat(strOverhead); - valOverhead = tmpVal * Math.pow(1024, i); - break; - } - } - sizeSum += valSize; - overheadSum += valOverhead; - }); - // Add some commas for readability: - // 1000000 becomes 1,000,000 - var strRowSum = rowsSum + ''; - var regex = /(\d+)(\d{3})/; - while (regex.test(strRowSum)) { - strRowSum = strRowSum.replace(regex, '$1' + ',' + '$2'); - } - // If approximated total value add ~ in front - if (rowSumApproximated) { - strRowSum = '~' + strRowSum; - } - // Calculate the magnitude for the size and overhead values - var size_magnitude = 0; - var overhead_magnitude = 0; - while (sizeSum >= 1024) { - sizeSum /= 1024; - size_magnitude++; - } - while (overheadSum >= 1024) { - overheadSum /= 1024; - overhead_magnitude++; - } - - sizeSum = Math.round(sizeSum * 10) / 10; - overheadSum = Math.round(overheadSum * 10) / 10; - - // Update summary with new data - var $summary = $('#tbl_summary_row'); - $summary.find('.tbl_num').text(PMA_sprintf(PMA_messages.strNTables, tableSum)); - if (rowSumApproximated) { - $summary.find('.row_count_sum').text(strRowSum); - } else { - $summary.find('.tbl_rows').text(strRowSum); - } - $summary.find('.tbl_size').text(sizeSum + ' ' + byteUnits[size_magnitude]); - $summary.find('.tbl_overhead').text(overheadSum + ' ' + byteUnits[overhead_magnitude]); -} - -/** - * Gets the real row count for a table or DB. - * @param object $target Target for appending the real count value. - */ -function PMA_fetchRealRowCount ($target) { - var $throbber = $('#pma_navigation').find('.throbber') - .first() - .clone() - .css({ visibility: 'visible', display: 'inline-block' }) - .on('click', false); - $target.html($throbber); - $.ajax({ - type: 'GET', - url: $target.attr('href'), - cache: false, - dataType: 'json', - success: function (response) { - if (response.success) { - // If to update all row counts for a DB. - if (response.real_row_count_all) { - $.each(JSON.parse(response.real_row_count_all), - function (index, table) { - // Update each table row count. - $('table.data td[data-table*="' + table.table + '"]') - .text(table.row_count); - } - ); - } - // If to update a particular table's row count. - if (response.real_row_count) { - // Append the parent cell with real row count. - $target.parent().text(response.real_row_count); - } - // Adjust the 'Sum' displayed at the bottom. - PMA_adjustTotals(); - } else { - PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount); - } - }, - error: function () { - PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount); - } - }); -} - -AJAX.registerOnload('db_structure.js', function () { -/** - * function to open the confirmation dialog for making table consistent with central list - * - * @param string msg message text to be displayed to user - * @param function success function to be called on success - * - */ - var jqConfirm = function (msg, success) { - var dialogObj = $('<div class=\'hide\'>' + msg + '</div>'); - $('body').append(dialogObj); - var buttonOptions = {}; - buttonOptions[PMA_messages.strContinue] = function () { - success(); - $(this).dialog('close'); - }; - buttonOptions[PMA_messages.strCancel] = function () { - $(this).dialog('close'); - $('#tablesForm')[0].reset(); - }; - $(dialogObj).dialog({ - resizable: false, - modal: true, - title: PMA_messages.confirmTitle, - buttons: buttonOptions - }); - }; - - /** - * Event handler on select of "Make consistent with central list" - */ - $('select[name=submit_mult]').on('change', function (event) { - if ($(this).val() === 'make_consistent_with_central_list') { - event.preventDefault(); - event.stopPropagation(); - jqConfirm( - PMA_messages.makeConsistentMessage, function () { - $('#tablesForm').submit(); - } - ); - return false; - } else if ($(this).val() === 'copy_tbl' || $(this).val() === 'add_prefix_tbl' || $(this).val() === 'replace_prefix_tbl' || $(this).val() === 'copy_tbl_change_prefix') { - event.preventDefault(); - event.stopPropagation(); - if ($('input[name="selected_tbl[]"]:checked').length === 0) { - return false; - } - var formData = $('#tablesForm').serialize(); - var modalTitle = ''; - if ($(this).val() === 'copy_tbl') { - modalTitle = PMA_messages.strCopyTablesTo; - } else if ($(this).val() === 'add_prefix_tbl') { - modalTitle = PMA_messages.strAddPrefix; - } else if ($(this).val() === 'replace_prefix_tbl') { - modalTitle = PMA_messages.strReplacePrefix; - } else if ($(this).val() === 'copy_tbl_change_prefix') { - modalTitle = PMA_messages.strCopyPrefix; - } - $.ajax({ - type: 'POST', - url: 'db_structure.php', - dataType: 'html', - data: formData - - }).done(function (data) { - var dialogObj = $('<div class=\'hide\'>' + data + '</div>'); - $('body').append(dialogObj); - var buttonOptions = {}; - buttonOptions[PMA_messages.strContinue] = function () { - $('#ajax_form').submit(); - $(this).dialog('close'); - }; - buttonOptions[PMA_messages.strCancel] = function () { - $(this).dialog('close'); - $('#tablesForm')[0].reset(); - }; - $(dialogObj).dialog({ - minWidth: 500, - resizable: false, - modal: true, - title: modalTitle, - buttons: buttonOptions - }); - }); - } else { - $('#tablesForm').submit(); - } - }); - - /** - * Ajax Event handler for 'Truncate Table' - */ - $(document).on('click', 'a.truncate_table_anchor.ajax', function (event) { - event.preventDefault(); - - /** - * @var $this_anchor Object referring to the anchor clicked - */ - var $this_anchor = $(this); - - // extract current table name and build the question string - /** - * @var curr_table_name String containing the name of the table to be truncated - */ - var curr_table_name = $this_anchor.parents('tr').children('th').children('a').text(); - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_messages.strTruncateTableStrongWarning + ' ' + - PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE `' + escapeHtml(curr_table_name) + '`') + - getForeignKeyCheckboxLoader(); - - $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - - var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); - - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - // Adjust table statistics - var $tr = $this_anchor.closest('tr'); - $tr.find('.tbl_rows').text('0'); - $tr.find('.tbl_size, .tbl_overhead').text('-'); - // Fetch inner span of this anchor - // and replace the icon with its disabled version - var span = $this_anchor.html().replace(/b_empty/, 'bd_empty'); - // To disable further attempts to truncate the table, - // replace the a element with its inner span (modified) - $this_anchor - .replaceWith(span) - .removeClass('truncate_table_anchor'); - PMA_adjustTotals(); - } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); - } - }); // end $.post() - }, loadForeignKeyCheckbox); // end $.PMA_confirm() - }); // end of Truncate Table Ajax action - - /** - * Ajax Event handler for 'Drop Table' or 'Drop View' - */ - $(document).on('click', 'a.drop_table_anchor.ajax', function (event) { - event.preventDefault(); - - var $this_anchor = $(this); - - // extract current table name and build the question string - /** - * @var $curr_row Object containing reference to the current row - */ - var $curr_row = $this_anchor.parents('tr'); - /** - * @var curr_table_name String containing the name of the table to be truncated - */ - var curr_table_name = $curr_row.children('th').children('a').text(); - /** - * @var is_view Boolean telling if we have a view - */ - var is_view = $curr_row.hasClass('is_view') || $this_anchor.hasClass('view'); - /** - * @var question String containing the question to be asked for confirmation - */ - var question; - if (! is_view) { - question = PMA_messages.strDropTableStrongWarning + ' ' + - PMA_sprintf(PMA_messages.strDoYouReally, 'DROP TABLE `' + escapeHtml(curr_table_name) + '`'); - } else { - question = - PMA_sprintf(PMA_messages.strDoYouReally, 'DROP VIEW `' + escapeHtml(curr_table_name) + '`'); - } - question += getForeignKeyCheckboxLoader(); - - $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) { - var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - - var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); - - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - $curr_row.hide('medium').remove(); - PMA_adjustTotals(); - PMA_reloadNavigation(); - PMA_ajaxRemoveMessage($msg); - } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); - } - }); // end $.post() - }, loadForeignKeyCheckbox); // end $.PMA_confirm() - }); // end of Drop Table Ajax action - - /** - * Attach Event Handler for 'Print' link - */ - $(document).on('click', '#printView', function (event) { - event.preventDefault(); - - // Take to preview mode - printPreview(); - }); // end of Print View action - - // Calculate Real End for InnoDB - /** - * Ajax Event handler for calculating the real end for a InnoDB table - * - */ - $(document).on('click', '#real_end_input', function (event) { - event.preventDefault(); - - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_messages.strOperationTakesLongTime; - - $(this).PMA_confirm(question, '', function () { - return true; - }); - return false; - }); // end Calculate Real End for InnoDB - - // Add tooltip to favorite icons. - $('.favorite_table_anchor').each(function () { - PMA_tooltip( - $(this), - 'a', - $(this).attr('title') - ); - }); - - // Get real row count via Ajax. - $('a.real_row_count').on('click', function (event) { - event.preventDefault(); - PMA_fetchRealRowCount($(this)); - }); - // Get all real row count. - $('a.row_count_sum').on('click', function (event) { - event.preventDefault(); - PMA_fetchRealRowCount($(this)); - }); -}); // end $() diff --git a/js/db_tracking.js b/js/db_tracking.js deleted file mode 100644 index 36b8ae3e2e..0000000000 --- a/js/db_tracking.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Unbind all event handlers before tearing down the page - */ -AJAX.registerTeardown('db_tracking.js', function () { - $('body').off('click', '#trackedForm.ajax button[name="submit_mult"], #trackedForm.ajax input[name="submit_mult"]'); - $('body').off('click', '#untrackedForm.ajax button[name="submit_mult"], #untrackedForm.ajax input[name="submit_mult"]'); - $('body').off('click', 'a.delete_tracking_anchor.ajax'); -}); - -/** - * Bind event handlers - */ -AJAX.registerOnload('db_tracking.js', function () { - var $versions = $('#versions'); - $versions.find('tr:first th').append($('<div class="sorticon"></div>')); - $versions.tablesorter({ - sortList: [[1, 0]], - headers: { - 0: { sorter: false }, - 2: { sorter: 'integer' }, - 5: { sorter: false }, - 6: { sorter: false }, - 7: { sorter: false } - } - }); - - var $noVersions = $('#noversions'); - $noVersions.find('tr:first th').append($('<div class="sorticon"></div>')); - $noVersions.tablesorter({ - sortList: [[1, 0]], - headers: { - 0: { sorter: false }, - 2: { sorter: false } - } - }); - - var $body = $('body'); - - /** - * Handles multi submit for tracked tables - */ - $body.on('click', '#trackedForm.ajax button[name="submit_mult"], #trackedForm.ajax input[name="submit_mult"]', function (e) { - e.preventDefault(); - var $button = $(this); - var $form = $button.parent('form'); - var argsep = PMA_commonParams.get('arg_separator'); - var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); - - if ($button.val() === 'delete_tracking') { - var question = PMA_messages.strDeleteTrackingDataMultiple; - $button.PMA_confirm(question, $form.attr('action'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strDeletingTrackingData); - AJAX.source = $form; - $.post(url, submitData, AJAX.responseHandler); - }); - } else { - PMA_ajaxShowMessage(); - AJAX.source = $form; - $.post($form.attr('action'), submitData, AJAX.responseHandler); - } - }); - - /** - * Handles multi submit for untracked tables - */ - $body.on('click', '#untrackedForm.ajax button[name="submit_mult"], #untrackedForm.ajax input[name="submit_mult"]', function (e) { - e.preventDefault(); - var $button = $(this); - var $form = $button.parent('form'); - var argsep = PMA_commonParams.get('arg_separator'); - var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); - PMA_ajaxShowMessage(); - AJAX.source = $form; - $.post($form.attr('action'), submitData, AJAX.responseHandler); - }); - - /** - * Ajax Event handler for 'Delete tracking' - */ - $body.on('click', 'a.delete_tracking_anchor.ajax', function (e) { - e.preventDefault(); - var $anchor = $(this); - var question = PMA_messages.strDeleteTrackingData; - $anchor.PMA_confirm(question, $anchor.attr('href'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strDeletingTrackingData); - AJAX.source = $anchor; - var params = { - 'ajax_page_request': true, - 'ajax_request': true - }; - $.post(url, params, AJAX.responseHandler); - }); - }); -}); diff --git a/js/export.js b/js/export.js deleted file mode 100644 index f47d829ede..0000000000 --- a/js/export.js +++ /dev/null @@ -1,996 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * Functions used in the export tab - * - */ - -/** - * Disables the "Dump some row(s)" sub-options - */ -function disable_dump_some_rows_sub_options () { - $('label[for=\'limit_to\']').fadeTo('fast', 0.4); - $('label[for=\'limit_from\']').fadeTo('fast', 0.4); - $('input[type=\'text\'][name=\'limit_to\']').prop('disabled', 'disabled'); - $('input[type=\'text\'][name=\'limit_from\']').prop('disabled', 'disabled'); -} - -/** - * Enables the "Dump some row(s)" sub-options - */ -function enable_dump_some_rows_sub_options () { - $('label[for=\'limit_to\']').fadeTo('fast', 1); - $('label[for=\'limit_from\']').fadeTo('fast', 1); - $('input[type=\'text\'][name=\'limit_to\']').prop('disabled', ''); - $('input[type=\'text\'][name=\'limit_from\']').prop('disabled', ''); -} - -/** - * Return template data as a json object - * - * @returns template data - */ -function getTemplateData () { - var $form = $('form[name="dump"]'); - var blacklist = ['token', 'server', 'db', 'table', 'single_table', - 'export_type', 'export_method', 'sql_query', 'template_id']; - var obj = {}; - var arr = $form.serializeArray(); - $.each(arr, function () { - if ($.inArray(this.name, blacklist) < 0) { - if (obj[this.name] !== undefined) { - if (! obj[this.name].push) { - obj[this.name] = [obj[this.name]]; - } - obj[this.name].push(this.value || ''); - } else { - obj[this.name] = this.value || ''; - } - } - }); - // include unchecked checboxes (which are ignored by serializeArray()) with null - // to uncheck them when loading the template - $form.find('input[type="checkbox"]:not(:checked)').each(function () { - if (obj[this.name] === undefined) { - obj[this.name] = null; - } - }); - // include empty multiselects - $form.find('select').each(function () { - if ($(this).find('option:selected').length === 0) { - obj[this.name] = []; - } - }); - return obj; -} - -/** - * Create a template with selected options - * - * @param name name of the template - */ -function createTemplate (name) { - var templateData = getTemplateData(); - - var params = { - ajax_request : true, - server : PMA_commonParams.get('server'), - db : PMA_commonParams.get('db'), - table : PMA_commonParams.get('table'), - exportType : $('input[name="export_type"]').val(), - templateAction : 'create', - templateName : name, - templateData : JSON.stringify(templateData) - }; - - PMA_ajaxShowMessage(); - $.post('tbl_export.php', params, function (response) { - if (response.success === true) { - $('#templateName').val(''); - $('#template').html(response.data); - $('#template').find('option').each(function () { - if ($(this).text() === name) { - $(this).prop('selected', true); - } - }); - PMA_ajaxShowMessage(PMA_messages.strTemplateCreated); - } else { - PMA_ajaxShowMessage(response.error, false); - } - }); -} - -/** - * Loads a template - * - * @param id ID of the template to load - */ -function loadTemplate (id) { - var params = { - ajax_request : true, - server : PMA_commonParams.get('server'), - db : PMA_commonParams.get('db'), - table : PMA_commonParams.get('table'), - exportType : $('input[name="export_type"]').val(), - templateAction : 'load', - templateId : id, - }; - - PMA_ajaxShowMessage(); - $.post('tbl_export.php', params, function (response) { - if (response.success === true) { - var $form = $('form[name="dump"]'); - var options = JSON.parse(response.data); - $.each(options, function (key, value) { - var $element = $form.find('[name="' + key + '"]'); - if ($element.length) { - if (($element.is('input') && $element.attr('type') === 'checkbox') && value === null) { - $element.prop('checked', false); - } else { - if (($element.is('input') && $element.attr('type') === 'checkbox') || - ($element.is('input') && $element.attr('type') === 'radio') || - ($element.is('select') && $element.attr('multiple') === 'multiple')) { - if (! value.push) { - value = [value]; - } - } - $element.val(value); - } - $element.trigger('change'); - } - }); - $('input[name="template_id"]').val(id); - PMA_ajaxShowMessage(PMA_messages.strTemplateLoaded); - } else { - PMA_ajaxShowMessage(response.error, false); - } - }); -} - -/** - * Updates an existing template with current options - * - * @param id ID of the template to update - */ -function updateTemplate (id) { - var templateData = getTemplateData(); - - var params = { - ajax_request : true, - server : PMA_commonParams.get('server'), - db : PMA_commonParams.get('db'), - table : PMA_commonParams.get('table'), - exportType : $('input[name="export_type"]').val(), - templateAction : 'update', - templateId : id, - templateData : JSON.stringify(templateData) - }; - - PMA_ajaxShowMessage(); - $.post('tbl_export.php', params, function (response) { - if (response.success === true) { - PMA_ajaxShowMessage(PMA_messages.strTemplateUpdated); - } else { - PMA_ajaxShowMessage(response.error, false); - } - }); -} - -/** - * Delete a template - * - * @param id ID of the template to delete - */ -function deleteTemplate (id) { - var params = { - ajax_request : true, - server : PMA_commonParams.get('server'), - db : PMA_commonParams.get('db'), - table : PMA_commonParams.get('table'), - exportType : $('input[name="export_type"]').val(), - templateAction : 'delete', - templateId : id, - }; - - PMA_ajaxShowMessage(); - $.post('tbl_export.php', params, function (response) { - if (response.success === true) { - $('#template').find('option[value="' + id + '"]').remove(); - PMA_ajaxShowMessage(PMA_messages.strTemplateDeleted); - } else { - PMA_ajaxShowMessage(response.error, false); - } - }); -} - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('export.js', function () { - $('#plugins').off('change'); - $('input[type=\'radio\'][name=\'sql_structure_or_data\']').off('change'); - $('input[type=\'radio\'][name$=\'_structure_or_data\']').off('change'); - $('input[type=\'radio\'][name=\'output_format\']').off('change'); - $('#checkbox_sql_include_comments').off('change'); - $('input[type=\'radio\'][name=\'quick_or_custom\']').off('change'); - $('input[type=\'radio\'][name=\'allrows\']').off('change'); - $('#btn_alias_config').off('click'); - $('.alias_remove').off('click'); - $('#db_alias_button').off('click'); - $('#table_alias_button').off('click'); - $('#column_alias_button').off('click'); - $('input[name="table_select[]"]').off('change'); - $('input[name="table_structure[]"]').off('change'); - $('input[name="table_data[]"]').off('change'); - $('#table_structure_all').off('change'); - $('#table_data_all').off('change'); - $('input[name="createTemplate"]').off('click'); - $('select[name="template"]').off('change'); - $('input[name="updateTemplate"]').off('click'); - $('input[name="deleteTemplate"]').off('click'); -}); - -AJAX.registerOnload('export.js', function () { - /** - * Export template handling code - */ - // create a new template - $('input[name="createTemplate"]').on('click', function (e) { - e.preventDefault(); - var name = $('input[name="templateName"]').val(); - if (name.length) { - createTemplate(name); - } - }); - - // load an existing template - $('select[name="template"]').on('change', function (e) { - e.preventDefault(); - var id = $(this).val(); - if (id.length) { - loadTemplate(id); - } - }); - - // udpate an existing template with new criteria - $('input[name="updateTemplate"]').on('click', function (e) { - e.preventDefault(); - var id = $('select[name="template"]').val(); - if (id.length) { - updateTemplate(id); - } - }); - - // delete an existing template - $('input[name="deleteTemplate"]').on('click', function (e) { - e.preventDefault(); - var id = $('select[name="template"]').val(); - if (id.length) { - deleteTemplate(id); - } - }); - - /** - * Toggles the hiding and showing of each plugin's options - * according to the currently selected plugin from the dropdown list - */ - $('#plugins').on('change', function () { - $('#format_specific_opts').find('div.format_specific_options').hide(); - var selected_plugin_name = $('#plugins').find('option:selected').val(); - $('#' + selected_plugin_name + '_options').show(); - }); - - /** - * Toggles the enabling and disabling of the SQL plugin's comment options that apply only when exporting structure - */ - $('input[type=\'radio\'][name=\'sql_structure_or_data\']').on('change', function () { - var comments_are_present = $('#checkbox_sql_include_comments').prop('checked'); - var show = $('input[type=\'radio\'][name=\'sql_structure_or_data\']:checked').val(); - if (show === 'data') { - // disable the SQL comment options - if (comments_are_present) { - $('#checkbox_sql_dates').prop('disabled', true).parent().fadeTo('fast', 0.4); - } - $('#checkbox_sql_relation').prop('disabled', true).parent().fadeTo('fast', 0.4); - $('#checkbox_sql_mime').prop('disabled', true).parent().fadeTo('fast', 0.4); - } else { - // enable the SQL comment options - if (comments_are_present) { - $('#checkbox_sql_dates').prop('disabled', false).parent().fadeTo('fast', 1); - } - $('#checkbox_sql_relation').prop('disabled', false).parent().fadeTo('fast', 1); - $('#checkbox_sql_mime').prop('disabled', false).parent().fadeTo('fast', 1); - } - - if (show === 'structure') { - $('#checkbox_sql_auto_increment').prop('disabled', true).parent().fadeTo('fast', 0.4); - } else { - $('#checkbox_sql_auto_increment').prop('disabled', false).parent().fadeTo('fast', 1); - } - }); - - // For separate-file exports only ZIP compression is allowed - $('input[type="checkbox"][name="as_separate_files"]').on('change', function () { - if ($(this).is(':checked')) { - $('#compression').val('zip'); - } - }); - - $('#compression').on('change', function () { - if ($('option:selected').val() !== 'zip') { - $('input[type="checkbox"][name="as_separate_files"]').prop('checked', false); - } - }); -}); - -function setup_table_structure_or_data () { - if ($('input[name=\'export_type\']').val() !== 'database') { - return; - } - var pluginName = $('#plugins').find('option:selected').val(); - var formElemName = pluginName + '_structure_or_data'; - var force_structure_or_data = !($('input[name=\'' + formElemName + '_default\']').length); - - if (force_structure_or_data === true) { - $('input[name="structure_or_data_forced"]').val(1); - $('.export_structure input[type="checkbox"], .export_data input[type="checkbox"]') - .prop('disabled', true); - $('.export_structure, .export_data').fadeTo('fast', 0.4); - } else { - $('input[name="structure_or_data_forced"]').val(0); - $('.export_structure input[type="checkbox"], .export_data input[type="checkbox"]') - .prop('disabled', false); - $('.export_structure, .export_data').fadeTo('fast', 1); - - var structure_or_data = $('input[name="' + formElemName + '_default"]').val(); - - if (structure_or_data === 'structure') { - $('.export_data input[type="checkbox"]') - .prop('checked', false); - } else if (structure_or_data === 'data') { - $('.export_structure input[type="checkbox"]') - .prop('checked', false); - } - if (structure_or_data === 'structure' || structure_or_data === 'structure_and_data') { - if (!$('.export_structure input[type="checkbox"]:checked').length) { - $('input[name="table_select[]"]:checked') - .closest('tr') - .find('.export_structure input[type="checkbox"]') - .prop('checked', true); - } - } - if (structure_or_data === 'data' || structure_or_data === 'structure_and_data') { - if (!$('.export_data input[type="checkbox"]:checked').length) { - $('input[name="table_select[]"]:checked') - .closest('tr') - .find('.export_data input[type="checkbox"]') - .prop('checked', true); - } - } - - check_selected_tables(); - check_table_select_all(); - check_table_select_struture_or_data(); - } -} - -/** - * Toggles the hiding and showing of plugin structure-specific and data-specific - * options - */ -function toggle_structure_data_opts () { - var pluginName = $('select#plugins').val(); - var radioFormName = pluginName + '_structure_or_data'; - var dataDiv = '#' + pluginName + '_data'; - var structureDiv = '#' + pluginName + '_structure'; - var show = $('input[type=\'radio\'][name=\'' + radioFormName + '\']:checked').val(); - if (show === 'data') { - $(dataDiv).slideDown('slow'); - $(structureDiv).slideUp('slow'); - } else { - $(structureDiv).slideDown('slow'); - if (show === 'structure') { - $(dataDiv).slideUp('slow'); - } else { - $(dataDiv).slideDown('slow'); - } - } -} - -/** - * Toggles the disabling of the "save to file" options - */ -function toggle_save_to_file () { - var $ulSaveAsfile = $('#ul_save_asfile'); - if (!$('#radio_dump_asfile').prop('checked')) { - $ulSaveAsfile.find('> li').fadeTo('fast', 0.4); - $ulSaveAsfile.find('> li > input').prop('disabled', true); - $ulSaveAsfile.find('> li > select').prop('disabled', true); - } else { - $ulSaveAsfile.find('> li').fadeTo('fast', 1); - $ulSaveAsfile.find('> li > input').prop('disabled', false); - $ulSaveAsfile.find('> li > select').prop('disabled', false); - } -} - -AJAX.registerOnload('export.js', function () { - toggle_save_to_file(); - $('input[type=\'radio\'][name=\'output_format\']').on('change', toggle_save_to_file); -}); - -/** - * For SQL plugin, toggles the disabling of the "display comments" options - */ -function toggle_sql_include_comments () { - $('#checkbox_sql_include_comments').on('change', function () { - var $ulIncludeComments = $('#ul_include_comments'); - if (!$('#checkbox_sql_include_comments').prop('checked')) { - $ulIncludeComments.find('> li').fadeTo('fast', 0.4); - $ulIncludeComments.find('> li > input').prop('disabled', true); - } else { - // If structure is not being exported, the comment options for structure should not be enabled - if ($('#radio_sql_structure_or_data_data').prop('checked')) { - $('#text_sql_header_comment').prop('disabled', false).parent('li').fadeTo('fast', 1); - } else { - $ulIncludeComments.find('> li').fadeTo('fast', 1); - $ulIncludeComments.find('> li > input').prop('disabled', false); - } - } - }); -} - -function check_table_select_all () { - var total = $('input[name="table_select[]"]').length; - var str_checked = $('input[name="table_structure[]"]:checked').length; - var data_checked = $('input[name="table_data[]"]:checked').length; - var str_all = $('#table_structure_all'); - var data_all = $('#table_data_all'); - - if (str_checked === total) { - str_all - .prop('indeterminate', false) - .prop('checked', true); - } else if (str_checked === 0) { - str_all - .prop('indeterminate', false) - .prop('checked', false); - } else { - str_all - .prop('indeterminate', true) - .prop('checked', false); - } - - if (data_checked === total) { - data_all - .prop('indeterminate', false) - .prop('checked', true); - } else if (data_checked === 0) { - data_all - .prop('indeterminate', false) - .prop('checked', false); - } else { - data_all - .prop('indeterminate', true) - .prop('checked', false); - } -} - -function check_table_select_struture_or_data () { - var str_checked = $('input[name="table_structure[]"]:checked').length; - var data_checked = $('input[name="table_data[]"]:checked').length; - var auto_increment = $('#checkbox_sql_auto_increment'); - - var pluginName = $('select#plugins').val(); - var dataDiv = '#' + pluginName + '_data'; - var structureDiv = '#' + pluginName + '_structure'; - - if (str_checked === 0) { - $(structureDiv).slideUp('slow'); - } else { - $(structureDiv).slideDown('slow'); - } - - if (data_checked === 0) { - $(dataDiv).slideUp('slow'); - auto_increment.prop('disabled', true).parent().fadeTo('fast', 0.4); - } else { - $(dataDiv).slideDown('slow'); - auto_increment.prop('disabled', false).parent().fadeTo('fast', 1); - } -} - -function toggle_table_select_all_str () { - var str_all = $('#table_structure_all').is(':checked'); - if (str_all) { - $('input[name="table_structure[]"]').prop('checked', true); - } else { - $('input[name="table_structure[]"]').prop('checked', false); - } -} - -function toggle_table_select_all_data () { - var data_all = $('#table_data_all').is(':checked'); - if (data_all) { - $('input[name="table_data[]"]').prop('checked', true); - } else { - $('input[name="table_data[]"]').prop('checked', false); - } -} - -function check_selected_tables (argument) { - $('.export_table_select tbody tr').each(function () { - check_table_selected(this); - }); -} - -function check_table_selected (row) { - var $row = $(row); - var table_select = $row.find('input[name="table_select[]"]'); - var str_check = $row.find('input[name="table_structure[]"]'); - var data_check = $row.find('input[name="table_data[]"]'); - - var data = data_check.is(':checked:not(:disabled)'); - var structure = str_check.is(':checked:not(:disabled)'); - - if (data && structure) { - table_select.prop({ checked: true, indeterminate: false }); - $row.addClass('marked'); - } else if (data || structure) { - table_select.prop({ checked: true, indeterminate: true }); - $row.removeClass('marked'); - } else { - table_select.prop({ checked: false, indeterminate: false }); - $row.removeClass('marked'); - } -} - -function toggle_table_select (row) { - var $row = $(row); - var table_selected = $row.find('input[name="table_select[]"]').is(':checked'); - - if (table_selected) { - $row.find('input[type="checkbox"]:not(:disabled)').prop('checked', true); - $row.addClass('marked'); - } else { - $row.find('input[type="checkbox"]:not(:disabled)').prop('checked', false); - $row.removeClass('marked'); - } -} - -function handleAddProcCheckbox () { - if ($('#table_structure_all').is(':checked') === true - && $('#table_data_all').is(':checked') === true - ) { - $('#checkbox_sql_procedure_function').prop('checked', true); - } else { - $('#checkbox_sql_procedure_function').prop('checked', false); - } -} - -AJAX.registerOnload('export.js', function () { - /** - * For SQL plugin, if "CREATE TABLE options" is checked/unchecked, check/uncheck each of its sub-options - */ - var $create = $('#checkbox_sql_create_table_statements'); - var $create_options = $('#ul_create_table_statements').find('input'); - $create.on('change', function () { - $create_options.prop('checked', $(this).prop('checked')); - }); - $create_options.on('change', function () { - if ($create_options.is(':checked')) { - $create.prop('checked', true); - } - }); - - /** - * Disables the view output as text option if the output must be saved as a file - */ - $('#plugins').on('change', function () { - var active_plugin = $('#plugins').find('option:selected').val(); - var force_file = $('#force_file_' + active_plugin).val(); - if (force_file === 'true') { - if ($('#radio_dump_asfile').prop('checked') !== true) { - $('#radio_dump_asfile').prop('checked', true); - toggle_save_to_file(); - } - $('#radio_view_as_text').prop('disabled', true).parent().fadeTo('fast', 0.4); - } else { - $('#radio_view_as_text').prop('disabled', false).parent().fadeTo('fast', 1); - } - }); - - $('input[type=\'radio\'][name$=\'_structure_or_data\']').on('change', function () { - toggle_structure_data_opts(); - }); - - $('input[name="table_select[]"]').on('change', function () { - toggle_table_select($(this).closest('tr')); - check_table_select_all(); - handleAddProcCheckbox(); - check_table_select_struture_or_data(); - }); - - $('input[name="table_structure[]"]').on('change', function () { - check_table_selected($(this).closest('tr')); - check_table_select_all(); - handleAddProcCheckbox(); - check_table_select_struture_or_data(); - }); - - $('input[name="table_data[]"]').on('change', function () { - check_table_selected($(this).closest('tr')); - check_table_select_all(); - handleAddProcCheckbox(); - check_table_select_struture_or_data(); - }); - - $('#table_structure_all').on('change', function () { - toggle_table_select_all_str(); - check_selected_tables(); - handleAddProcCheckbox(); - check_table_select_struture_or_data(); - }); - - $('#table_data_all').on('change', function () { - toggle_table_select_all_data(); - check_selected_tables(); - handleAddProcCheckbox(); - check_table_select_struture_or_data(); - }); - - if ($('input[name=\'export_type\']').val() === 'database') { - // Hide structure or data radio buttons - $('input[type=\'radio\'][name$=\'_structure_or_data\']').each(function () { - var $this = $(this); - var name = $this.prop('name'); - var val = $('input[name="' + name + '"]:checked').val(); - var name_default = name + '_default'; - if (!$('input[name="' + name_default + '"]').length) { - $this - .after( - $('<input type="hidden" name="' + name_default + '" value="' + val + '" disabled>') - ) - .after( - $('<input type="hidden" name="' + name + '" value="structure_and_data">') - ); - $this.parent().find('label').remove(); - } else { - $this.parent().remove(); - } - }); - $('input[type=\'radio\'][name$=\'_structure_or_data\']').remove(); - - // Disable CREATE table checkbox for sql - var createTableCheckbox = $('#checkbox_sql_create_table'); - createTableCheckbox.prop('checked', true); - var dummyCreateTable = $('#checkbox_sql_create_table') - .clone() - .removeAttr('id') - .attr('type', 'hidden'); - createTableCheckbox - .prop('disabled', true) - .after(dummyCreateTable) - .parent() - .fadeTo('fast', 0.4); - - setup_table_structure_or_data(); - } - - /** - * Handle force structure_or_data - */ - $('#plugins').on('change', setup_table_structure_or_data); -}); - -/** - * Toggles display of options when quick and custom export are selected - */ -function toggle_quick_or_custom () { - if ($('input[name=\'quick_or_custom\']').length === 0 // custom_no_form option - || $('#radio_custom_export').prop('checked') // custom - ) { - $('#databases_and_tables').show(); - $('#rows').show(); - $('#output').show(); - $('#format_specific_opts').show(); - $('#output_quick_export').hide(); - var selected_plugin_name = $('#plugins').find('option:selected').val(); - $('#' + selected_plugin_name + '_options').show(); - } else { // quick - $('#databases_and_tables').hide(); - $('#rows').hide(); - $('#output').hide(); - $('#format_specific_opts').hide(); - $('#output_quick_export').show(); - } -} -var time_out; -function check_time_out (time_limit) { - if (typeof time_limit === 'undefined' || time_limit === 0) { - return true; - } - // margin of one second to avoid race condition to set/access session variable - time_limit = time_limit + 1; - var href = 'export.php'; - var params = { - 'ajax_request' : true, - 'check_time_out' : true - }; - clearTimeout(time_out); - time_out = setTimeout(function () { - $.get(href, params, function (data) { - if (data.message === 'timeout') { - PMA_ajaxShowMessage( - '<div class="error">' + - PMA_messages.strTimeOutError + - '</div>', - false - ); - } - }); - }, time_limit * 1000); -} - -/** - * Handler for Database/table alias select - * - * @param event object the event object - * - * @return void - */ -function aliasSelectHandler (event) { - var sel = event.data.sel; - var type = event.data.type; - var inputId = $(this).val(); - var $label = $(this).next('label'); - $('input#' + $label.attr('for')).addClass('hide'); - $('input#' + inputId).removeClass('hide'); - $label.attr('for', inputId); - $('#alias_modal ' + sel + '[id$=' + type + ']:visible').addClass('hide'); - var $inputWrapper = $('#alias_modal ' + sel + '#' + inputId + type); - $inputWrapper.removeClass('hide'); - if (type === '_cols' && $inputWrapper.length > 0) { - var outer = $inputWrapper[0].outerHTML; - // Replace opening tags - var regex = /<dummy_inp/gi; - if (outer.match(regex)) { - var newTag = outer.replace(regex, '<input'); - // Replace closing tags - regex = /<\/dummy_inp/gi; - newTag = newTag.replace(regex, '</input'); - // Assign replacement - $inputWrapper.replaceWith(newTag); - } - } else if (type === '_tables') { - $('.table_alias_select:visible').trigger('change'); - } - $('#alias_modal').dialog('option', 'position', 'center'); -} - -/** - * Handler for Alias dialog box - * - * @param event object the event object - * - * @return void - */ -function createAliasModal (event) { - event.preventDefault(); - var dlgButtons = {}; - dlgButtons[PMA_messages.strSaveAndClose] = function () { - $(this).dialog('close'); - $('#alias_modal').parent().appendTo($('form[name="dump"]')); - }; - $('#alias_modal').dialog({ - width: Math.min($(window).width() - 100, 700), - maxHeight: $(window).height(), - modal: true, - dialogClass: 'alias-dialog', - buttons: dlgButtons, - create: function () { - $(this).css('maxHeight', $(window).height() - 150); - var db = PMA_commonParams.get('db'); - if (db) { - var option = $('<option></option>'); - option.text(db); - option.attr('value', db); - $('#db_alias_select').append(option).val(db).trigger('change'); - } else { - var params = { - ajax_request : true, - server : PMA_commonParams.get('server'), - type: 'list-databases' - }; - $.post('ajax.php', params, function (response) { - if (response.success === true) { - $.each(response.databases, function (idx, value) { - var option = $('<option></option>'); - option.text(value); - option.attr('value', value); - $('#db_alias_select').append(option); - }); - } else { - PMA_ajaxShowMessage(response.error, false); - } - }); - } - }, - close: function () { - var isEmpty = true; - $(this).find('input[type="text"]').each(function () { - // trim empty input fields on close - if ($(this).val()) { - isEmpty = false; - } else { - $(this).parents('tr').remove(); - } - }); - // Toggle checkbox based on aliases - $('input#btn_alias_config').prop('checked', !isEmpty); - }, - position: { my: 'center top', at: 'center top', of: window } - }); -} - -function aliasToggleRow (elm) { - var inputs = elm.parents('tr').find('input,button'); - if (elm.val()) { - inputs.attr('disabled', false); - } else { - inputs.attr('disabled', true); - } -} - -function addAlias (type, name, field, value) { - if (value === '') { - return; - } - - var row = $('#alias_data tfoot tr').clone(); - row.find('th').text(type); - row.find('td:first').text(name); - row.find('input').attr('name', field); - row.find('input').val(value); - row.find('.alias_remove').on('click', function () { - $(this).parents('tr').remove(); - }); - - var matching = $('#alias_data [name="' + $.escapeSelector(field) + '"]'); - if (matching.length > 0) { - matching.parents('tr').remove(); - } - - $('#alias_data tbody').append(row); -} - -AJAX.registerOnload('export.js', function () { - $('input[type=\'radio\'][name=\'quick_or_custom\']').on('change', toggle_quick_or_custom); - - $('#scroll_to_options_msg').hide(); - $('#format_specific_opts').find('div.format_specific_options') - .hide() - .css({ - 'border': 0, - 'margin': 0, - 'padding': 0 - }) - .find('h3') - .remove(); - toggle_quick_or_custom(); - toggle_structure_data_opts(); - toggle_sql_include_comments(); - check_table_select_all(); - handleAddProcCheckbox(); - - /** - * Initially disables the "Dump some row(s)" sub-options - */ - disable_dump_some_rows_sub_options(); - - /** - * Disables the "Dump some row(s)" sub-options when it is not selected - */ - $('input[type=\'radio\'][name=\'allrows\']').on('change', function () { - if ($('input[type=\'radio\'][name=\'allrows\']').prop('checked')) { - enable_dump_some_rows_sub_options(); - } else { - disable_dump_some_rows_sub_options(); - } - }); - - // Open Alias Modal Dialog on click - $('#btn_alias_config').on('click', createAliasModal); - $('.alias_remove').on('click', function () { - $(this).parents('tr').remove(); - }); - $('#db_alias_select').on('change', function () { - aliasToggleRow($(this)); - var db = $(this).val(); - var table = PMA_commonParams.get('table'); - if (table) { - var option = $('<option></option>'); - option.text(table); - option.attr('value', table); - $('#table_alias_select').append(option).val(table).trigger('change'); - } else { - var params = { - ajax_request : true, - server : PMA_commonParams.get('server'), - db : $(this).val(), - type: 'list-tables' - }; - $.post('ajax.php', params, function (response) { - if (response.success === true) { - $.each(response.tables, function (idx, value) { - var option = $('<option></option>'); - option.text(value); - option.attr('value', value); - $('#table_alias_select').append(option); - }); - } else { - PMA_ajaxShowMessage(response.error, false); - } - }); - } - }); - $('#table_alias_select').on('change', function () { - aliasToggleRow($(this)); - var params = { - ajax_request : true, - server : PMA_commonParams.get('server'), - db : $('#db_alias_select').val(), - table: $(this).val(), - type: 'list-columns' - }; - $.post('ajax.php', params, function (response) { - if (response.success === true) { - $.each(response.columns, function (idx, value) { - var option = $('<option></option>'); - option.text(value); - option.attr('value', value); - $('#column_alias_select').append(option); - }); - } else { - PMA_ajaxShowMessage(response.error, false); - } - }); - }); - $('#column_alias_select').on('change', function () { - aliasToggleRow($(this)); - }); - $('#db_alias_button').on('click', function (e) { - e.preventDefault(); - var db = $('#db_alias_select').val(); - addAlias( - PMA_messages.strAliasDatabase, - db, - 'aliases[' + db + '][alias]', - $('#db_alias_name').val() - ); - $('#db_alias_name').val(''); - }); - $('#table_alias_button').on('click', function (e) { - e.preventDefault(); - var db = $('#db_alias_select').val(); - var table = $('#table_alias_select').val(); - addAlias( - PMA_messages.strAliasTable, - db + '.' + table, - 'aliases[' + db + '][tables][' + table + '][alias]', - $('#table_alias_name').val() - ); - $('#table_alias_name').val(''); - }); - $('#column_alias_button').on('click', function (e) { - e.preventDefault(); - var db = $('#db_alias_select').val(); - var table = $('#table_alias_select').val(); - var column = $('#column_alias_select').val(); - addAlias( - PMA_messages.strAliasColumn, - db + '.' + table + '.' + column, - 'aliases[' + db + '][tables][' + table + '][colums][' + column + ']', - $('#column_alias_name').val() - ); - $('#column_alias_name').val(''); - }); -}); diff --git a/js/import.js b/js/import.js deleted file mode 100644 index 8efebe9fbe..0000000000 --- a/js/import.js +++ /dev/null @@ -1,155 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * Functions used in the import tab - * - */ - - -/** - * Toggles the hiding and showing of each plugin's options - * according to the currently selected plugin from the dropdown list - */ -function changePluginOpts () { - $('#format_specific_opts').find('div.format_specific_options').each(function () { - $(this).hide(); - }); - var selected_plugin_name = $('#plugins').find('option:selected').val(); - $('#' + selected_plugin_name + '_options').fadeIn('slow'); - if (selected_plugin_name === 'csv') { - $('#import_notification').text(PMA_messages.strImportCSV); - } else { - $('#import_notification').text(''); - } -} - -/** - * Toggles the hiding and showing of each plugin's options and sets the selected value - * in the plugin dropdown list according to the format of the selected file - */ -function matchFile (fname) { - var fname_array = fname.toLowerCase().split('.'); - var len = fname_array.length; - if (len !== 0) { - var extension = fname_array[len - 1]; - if (extension === 'gz' || extension === 'bz2' || extension === 'zip') { - len--; - } - // Only toggle if the format of the file can be imported - if ($('select[name=\'format\'] option').filterByValue(fname_array[len - 1]).length === 1) { - $('select[name=\'format\'] option').filterByValue(fname_array[len - 1]).prop('selected', true); - changePluginOpts(); - } - } -} - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('import.js', function () { - $('#plugins').off('change'); - $('#input_import_file').off('change'); - $('#select_local_import_file').off('change'); - $('#input_import_file').off('change').off('focus'); - $('#select_local_import_file').off('focus'); - $('#text_csv_enclosed').add('#text_csv_escaped').off('keyup'); -}); - -AJAX.registerOnload('import.js', function () { - // import_file_form validation. - $(document).on('submit', '#import_file_form', function (event) { - var radioLocalImport = $('#radio_local_import_file'); - var radioImport = $('#radio_import_file'); - var fileMsg = '<div class="error"><img src="themes/dot.gif" title="" alt="" class="icon ic_s_error" /> ' + PMA_messages.strImportDialogMessage + '</div>'; - - if (radioLocalImport.length !== 0) { - // remote upload. - - if (radioImport.is(':checked') && $('#input_import_file').val() === '') { - $('#input_import_file').trigger('focus'); - PMA_ajaxShowMessage(fileMsg, false); - return false; - } - - if (radioLocalImport.is(':checked')) { - if ($('#select_local_import_file').length === 0) { - PMA_ajaxShowMessage('<div class="error"><img src="themes/dot.gif" title="" alt="" class="icon ic_s_error" /> ' + PMA_messages.strNoImportFile + ' </div>', false); - return false; - } - - if ($('#select_local_import_file').val() === '') { - $('#select_local_import_file').trigger('focus'); - PMA_ajaxShowMessage(fileMsg, false); - return false; - } - } - } else { - // local upload. - if ($('#input_import_file').val() === '') { - $('#input_import_file').trigger('focus'); - PMA_ajaxShowMessage(fileMsg, false); - return false; - } - } - - // show progress bar. - $('#upload_form_status').css('display', 'inline'); - $('#upload_form_status_info').css('display', 'inline'); - }); - - // Initially display the options for the selected plugin - changePluginOpts(); - - // Whenever the selected plugin changes, change the options displayed - $('#plugins').on('change', function () { - changePluginOpts(); - }); - - $('#input_import_file').on('change', function () { - matchFile($(this).val()); - }); - - $('#select_local_import_file').on('change', function () { - matchFile($(this).val()); - }); - - /* - * When the "Browse the server" form is clicked or the "Select from the web server upload directory" - * form is clicked, the radio button beside it becomes selected and the other form becomes disabled. - */ - $('#input_import_file').on('focus change', function () { - $('#radio_import_file').prop('checked', true); - $('#radio_local_import_file').prop('checked', false); - }); - $('#select_local_import_file').on('focus', function () { - $('#radio_local_import_file').prop('checked', true); - $('#radio_import_file').prop('checked', false); - }); - - /** - * Set up the interface for Javascript-enabled browsers since the default is for - * Javascript-disabled browsers - */ - $('#scroll_to_options_msg').hide(); - $('#format_specific_opts').find('div.format_specific_options') - .css({ - 'border': 0, - 'margin': 0, - 'padding': 0 - }) - .find('h3') - .remove(); - // $("form[name=import] *").unwrap(); - - /** - * for input element text_csv_enclosed and text_csv_escaped allow just one character to enter. - * as mysql allows just one character for these fields, - * if first character is escape then allow two including escape character. - */ - $('#text_csv_enclosed').add('#text_csv_escaped').on('keyup', function () { - if ($(this).val().length === 2 && $(this).val().charAt(0) !== '\\') { - $(this).val($(this).val().substring(0, 1)); - return false; - } - return true; - }); -}); diff --git a/js/indexes.js b/js/indexes.js deleted file mode 100644 index 4ce50bc60d..0000000000 --- a/js/indexes.js +++ /dev/null @@ -1,755 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview function used for index manipulation pages - * @name Table Structure - * - * @requires jQuery - * @requires jQueryUI - * @required js/functions.js - */ - -/** - * Returns the array of indexes based on the index choice - * - * @param index_choice index choice - */ -function PMA_getIndexArray (index_choice) { - var source_array = null; - - switch (index_choice.toLowerCase()) { - case 'primary': - source_array = primary_indexes; - break; - case 'unique': - source_array = unique_indexes; - break; - case 'index': - source_array = indexes; - break; - case 'fulltext': - source_array = fulltext_indexes; - break; - case 'spatial': - source_array = spatial_indexes; - break; - default: - return null; - } - return source_array; -} - -/** - * Hides/shows the inputs and submits appropriately depending - * on whether the index type chosen is 'SPATIAL' or not. - */ -function checkIndexType () { - /** - * @var Object Dropdown to select the index choice. - */ - var $select_index_choice = $('#select_index_choice'); - /** - * @var Object Dropdown to select the index type. - */ - var $select_index_type = $('#select_index_type'); - /** - * @var Object Table header for the size column. - */ - var $size_header = $('#index_columns').find('thead tr th:nth-child(2)'); - /** - * @var Object Inputs to specify the columns for the index. - */ - var $column_inputs = $('select[name="index[columns][names][]"]'); - /** - * @var Object Inputs to specify sizes for columns of the index. - */ - var $size_inputs = $('input[name="index[columns][sub_parts][]"]'); - /** - * @var Object Footer containg the controllers to add more columns - */ - var $add_more = $('#index_frm').find('.add_more'); - - if ($select_index_choice.val() === 'SPATIAL') { - // Disable and hide the size column - $size_header.hide(); - $size_inputs.each(function () { - $(this) - .prop('disabled', true) - .parent('td').hide(); - }); - - // Disable and hide the columns of the index other than the first one - var initial = true; - $column_inputs.each(function () { - $column_input = $(this); - if (! initial) { - $column_input - .prop('disabled', true) - .parent('td').hide(); - } else { - initial = false; - } - }); - - // Hide controllers to add more columns - $add_more.hide(); - } else { - // Enable and show the size column - $size_header.show(); - $size_inputs.each(function () { - $(this) - .prop('disabled', false) - .parent('td').show(); - }); - - // Enable and show the columns of the index - $column_inputs.each(function () { - $(this) - .prop('disabled', false) - .parent('td').show(); - }); - - // Show controllers to add more columns - $add_more.show(); - } - - if ($select_index_choice.val() === 'SPATIAL' || - $select_index_choice.val() === 'FULLTEXT') { - $select_index_type.val('').prop('disabled', true); - } else { - $select_index_type.prop('disabled', false); - } -} - -/** - * Sets current index information into form parameters. - * - * @param array source_array Array containing index columns - * @param string index_choice Choice of index - * - * @return void - */ -function PMA_setIndexFormParameters (source_array, index_choice) { - if (index_choice === 'index') { - $('input[name="indexes"]').val(JSON.stringify(source_array)); - } else { - $('input[name="' + index_choice + '_indexes"]').val(JSON.stringify(source_array)); - } -} - -/** - * Removes a column from an Index. - * - * @param string col_index Index of column in form - * - * @return void - */ -function PMA_removeColumnFromIndex (col_index) { - // Get previous index details. - var previous_index = $('select[name="field_key[' + col_index + ']"]') - .attr('data-index'); - if (previous_index.length) { - previous_index = previous_index.split(','); - var source_array = PMA_getIndexArray(previous_index[0]); - if (source_array === null) { - return; - } - - // Remove column from index array. - var source_length = source_array[previous_index[1]].columns.length; - for (var i = 0; i < source_length; i++) { - if (source_array[previous_index[1]].columns[i].col_index === col_index) { - source_array[previous_index[1]].columns.splice(i, 1); - } - } - - // Remove index completely if no columns left. - if (source_array[previous_index[1]].columns.length === 0) { - source_array.splice(previous_index[1], 1); - } - - // Update current index details. - $('select[name="field_key[' + col_index + ']"]').attr('data-index', ''); - // Update form index parameters. - PMA_setIndexFormParameters(source_array, previous_index[0].toLowerCase()); - } -} - -/** - * Adds a column to an Index. - * - * @param array source_array Array holding corresponding indexes - * @param string array_index Index of an INDEX in array - * @param string index_choice Choice of Index - * @param string col_index Index of column on form - * - * @return void - */ -function PMA_addColumnToIndex (source_array, array_index, index_choice, col_index) { - if (col_index >= 0) { - // Remove column from other indexes (if any). - PMA_removeColumnFromIndex(col_index); - } - var index_name = $('input[name="index[Key_name]"]').val(); - var index_comment = $('input[name="index[Index_comment]"]').val(); - var key_block_size = $('input[name="index[Key_block_size]"]').val(); - var parser = $('input[name="index[Parser]"]').val(); - var index_type = $('select[name="index[Index_type]"]').val(); - var columns = []; - $('#index_columns').find('tbody').find('tr').each(function () { - // Get columns in particular order. - var col_index = $(this).find('select[name="index[columns][names][]"]').val(); - var size = $(this).find('input[name="index[columns][sub_parts][]"]').val(); - columns.push({ - 'col_index': col_index, - 'size': size - }); - }); - - // Update or create an index. - source_array[array_index] = { - 'Key_name': index_name, - 'Index_comment': index_comment, - 'Index_choice': index_choice.toUpperCase(), - 'Key_block_size': key_block_size, - 'Parser': parser, - 'Index_type': index_type, - 'columns': columns - }; - - // Display index name (or column list) - var displayName = index_name; - if (displayName === '') { - var columnNames = []; - $.each(columns, function () { - columnNames.push($('input[name="field_name[' + this.col_index + ']"]').val()); - }); - displayName = '[' + columnNames.join(', ') + ']'; - } - $.each(columns, function () { - var id = 'index_name_' + this.col_index + '_8'; - var $name = $('#' + id); - if ($name.length === 0) { - $name = $('<a id="' + id + '" href="#" class="ajax show_index_dialog"></a>'); - $name.insertAfter($('select[name="field_key[' + this.col_index + ']"]')); - } - var $text = $('<small>').text(displayName); - $name.html($text); - }); - - if (col_index >= 0) { - // Update index details on form. - $('select[name="field_key[' + col_index + ']"]') - .attr('data-index', index_choice + ',' + array_index); - } - PMA_setIndexFormParameters(source_array, index_choice.toLowerCase()); -} - -/** - * Get choices list for a column to create a composite index with. - * - * @param string index_choice Choice of index - * @param array source_array Array hodling columns for particular index - * - * @return jQuery Object - */ -function PMA_getCompositeIndexList (source_array, col_index) { - // Remove any previous list. - if ($('#composite_index_list').length) { - $('#composite_index_list').remove(); - } - - // Html list. - var $composite_index_list = $( - '<ul id="composite_index_list">' + - '<div>' + PMA_messages.strCompositeWith + '</div>' + - '</ul>' - ); - - // Add each column to list available for composite index. - var source_length = source_array.length; - var already_present = false; - for (var i = 0; i < source_length; i++) { - var sub_array_len = source_array[i].columns.length; - var column_names = []; - for (var j = 0; j < sub_array_len; j++) { - column_names.push( - $('input[name="field_name[' + source_array[i].columns[j].col_index + ']"]').val() - ); - - if (col_index === source_array[i].columns[j].col_index) { - already_present = true; - } - } - - $composite_index_list.append( - '<li>' + - '<input type="radio" name="composite_with" ' + - (already_present ? 'checked="checked"' : '') + - ' id="composite_index_' + i + '" value="' + i + '">' + - '<label for="composite_index_' + i + '">' + column_names.join(', ') + - '</lablel>' + - '</li>' - ); - } - - return $composite_index_list; -} - -/** - * Shows 'Add Index' dialog. - * - * @param array source_array Array holding particluar index - * @param string array_index Index of an INDEX in array - * @param array target_columns Columns for an INDEX - * @param string col_index Index of column on form - * @param object index Index detail object - * - * @return void - */ -function PMA_showAddIndexDialog (source_array, array_index, target_columns, col_index, index) { - // Prepare post-data. - var $table = $('input[name="table"]'); - var table = $table.length > 0 ? $table.val() : ''; - var post_data = { - server: PMA_commonParams.get('server'), - db: $('input[name="db"]').val(), - table: table, - ajax_request: 1, - create_edit_table: 1, - index: index - }; - - var columns = {}; - for (var i = 0; i < target_columns.length; i++) { - var column_name = $('input[name="field_name[' + target_columns[i] + ']"]').val(); - var column_type = $('select[name="field_type[' + target_columns[i] + ']"]').val().toLowerCase(); - columns[column_name] = [column_type, target_columns[i]]; - } - post_data.columns = JSON.stringify(columns); - - var button_options = {}; - button_options[PMA_messages.strGo] = function () { - var is_missing_value = false; - $('select[name="index[columns][names][]"]').each(function () { - if ($(this).val() === '') { - is_missing_value = true; - } - }); - - if (! is_missing_value) { - PMA_addColumnToIndex( - source_array, - array_index, - index.Index_choice, - col_index - ); - } else { - PMA_ajaxShowMessage( - '<div class="error"><img src="themes/dot.gif" title="" alt=""' + - ' class="icon ic_s_error" /> ' + PMA_messages.strMissingColumn + - ' </div>', false - ); - - return false; - } - - $(this).dialog('close'); - }; - button_options[PMA_messages.strCancel] = function () { - if (col_index >= 0) { - // Handle state on 'Cancel'. - var $select_list = $('select[name="field_key[' + col_index + ']"]'); - if (! $select_list.attr('data-index').length) { - $select_list.find('option[value*="none"]').attr('selected', 'selected'); - } else { - var previous_index = $select_list.attr('data-index').split(','); - $select_list.find('option[value*="' + previous_index[0].toLowerCase() + '"]') - .attr('selected', 'selected'); - } - } - $(this).dialog('close'); - }; - var $msgbox = PMA_ajaxShowMessage(); - $.post('tbl_indexes.php', post_data, function (data) { - if (data.success === false) { - // in the case of an error, show the error message returned. - PMA_ajaxShowMessage(data.error, false); - } else { - PMA_ajaxRemoveMessage($msgbox); - // Show dialog if the request was successful - var $div = $('<div/>'); - $div - .append(data.message) - .dialog({ - title: PMA_messages.strAddIndex, - width: 450, - minHeight: 250, - open: function () { - checkIndexName('index_frm'); - PMA_showHints($div); - PMA_init_slider(); - $('#index_columns').find('td').each(function () { - $(this).css('width', $(this).width() + 'px'); - }); - $('#index_columns').find('tbody').sortable({ - axis: 'y', - containment: $('#index_columns').find('tbody'), - tolerance: 'pointer' - }); - // We dont need the slider at this moment. - $(this).find('fieldset.tblFooters').remove(); - }, - modal: true, - buttons: button_options, - close: function () { - $(this).remove(); - } - }); - } - }); -} - -/** - * Creates a advanced index type selection dialog. - * - * @param array source_array Array holding a particular type of indexes - * @param string index_choice Choice of index - * @param string col_index Index of new column on form - * - * @return void - */ -function PMA_indexTypeSelectionDialog (source_array, index_choice, col_index) { - var $single_column_radio = $('<input type="radio" id="single_column" name="index_choice"' + - ' checked="checked">' + - '<label for="single_column">' + PMA_messages.strCreateSingleColumnIndex + '</label>'); - var $composite_index_radio = $('<input type="radio" id="composite_index"' + - ' name="index_choice">' + - '<label for="composite_index">' + PMA_messages.strCreateCompositeIndex + '</label>'); - var $dialog_content = $('<fieldset id="advance_index_creator"></fieldset>'); - $dialog_content.append('<legend>' + index_choice.toUpperCase() + '</legend>'); - - - // For UNIQUE/INDEX type, show choice for single-column and composite index. - $dialog_content.append($single_column_radio); - $dialog_content.append($composite_index_radio); - - var button_options = {}; - // 'OK' operation. - button_options[PMA_messages.strGo] = function () { - if ($('#single_column').is(':checked')) { - var index = { - 'Key_name': (index_choice === 'primary' ? 'PRIMARY' : ''), - 'Index_choice': index_choice.toUpperCase() - }; - PMA_showAddIndexDialog(source_array, (source_array.length), [col_index], col_index, index); - } - - if ($('#composite_index').is(':checked')) { - if ($('input[name="composite_with"]').length !== 0 && $('input[name="composite_with"]:checked').length === 0 - ) { - PMA_ajaxShowMessage( - '<div class="error"><img src="themes/dot.gif" title=""' + - ' alt="" class="icon ic_s_error" /> ' + - PMA_messages.strFormEmpty + - ' </div>', - false - ); - return false; - } - - var array_index = $('input[name="composite_with"]:checked').val(); - var source_length = source_array[array_index].columns.length; - var target_columns = []; - for (var i = 0; i < source_length; i++) { - target_columns.push(source_array[array_index].columns[i].col_index); - } - target_columns.push(col_index); - - PMA_showAddIndexDialog(source_array, array_index, target_columns, col_index, - source_array[array_index]); - } - - $(this).remove(); - }; - button_options[PMA_messages.strCancel] = function () { - // Handle state on 'Cancel'. - var $select_list = $('select[name="field_key[' + col_index + ']"]'); - if (! $select_list.attr('data-index').length) { - $select_list.find('option[value*="none"]').attr('selected', 'selected'); - } else { - var previous_index = $select_list.attr('data-index').split(','); - $select_list.find('option[value*="' + previous_index[0].toLowerCase() + '"]') - .attr('selected', 'selected'); - } - $(this).remove(); - }; - var $dialog = $('<div/>').append($dialog_content).dialog({ - minWidth: 525, - minHeight: 200, - modal: true, - title: PMA_messages.strAddIndex, - resizable: false, - buttons: button_options, - open: function () { - $('#composite_index').on('change', function () { - if ($(this).is(':checked')) { - $dialog_content.append(PMA_getCompositeIndexList(source_array, col_index)); - } - }); - $('#single_column').on('change', function () { - if ($(this).is(':checked')) { - if ($('#composite_index_list').length) { - $('#composite_index_list').remove(); - } - } - }); - }, - close: function () { - $('#composite_index').off('change'); - $('#single_column').off('change'); - $(this).remove(); - } - }); -} - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('indexes.js', function () { - $(document).off('click', '#save_index_frm'); - $(document).off('click', '#preview_index_frm'); - $(document).off('change', '#select_index_choice'); - $(document).off('click', 'a.drop_primary_key_index_anchor.ajax'); - $(document).off('click', '#table_index tbody tr td.edit_index.ajax, #index_div .add_index.ajax'); - $(document).off('click', '#index_frm input[type=submit]'); - $('body').off('change', 'select[name*="field_key"]'); - $(document).off('click', '.show_index_dialog'); -}); - -/** - * @description <p>Ajax scripts for table index page</p> - * - * Actions ajaxified here: - * <ul> - * <li>Showing/hiding inputs depending on the index type chosen</li> - * <li>create/edit/drop indexes</li> - * </ul> - */ -AJAX.registerOnload('indexes.js', function () { - // Re-initialize variables. - primary_indexes = []; - unique_indexes = []; - indexes = []; - fulltext_indexes = []; - spatial_indexes = []; - - // for table creation form - var $engine_selector = $('.create_table_form select[name=tbl_storage_engine]'); - if ($engine_selector.length) { - PMA_hideShowConnection($engine_selector); - } - - var $form = $('#index_frm'); - if ($form.length > 0) { - showIndexEditDialog($form); - } - - $(document).on('click', '#save_index_frm', function (event) { - event.preventDefault(); - var $form = $('#index_frm'); - var argsep = PMA_commonParams.get('arg_separator'); - var submitData = $form.serialize() + argsep + 'do_save_data=1' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true'; - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - AJAX.source = $form; - $.post($form.attr('action'), submitData, AJAX.responseHandler); - }); - - $(document).on('click', '#preview_index_frm', function (event) { - event.preventDefault(); - PMA_previewSQL($('#index_frm')); - }); - - $(document).on('change', '#select_index_choice', function (event) { - event.preventDefault(); - checkIndexType(); - checkIndexName('index_frm'); - }); - - /** - * Ajax Event handler for 'Drop Index' - */ - $(document).on('click', 'a.drop_primary_key_index_anchor.ajax', function (event) { - event.preventDefault(); - var $anchor = $(this); - /** - * @var $curr_row Object containing reference to the current field's row - */ - var $curr_row = $anchor.parents('tr'); - /** @var Number of columns in the key */ - var rows = $anchor.parents('td').attr('rowspan') || 1; - /** @var Rows that should be hidden */ - var $rows_to_hide = $curr_row; - for (var i = 1, $last_row = $curr_row.next(); i < rows; i++, $last_row = $last_row.next()) { - $rows_to_hide = $rows_to_hide.add($last_row); - } - - var question = escapeHtml( - $curr_row.children('td') - .children('.drop_primary_key_index_msg') - .val() - ); - - $anchor.PMA_confirm(question, $anchor.attr('href'), function (url) { - var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingPrimaryKeyIndex, false); - var params = getJSConfirmCommonParam(this, $anchor.getPostData()); - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxRemoveMessage($msg); - var $table_ref = $rows_to_hide.closest('table'); - if ($rows_to_hide.length === $table_ref.find('tbody > tr').length) { - // We are about to remove all rows from the table - $table_ref.hide('medium', function () { - $('div.no_indexes_defined').show('medium'); - $rows_to_hide.remove(); - }); - $table_ref.siblings('div.notice').hide('medium'); - } else { - // We are removing some of the rows only - $rows_to_hide.hide('medium', function () { - $(this).remove(); - }); - } - if ($('.result_query').length) { - $('.result_query').remove(); - } - if (data.sql_query) { - $('<div class="result_query"></div>') - .html(data.sql_query) - .prependTo('#structure_content'); - PMA_highlightSQL($('#page_content')); - } - PMA_commonActions.refreshMain(false, function () { - $('a.ajax[href^=#indexes]').trigger('click'); - }); - PMA_reloadNavigation(); - } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); - } - }); // end $.post() - }); // end $.PMA_confirm() - }); // end Drop Primary Key/Index - - /** - *Ajax event handler for index edit - **/ - $(document).on('click', '#table_index tbody tr td.edit_index.ajax, #index_div .add_index.ajax', function (event) { - event.preventDefault(); - var url; - var title; - if ($(this).find('a').length === 0) { - // Add index - var valid = checkFormElementInRange( - $(this).closest('form')[0], - 'added_fields', - 'Column count has to be larger than zero.' - ); - if (! valid) { - return; - } - url = $(this).closest('form').serialize(); - title = PMA_messages.strAddIndex; - } else { - // Edit index - url = $(this).find('a').attr('href'); - if (url.substring(0, 16) === 'tbl_indexes.php?') { - url = url.substring(16, url.length); - } - title = PMA_messages.strEditIndex; - } - url += PMA_commonParams.get('arg_separator') + 'ajax_request=true'; - indexEditorDialog(url, title, function () { - // refresh the page using ajax - PMA_commonActions.refreshMain(false, function () { - $('a.ajax[href^=#indexes]').trigger('click'); - }); - }); - }); - - /** - * Ajax event handler for advanced index creation during table creation - * and column addition. - */ - $('body').on('change', 'select[name*="field_key"]', function () { - // Index of column on Table edit and create page. - var col_index = /\d+/.exec($(this).attr('name')); - col_index = col_index[0]; - // Choice of selected index. - var index_choice = /[a-z]+/.exec($(this).val()); - index_choice = index_choice[0]; - // Array containing corresponding indexes. - var source_array = null; - - if (index_choice === 'none') { - PMA_removeColumnFromIndex(col_index); - return false; - } - - // Select a source array. - source_array = PMA_getIndexArray(index_choice); - if (source_array === null) { - return; - } - - if (source_array.length === 0) { - var index = { - 'Key_name': (index_choice === 'primary' ? 'PRIMARY' : ''), - 'Index_choice': index_choice.toUpperCase() - }; - PMA_showAddIndexDialog(source_array, 0, [col_index], col_index, index); - } else { - if (index_choice === 'primary') { - var array_index = 0; - var source_length = source_array[array_index].columns.length; - var target_columns = []; - for (var i = 0; i < source_length; i++) { - target_columns.push(source_array[array_index].columns[i].col_index); - } - target_columns.push(col_index); - - PMA_showAddIndexDialog(source_array, array_index, target_columns, col_index, - source_array[array_index]); - } else { - // If there are multiple columns selected for an index, show advanced dialog. - PMA_indexTypeSelectionDialog(source_array, index_choice, col_index); - } - } - }); - - $(document).on('click', '.show_index_dialog', function (e) { - e.preventDefault(); - - // Get index details. - var previous_index = $(this).prev('select') - .attr('data-index') - .split(','); - - var index_choice = previous_index[0]; - var array_index = previous_index[1]; - - var source_array = PMA_getIndexArray(index_choice); - var source_length = source_array[array_index].columns.length; - - var target_columns = []; - for (var i = 0; i < source_length; i++) { - target_columns.push(source_array[array_index].columns[i].col_index); - } - - PMA_showAddIndexDialog(source_array, array_index, target_columns, -1, source_array[array_index]); - }); - - $('#index_frm').on('submit', function () { - if (typeof(this.elements['index[Key_name]'].disabled) !== 'undefined') { - this.elements['index[Key_name]'].disabled = false; - } - }); -}); diff --git a/js/microhistory.js b/js/microhistory.js deleted file mode 100644 index 46c98a88ff..0000000000 --- a/js/microhistory.js +++ /dev/null @@ -1,335 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * An implementation of a client-side page cache. - * This object also uses the cache to provide a simple microhistory, - * that is the ability to use the back and forward buttons in the browser - */ -PMA_MicroHistory = { - /** - * @var int The maximum number of pages to keep in the cache - */ - MAX: 6, - /** - * @var object A hash used to prime the cache with data about the initially - * loaded page. This is set in the footer, and then loaded - * by a double-queued event further down this file. - */ - primer: {}, - /** - * @var array Stores the content of the cached pages - */ - pages: [], - /** - * @var int The index of the currently loaded page - * This is used to know at which point in the history we are - */ - current: 0, - /** - * Saves a new page in the cache - * - * @param string hash The hash part of the url that is being loaded - * @param array scripts A list of scripts that is required for the page - * @param string menu A hash that links to a menu stored - * in a dedicated menu cache - * @param array params A list of parameters used by PMA_commonParams() - * @param string rel A relationship to the current page: - * 'samepage': Forces the response to be treated as - * the same page as the current one - * 'newpage': Forces the response to be treated as - * a new page - * undefined: Default behaviour, 'samepage' if the - * selflinks of the two pages are the same. - * 'newpage' otherwise - * - * @return void - */ - add: function (hash, scripts, menu, params, rel) { - if (this.pages.length > PMA_MicroHistory.MAX) { - // Trim the cache, to the maximum number of allowed entries - // This way we will have a cached menu for every page - for (var i = 0; i < this.pages.length - this.MAX; i++) { - delete this.pages[i]; - } - } - while (this.current < this.pages.length) { - // trim the cache if we went back in the history - // and are now going forward again - this.pages.pop(); - } - if (rel === 'newpage' || - ( - typeof rel === 'undefined' && ( - typeof this.pages[this.current - 1] === 'undefined' || - this.pages[this.current - 1].hash !== hash - ) - ) - ) { - this.pages.push({ - hash: hash, - content: $('#page_content').html(), - scripts: scripts, - selflink: $('#selflink').html(), - menu: menu, - params: params - }); - PMA_SetUrlHash(this.current, hash); - this.current++; - } - }, - /** - * Restores a page from the cache. This is called when the hash - * part of the url changes and it's structure appears to be valid - * - * @param string index Which page from the history to load - * - * @return void - */ - navigate: function (index) { - if (typeof this.pages[index] === 'undefined' || - typeof this.pages[index].content === 'undefined' || - typeof this.pages[index].menu === 'undefined' || - ! PMA_MicroHistory.menus.get(this.pages[index].menu) - ) { - PMA_ajaxShowMessage( - '<div class="error">' + PMA_messages.strInvalidPage + '</div>', - false - ); - } else { - AJAX.active = true; - var record = this.pages[index]; - AJAX.scriptHandler.reset(function () { - $('#page_content').html(record.content); - $('#selflink').html(record.selflink); - PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(record.menu)); - PMA_commonParams.setAll(record.params); - AJAX.scriptHandler.load(record.scripts); - PMA_MicroHistory.current = ++index; - }); - } - }, - /** - * Resaves the content of the current page in the cache. - * Necessary in order not to show the user some outdated version of the page - * - * @return void - */ - update: function () { - var page = this.pages[this.current - 1]; - if (page) { - page.content = $('#page_content').html(); - } - }, - /** - * @var object Dedicated menu cache - */ - menus: { - /** - * Returns the number of items in an associative array - * - * @return int - */ - size: function (obj) { - var size = 0; - var key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - size++; - } - } - return size; - }, - /** - * @var hash Stores the content of the cached menus - */ - data: {}, - /** - * Saves a new menu in the cache - * - * @param string hash The hash (trimmed md5) of the menu to be saved - * @param string content The HTML code of the menu to be saved - * - * @return void - */ - add: function (hash, content) { - if (this.size(this.data) > PMA_MicroHistory.MAX) { - // when the cache grows, we remove the oldest entry - var oldest; - var key; - var init = 0; - for (var i in this.data) { - if (this.data[i]) { - if (! init || this.data[i].timestamp.getTime() < oldest.getTime()) { - oldest = this.data[i].timestamp; - key = i; - init = 1; - } - } - } - delete this.data[key]; - } - this.data[hash] = { - content: content, - timestamp: new Date() - }; - }, - /** - * Retrieves a menu given its hash - * - * @param string hash The hash of the menu to be retrieved - * - * @return string - */ - get: function (hash) { - if (this.data[hash]) { - return this.data[hash].content; - } else { - // This should never happen as long as the number of stored menus - // is larger or equal to the number of pages in the page cache - return ''; - } - }, - /** - * Prepares part of the parameter string used during page requests, - * this is necessary to tell the server which menus we have in the cache - * - * @return string - */ - getRequestParam: function () { - var param = ''; - var menuHashes = []; - for (var i in this.data) { - menuHashes.push(i); - } - var menuHashesParam = menuHashes.join('-'); - if (menuHashesParam) { - param = PMA_commonParams.get('arg_separator') + 'menuHashes=' + menuHashesParam; - } - return param; - }, - /** - * Replaces the menu with new content - * - * @return void - */ - replace: function (content) { - $('#floating_menubar').html(content) - // Remove duplicate wrapper - // TODO: don't send it in the response - .children().first().remove(); - $('#topmenu').menuResizer(PMA_mainMenuResizerCallback); - } - } -}; - -/** - * URL hash management module. - * Allows direct bookmarking and microhistory. - */ -PMA_SetUrlHash = (function (jQuery, window) { - 'use strict'; - /** - * Indictaes whether we have already completed - * the initialisation of the hash - * - * @access private - */ - var ready = false; - /** - * Stores a hash that needed to be set when we were not ready - * - * @access private - */ - var savedHash = ''; - /** - * Flag to indicate if the change of hash was triggered - * by a user pressing the back/forward button or if - * the change was triggered internally - * - * @access private - */ - var userChange = true; - - // Fix favicon disappearing in Firefox when setting location.hash - function resetFavicon () { - if (navigator.userAgent.indexOf('Firefox') > -1) { - // Move the link tags for the favicon to the bottom - // of the head element to force a reload of the favicon - $('head > link[href="favicon\\.ico"]').appendTo('head'); - } - } - - /** - * Sets the hash part of the URL - * - * @access public - */ - function setUrlHash (index, hash) { - /* - * Known problem: - * Setting hash leads to reload in webkit: - * http://www.quirksmode.org/bugreports/archives/2005/05/Safari_13_visual_anomaly_with_windowlocationhref.html - * - * so we expect that users are not running an ancient Safari version - */ - - userChange = false; - if (ready) { - window.location.hash = 'PMAURL-' + index + ':' + hash; - resetFavicon(); - } else { - savedHash = 'PMAURL-' + index + ':' + hash; - } - } - /** - * Start initialisation - */ - var urlhash = window.location.hash; - if (urlhash.substring(0, 8) === '#PMAURL-') { - // We have a valid hash, let's redirect the user - // to the page that it's pointing to - var colon_position = urlhash.indexOf(':'); - var questionmark_position = urlhash.indexOf('?'); - if (colon_position !== -1 && questionmark_position !== -1 && colon_position < questionmark_position) { - var hash_url = urlhash.substring(colon_position + 1, questionmark_position); - if (PMA_gotoWhitelist.indexOf(hash_url) !== -1) { - window.location = urlhash.substring( - colon_position + 1 - ); - } - } - } else { - // We don't have a valid hash, so we'll set it up - // when the page finishes loading - jQuery(function () { - /* Check if we should set URL */ - if (savedHash !== '') { - window.location.hash = savedHash; - savedHash = ''; - resetFavicon(); - } - // Indicate that we're done initialising - ready = true; - }); - } - /** - * Register an event handler for when the url hash changes - */ - jQuery(function () { - jQuery(window).hashchange(function () { - if (userChange === false) { - // Ignore internally triggered hash changes - userChange = true; - } else if (/^#PMAURL-\d+:/.test(window.location.hash)) { - // Change page if the hash changed was triggered by a user action - var index = window.location.hash.substring( - 8, window.location.hash.indexOf(':') - ); - PMA_MicroHistory.navigate(index); - } - }); - }); - /** - * Publicly exposes a reference to the otherwise private setUrlHash function - */ - return setUrlHash; -}(jQuery, window)); diff --git a/js/server_databases.js b/js/server_databases.js deleted file mode 100644 index 2285619b74..0000000000 --- a/js/server_databases.js +++ /dev/null @@ -1,149 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview functions used on the server databases list page - * @name Server Databases - * - * @requires jQuery - * @requires jQueryUI - * @required js/functions.js - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_databases.js', function () { - $(document).off('submit', '#dbStatsForm'); - $(document).off('submit', '#create_database_form.ajax'); -}); - -/** - * AJAX scripts for server_databases.php - * - * Actions ajaxified here: - * Drop Databases - * - */ -AJAX.registerOnload('server_databases.js', function () { - /** - * Attach Event Handler for 'Drop Databases' - */ - $(document).on('submit', '#dbStatsForm', function (event) { - event.preventDefault(); - - var $form = $(this); - - /** - * @var selected_dbs Array containing the names of the checked databases - */ - var selected_dbs = []; - // loop over all checked checkboxes, except the .checkall_box checkbox - $form.find('input:checkbox:checked:not(.checkall_box)').each(function () { - $(this).closest('tr').addClass('removeMe'); - selected_dbs[selected_dbs.length] = 'DROP DATABASE `' + escapeHtml($(this).val()) + '`;'; - }); - if (! selected_dbs.length) { - PMA_ajaxShowMessage( - $('<div class="notice" />').text( - PMA_messages.strNoDatabasesSelected - ), - 2000 - ); - return; - } - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_messages.strDropDatabaseStrongWarning + ' ' + - PMA_sprintf(PMA_messages.strDoYouReally, selected_dbs.join('<br />')); - - var argsep = PMA_commonParams.get('arg_separator'); - $(this).PMA_confirm( - question, - $form.prop('action') + '?' + $(this).serialize() + - argsep + 'drop_selected_dbs=1' + argsep + 'is_js_confirmed=1' + argsep + 'ajax_request=true', - function (url) { - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest, false); - - var params = getJSConfirmCommonParam(this); - - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - - var $rowsToRemove = $form.find('tr.removeMe'); - var $databasesCount = $('#filter-rows-count'); - var newCount = parseInt($databasesCount.text(), 10) - $rowsToRemove.length; - $databasesCount.text(newCount); - - $rowsToRemove.remove(); - $form.find('tbody').PMA_sort_table('.name'); - if ($form.find('tbody').find('tr').length === 0) { - // user just dropped the last db on this page - PMA_commonActions.refreshMain(); - } - PMA_reloadNavigation(); - } else { - $form.find('tr.removeMe').removeClass('removeMe'); - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - } - ); // end $.PMA_confirm() - }); // end of Drop Database action - - /** - * Attach Ajax event handlers for 'Create Database'. - */ - $(document).on('submit', '#create_database_form.ajax', function (event) { - event.preventDefault(); - - var $form = $(this); - - // TODO Remove this section when all browsers support HTML5 "required" property - var newDbNameInput = $form.find('input[name=new_db]'); - if (newDbNameInput.val() === '') { - newDbNameInput.focus(); - alert(PMA_messages.strFormEmpty); - return; - } - // end remove - - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - PMA_prepareForAjaxRequest($form); - - $.post($form.attr('action'), $form.serialize(), function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - - var $databases_count_object = $('#filter-rows-count'); - var databases_count = parseInt($databases_count_object.text(), 10) + 1; - $databases_count_object.text(databases_count); - PMA_reloadNavigation(); - - // make ajax request to load db structure page - taken from ajax.js - var dbStruct_url = data.url_query; - dbStruct_url = dbStruct_url.replace(/amp;/ig, ''); - var params = 'ajax_request=true' + PMA_commonParams.get('arg_separator') + 'ajax_page_request=true'; - if (! (history && history.pushState)) { - params += PMA_MicroHistory.menus.getRequestParam(); - } - $.get(dbStruct_url, params, AJAX.responseHandler); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }); // end $(document).on() - - /* Don't show filter if number of databases are very few */ - var databasesCount = $('#filter-rows-count').html(); - if (databasesCount <= 10) { - $('#tableFilter').hide(); - } - - var tableRows = $('.server_databases'); - $.each(tableRows, function (index, item) { - $(this).on('click', function () { - PMA_commonActions.setDb($(this).attr('data')); - }); - }); -}); // end $() diff --git a/js/server_plugins.js b/js/server_plugins.js deleted file mode 100644 index 7baadabd82..0000000000 --- a/js/server_plugins.js +++ /dev/null @@ -1,16 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * Functions used in server plugins pages - */ -AJAX.registerOnload('server_plugins.js', function () { - // Make columns sortable, but only for tables with more than 1 data row - var $tables = $('#plugins_plugins table:has(tbody tr + tr)'); - $tables.tablesorter({ - sortList: [[0, 0]], - headers: { - 1: { sorter: false } - } - }); - $tables.find('thead th') - .append('<div class="sorticon"></div>'); -}); diff --git a/js/server_privileges.js b/js/server_privileges.js deleted file mode 100644 index d03d68f3df..0000000000 --- a/js/server_privileges.js +++ /dev/null @@ -1,426 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview functions used in server privilege pages - * @name Server Privileges - * - * @requires jQuery - * @requires jQueryUI - * @requires js/functions.js - * - */ - -/** - * AJAX scripts for server_privileges page. - * - * Actions ajaxified here: - * Add user - * Revoke a user - * Edit privileges - * Export privileges - * Paginate table of users - * Flush privileges - * - * @memberOf jQuery - * @name document.ready - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_privileges.js', function () { - $('#fieldset_add_user_login').off('change', 'input[name=\'username\']'); - $(document).off('click', '#fieldset_delete_user_footer #buttonGo.ajax'); - $(document).off('click', 'a.edit_user_group_anchor.ajax'); - $(document).off('click', 'button.mult_submit[value=export]'); - $(document).off('click', 'a.export_user_anchor.ajax'); - $(document).off('click', '#initials_table a.ajax'); - $('#checkbox_drop_users_db').off('click'); - $(document).off('click', '.checkall_box'); - $(document).off('change', '#checkbox_SSL_priv'); - $(document).off('change', 'input[name="ssl_type"]'); - $(document).off('change', '#select_authentication_plugin'); -}); - -AJAX.registerOnload('server_privileges.js', function () { - /** - * Display a warning if there is already a user by the name entered as the username. - */ - $('#fieldset_add_user_login').on('change', 'input[name=\'username\']', function () { - var username = $(this).val(); - var $warning = $('#user_exists_warning'); - if ($('#select_pred_username').val() === 'userdefined' && username !== '') { - var href = $('form[name=\'usersForm\']').attr('action'); - var params = { - 'ajax_request' : true, - 'server' : PMA_commonParams.get('server'), - 'validate_username' : true, - 'username' : username - }; - $.get(href, params, function (data) { - if (data.user_exists) { - $warning.show(); - } else { - $warning.hide(); - } - }); - } else { - $warning.hide(); - } - }); - - /** - * Indicating password strength - */ - $('#text_pma_pw').on('keyup', function () { - meter_obj = $('#password_strength_meter'); - meter_obj_label = $('#password_strength'); - username = $('input[name="username"]'); - username = username.val(); - checkPasswordStrength($(this).val(), meter_obj, meter_obj_label, username); - }); - - $('#text_pma_change_pw').on('keyup', function () { - meter_obj = $('#change_password_strength_meter'); - meter_obj_label = $('#change_password_strength'); - checkPasswordStrength($(this).val(), meter_obj, meter_obj_label, PMA_commonParams.get('user')); - }); - - /** - * Display a notice if sha256_password is selected - */ - $(document).on('change', '#select_authentication_plugin', function () { - var selected_plugin = $(this).val(); - if (selected_plugin === 'sha256_password') { - $('#ssl_reqd_warning').show(); - } else { - $('#ssl_reqd_warning').hide(); - } - }); - - /** - * AJAX handler for 'Revoke User' - * - * @see PMA_ajaxShowMessage() - * @memberOf jQuery - * @name revoke_user_click - */ - $(document).on('click', '#fieldset_delete_user_footer #buttonGo.ajax', function (event) { - event.preventDefault(); - - var $thisButton = $(this); - var $form = $('#usersForm'); - - $thisButton.PMA_confirm(PMA_messages.strDropUserWarning, $form.attr('action'), function (url) { - var $drop_users_db_checkbox = $('#checkbox_drop_users_db'); - if ($drop_users_db_checkbox.is(':checked')) { - var is_confirmed = confirm(PMA_messages.strDropDatabaseStrongWarning + '\n' + PMA_sprintf(PMA_messages.strDoYouReally, 'DROP DATABASE')); - if (! is_confirmed) { - // Uncheck the drop users database checkbox - $drop_users_db_checkbox.prop('checked', false); - } - } - - PMA_ajaxShowMessage(PMA_messages.strRemovingSelectedUsers); - - var argsep = PMA_commonParams.get('arg_separator'); - $.post(url, $form.serialize() + argsep + 'delete=' + $thisButton.val() + argsep + 'ajax_request=true', function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - // Refresh navigation, if we droppped some databases with the name - // that is the same as the username of the deleted user - if ($('#checkbox_drop_users_db:checked').length) { - PMA_reloadNavigation(); - } - // Remove the revoked user from the users list - $form.find('input:checkbox:checked').parents('tr').slideUp('medium', function () { - var this_user_initial = $(this).find('input:checkbox').val().charAt(0).toUpperCase(); - $(this).remove(); - - // If this is the last user with this_user_initial, remove the link from #initials_table - if ($('#tableuserrights').find('input:checkbox[value^="' + this_user_initial + '"], input:checkbox[value^="' + this_user_initial.toLowerCase() + '"]').length === 0) { - $('#initials_table').find('td > a:contains(' + this_user_initial + ')').parent('td').html(this_user_initial); - } - - // Re-check the classes of each row - $form - .find('tbody').find('tr:odd') - .removeClass('even').addClass('odd') - .end() - .find('tr:even') - .removeClass('odd').addClass('even'); - - // update the checkall checkbox - $(checkboxes_sel).trigger('change'); - }); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }); - }); // end Revoke User - - $(document).on('click', 'a.edit_user_group_anchor.ajax', function (event) { - event.preventDefault(); - $(this).parents('tr').addClass('current_row'); - var $msg = PMA_ajaxShowMessage(); - $.get( - $(this).attr('href'), - { - 'ajax_request': true, - 'edit_user_group_dialog': true - }, - function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxRemoveMessage($msg); - var buttonOptions = {}; - buttonOptions[PMA_messages.strGo] = function () { - var usrGroup = $('#changeUserGroupDialog') - .find('select[name="userGroup"]') - .val(); - var $message = PMA_ajaxShowMessage(); - var argsep = PMA_commonParams.get('arg_separator'); - $.post( - 'server_privileges.php', - $('#changeUserGroupDialog').find('form').serialize() + argsep + 'ajax_request=1', - function (data) { - PMA_ajaxRemoveMessage($message); - if (typeof data !== 'undefined' && data.success === true) { - $('#usersForm') - .find('.current_row') - .removeClass('current_row') - .find('.usrGroup') - .text(usrGroup); - } else { - PMA_ajaxShowMessage(data.error, false); - $('#usersForm') - .find('.current_row') - .removeClass('current_row'); - } - } - ); - $(this).dialog('close'); - }; - buttonOptions[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - var $dialog = $('<div/>') - .attr('id', 'changeUserGroupDialog') - .append(data.message) - .dialog({ - width: 500, - minWidth: 300, - modal: true, - buttons: buttonOptions, - title: $('legend', $(data.message)).text(), - close: function () { - $(this).remove(); - } - }); - $dialog.find('legend').remove(); - } else { - PMA_ajaxShowMessage(data.error, false); - $('#usersForm') - .find('.current_row') - .removeClass('current_row'); - } - } - ); - }); - - /** - * AJAX handler for 'Export Privileges' - * - * @see PMA_ajaxShowMessage() - * @memberOf jQuery - * @name export_user_click - */ - $(document).on('click', 'button.mult_submit[value=export]', function (event) { - event.preventDefault(); - // can't export if no users checked - if ($(this.form).find('input:checked').length === 0) { - PMA_ajaxShowMessage(PMA_messages.strNoAccountSelected, 2000, 'success'); - return; - } - var $msgbox = PMA_ajaxShowMessage(); - var button_options = {}; - button_options[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - var argsep = PMA_commonParams.get('arg_separator'); - $.post( - $(this.form).prop('action'), - $(this.form).serialize() + argsep + 'submit_mult=export' + argsep + 'ajax_request=true', - function (data) { - if (typeof data !== 'undefined' && data.success === true) { - var $ajaxDialog = $('<div />') - .append(data.message) - .dialog({ - title: data.title, - width: 500, - buttons: button_options, - close: function () { - $(this).remove(); - } - }); - PMA_ajaxRemoveMessage($msgbox); - // Attach syntax highlighted editor to export dialog - PMA_getSQLEditor($ajaxDialog.find('textarea')); - } else { - PMA_ajaxShowMessage(data.error, false); - } - } - ); // end $.post - }); - // if exporting non-ajax, highlight anyways - PMA_getSQLEditor($('textarea.export')); - - $(document).on('click', 'a.export_user_anchor.ajax', function (event) { - event.preventDefault(); - var $msgbox = PMA_ajaxShowMessage(); - /** - * @var button_options Object containing options for jQueryUI dialog buttons - */ - var button_options = {}; - button_options[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - $.get($(this).attr('href'), { 'ajax_request': true }, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - var $ajaxDialog = $('<div />') - .append(data.message) - .dialog({ - title: data.title, - width: 500, - buttons: button_options, - close: function () { - $(this).remove(); - } - }); - PMA_ajaxRemoveMessage($msgbox); - // Attach syntax highlighted editor to export dialog - PMA_getSQLEditor($ajaxDialog.find('textarea')); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.get - }); // end export privileges - - /** - * AJAX handler to Paginate the Users Table - * - * @see PMA_ajaxShowMessage() - * @name paginate_users_table_click - * @memberOf jQuery - */ - $(document).on('click', '#initials_table a.ajax', function (event) { - event.preventDefault(); - var $msgbox = PMA_ajaxShowMessage(); - $.get($(this).attr('href'), { 'ajax_request' : true }, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxRemoveMessage($msgbox); - // This form is not on screen when first entering Privileges - // if there are more than 50 users - $('div.notice').remove(); - $('#usersForm').hide('medium').remove(); - $('#fieldset_add_user').hide('medium').remove(); - $('#initials_table') - .prop('id', 'initials_table_old') - .after(data.message).show('medium') - .siblings('h2').not(':first').remove(); - // prevent double initials table - $('#initials_table_old').remove(); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.get - }); // end of the paginate users table - - $(document).on('change', 'input[name="ssl_type"]', function (e) { - var $div = $('#specified_div'); - if ($('#ssl_type_SPECIFIED').is(':checked')) { - $div.find('input').prop('disabled', false); - } else { - $div.find('input').prop('disabled', true); - } - }); - - $(document).on('change', '#checkbox_SSL_priv', function (e) { - var $div = $('#require_ssl_div'); - if ($(this).is(':checked')) { - $div.find('input').prop('disabled', false); - $('#ssl_type_SPECIFIED').trigger('change'); - } else { - $div.find('input').prop('disabled', true); - } - }); - - $('#checkbox_SSL_priv').trigger('change'); - - /* - * Create submenu for simpler interface - */ - var addOrUpdateSubmenu = function () { - var $topmenu2 = $('#topmenu2'); - var $edit_user_dialog = $('#edit_user_dialog'); - var submenu_label; - var submenu_link; - var link_number; - - // if submenu exists yet, remove it first - if ($topmenu2.length > 0) { - $topmenu2.remove(); - } - - // construct a submenu from the existing fieldsets - $topmenu2 = $('<ul/>').prop('id', 'topmenu2'); - - $('#edit_user_dialog .submenu-item').each(function () { - submenu_label = $(this).find('legend[data-submenu-label]').data('submenu-label'); - - submenu_link = $('<a/>') - .prop('href', '#') - .html(submenu_label); - - $('<li/>') - .append(submenu_link) - .appendTo($topmenu2); - }); - - // click handlers for submenu - $topmenu2.find('a').on('click', function (e) { - e.preventDefault(); - // if already active, ignore click - if ($(this).hasClass('tabactive')) { - return; - } - $topmenu2.find('a').removeClass('tabactive'); - $(this).addClass('tabactive'); - - // which section to show now? - link_number = $topmenu2.find('a').index($(this)); - // hide all sections but the one to show - $('#edit_user_dialog .submenu-item').hide().eq(link_number).show(); - }); - - // make first menu item active - // TODO: support URL hash history - $topmenu2.find('> :first-child a').addClass('tabactive'); - $edit_user_dialog.prepend($topmenu2); - - // hide all sections but the first - $('#edit_user_dialog .submenu-item').hide().eq(0).show(); - - // scroll to the top - $('html, body').animate({ scrollTop: 0 }, 'fast'); - }; - - $('input.autofocus').focus(); - $(checkboxes_sel).trigger('change'); - displayPasswordGenerateButton(); - if ($('#edit_user_dialog').length > 0) { - addOrUpdateSubmenu(); - } - - var windowwidth = $(window).width(); - $('.jsresponsive').css('max-width', (windowwidth - 35) + 'px'); -}); diff --git a/js/server_status_advisor.js b/js/server_status_advisor.js deleted file mode 100644 index d5f65c8f4b..0000000000 --- a/js/server_status_advisor.js +++ /dev/null @@ -1,101 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * Server Status Advisor - * - * @package PhpMyAdmin - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_status_advisor.js', function () { - $('a[href="#openAdvisorInstructions"]').off('click'); - $('#statustabs_advisor').html(''); - $('#advisorDialog').remove(); - $('#instructionsDialog').remove(); -}); - -AJAX.registerOnload('server_status_advisor.js', function () { - // if no advisor is loaded - if ($('#advisorData').length === 0) { - return; - } - - /** ** Server config advisor ****/ - var $dialog = $('<div />').attr('id', 'advisorDialog'); - var $instructionsDialog = $('<div />') - .attr('id', 'instructionsDialog') - .html($('#advisorInstructionsDialog').html()); - - $('a[href="#openAdvisorInstructions"]').on('click', function () { - var dlgBtns = {}; - dlgBtns[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - $instructionsDialog.dialog({ - title: PMA_messages.strAdvisorSystem, - width: 700, - buttons: dlgBtns - }); - }); - - var $cnt = $('#statustabs_advisor'); - var $tbody; - var $tr; - var str; - var even = true; - - data = JSON.parse($('#advisorData').text()); - $cnt.html(''); - - if (data.parse.errors.length > 0) { - $cnt.append('<b>Rules file not well formed, following errors were found:</b><br />- '); - $cnt.append(data.parse.errors.join('<br/>- ')); - $cnt.append('<p></p>'); - } - - if (data.run.errors.length > 0) { - $cnt.append('<b>Errors occurred while executing rule expressions:</b><br />- '); - $cnt.append(data.run.errors.join('<br/>- ')); - $cnt.append('<p></p>'); - } - - if (data.run.fired.length > 0) { - $cnt.append('<p><b>' + PMA_messages.strPerformanceIssues + '</b></p>'); - $cnt.append('<table class="data" id="rulesFired" border="0"><thead><tr>' + - '<th>' + PMA_messages.strIssuse + '</th><th>' + PMA_messages.strRecommendation + - '</th></tr></thead><tbody></tbody></table>'); - $tbody = $cnt.find('table#rulesFired'); - - var rc_stripped; - - $.each(data.run.fired, function (key, value) { - // recommendation may contain links, don't show those in overview table (clicking on them redirects the user) - rc_stripped = $.trim($('<div>').html(value.recommendation).text()); - $tbody.append($tr = $('<tr class="linkElem noclick"><td>' + - value.issue + '</td><td>' + rc_stripped + ' </td></tr>')); - even = !even; - $tr.data('rule', value); - - $tr.on('click', function () { - var rule = $(this).data('rule'); - $dialog - .dialog({ title: PMA_messages.strRuleDetails }) - .html( - '<p><b>' + PMA_messages.strIssuse + ':</b><br />' + rule.issue + '</p>' + - '<p><b>' + PMA_messages.strRecommendation + ':</b><br />' + rule.recommendation + '</p>' + - '<p><b>' + PMA_messages.strJustification + ':</b><br />' + rule.justification + '</p>' + - '<p><b>' + PMA_messages.strFormula + ':</b><br />' + rule.formula + '</p>' + - '<p><b>' + PMA_messages.strTest + ':</b><br />' + rule.test + '</p>' - ); - - var dlgBtns = {}; - dlgBtns[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - - $dialog.dialog({ width: 600, buttons: dlgBtns }); - }); - }); - } -}); diff --git a/js/server_status_monitor.js b/js/server_status_monitor.js deleted file mode 100644 index e6b67e920c..0000000000 --- a/js/server_status_monitor.js +++ /dev/null @@ -1,2180 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -var runtime = {}; -var server_time_diff; -var server_os; -var is_superuser; -var server_db_isLocal; -var chartSize; -AJAX.registerOnload('server_status_monitor.js', function () { - var $js_data_form = $('#js_data'); - server_time_diff = new Date().getTime() - $js_data_form.find('input[name=server_time]').val(); - server_os = $js_data_form.find('input[name=server_os]').val(); - is_superuser = $js_data_form.find('input[name=is_superuser]').val(); - server_db_isLocal = $js_data_form.find('input[name=server_db_isLocal]').val(); -}); - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_status_monitor.js', function () { - $('#emptyDialog').remove(); - $('#addChartDialog').remove(); - $('a.popupLink').off('click'); - $('body').off('click'); -}); -/** - * Popup behaviour - */ -AJAX.registerOnload('server_status_monitor.js', function () { - $('<div />') - .attr('id', 'emptyDialog') - .appendTo('#page_content'); - $('#addChartDialog') - .appendTo('#page_content'); - - $('a.popupLink').on('click', function () { - var $link = $(this); - $('div.' + $link.attr('href').substr(1)) - .show() - .offset({ top: $link.offset().top + $link.height() + 5, left: $link.offset().left }) - .addClass('openedPopup'); - - return false; - }); - $('body').on('click', function (event) { - $('div.openedPopup').each(function () { - var $cnt = $(this); - var pos = $cnt.offset(); - // Hide if the mouseclick is outside the popupcontent - if (event.pageX < pos.left || - event.pageY < pos.top || - event.pageX > pos.left + $cnt.outerWidth() || - event.pageY > pos.top + $cnt.outerHeight() - ) { - $cnt.hide().removeClass('openedPopup'); - } - }); - }); -}); - -AJAX.registerTeardown('server_status_monitor.js', function () { - $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').off('click'); - $('div.popupContent select[name="chartColumns"]').off('change'); - $('div.popupContent select[name="gridChartRefresh"]').off('change'); - $('a[href="#addNewChart"]').off('click'); - $('a[href="#exportMonitorConfig"]').off('click'); - $('a[href="#importMonitorConfig"]').off('click'); - $('a[href="#clearMonitorConfig"]').off('click'); - $('a[href="#pauseCharts"]').off('click'); - $('a[href="#monitorInstructionsDialog"]').off('click'); - $('input[name="chartType"]').off('click'); - $('input[name="useDivisor"]').off('click'); - $('input[name="useUnit"]').off('click'); - $('select[name="varChartList"]').off('click'); - $('a[href="#kibDivisor"]').off('click'); - $('a[href="#mibDivisor"]').off('click'); - $('a[href="#submitClearSeries"]').off('click'); - $('a[href="#submitAddSeries"]').off('click'); - // $("input#variableInput").destroy(); - $('#chartPreset').off('click'); - $('#chartStatusVar').off('click'); - destroyGrid(); -}); - -AJAX.registerOnload('server_status_monitor.js', function () { - // Show tab links - $('div.tabLinks').show(); - $('#loadingMonitorIcon').remove(); - // Codemirror is loaded on demand so we might need to initialize it - if (! codemirror_editor) { - var $elm = $('#sqlquery'); - if ($elm.length > 0 && typeof CodeMirror !== 'undefined') { - codemirror_editor = CodeMirror.fromTextArea( - $elm[0], - { - lineNumbers: true, - matchBrackets: true, - indentUnit: 4, - mode: 'text/x-mysql', - lineWrapping: true - } - ); - } - } - // Timepicker is loaded on demand so we need to initialize - // datetime fields from the 'load log' dialog - $('#logAnalyseDialog').find('.datetimefield').each(function () { - PMA_addDatepicker($(this)); - }); - - /** ** Monitor charting implementation ****/ - /* Saves the previous ajax response for differential values */ - var oldChartData = null; - // Holds about to be created chart - var newChart = null; - var chartSpacing; - - // Whenever the monitor object (runtime.charts) or the settings object - // (monitorSettings) changes in a way incompatible to the previous version, - // increase this number. It will reset the users monitor and settings object - // in his localStorage to the default configuration - var monitorProtocolVersion = '1.0'; - - // Runtime parameter of the monitor, is being fully set in initGrid() - runtime = { - // Holds all visible charts in the grid - charts: null, - // Stores the timeout handler so it can be cleared - refreshTimeout: null, - // Stores the GET request to refresh the charts - refreshRequest: null, - // Chart auto increment - chartAI: 0, - // To play/pause the monitor - redrawCharts: false, - // Object that contains a list of nodes that need to be retrieved - // from the server for chart updates - dataList: [], - // Current max points per chart (needed for auto calculation) - gridMaxPoints: 20, - // displayed time frame - xmin: -1, - xmax: -1 - }; - var monitorSettings = null; - - var defaultMonitorSettings = { - columns: 3, - chartSize: { width: 295, height: 250 }, - // Max points in each chart. Settings it to 'auto' sets - // gridMaxPoints to (chartwidth - 40) / 12 - gridMaxPoints: 'auto', - /* Refresh rate of all grid charts in ms */ - gridRefresh: 5000 - }; - - // Allows drag and drop rearrange and print/edit icons on charts - var editMode = false; - - /* List of preconfigured charts that the user may select */ - var presetCharts = { - // Query cache efficiency - 'qce': { - title: PMA_messages.strQueryCacheEfficiency, - series: [{ - label: PMA_messages.strQueryCacheEfficiency - }], - nodes: [{ - dataPoints: [{ type: 'statusvar', name: 'Qcache_hits' }, { type: 'statusvar', name: 'Com_select' }], - transformFn: 'qce' - }], - maxYLabel: 0 - }, - // Query cache usage - 'qcu': { - title: PMA_messages.strQueryCacheUsage, - series: [{ - label: PMA_messages.strQueryCacheUsed - }], - nodes: [{ - dataPoints: [{ type: 'statusvar', name: 'Qcache_free_memory' }, { type: 'servervar', name: 'query_cache_size' }], - transformFn: 'qcu' - }], - maxYLabel: 0 - } - }; - - // time span selection - var selectionTimeDiff = []; - var selectionStartX; - var selectionStartY; - var selectionEndX; - var selectionEndY; - var drawTimeSpan = false; - - // chart tooltip - var tooltipBox; - - /* Add OS specific system info charts to the preset chart list */ - switch (server_os) { - case 'WINNT': - $.extend(presetCharts, { - 'cpu': { - title: PMA_messages.strSystemCPUUsage, - series: [{ - label: PMA_messages.strAverageLoad - }], - nodes: [{ - dataPoints: [{ type: 'cpu', name: 'loadavg' }] - }], - maxYLabel: 100 - }, - - 'memory': { - title: PMA_messages.strSystemMemory, - series: [{ - label: PMA_messages.strTotalMemory, - fill: true - }, { - dataType: 'memory', - label: PMA_messages.strUsedMemory, - fill: true - }], - nodes: [{ dataPoints: [{ type: 'memory', name: 'MemTotal' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 } - ], - maxYLabel: 0 - }, - - 'swap': { - title: PMA_messages.strSystemSwap, - series: [{ - label: PMA_messages.strTotalSwap, - fill: true - }, { - label: PMA_messages.strUsedSwap, - fill: true - }], - nodes: [{ dataPoints: [{ type: 'memory', name: 'SwapTotal' }] }, - { dataPoints: [{ type: 'memory', name: 'SwapUsed' }] } - ], - maxYLabel: 0 - } - }); - break; - - case 'Linux': - $.extend(presetCharts, { - 'cpu': { - title: PMA_messages.strSystemCPUUsage, - series: [{ - label: PMA_messages.strAverageLoad - }], - nodes: [{ dataPoints: [{ type: 'cpu', name: 'irrelevant' }], transformFn: 'cpu-linux' }], - maxYLabel: 0 - }, - 'memory': { - title: PMA_messages.strSystemMemory, - series: [ - { label: PMA_messages.strBufferedMemory, fill: true }, - { label: PMA_messages.strUsedMemory, fill: true }, - { label: PMA_messages.strCachedMemory, fill: true }, - { label: PMA_messages.strFreeMemory, fill: true } - ], - nodes: [ - { dataPoints: [{ type: 'memory', name: 'Buffers' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'Cached' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 } - ], - maxYLabel: 0 - }, - 'swap': { - title: PMA_messages.strSystemSwap, - series: [ - { label: PMA_messages.strCachedSwap, fill: true }, - { label: PMA_messages.strUsedSwap, fill: true }, - { label: PMA_messages.strFreeSwap, fill: true } - ], - nodes: [ - { dataPoints: [{ type: 'memory', name: 'SwapCached' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 } - ], - maxYLabel: 0 - } - }); - break; - - case 'SunOS': - $.extend(presetCharts, { - 'cpu': { - title: PMA_messages.strSystemCPUUsage, - series: [{ - label: PMA_messages.strAverageLoad - }], - nodes: [{ - dataPoints: [{ type: 'cpu', name: 'loadavg' }] - }], - maxYLabel: 0 - }, - 'memory': { - title: PMA_messages.strSystemMemory, - series: [ - { label: PMA_messages.strUsedMemory, fill: true }, - { label: PMA_messages.strFreeMemory, fill: true } - ], - nodes: [ - { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 } - ], - maxYLabel: 0 - }, - 'swap': { - title: PMA_messages.strSystemSwap, - series: [ - { label: PMA_messages.strUsedSwap, fill: true }, - { label: PMA_messages.strFreeSwap, fill: true } - ], - nodes: [ - { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 }, - { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 } - ], - maxYLabel: 0 - } - }); - break; - } - - // Default setting for the chart grid - var defaultChartGrid = { - 'c0': { - title: PMA_messages.strQuestions, - series: [ - { label: PMA_messages.strQuestions } - ], - nodes: [ - { dataPoints: [{ type: 'statusvar', name: 'Questions' }], display: 'differential' } - ], - maxYLabel: 0 - }, - 'c1': { - title: PMA_messages.strChartConnectionsTitle, - series: [ - { label: PMA_messages.strConnections }, - { label: PMA_messages.strProcesses } - ], - nodes: [ - { dataPoints: [{ type: 'statusvar', name: 'Connections' }], display: 'differential' }, - { dataPoints: [{ type: 'proc', name: 'processes' }] } - ], - maxYLabel: 0 - }, - 'c2': { - title: PMA_messages.strTraffic, - series: [ - { label: PMA_messages.strBytesSent }, - { label: PMA_messages.strBytesReceived } - ], - nodes: [ - { dataPoints: [{ type: 'statusvar', name: 'Bytes_sent' }], display: 'differential', valueDivisor: 1024 }, - { dataPoints: [{ type: 'statusvar', name: 'Bytes_received' }], display: 'differential', valueDivisor: 1024 } - ], - maxYLabel: 0 - } - }; - - // Server is localhost => We can add cpu/memory/swap to the default chart - if (server_db_isLocal && typeof presetCharts.cpu !== 'undefined') { - defaultChartGrid.c3 = presetCharts.cpu; - defaultChartGrid.c4 = presetCharts.memory; - defaultChartGrid.c5 = presetCharts.swap; - } - - $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').on('click', function (event) { - event.preventDefault(); - editMode = !editMode; - if ($(this).attr('href') === '#endChartEditMode') { - editMode = false; - } - - $('a[href="#endChartEditMode"]').toggle(editMode); - - if (editMode) { - // Close the settings popup - $('div.popupContent').hide().removeClass('openedPopup'); - - $('#chartGrid').sortableTable({ - ignoreRect: { - top: 8, - left: chartSize.width - 63, - width: 54, - height: 24 - } - }); - } else { - $('#chartGrid').sortableTable('destroy'); - } - saveMonitor(); // Save settings - return false; - }); - - // global settings - $('div.popupContent select[name="chartColumns"]').on('change', function () { - monitorSettings.columns = parseInt(this.value, 10); - - calculateChartSize(); - // Empty cells should keep their size so you can drop onto them - $('#chartGrid').find('tr td').css('width', chartSize.width + 'px'); - $('#chartGrid').find('.monitorChart').css({ - width: chartSize.width + 'px', - height: chartSize.height + 'px' - }); - - /* Reorder all charts that it fills all column cells */ - var numColumns; - var $tr = $('#chartGrid').find('tr:first'); - var row = 0; - - var tempManageCols = function () { - if (numColumns > monitorSettings.columns) { - if ($tr.next().length === 0) { - $tr.after('<tr></tr>'); - } - $tr.next().prepend($(this)); - } - numColumns++; - }; - - var tempAddCol = function () { - if ($(this).next().length !== 0) { - $(this).append($(this).next().find('td:first')); - } - }; - - while ($tr.length !== 0) { - numColumns = 1; - // To many cells in one row => put into next row - $tr.find('td').each(tempManageCols); - - // To little cells in one row => for each cell to little, - // move all cells backwards by 1 - if ($tr.next().length > 0) { - var cnt = monitorSettings.columns - $tr.find('td').length; - for (var i = 0; i < cnt; i++) { - $tr.append($tr.next().find('td:first')); - $tr.nextAll().each(tempAddCol); - } - } - - $tr = $tr.next(); - row++; - } - - if (monitorSettings.gridMaxPoints === 'auto') { - runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12); - } - - runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh; - runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh; - - if (editMode) { - $('#chartGrid').sortableTable('refresh'); - } - - refreshChartGrid(); - saveMonitor(); // Save settings - }); - - $('div.popupContent select[name="gridChartRefresh"]').on('change', function () { - monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000; - clearTimeout(runtime.refreshTimeout); - - if (runtime.refreshRequest) { - runtime.refreshRequest.abort(); - } - - runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh; - // fixing chart shift towards left on refresh rate change - // runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh; - runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh); - - saveMonitor(); // Save settings - }); - - $('a[href="#addNewChart"]').on('click', function (event) { - event.preventDefault(); - var dlgButtons = { }; - - dlgButtons[PMA_messages.strAddChart] = function () { - var type = $('input[name="chartType"]:checked').val(); - - if (type === 'preset') { - newChart = presetCharts[$('#addChartDialog').find('select[name="presetCharts"]').prop('value')]; - } else { - // If user builds his own chart, it's being set/updated - // each time he adds a series - // So here we only warn if he didn't add a series yet - if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) { - alert(PMA_messages.strAddOneSeriesWarning); - return; - } - } - - newChart.title = $('input[name="chartTitle"]').val(); - // Add a cloned object to the chart grid - addChart($.extend(true, {}, newChart)); - - newChart = null; - - saveMonitor(); // Save settings - - $(this).dialog('close'); - }; - - dlgButtons[PMA_messages.strClose] = function () { - newChart = null; - $('span#clearSeriesLink').hide(); - $('#seriesPreview').html(''); - $(this).dialog('close'); - }; - - var $presetList = $('#addChartDialog').find('select[name="presetCharts"]'); - if ($presetList.html().length === 0) { - $.each(presetCharts, function (key, value) { - $presetList.append('<option value="' + key + '">' + value.title + '</option>'); - }); - $presetList.on('change', function () { - $('input[name="chartTitle"]').val( - $presetList.find(':selected').text() - ); - $('#chartPreset').prop('checked', true); - }); - $('#chartPreset').on('click', function () { - $('input[name="chartTitle"]').val( - $presetList.find(':selected').text() - ); - }); - $('#chartStatusVar').on('click', function () { - $('input[name="chartTitle"]').val( - $('#chartSeries').find(':selected').text().replace(/_/g, ' ') - ); - }); - $('#chartSeries').on('change', function () { - $('input[name="chartTitle"]').val( - $('#chartSeries').find(':selected').text().replace(/_/g, ' ') - ); - }); - } - - $('#addChartDialog').dialog({ - width: 'auto', - height: 'auto', - buttons: dlgButtons - }); - - $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>'); - - return false; - }); - - $('a[href="#exportMonitorConfig"]').on('click', function (event) { - event.preventDefault(); - var gridCopy = {}; - $.each(runtime.charts, function (key, elem) { - gridCopy[key] = {}; - gridCopy[key].nodes = elem.nodes; - gridCopy[key].settings = elem.settings; - gridCopy[key].title = elem.title; - }); - var exportData = { - monitorCharts: gridCopy, - monitorSettings: monitorSettings - }; - - var blob = new Blob([JSON.stringify(exportData)], { type: 'application/octet-stream' }); - var url = window.URL.createObjectURL(blob); - window.location.href = url; - window.URL.revokeObjectURL(url); - }); - - $('a[href="#importMonitorConfig"]').on('click', function (event) { - event.preventDefault(); - $('#emptyDialog').dialog({ title: PMA_messages.strImportDialogTitle }); - $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ':<br/><form>' + - '<input type="file" name="file" id="import_file"> </form>'); - - var dlgBtns = {}; - - dlgBtns[PMA_messages.strImport] = function () { - var input = $('#emptyDialog').find('#import_file')[0]; - var reader = new FileReader(); - - reader.onerror = function (event) { - alert(PMA_messages.strFailedParsingConfig + '\n' + event.target.error.code); - }; - reader.onload = function (e) { - var data = e.target.result; - - // Try loading config - try { - json = JSON.parse(data); - } catch (err) { - alert(PMA_messages.strFailedParsingConfig); - $('#emptyDialog').dialog('close'); - return; - } - - // Basic check, is this a monitor config json? - if (!json || ! json.monitorCharts || ! json.monitorCharts) { - alert(PMA_messages.strFailedParsingConfig); - $('#emptyDialog').dialog('close'); - return; - } - - // If json ok, try applying config - try { - window.localStorage.monitorCharts = JSON.stringify(json.monitorCharts); - window.localStorage.monitorSettings = JSON.stringify(json.monitorSettings); - rebuildGrid(); - } catch (err) { - console.log(err); - alert(PMA_messages.strFailedBuildingGrid); - // If an exception is thrown, load default again - if (isStorageSupported('localStorage')) { - window.localStorage.removeItem('monitorCharts'); - window.localStorage.removeItem('monitorSettings'); - } - rebuildGrid(); - } - - $('#emptyDialog').dialog('close'); - }; - reader.readAsText(input.files[0]); - }; - - dlgBtns[PMA_messages.strCancel] = function () { - $(this).dialog('close'); - }; - - $('#emptyDialog').dialog({ - width: 'auto', - height: 'auto', - buttons: dlgBtns - }); - }); - - $('a[href="#clearMonitorConfig"]').on('click', function (event) { - event.preventDefault(); - if (isStorageSupported('localStorage')) { - window.localStorage.removeItem('monitorCharts'); - window.localStorage.removeItem('monitorSettings'); - window.localStorage.removeItem('monitorVersion'); - } - $(this).hide(); - rebuildGrid(); - }); - - $('a[href="#pauseCharts"]').on('click', function (event) { - event.preventDefault(); - runtime.redrawCharts = ! runtime.redrawCharts; - if (! runtime.redrawCharts) { - $(this).html(PMA_getImage('play') + PMA_messages.strResumeMonitor); - } else { - $(this).html(PMA_getImage('pause') + PMA_messages.strPauseMonitor); - if (! runtime.charts) { - initGrid(); - $('a[href="#settingsPopup"]').show(); - } - } - return false; - }); - - $('a[href="#monitorInstructionsDialog"]').on('click', function (event) { - event.preventDefault(); - - var $dialog = $('#monitorInstructionsDialog'); - - $dialog.dialog({ - width: 595, - height: 'auto' - }).find('img.ajaxIcon').show(); - - var loadLogVars = function (getvars) { - var vars = { ajax_request: true, logging_vars: true }; - if (getvars) { - $.extend(vars, getvars); - } - - $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'), vars, - function (data) { - var logVars; - if (typeof data !== 'undefined' && data.success === true) { - logVars = data.message; - } else { - return serverResponseError(); - } - var icon = PMA_getImage('s_success'); - var msg = ''; - var str = ''; - - if (logVars.general_log === 'ON') { - if (logVars.slow_query_log === 'ON') { - msg = PMA_messages.strBothLogOn; - } else { - msg = PMA_messages.strGenLogOn; - } - } - - if (msg.length === 0 && logVars.slow_query_log === 'ON') { - msg = PMA_messages.strSlowLogOn; - } - - if (msg.length === 0) { - icon = PMA_getImage('s_error'); - msg = PMA_messages.strBothLogOff; - } - - str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">'; - str += icon + msg + '<br />'; - - if (logVars.log_output !== 'TABLE') { - str += PMA_getImage('s_error') + ' ' + PMA_messages.strLogOutNotTable + '<br />'; - } else { - str += PMA_getImage('s_success') + ' ' + PMA_messages.strLogOutIsTable + '<br />'; - } - - if (logVars.slow_query_log === 'ON') { - if (logVars.long_query_time > 2) { - str += PMA_getImage('s_attention') + ' '; - str += PMA_sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time); - str += '<br />'; - } - - if (logVars.long_query_time < 2) { - str += PMA_getImage('s_success') + ' '; - str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time); - str += '<br />'; - } - } - - str += '</div>'; - - if (is_superuser) { - str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>'; - str += '<div class="smallIndent">'; - str += PMA_messages.strSettingsAppliedGlobal + '<br/>'; - - var varValue = 'TABLE'; - if (logVars.log_output === 'TABLE') { - varValue = 'FILE'; - } - - str += '- <a class="set" href="#log_output-' + varValue + '">'; - str += PMA_sprintf(PMA_messages.strSetLogOutput, varValue); - str += ' </a><br />'; - - if (logVars.general_log !== 'ON') { - str += '- <a class="set" href="#general_log-ON">'; - str += PMA_sprintf(PMA_messages.strEnableVar, 'general_log'); - str += ' </a><br />'; - } else { - str += '- <a class="set" href="#general_log-OFF">'; - str += PMA_sprintf(PMA_messages.strDisableVar, 'general_log'); - str += ' </a><br />'; - } - - if (logVars.slow_query_log !== 'ON') { - str += '- <a class="set" href="#slow_query_log-ON">'; - str += PMA_sprintf(PMA_messages.strEnableVar, 'slow_query_log'); - str += ' </a><br />'; - } else { - str += '- <a class="set" href="#slow_query_log-OFF">'; - str += PMA_sprintf(PMA_messages.strDisableVar, 'slow_query_log'); - str += ' </a><br />'; - } - - varValue = 5; - if (logVars.long_query_time > 2) { - varValue = 1; - } - - str += '- <a class="set" href="#long_query_time-' + varValue + '">'; - str += PMA_sprintf(PMA_messages.setSetLongQueryTime, varValue); - str += ' </a><br />'; - } else { - str += PMA_messages.strNoSuperUser + '<br/>'; - } - - str += '</div>'; - - $dialog.find('div.monitorUse').toggle( - logVars.log_output === 'TABLE' && (logVars.slow_query_log === 'ON' || logVars.general_log === 'ON') - ); - - $dialog.find('div.ajaxContent').html(str); - $dialog.find('img.ajaxIcon').hide(); - $dialog.find('a.set').on('click', function () { - var nameValue = $(this).attr('href').split('-'); - loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1] }); - $dialog.find('img.ajaxIcon').show(); - }); - } - ); - }; - - - loadLogVars(); - - return false; - }); - - $('input[name="chartType"]').on('change', function () { - $('#chartVariableSettings').toggle(this.checked && this.value === 'variable'); - var title = $('input[name="chartTitle"]').val(); - if (title === PMA_messages.strChartTitle || - title === $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text() - ) { - $('input[name="chartTitle"]') - .data('lastRadio', $(this).attr('id')) - .val($('label[for="' + $(this).attr('id') + '"]').text()); - } - }); - - $('input[name="useDivisor"]').on('change', function () { - $('span.divisorInput').toggle(this.checked); - }); - - $('input[name="useUnit"]').on('change', function () { - $('span.unitInput').toggle(this.checked); - }); - - $('select[name="varChartList"]').on('change', function () { - if (this.selectedIndex !== 0) { - $('#variableInput').val(this.value); - } - }); - - $('a[href="#kibDivisor"]').on('click', function (event) { - event.preventDefault(); - $('input[name="valueDivisor"]').val(1024); - $('input[name="valueUnit"]').val(PMA_messages.strKiB); - $('span.unitInput').toggle(true); - $('input[name="useUnit"]').prop('checked', true); - return false; - }); - - $('a[href="#mibDivisor"]').on('click', function (event) { - event.preventDefault(); - $('input[name="valueDivisor"]').val(1024 * 1024); - $('input[name="valueUnit"]').val(PMA_messages.strMiB); - $('span.unitInput').toggle(true); - $('input[name="useUnit"]').prop('checked', true); - return false; - }); - - $('a[href="#submitClearSeries"]').on('click', function (event) { - event.preventDefault(); - $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>'); - newChart = null; - $('#clearSeriesLink').hide(); - }); - - $('a[href="#submitAddSeries"]').on('click', function (event) { - event.preventDefault(); - if ($('#variableInput').val() === '') { - return false; - } - - if (newChart === null) { - $('#seriesPreview').html(''); - - newChart = { - title: $('input[name="chartTitle"]').val(), - nodes: [], - series: [], - maxYLabel: 0 - }; - } - - var serie = { - dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }], - display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : '' - }; - - if (serie.dataPoints[0].name === 'Processes') { - serie.dataPoints[0].type = 'proc'; - } - - if ($('input[name="useDivisor"]').prop('checked')) { - serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10); - } - - if ($('input[name="useUnit"]').prop('checked')) { - serie.unit = $('input[name="valueUnit"]').val(); - } - - var str = serie.display === 'differential' ? ', ' + PMA_messages.strDifferential : ''; - str += serie.valueDivisor ? (', ' + PMA_sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : ''; - str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : ''; - - var newSeries = { - label: $('#variableInput').val().replace(/_/g, ' ') - }; - newChart.series.push(newSeries); - $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '<br/>'); - newChart.nodes.push(serie); - $('#variableInput').val(''); - $('input[name="differentialValue"]').prop('checked', true); - $('input[name="useDivisor"]').prop('checked', false); - $('input[name="useUnit"]').prop('checked', false); - $('input[name="useDivisor"]').trigger('change'); - $('input[name="useUnit"]').trigger('change'); - $('select[name="varChartList"]').get(0).selectedIndex = 0; - - $('#clearSeriesLink').show(); - - return false; - }); - - $('#variableInput').autocomplete({ - source: variableNames - }); - - /* Initializes the monitor, called only once */ - function initGrid () { - var i; - - /* Apply default values & config */ - if (isStorageSupported('localStorage')) { - if (typeof window.localStorage.monitorCharts !== 'undefined') { - runtime.charts = JSON.parse(window.localStorage.monitorCharts); - } - if (typeof window.localStorage.monitorSettings !== 'undefined') { - monitorSettings = JSON.parse(window.localStorage.monitorSettings); - } - - $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null); - - if (runtime.charts !== null - && typeof window.localStorage.monitorVersion !== 'undefined' - && monitorProtocolVersion !== window.localStorage.monitorVersion - ) { - $('#emptyDialog').dialog({ title: PMA_messages.strIncompatibleMonitorConfig }); - $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription); - - var dlgBtns = {}; - dlgBtns[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - - $('#emptyDialog').dialog({ - width: 400, - buttons: dlgBtns - }); - } - } - - if (runtime.charts === null) { - runtime.charts = defaultChartGrid; - } - if (monitorSettings === null) { - monitorSettings = defaultMonitorSettings; - } - - $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000); - $('select[name="chartColumns"]').val(monitorSettings.columns); - - if (monitorSettings.gridMaxPoints === 'auto') { - runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12); - } else { - runtime.gridMaxPoints = monitorSettings.gridMaxPoints; - } - - runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh; - runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh; - - /* Calculate how much spacing there is between each chart */ - $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>'); - chartSpacing = { - width: $('#chartGrid').find('td:nth-child(2)').offset().left - - $('#chartGrid').find('td:nth-child(1)').offset().left, - height: $('#chartGrid').find('tr:nth-child(2) td:nth-child(2)').offset().top - - $('#chartGrid').find('tr:nth-child(1) td:nth-child(1)').offset().top - }; - $('#chartGrid').html(''); - - /* Add all charts - in correct order */ - var keys = []; - $.each(runtime.charts, function (key, value) { - keys.push(key); - }); - keys.sort(); - for (i = 0; i < keys.length; i++) { - addChart(runtime.charts[keys[i]], true); - } - - /* Fill in missing cells */ - var numCharts = $('#chartGrid').find('.monitorChart').length; - var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns; - for (i = 0; i < numMissingCells; i++) { - $('#chartGrid').find('tr:last').append('<td></td>'); - } - - // Empty cells should keep their size so you can drop onto them - calculateChartSize(); - $('#chartGrid').find('tr td').css('width', chartSize.width + 'px'); - - buildRequiredDataList(); - refreshChartGrid(); - } - - /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart - * data from each chart and restores it after the monitor is initialized again */ - function rebuildGrid () { - var oldData = null; - if (runtime.charts) { - oldData = {}; - $.each(runtime.charts, function (key, chartObj) { - for (var i = 0, l = chartObj.nodes.length; i < l; i++) { - oldData[chartObj.nodes[i].dataPoint] = []; - for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) { - oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]); - } - } - }); - } - - destroyGrid(); - initGrid(); - } - - /* Calculactes the dynamic chart size that depends on the column width */ - function calculateChartSize () { - var panelWidth; - if ($('body').height() > $(window).height()) { // has vertical scroll bar - panelWidth = $('#logTable').innerWidth(); - } else { - panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar - } - - var wdt = panelWidth; - var windowWidth = $(window).width(); - - if (windowWidth > 768) { - wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns; - } - - chartSize = { - width: Math.floor(wdt), - height: Math.floor(0.75 * wdt) - }; - } - - /* Adds a chart to the chart grid */ - function addChart (chartObj, initialize) { - var i; - var settings = { - title: escapeHtml(chartObj.title), - grid: { - drawBorder: false, - shadow: false, - background: 'rgba(0,0,0,0)' - }, - axes: { - xaxis: { - renderer: $.jqplot.DateAxisRenderer, - tickOptions: { - formatString: '%H:%M:%S', - showGridline: false - }, - min: runtime.xmin, - max: runtime.xmax - }, - yaxis: { - min: 0, - max: 100, - tickInterval: 20 - } - }, - seriesDefaults: { - rendererOptions: { - smooth: true - }, - showLine: true, - lineWidth: 2, - markerOptions: { - size: 6 - } - }, - highlighter: { - show: true - } - }; - - if (settings.title === PMA_messages.strSystemCPUUsage || - settings.title === PMA_messages.strQueryCacheEfficiency - ) { - settings.axes.yaxis.tickOptions = { - formatString: '%d %%' - }; - } else if (settings.title === PMA_messages.strSystemMemory || - settings.title === PMA_messages.strSystemSwap - ) { - settings.stackSeries = true; - settings.axes.yaxis.tickOptions = { - formatter: $.jqplot.byteFormatter(2) // MiB - }; - } else if (settings.title === PMA_messages.strTraffic) { - settings.axes.yaxis.tickOptions = { - formatter: $.jqplot.byteFormatter(1) // KiB - }; - } else if (settings.title === PMA_messages.strQuestions || - settings.title === PMA_messages.strConnections - ) { - settings.axes.yaxis.tickOptions = { - formatter: function (format, val) { - if (Math.abs(val) >= 1000000) { - return $.jqplot.sprintf('%.3g M', val / 1000000); - } else if (Math.abs(val) >= 1000) { - return $.jqplot.sprintf('%.3g k', val / 1000); - } else { - return $.jqplot.sprintf('%d', val); - } - } - }; - } - - settings.series = chartObj.series; - - if ($('#' + 'gridchart' + runtime.chartAI).length === 0) { - var numCharts = $('#chartGrid').find('.monitorChart').length; - - if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) { - $('#chartGrid').append('<tr></tr>'); - } - - if (!chartSize) { - calculateChartSize(); - } - $('#chartGrid').find('tr:last').append( - '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' + - '<div class="ui-state-default monitorChart"' + - ' id="gridchart' + runtime.chartAI + '"' + - ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' + - '</div></td>' - ); - } - - // Set series' data as [0,0], smooth lines won't plot with data array having null values. - // also chart won't plot initially with no data and data comes on refreshChartGrid() - var series = []; - for (i in chartObj.series) { - series.push([[0, 0]]); - } - - var tempTooltipContentEditor = function (str, seriesIndex, pointIndex, plot) { - var j; - // TODO: move style to theme CSS - var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' + - 'opacity:0.95;filter:alpha(opacity=95);padding:5px;">'; - // x value i.e. time - var timeValue = str.split(',')[0]; - var seriesValue; - tooltipHtml += 'Time: ' + timeValue; - tooltipHtml += '<span style="font-weight:bold;">'; - // Add y values to the tooltip per series - for (j in plot.series) { - // get y value if present - if (plot.series[j].data.length > pointIndex) { - seriesValue = plot.series[j].data[pointIndex][1]; - } else { - return; - } - var seriesLabel = plot.series[j].label; - var seriesColor = plot.series[j].color; - // format y value - if (plot.series[0]._yaxis.tickOptions.formatter) { - // using formatter function - seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue); - } else if (plot.series[0]._yaxis.tickOptions.formatString) { - // using format string - seriesValue = PMA_sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue); - } - tooltipHtml += '<br /><span style="color:' + seriesColor + '">' + - seriesLabel + ': ' + seriesValue + '</span>'; - } - tooltipHtml += '</span></div>'; - return tooltipHtml; - }; - - // set Tooltip for each series - for (i in settings.series) { - settings.series[i].highlighter = { - show: true, - tooltipContentEditor: tempTooltipContentEditor - }; - } - - chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings); - // remove [0,0] after plotting - for (i in chartObj.chart.series) { - chartObj.chart.series[i].data.shift(); - } - - var $legend = $('<div />').css('padding', '0.5em'); - for (i in chartObj.chart.series) { - $legend.append( - $('<div />').append( - $('<div>').css({ - width: '1em', - height: '1em', - background: chartObj.chart.seriesColors[i] - }).addClass('floatleft') - ).append( - $('<div>').text( - chartObj.chart.series[i].label - ).addClass('floatleft') - ).append( - $('<div class="clearfloat">') - ).addClass('floatleft') - ); - } - $('#gridchart' + runtime.chartAI) - .parent() - .append($legend); - - if (initialize !== true) { - runtime.charts['c' + runtime.chartAI] = chartObj; - buildRequiredDataList(); - } - - // time span selection - $('#gridchart' + runtime.chartAI).on('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) { - drawTimeSpan = true; - selectionTimeDiff.push(datapos.xaxis); - if ($('#selection_box').length) { - $('#selection_box').remove(); - } - var selectionBox = $('<div id="selection_box" style="z-index:1000;height:205px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">'); - $(document.body).append(selectionBox); - selectionStartX = ev.pageX; - selectionStartY = ev.pageY; - selectionBox - .attr({ id: 'selection_box' }) - .css({ - top: selectionStartY - gridpos.y, - left: selectionStartX - }) - .fadeIn(); - }); - - $('#gridchart' + runtime.chartAI).on('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) { - if (! drawTimeSpan || editMode) { - return; - } - - selectionTimeDiff.push(datapos.xaxis); - - if (selectionTimeDiff[1] <= selectionTimeDiff[0]) { - selectionTimeDiff = []; - return; - } - // get date from timestamp - var min = new Date(Math.ceil(selectionTimeDiff[0])); - var max = new Date(Math.ceil(selectionTimeDiff[1])); - PMA_getLogAnalyseDialog(min, max); - selectionTimeDiff = []; - drawTimeSpan = false; - }); - - $('#gridchart' + runtime.chartAI).on('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) { - if (! drawTimeSpan || editMode) { - return; - } - if (selectionStartX !== undefined) { - $('#selection_box') - .css({ - width: Math.ceil(ev.pageX - selectionStartX) - }) - .fadeIn(); - } - }); - - $('#gridchart' + runtime.chartAI).on('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) { - drawTimeSpan = false; - }); - - $(document.body).mouseup(function () { - if ($('#selection_box').length) { - $('#selection_box').remove(); - } - }); - - // Edit, Print icon only in edit mode - $('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode); - - runtime.chartAI++; - } - - function PMA_getLogAnalyseDialog (min, max) { - var $logAnalyseDialog = $('#logAnalyseDialog'); - var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]'); - var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]'); - $dateStart.prop('readonly', true); - $dateEnd.prop('readonly', true); - - var dlgBtns = { }; - - dlgBtns[PMA_messages.strFromSlowLog] = function () { - loadLog('slow', min, max); - $(this).dialog('close'); - }; - - dlgBtns[PMA_messages.strFromGeneralLog] = function () { - loadLog('general', min, max); - $(this).dialog('close'); - }; - - $logAnalyseDialog.dialog({ - width: 'auto', - height: 'auto', - buttons: dlgBtns - }); - - PMA_addDatepicker($dateStart, 'datetime', { - showMillisec: false, - showMicrosec: false, - timeFormat: 'HH:mm:ss' - }); - PMA_addDatepicker($dateEnd, 'datetime', { - showMillisec: false, - showMicrosec: false, - timeFormat: 'HH:mm:ss' - }); - $dateStart.datepicker('setDate', min); - $dateEnd.datepicker('setDate', max); - } - - function loadLog (type, min, max) { - var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min; - var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max; - - loadLogStatistics({ - src: type, - start: dateStart, - end: dateEnd, - removeVariables: $('#removeVariables').prop('checked'), - limitTypes: $('#limitTypes').prop('checked') - }); - } - - /* Called in regular intervals, this function updates the values of each chart in the grid */ - function refreshChartGrid () { - /* Send to server */ - runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), { - ajax_request: true, - chart_data: 1, - type: 'chartgrid', - requiredData: JSON.stringify(runtime.dataList), - server: PMA_commonParams.get('server') - }, function (data) { - var chartData; - if (typeof data !== 'undefined' && data.success === true) { - chartData = data.message; - } else { - return serverResponseError(); - } - var value; - var i = 0; - var diff; - var total; - - /* Update values in each graph */ - $.each(runtime.charts, function (orderKey, elem) { - var key = elem.chartID; - // If newly added chart, we have no data for it yet - if (! chartData[key]) { - return; - } - // Draw all series - total = 0; - for (var j = 0; j < elem.nodes.length; j++) { - // Update x-axis - if (i === 0 && j === 0) { - if (oldChartData === null) { - diff = chartData.x - runtime.xmax; - } else { - diff = parseInt(chartData.x - oldChartData.x, 10); - } - - runtime.xmin += diff; - runtime.xmax += diff; - } - - // elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false); - /* Calculate y value */ - - // If transform function given, use it - if (elem.nodes[j].transformFn) { - value = chartValueTransform( - elem.nodes[j].transformFn, - chartData[key][j], - // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null - ( - oldChartData === null || - oldChartData[key] === null || - oldChartData[key] === undefined ? null : oldChartData[key][j] - ) - ); - - // Otherwise use original value and apply differential and divisor if given, - // in this case we have only one data point per series - located at chartData[key][j][0] - } else { - value = parseFloat(chartData[key][j][0].value); - - if (elem.nodes[j].display === 'differential') { - if (oldChartData === null || - oldChartData[key] === null || - oldChartData[key] === undefined - ) { - continue; - } - value -= oldChartData[key][j][0].value; - } - - if (elem.nodes[j].valueDivisor) { - value = value / elem.nodes[j].valueDivisor; - } - } - - // Set y value, if defined - if (value !== undefined) { - elem.chart.series[j].data.push([chartData.x, value]); - if (value > elem.maxYLabel) { - elem.maxYLabel = value; - } else if (elem.maxYLabel === 0) { - elem.maxYLabel = 0.5; - } - // free old data point values and update maxYLabel - if (elem.chart.series[j].data.length > runtime.gridMaxPoints && - elem.chart.series[j].data[0][0] < runtime.xmin - ) { - // check if the next freeable point is highest - if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) { - elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints); - elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data); - } else { - elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints); - } - } - if (elem.title === PMA_messages.strSystemMemory || - elem.title === PMA_messages.strSystemSwap - ) { - total += value; - } - } - } - - // update chart options - // keep ticks number/positioning consistent while refreshrate changes - var tickInterval = (runtime.xmax - runtime.xmin) / 5; - elem.chart.axes.xaxis.ticks = [(runtime.xmax - tickInterval * 4), - (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2), - (runtime.xmax - tickInterval), runtime.xmax]; - - if (elem.title !== PMA_messages.strSystemCPUUsage && - elem.title !== PMA_messages.strQueryCacheEfficiency && - elem.title !== PMA_messages.strSystemMemory && - elem.title !== PMA_messages.strSystemSwap - ) { - elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1); - elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5); - } else if (elem.title === PMA_messages.strSystemMemory || - elem.title === PMA_messages.strSystemSwap - ) { - elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100; - elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5); - } - i++; - - if (runtime.redrawCharts) { - elem.chart.replot(); - } - }); - - oldChartData = chartData; - - runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh); - }); - } - - /* Function to get highest plotted point's y label, to scale the chart, - * TODO: make jqplot's autoscale:true work here - */ - function getMaxYLabel (dataValues) { - var maxY = dataValues[0][1]; - $.each(dataValues, function (k, v) { - maxY = (v[1] > maxY) ? v[1] : maxY; - }); - return maxY; - } - - /* Function that supplies special value transform functions for chart values */ - function chartValueTransform (name, cur, prev) { - switch (name) { - case 'cpu-linux': - if (prev === null) { - return undefined; - } - // cur and prev are datapoint arrays, but containing - // only 1 element for cpu-linux - cur = cur[0]; - prev = prev[0]; - - var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle); - var diff_idle = cur.idle - prev.idle; - return 100 * (diff_total - diff_idle) / diff_total; - - // Query cache efficiency (%) - case 'qce': - if (prev === null) { - return undefined; - } - // cur[0].value is Qcache_hits, cur[1].value is Com_select - var diffQHits = cur[0].value - prev[0].value; - // No NaN please :-) - if (cur[1].value - prev[1].value === 0) { - return 0; - } - - return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100; - - // Query cache usage (%) - case 'qcu': - if (cur[1].value === 0) { - return 0; - } - // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size - return 100 - cur[0].value / cur[1].value * 100; - } - return undefined; - } - - /* Build list of nodes that need to be retrieved from server. - * It creates something like a stripped down version of the runtime.charts object. - */ - function buildRequiredDataList () { - runtime.dataList = {}; - // Store an own id, because the property name is subject of reordering, - // thus destroying our mapping with runtime.charts <=> runtime.dataList - var chartID = 0; - $.each(runtime.charts, function (key, chart) { - runtime.dataList[chartID] = []; - for (var i = 0, l = chart.nodes.length; i < l; i++) { - runtime.dataList[chartID][i] = chart.nodes[i].dataPoints; - } - runtime.charts[key].chartID = chartID; - chartID++; - }); - } - - /* Loads the log table data, generates the table and handles the filters */ - function loadLogStatistics (opts) { - var tableStr = ''; - var logRequest = null; - - if (! opts.removeVariables) { - opts.removeVariables = false; - } - if (! opts.limitTypes) { - opts.limitTypes = false; - } - - $('#emptyDialog').dialog({ title: PMA_messages.strAnalysingLogsTitle }); - $('#emptyDialog').html(PMA_messages.strAnalysingLogs + - ' <img class="ajaxIcon" src="' + pmaThemeImage + - 'ajax_clock_small.gif" alt="">'); - var dlgBtns = {}; - - dlgBtns[PMA_messages.strCancelRequest] = function () { - if (logRequest !== null) { - logRequest.abort(); - } - - $(this).dialog('close'); - }; - - $('#emptyDialog').dialog({ - width: 'auto', - height: 'auto', - buttons: dlgBtns - }); - - - logRequest = $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'), - { ajax_request: true, - log_data: 1, - type: opts.src, - time_start: Math.round(opts.start / 1000), - time_end: Math.round(opts.end / 1000), - removeVariables: opts.removeVariables, - limitTypes: opts.limitTypes - }, - function (data) { - var logData; - var dlgBtns = {}; - if (typeof data !== 'undefined' && data.success === true) { - logData = data.message; - } else { - return serverResponseError(); - } - - if (logData.rows.length === 0) { - $('#emptyDialog').dialog({ title: PMA_messages.strNoDataFoundTitle }); - $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>'); - - dlgBtns[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - - $('#emptyDialog').dialog('option', 'buttons', dlgBtns); - return; - } - - runtime.logDataCols = buildLogTable(logData, opts.removeVariables); - - /* Show some stats in the dialog */ - $('#emptyDialog').dialog({ title: PMA_messages.strLoadingLogs }); - $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>'); - $.each(logData.sum, function (key, value) { - key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase(); - if (key === 'Total') { - key = '<b>' + key + '</b>'; - } - $('#emptyDialog').append(key + ': ' + value + '<br/>'); - }); - - /* Add filter options if more than a bunch of rows there to filter */ - if (logData.numRows > 12) { - $('#logTable').prepend( - '<fieldset id="logDataFilter">' + - ' <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' + - ' <div class="formelement">' + - ' <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' + - ' <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' + - ' </div>' + - ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') + - ' <div class="formelement">' + - ' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' + - ' <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' + - ' </div' + - '</fieldset>' - ); - - $('#noWHEREData').on('change', function () { - filterQueries(true); - }); - - if (logData.numRows > 250) { - $('#startFilterQueryText').on('click', filterQueries); - } else { - $('#filterQueryText').on('keyup', filterQueries); - } - } - - dlgBtns[PMA_messages.strJumpToTable] = function () { - $(this).dialog('close'); - $(document).scrollTop($('#logTable').offset().top); - }; - - $('#emptyDialog').dialog('option', 'buttons', dlgBtns); - } - ); - - /* Handles the actions performed when the user uses any of the - * log table filters which are the filter by name and grouping - * with ignoring data in WHERE clauses - * - * @param boolean Should be true when the users enabled or disabled - * to group queries ignoring data in WHERE clauses - */ - function filterQueries (varFilterChange) { - var cell; - var textFilter; - var val = $('#filterQueryText').val(); - - if (val.length === 0) { - textFilter = null; - } else { - try { - textFilter = new RegExp(val, 'i'); - $('#filterQueryText').removeClass('error'); - } catch (e) { - if (e instanceof SyntaxError) { - $('#filterQueryText').addClass('error'); - textFilter = null; - } - } - } - - var rowSum = 0; - var totalSum = 0; - var i = 0; - var q; - var noVars = $('#noWHEREData').prop('checked'); - var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi; - var functionFilter = /([a-z0-9_]+)\(.+?\)/gi; - var filteredQueries = {}; - var filteredQueriesLines = {}; - var hide = false; - var rowData; - var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2]; - var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1]; - var isSlowLog = opts.src === 'slow'; - var columnSums = {}; - - // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.) - var countRow = function (query, row) { - var cells = row.match(/<td>(.*?)<\/td>/gi); - if (!columnSums[query]) { - columnSums[query] = [0, 0, 0, 0]; - } - - // lock_time and query_time and displayed in timespan format - columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, '')); - columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, '')); - // rows_examind and rows_sent are just numbers - columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10); - columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10); - }; - - // We just assume the sql text is always in the second last column, and that the total count is right of it - $('#logTable').find('table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () { - var $t = $(this); - // If query is a SELECT and user enabled or disabled to group - // queries ignoring data in where statements, we - // need to re-calculate the sums of each row - if (varFilterChange && $t.html().match(/^SELECT/i)) { - if (noVars) { - // Group on => Sum up identical columns, and hide all but 1 - - q = $t.text().replace(equalsFilter, '$1=...$6').trim(); - q = q.replace(functionFilter, ' $1(...)'); - - // Js does not specify a limit on property name length, - // so we can abuse it as index :-) - if (filteredQueries[q]) { - filteredQueries[q] += parseInt($t.next().text(), 10); - totalSum += parseInt($t.next().text(), 10); - hide = true; - } else { - filteredQueries[q] = parseInt($t.next().text(), 10); - filteredQueriesLines[q] = i; - $t.text(q); - } - if (isSlowLog) { - countRow(q, $t.parent().html()); - } - } else { - // Group off: Restore original columns - - rowData = $t.parent().data('query'); - // Restore SQL text - $t.text(rowData[queryColumnName]); - // Restore total count - $t.next().text(rowData[sumColumnName]); - // Restore slow log columns - if (isSlowLog) { - $t.parent().children('td:nth-child(3)').text(rowData.query_time); - $t.parent().children('td:nth-child(4)').text(rowData.lock_time); - $t.parent().children('td:nth-child(5)').text(rowData.rows_sent); - $t.parent().children('td:nth-child(6)').text(rowData.rows_examined); - } - } - } - - // If not required to be hidden, do we need - // to hide because of a not matching text filter? - if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) { - hide = true; - } - - // Now display or hide this column - if (hide) { - $t.parent().css('display', 'none'); - } else { - totalSum += parseInt($t.next().text(), 10); - rowSum++; - $t.parent().css('display', ''); - } - - hide = false; - i++; - }); - - // We finished summarizing counts => Update count values of all grouped entries - if (varFilterChange) { - if (noVars) { - var numCol; - var row; - var $table = $('#logTable').find('table tbody'); - $.each(filteredQueriesLines, function (key, value) { - if (filteredQueries[key] <= 1) { - return; - } - - row = $table.children('tr:nth-child(' + (value + 1) + ')'); - numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')'); - numCol.text(filteredQueries[key]); - - if (isSlowLog) { - row.children('td:nth-child(3)').text(secToTime(columnSums[key][0])); - row.children('td:nth-child(4)').text(secToTime(columnSums[key][1])); - row.children('td:nth-child(5)').text(columnSums[key][2]); - row.children('td:nth-child(6)').text(columnSums[key][3]); - } - }); - } - - $('#logTable').find('table').trigger('update'); - setTimeout(function () { - $('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]); - }, 0); - } - - // Display some stats at the bottom of the table - $('#logTable').find('table tfoot tr') - .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' + - PMA_messages.strSumRows + ' ' + rowSum + '<span class="floatright">' + - PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>'); - } - } - - /* Turns a timespan (12:12:12) into a number */ - function timeToSec (timeStr) { - var time = timeStr.split(':'); - return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10); - } - - /* Turns a number into a timespan (100 into 00:01:40) */ - function secToTime (timeInt) { - var hours = Math.floor(timeInt / 3600); - timeInt -= hours * 3600; - var minutes = Math.floor(timeInt / 60); - timeInt -= minutes * 60; - - if (hours < 10) { - hours = '0' + hours; - } - if (minutes < 10) { - minutes = '0' + minutes; - } - if (timeInt < 10) { - timeInt = '0' + timeInt; - } - - return hours + ':' + minutes + ':' + timeInt; - } - - /* Constructs the log table out of the retrieved server data */ - function buildLogTable (data, groupInserts) { - var rows = data.rows; - var cols = []; - var $table = $('<table class="sortable"></table>'); - var $tBody; - var $tRow; - var $tCell; - - $('#logTable').html($table); - - var tempPushKey = function (key, value) { - cols.push(key); - }; - - var formatValue = function (name, value) { - if (name === 'user_host') { - return value.replace(/(\[.*?\])+/g, ''); - } - return escapeHtml(value); - }; - - for (var i = 0, l = rows.length; i < l; i++) { - if (i === 0) { - $.each(rows[0], tempPushKey); - $table.append('<thead>' + - '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' + - '</thead>' - ); - - $table.append($tBody = $('<tbody></tbody>')); - } - - $tBody.append($tRow = $('<tr class="noclick"></tr>')); - var cl = ''; - for (var j = 0, ll = cols.length; j < ll; j++) { - // Assuming the query column is the second last - if (j === cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) { - $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>')); - $tCell.on('click', openQueryAnalyzer); - } else { - $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'); - } - - $tRow.data('query', rows[i]); - } - } - - $table.append('<tfoot>' + - '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows + - ' ' + data.numRows + '<span class="floatright">' + PMA_messages.strTotal + - '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>'); - - // Append a tooltip to the count column, if there exist one - if ($('#logTable').find('tr:first th:last').text().indexOf('#') > -1) { - $('#logTable').find('tr:first th:last').append(' ' + PMA_getImage('b_help', '', { 'class': 'qroupedQueryInfoIcon' })); - - var tooltipContent = PMA_messages.strCountColumnExplanation; - if (groupInserts) { - tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>'; - } - - PMA_tooltip( - $('img.qroupedQueryInfoIcon'), - 'img', - tooltipContent - ); - } - - $('#logTable').find('table').tablesorter({ - sortList: [[cols.length - 1, 1]], - widgets: ['fast-zebra'] - }); - - $('#logTable').find('table thead th') - .append('<div class="sorticon"></div>'); - - return cols; - } - - /* Opens the query analyzer dialog */ - function openQueryAnalyzer () { - var rowData = $(this).parent().data('query'); - var query = rowData.argument || rowData.sql_text; - - if (codemirror_editor) { - // TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed - // query = PMA_SQLPrettyPrint(query); - codemirror_editor.setValue(query); - // Codemirror is bugged, it doesn't refresh properly sometimes. - // Following lines seem to fix that - setTimeout(function () { - codemirror_editor.refresh(); - }, 50); - } else { - $('#sqlquery').val(query); - } - - var profilingChart = null; - var dlgBtns = {}; - - dlgBtns[PMA_messages.strAnalyzeQuery] = function () { - loadQueryAnalysis(rowData); - }; - dlgBtns[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - - $('#queryAnalyzerDialog').dialog({ - width: 'auto', - height: 'auto', - resizable: false, - buttons: dlgBtns, - close: function () { - if (profilingChart !== null) { - profilingChart.destroy(); - } - $('#queryAnalyzerDialog').find('div.placeHolder').html(''); - if (codemirror_editor) { - codemirror_editor.setValue(''); - } else { - $('#sqlquery').val(''); - } - } - }); - } - - /* Loads and displays the analyzed query data */ - function loadQueryAnalysis (rowData) { - var db = rowData.db || ''; - - $('#queryAnalyzerDialog').find('div.placeHolder').html( - PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' + - pmaThemeImage + 'ajax_clock_small.gif" alt="">'); - - $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), { - ajax_request: true, - query_analyzer: true, - query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(), - database: db, - server: PMA_commonParams.get('server') - }, function (data) { - var i; - var l; - if (typeof data !== 'undefined' && data.success === true) { - data = data.message; - } - if (data.error) { - if (data.error.indexOf('1146') !== -1 || data.error.indexOf('1046') !== -1) { - data.error = PMA_messages.strServerLogError; - } - $('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="error">' + data.error + '</div>'); - return; - } - var totalTime = 0; - // Float sux, I'll use table :( - $('#queryAnalyzerDialog').find('div.placeHolder') - .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>'); - - var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html(); - if (data.explain.length > 1) { - explain += ' ('; - for (i = 0; i < data.explain.length; i++) { - if (i > 0) { - explain += ', '; - } - explain += '<a href="#showExplain-' + i + '">' + i + '</a>'; - } - explain += ')'; - } - explain += '<p></p>'; - - var tempExplain = function (key, value) { - value = (value === null) ? 'null' : escapeHtml(value); - - if (key === 'type' && value.toLowerCase() === 'all') { - value = '<span class="attention">' + value + '</span>'; - } - if (key === 'Extra') { - value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>'); - } - explain += key + ': ' + value + '<br />'; - }; - - for (i = 0, l = data.explain.length; i < l; i++) { - explain += '<div class="explain-' + i + '"' + (i > 0 ? 'style="display:none;"' : '') + '>'; - $.each(data.explain[i], tempExplain); - explain += '</div>'; - } - - explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows; - - $('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain); - - $('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').on('click', function () { - var id = $(this).attr('href').split('-')[1]; - $(this).parent().find('div[class*="explain"]').hide(); - $(this).parent().find('div[class*="explain-' + id + '"]').show(); - }); - - if (data.profiling) { - var chartData = []; - var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>'; - var duration; - var otherTime = 0; - - for (i = 0, l = data.profiling.length; i < l; i++) { - duration = parseFloat(data.profiling[i].duration); - - totalTime += duration; - - numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>'; - } - - // Only put those values in the pie which are > 2% - for (i = 0, l = data.profiling.length; i < l; i++) { - duration = parseFloat(data.profiling[i].duration); - - if (duration / totalTime > 0.02) { - chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]); - } else { - otherTime += duration; - } - } - - if (otherTime > 0) { - chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]); - } - - numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>'; - numberTable += '</tbody></table>'; - - $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append( - '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' + - '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' + - numberTable + ' <div id="queryProfiling"></div>'); - - $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').on('click', function () { - $('#queryAnalyzerDialog').find('#queryProfiling').hide(); - $('#queryAnalyzerDialog').find('table.queryNums').show(); - return false; - }); - - $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').on('click', function () { - $('#queryAnalyzerDialog').find('#queryProfiling').show(); - $('#queryAnalyzerDialog').find('table.queryNums').hide(); - return false; - }); - - profilingChart = PMA_createProfilingChart( - 'queryProfiling', - chartData - ); - - // $('#queryProfiling').resizable(); - } - }); - } - - /* Saves the monitor to localstorage */ - function saveMonitor () { - var gridCopy = {}; - - $.each(runtime.charts, function (key, elem) { - gridCopy[key] = {}; - gridCopy[key].nodes = elem.nodes; - gridCopy[key].settings = elem.settings; - gridCopy[key].title = elem.title; - gridCopy[key].series = elem.series; - gridCopy[key].maxYLabel = elem.maxYLabel; - }); - - if (isStorageSupported('localStorage')) { - window.localStorage.monitorCharts = JSON.stringify(gridCopy); - window.localStorage.monitorSettings = JSON.stringify(monitorSettings); - window.localStorage.monitorVersion = monitorProtocolVersion; - } - - $('a[href="#clearMonitorConfig"]').show(); - } -}); - -// Run the monitor once loaded -AJAX.registerOnload('server_status_monitor.js', function () { - $('a[href="#pauseCharts"]').trigger('click'); -}); - -function serverResponseError () { - var btns = {}; - btns[PMA_messages.strReloadPage] = function () { - window.location.reload(); - }; - $('#emptyDialog').dialog({ title: PMA_messages.strRefreshFailed }); - $('#emptyDialog').html( - PMA_getImage('s_attention') + - PMA_messages.strInvalidResponseExplanation - ); - $('#emptyDialog').dialog({ buttons: btns }); -} - -/* Destroys all monitor related resources */ -function destroyGrid () { - if (runtime.charts) { - $.each(runtime.charts, function (key, value) { - try { - value.chart.destroy(); - } catch (err) {} - }); - } - - try { - runtime.refreshRequest.abort(); - } catch (err) {} - try { - clearTimeout(runtime.refreshTimeout); - } catch (err) {} - $('#chartGrid').html(''); - runtime.charts = null; - runtime.chartAI = 0; - monitorSettings = null; // TODO:this not global variable -} diff --git a/js/server_status_processes.js b/js/server_status_processes.js deleted file mode 100644 index 928c10b328..0000000000 --- a/js/server_status_processes.js +++ /dev/null @@ -1,187 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * Server Status Processes - * - * @package PhpMyAdmin - */ - -// object to store process list state information -var processList = { - - // denotes whether auto refresh is on or off - autoRefresh: false, - // stores the GET request which refresh process list - refreshRequest: null, - // stores the timeout id returned by setTimeout - refreshTimeout: null, - // the refresh interval in seconds - refreshInterval: null, - // the refresh URL (required to save last used option) - // i.e. full or sorting url - refreshUrl: null, - - /** - * Handles killing of a process - * - * @return void - */ - init: function () { - processList.setRefreshLabel(); - if (processList.refreshUrl === null) { - processList.refreshUrl = 'server_status_processes.php' + - PMA_commonParams.get('common_query'); - } - if (processList.refreshInterval === null) { - processList.refreshInterval = $('#id_refreshRate').val(); - } else { - $('#id_refreshRate').val(processList.refreshInterval); - } - }, - - /** - * Handles killing of a process - * - * @param object the event object - * - * @return void - */ - killProcessHandler: function (event) { - event.preventDefault(); - var url = $(this).attr('href'); - // Get row element of the process to be killed. - var $tr = $(this).closest('tr'); - $.getJSON(url, function (data) { - // Check if process was killed or not. - if (data.hasOwnProperty('success') && data.success) { - // remove the row of killed process. - $tr.remove(); - // As we just removed a row, reapply odd-even classes - // to keep table stripes consistent - var $tableProcessListTr = $('#tableprocesslist').find('> tbody > tr'); - $tableProcessListTr.filter(':even').removeClass('odd').addClass('even'); - $tableProcessListTr.filter(':odd').removeClass('even').addClass('odd'); - // Show process killed message - PMA_ajaxShowMessage(data.message, false); - } else { - // Show process error message - PMA_ajaxShowMessage(data.error, false); - } - }); - }, - - /** - * Handles Auto Refreshing - * - * @param object the event object - * - * @return void - */ - refresh: function (event) { - // abort any previous pending requests - // this is necessary, it may go into - // multiple loops causing unnecessary - // requests even after leaving the page. - processList.abortRefresh(); - // if auto refresh is enabled - if (processList.autoRefresh) { - var interval = parseInt(processList.refreshInterval, 10) * 1000; - var urlParams = processList.getUrlParams(); - processList.refreshRequest = $.get(processList.refreshUrl, - urlParams, - function (data) { - if (data.hasOwnProperty('success') && data.success) { - $newTable = $(data.message); - $('#tableprocesslist').html($newTable.html()); - PMA_highlightSQL($('#tableprocesslist')); - } - processList.refreshTimeout = setTimeout( - processList.refresh, - interval - ); - }); - } - }, - - /** - * Stop current request and clears timeout - * - * @return void - */ - abortRefresh: function () { - if (processList.refreshRequest !== null) { - processList.refreshRequest.abort(); - processList.refreshRequest = null; - } - clearTimeout(processList.refreshTimeout); - }, - - /** - * Set label of refresh button - * change between play & pause - * - * @return void - */ - setRefreshLabel: function () { - var img = 'play'; - var label = PMA_messages.strStartRefresh; - if (processList.autoRefresh) { - img = 'pause'; - label = PMA_messages.strStopRefresh; - processList.refresh(); - } - $('a#toggleRefresh').html(PMA_getImage(img) + escapeHtml(label)); - }, - - /** - * Return the Url Parameters - * for autorefresh request, - * includes showExecuting if the filter is checked - * - * @return urlParams - url parameters with autoRefresh request - */ - getUrlParams: function () { - var urlParams = { 'ajax_request': true, 'refresh': true }; - if ($('#showExecuting').is(':checked')) { - urlParams.showExecuting = true; - return urlParams; - } - return urlParams; - } -}; - -AJAX.registerOnload('server_status_processes.js', function () { - processList.init(); - // Bind event handler for kill_process - $('#tableprocesslist').on( - 'click', - 'a.kill_process', - processList.killProcessHandler - ); - // Bind event handler for toggling refresh of process list - $('a#toggleRefresh').on('click', function (event) { - event.preventDefault(); - processList.autoRefresh = !processList.autoRefresh; - processList.setRefreshLabel(); - }); - // Bind event handler for change in refresh rate - $('#id_refreshRate').on('change', function (event) { - processList.refreshInterval = $(this).val(); - processList.refresh(); - }); - // Bind event handler for table header links - $('#tableprocesslist').on('click', 'thead a', function () { - processList.refreshUrl = $(this).attr('href'); - }); -}); - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_status_processes.js', function () { - $('#tableprocesslist').off('click', 'a.kill_process'); - $('a#toggleRefresh').off('click'); - $('#id_refreshRate').off('change'); - $('#tableprocesslist').off('click', 'thead a'); - // stop refreshing further - processList.abortRefresh(); -}); diff --git a/js/server_status_queries.js b/js/server_status_queries.js deleted file mode 100644 index 056cffebc7..0000000000 --- a/js/server_status_queries.js +++ /dev/null @@ -1,34 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_status_queries.js', function () { - var queryPieChart = $('#serverstatusquerieschart').data('queryPieChart'); - if (queryPieChart) { - queryPieChart.destroy(); - } -}); - -AJAX.registerOnload('server_status_queries.js', function () { - // Build query statistics chart - var cdata = []; - try { - $.each($('#serverstatusquerieschart').data('chart'), function (key, value) { - cdata.push([key, parseInt(value, 10)]); - }); - $('#serverstatusquerieschart').data( - 'queryPieChart', - PMA_createProfilingChart( - 'serverstatusquerieschart', - cdata - ) - ); - } catch (exception) { - // Could not load chart, no big deal... - } - - initTableSorter('statustabs_queries'); -}); diff --git a/js/server_status_sorter.js b/js/server_status_sorter.js deleted file mode 100644 index 36c918a8ae..0000000000 --- a/js/server_status_sorter.js +++ /dev/null @@ -1,70 +0,0 @@ -// TODO: tablesorter shouldn't sort already sorted columns -function initTableSorter (tabid) { - var $table; - var opts; - switch (tabid) { - case 'statustabs_queries': - $table = $('#serverstatusqueriesdetails'); - opts = { - sortList: [[3, 1]], - headers: { - 1: { sorter: 'fancyNumber' }, - 2: { sorter: 'fancyNumber' } - } - }; - break; - } - $table.tablesorter(opts); - $table.find('tr:first th') - .append('<div class="sorticon"></div>'); -} - -$(function () { - $.tablesorter.addParser({ - id: 'fancyNumber', - is: function (s) { - return (/^[0-9]?[0-9,\.]*\s?(k|M|G|T|%)?$/).test(s); - }, - format: function (s) { - var num = jQuery.tablesorter.formatFloat( - s.replace(PMA_messages.strThousandsSeparator, '') - .replace(PMA_messages.strDecimalSeparator, '.') - ); - - var factor = 1; - switch (s.charAt(s.length - 1)) { - case '%': - factor = -2; - break; - // Todo: Complete this list (as well as in the regexp a few lines up) - case 'k': - factor = 3; - break; - case 'M': - factor = 6; - break; - case 'G': - factor = 9; - break; - case 'T': - factor = 12; - break; - } - - return num * Math.pow(10, factor); - }, - type: 'numeric' - }); - - $.tablesorter.addParser({ - id: 'withinSpanNumber', - is: function (s) { - return (/<span class="original"/).test(s); - }, - format: function (s, table, html) { - var res = html.innerHTML.match(/<span(\s*style="display:none;"\s*)?\s*class="original">(.*)?<\/span>/); - return (res && res.length >= 3) ? res[2] : 0; - }, - type: 'numeric' - }); -}); diff --git a/js/server_status_variables.js b/js/server_status_variables.js deleted file mode 100644 index 6adfc99974..0000000000 --- a/js/server_status_variables.js +++ /dev/null @@ -1,100 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * - * - * @package PhpMyAdmin - */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_status_variables.js', function () { - $('#filterAlert').off('change'); - $('#filterText').off('keyup'); - $('#filterCategory').off('change'); - $('#dontFormat').off('change'); -}); - -AJAX.registerOnload('server_status_variables.js', function () { - // Filters for status variables - var textFilter = null; - var alertFilter = $('#filterAlert').prop('checked'); - var categoryFilter = $('#filterCategory').find(':selected').val(); - var text = ''; // Holds filter text - - /* 3 Filtering functions */ - $('#filterAlert').on('change', function () { - alertFilter = this.checked; - filterVariables(); - }); - - $('#filterCategory').on('change', function () { - categoryFilter = $(this).val(); - filterVariables(); - }); - - $('#dontFormat').on('change', function () { - // Hiding the table while changing values speeds up the process a lot - $('#serverstatusvariables').hide(); - $('#serverstatusvariables').find('td.value span.original').toggle(this.checked); - $('#serverstatusvariables').find('td.value span.formatted').toggle(! this.checked); - $('#serverstatusvariables').show(); - }).trigger('change'); - - $('#filterText').on('keyup', function (e) { - var word = $(this).val().replace(/_/g, ' '); - if (word.length === 0) { - textFilter = null; - } else { - try { - textFilter = new RegExp('(^| )' + word, 'i'); - $(this).removeClass('error'); - } catch (e) { - if (e instanceof SyntaxError) { - $(this).addClass('error'); - textFilter = null; - } - } - } - text = word; - filterVariables(); - }).trigger('keyup'); - - /* Filters the status variables by name/category/alert in the variables tab */ - function filterVariables () { - var useful_links = 0; - var section = text; - - if (categoryFilter.length > 0) { - section = categoryFilter; - } - - if (section.length > 1) { - $('#linkSuggestions').find('span').each(function () { - if ($(this).attr('class').indexOf('status_' + section) !== -1) { - useful_links++; - $(this).css('display', ''); - } else { - $(this).css('display', 'none'); - } - }); - } - - if (useful_links > 0) { - $('#linkSuggestions').css('display', ''); - } else { - $('#linkSuggestions').css('display', 'none'); - } - - $('#serverstatusvariables').find('th.name').each(function () { - if ((textFilter === null || textFilter.exec($(this).text())) && - (! alertFilter || $(this).next().find('span.attention').length > 0) && - (categoryFilter.length === 0 || $(this).parent().hasClass('s_' + categoryFilter)) - ) { - $(this).parent().css('display', ''); - } else { - $(this).parent().css('display', 'none'); - } - }); - } -}); diff --git a/js/server_user_groups.js b/js/server_user_groups.js deleted file mode 100644 index 513777a97f..0000000000 --- a/js/server_user_groups.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_user_groups.js', function () { - $(document).off('click', 'a.deleteUserGroup.ajax'); -}); - -/** - * Bind event handlers - */ -AJAX.registerOnload('server_user_groups.js', function () { - // update the checkall checkbox on Edit user group page - $(checkboxes_sel).trigger('change'); - - $(document).on('click', 'a.deleteUserGroup.ajax', function (event) { - event.preventDefault(); - var $link = $(this); - var groupName = $link.parents('tr').find('td:first').text(); - var buttonOptions = {}; - buttonOptions[PMA_messages.strGo] = function () { - $(this).dialog('close'); - $link.removeClass('ajax').trigger('click'); - }; - buttonOptions[PMA_messages.strClose] = function () { - $(this).dialog('close'); - }; - $('<div/>') - .attr('id', 'confirmUserGroupDeleteDialog') - .append(PMA_sprintf(PMA_messages.strDropUserGroupWarning, escapeHtml(groupName))) - .dialog({ - width: 300, - minWidth: 200, - modal: true, - buttons: buttonOptions, - title: PMA_messages.strConfirm, - close: function () { - $(this).remove(); - } - }); - }); -}); diff --git a/js/server_variables.js b/js/server_variables.js deleted file mode 100644 index 99fb8e339f..0000000000 --- a/js/server_variables.js +++ /dev/null @@ -1,112 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('server_variables.js', function () { - $(document).off('click', 'a.editLink'); - $('#serverVariables').find('.var-name').find('a img').remove(); -}); - -AJAX.registerOnload('server_variables.js', function () { - var $editLink = $('a.editLink'); - var $saveLink = $('a.saveLink'); - var $cancelLink = $('a.cancelLink'); - - $('#serverVariables').find('.var-name').find('a').append( - $('#docImage').clone().css('display', 'inline-block') - ); - - /* Launches the variable editor */ - $(document).on('click', 'a.editLink', function (event) { - event.preventDefault(); - editVariable(this); - }); - - /* Allows the user to edit a server variable */ - function editVariable (link) { - var $link = $(link); - var $cell = $link.parent(); - var $valueCell = $link.parents('.var-row').find('.var-value'); - var varName = $link.data('variable'); - - var $mySaveLink = $saveLink.clone().css('display', 'inline-block'); - var $myCancelLink = $cancelLink.clone().css('display', 'inline-block'); - var $msgbox = PMA_ajaxShowMessage(); - var $myEditLink = $cell.find('a.editLink'); - $cell.addClass('edit'); // variable is being edited - $myEditLink.remove(); // remove edit link - - $mySaveLink.on('click', function () { - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - $.post($(this).attr('href'), { - ajax_request: true, - type: 'setval', - varName: varName, - varValue: $valueCell.find('input').val() - }, function (data) { - if (data.success) { - $valueCell - .html(data.variable) - .data('content', data.variable); - PMA_ajaxRemoveMessage($msgbox); - } else { - if (data.error === '') { - PMA_ajaxShowMessage(PMA_messages.strRequestFailed, false); - } else { - PMA_ajaxShowMessage(data.error, false); - } - $valueCell.html($valueCell.data('content')); - } - $cell.removeClass('edit').html($myEditLink); - }); - return false; - }); - - $myCancelLink.on('click', function () { - $valueCell.html($valueCell.data('content')); - $cell.removeClass('edit').html($myEditLink); - return false; - }); - - $.get($mySaveLink.attr('href'), { - ajax_request: true, - type: 'getval', - varName: varName - }, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - var $links = $('<div />') - .append($myCancelLink) - .append(' ') - .append($mySaveLink); - var $editor = $('<div />', { 'class': 'serverVariableEditor' }) - .append( - $('<div/>').append( - $('<input />', { type: 'text' }).val(data.message) - ) - ); - // Save and replace content - $cell - .html($links) - .children() - .css('display', 'flex'); - $valueCell - .data('content', $valueCell.html()) - .html($editor) - .find('input') - .focus() - .on('keydown', function (event) { // Keyboard shortcuts - if (event.keyCode === 13) { // Enter key - $mySaveLink.trigger('click'); - } else if (event.keyCode === 27) { // Escape key - $myCancelLink.trigger('click'); - } - }); - PMA_ajaxRemoveMessage($msgbox); - } else { - $cell.removeClass('edit').html($myEditLink); - PMA_ajaxShowMessage(data.error); - } - }); - } -}); diff --git a/js/shortcuts_handler.js b/js/shortcuts_handler.js deleted file mode 100644 index 4fc3c59a7b..0000000000 --- a/js/shortcuts_handler.js +++ /dev/null @@ -1,101 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview Handle shortcuts in various pages - * @name Shortcuts handler - * - * @requires jQuery - * @requires jQueryUI - */ - -/** - * Register key events on load - */ -$(document).ready(function () { - var databaseOp = false; - var tableOp = false; - var keyD = 68; - var keyT = 84; - var keyK = 75; - var keyS = 83; - var keyF = 70; - var keyE = 69; - var keyH = 72; - var keyC = 67; - var keyBackSpace = 8; - $(document).on('keyup', function (e) { - if (e.target.nodeName === 'INPUT' || e.target.nodeName === 'TEXTAREA' || e.target.nodeName === 'SELECT') { - return; - } - - if (e.keyCode === keyD) { - setTimeout(function () { - databaseOp = false; - }, 2000); - } else if (e.keyCode === keyT) { - setTimeout(function () { - tableOp = false; - }, 2000); - } - }); - $(document).on('keydown', function (e) { - if (e.ctrlKey && e.altKey && e.keyCode === keyC) { - PMA_console.toggle(); - } - - if (e.ctrlKey && e.keyCode === keyK) { - e.preventDefault(); - PMA_console.toggle(); - } - - if (e.target.nodeName === 'INPUT' || e.target.nodeName === 'TEXTAREA' || e.target.nodeName === 'SELECT') { - return; - } - - var isTable; - var isDb; - if (e.keyCode === keyD) { - databaseOp = true; - } else if (e.keyCode === keyK) { - e.preventDefault(); - PMA_console.toggle(); - } else if (e.keyCode === keyS) { - if (databaseOp === true) { - isTable = PMA_commonParams.get('table'); - isDb = PMA_commonParams.get('db'); - if (isDb && ! isTable) { - $('.tab .ic_b_props').first().trigger('click'); - } - } else if (tableOp === true) { - isTable = PMA_commonParams.get('table'); - isDb = PMA_commonParams.get('db'); - if (isDb && isTable) { - $('.tab .ic_b_props').first().trigger('click'); - } - } else { - $('#pma_navigation_settings_icon').trigger('click'); - } - } else if (e.keyCode === keyF) { - if (databaseOp === true) { - isTable = PMA_commonParams.get('table'); - isDb = PMA_commonParams.get('db'); - if (isDb && ! isTable) { - $('.tab .ic_b_search').first().trigger('click'); - } - } else if (tableOp === true) { - isTable = PMA_commonParams.get('table'); - isDb = PMA_commonParams.get('db'); - if (isDb && isTable) { - $('.tab .ic_b_search').first().trigger('click'); - } - } - } else if (e.keyCode === keyT) { - tableOp = true; - } else if (e.keyCode === keyE) { - $('.ic_b_export').first().trigger('click'); - } else if (e.keyCode === keyBackSpace) { - window.history.back(); - } else if (e.keyCode === keyH) { - $('.ic_b_home').first().trigger('click'); - } - }); -}); diff --git a/js/src/classes/Console/PMA_ConsoleResizer.js b/js/src/classes/Console/PMA_ConsoleResizer.js index 0f2c1193a2..19896ffaa6 100644 --- a/js/src/classes/Console/PMA_ConsoleResizer.js +++ b/js/src/classes/Console/PMA_ConsoleResizer.js @@ -4,9 +4,12 @@ * Resizer object * Careful: this object UI logics highly related with functions under PMA_console * Resizing min-height is 32, if small than it, console will collapse - * @namespace ConsoleResizer + * @class ConsoleResizer */ export default class ConsoleResizer { + /** + * @param {Object} instance Instance of PMA Console + */ constructor (instance) { this._posY = 0; this._height = 0; @@ -18,10 +21,16 @@ export default class ConsoleResizer { this._mouseup = this._mouseup.bind(this); this.setPmaConsole(instance); } + + /** + * @param {Object} instance Instance of PMA Console + * @return {void} + */ setPmaConsole (instance) { this.pmaConsole = instance; this.initialize(); } + /** * Mousedown event handler for bind to resizer * @@ -40,6 +49,7 @@ export default class ConsoleResizer { return false; }); } + /** * Mousemove event handler for bind to resizer * @@ -65,6 +75,7 @@ export default class ConsoleResizer { } } } + /** * Mouseup event handler for bind to resizer * @@ -77,6 +88,7 @@ export default class ConsoleResizer { $(document).off('mouseup'); $(document).off('selectstart'); } + /** * Used for console resizer initialize * diff --git a/js/src/classes/Console/PMA_consoleBookmarks.js b/js/src/classes/Console/PMA_consoleBookmarks.js index 8cbeb08a83..a6296b8af7 100644 --- a/js/src/classes/Console/PMA_consoleBookmarks.js +++ b/js/src/classes/Console/PMA_consoleBookmarks.js @@ -1,11 +1,21 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import CommonParams from '../../variables/common_params'; import { PMA_Messages as messages } from '../../variables/export_variables'; + /** - * @namespace ConsoleBookmarks + * @class ConsoleBookmarks * Console bookmarks card, and bookmarks items management object */ export default class ConsoleBookmarks { + /** + * @constructor + * @param {Object} instance Instance of the PMA Console + * @return {void} + */ constructor (instance) { this._bookmarks = []; this.pmaConsole = null; @@ -15,10 +25,23 @@ export default class ConsoleBookmarks { this.initialize = this.initialize.bind(this); this.setPmaConsole(instance); } + + /** + * @param {Object} instance Instance of PMA Console + * @return {void} + */ setPmaConsole (instance) { this.pmaConsole = instance; this.initialize(); } + + /** + * @param {string} queryString Query string to be bookmarked + * @param {string} targetDb Target database for the query string + * @param {string} label Label for the query + * @param {bool} isShared Is the query shared + * @return {void} + */ addBookmark (queryString, targetDb, label, isShared) { $('#pma_bookmarks').find('.add [name=shared]').prop('checked', false); $('#pma_bookmarks').find('.add [name=label]').val(''); @@ -43,6 +66,11 @@ export default class ConsoleBookmarks { break; } } + + /** + * Method to refresh the bookmak list + * @return {void} + */ refresh () { $.get('import.php', { ajax_request: true, @@ -55,6 +83,7 @@ export default class ConsoleBookmarks { } }.bind(this)); } + /** * Used for console bookmarks initialize * message events are already binded by PMA_consoleMsg._msgEventBinds diff --git a/js/src/classes/Console/PMA_consoleDebug.js b/js/src/classes/Console/PMA_consoleDebug.js index 29523db8dc..9f0728fcf0 100644 --- a/js/src/classes/Console/PMA_consoleDebug.js +++ b/js/src/classes/Console/PMA_consoleDebug.js @@ -9,9 +9,13 @@ import { escapeHtml } from '../../utils/Sanitise'; /** * Console debug object - * @namespace ConsoleDebug + * @class ConsoleDebug */ export default class ConsoleDebug { + /** + * @constructor + * @param {Object} instance Instance of PMA Console + */ constructor (instance) { this.pmaConsole = null; this._config = { @@ -36,10 +40,20 @@ export default class ConsoleDebug { this.refresh = this.refresh.bind(this); this.setPmaConsole(instance); } + + /** + * @param {Object} instance Instance of PMA Console + * @return {void} + */ setPmaConsole (instance) { this.pmaConsole = instance; this.initialize(); } + + /** + * Used for Console Debug initialise + * @return {void} + */ initialize () { var self = this; // Try to get debug info after every AJAX request diff --git a/js/src/classes/Console/PMA_consoleInput.js b/js/src/classes/Console/PMA_consoleInput.js index ebf82ae7c7..2b668e760a 100644 --- a/js/src/classes/Console/PMA_consoleInput.js +++ b/js/src/classes/Console/PMA_consoleInput.js @@ -11,15 +11,14 @@ import CommonParams from '../../variables/common_params'; /** * Console input object - * @namespace ConsoleInput + * @class ConsoleInput */ export default class ConsoleInput { /** * @constructor - * - * @param {object} pmaConsoleInstance Instance of pma console + * @param {object} instance Instance of PMA Console */ - constructor (pmaConsoleInstance) { + constructor (instance) { /** * @var array, contains Codemirror objects or input jQuery objects * @access private @@ -61,12 +60,22 @@ export default class ConsoleInput { this.setText = this.setText.bind(this); this.getText = this.getText.bind(this); - this.setPmaConsole(pmaConsoleInstance); + this.setPmaConsole(instance); } + + /** + * @param {Object} instance Instance of PMA Console + * @return {void} + */ setPmaConsole (instance) { this.pmaConsole = instance; this.initialize(); } + + /** + * Used for Console Input initialise + * @return {void} + */ initialize () { // _cm object can't be reinitialize if (this._inputs !== null) { @@ -119,6 +128,11 @@ export default class ConsoleInput { } $('#pma_console').find('.console_query_input').keydown(this._keydown); } + + /** + * @param {jQueryEvent} event + * @return {void} + */ _historyNavigate (event) { if (event.keyCode === 38 || event.keyCode === 40) { var upPermitted = false; @@ -172,6 +186,7 @@ export default class ConsoleInput { } } } + /** * Mousedown event handler for bind to input * Shortcut is Ctrl+Enter key or just ENTER, depending on console's @@ -192,6 +207,7 @@ export default class ConsoleInput { } } } + /** * Used for send text to PMA_console.execute() * @@ -204,6 +220,7 @@ export default class ConsoleInput { this.pmaConsole.execute(this._inputs.console.val()); } } + /** * Used for clear the input * @@ -213,6 +230,7 @@ export default class ConsoleInput { clear (target) { this.setText('', target); } + /** * Used for set focus to input * @@ -221,6 +239,7 @@ export default class ConsoleInput { focus () { this._inputs.console.focus(); } + /** * Used for blur input * @@ -233,6 +252,7 @@ export default class ConsoleInput { this._inputs.console.blur(); } } + /** * Used for set text in input * @@ -262,6 +282,7 @@ export default class ConsoleInput { } } } + /** * Used for getting the text of input * diff --git a/js/src/classes/Console/PMA_consoleMessages.js b/js/src/classes/Console/PMA_consoleMessages.js index 289d6fec70..6af0e01737 100644 --- a/js/src/classes/Console/PMA_consoleMessages.js +++ b/js/src/classes/Console/PMA_consoleMessages.js @@ -1,15 +1,20 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ -import CodeMirror from 'codemirror'; -import PMA_commonParams from '../../variables/common_params'; + /** * Module import */ +import CodeMirror from 'codemirror'; +import PMA_commonParams from '../../variables/common_params'; import { PMA_Messages as messages } from '../../variables/export_variables'; + /** * Console messages, and message items management object - * @namespace ConsoleMessages + * @class ConsoleMessages */ export default class ConsoleMessages { + /** + * @param {Object} instance Instance of PMA Console + */ constructor (instance) { this.pmaConsole = null; this.clear = this.clear.bind(this); @@ -25,10 +30,16 @@ export default class ConsoleMessages { this.setPmaConsole = this.setPmaConsole.bind(this); this.setPmaConsole(instance); } + + /** + * @param {Object} instance Instance of PMA Console + * @return {void} + */ setPmaConsole (instance) { this.pmaConsole = instance; this.initialize(); } + /** * Used for clear the messages * @@ -39,6 +50,7 @@ export default class ConsoleMessages { $('#pma_console').find('.content .console_message_container .message.failed').remove(); $('#pma_console').find('.content .console_message_container .message.expanded').find('.action.collapse').click(); } + /** * Used for show history messages * @@ -47,6 +59,7 @@ export default class ConsoleMessages { showHistory () { $('#pma_console').find('.content .console_message_container .message.hide').removeClass('hide'); } + /** * Used for getting a perticular history query * @@ -63,6 +76,7 @@ export default class ConsoleMessages { return $query.text(); } } + /** * Used to show the correct message depending on which key * combination executes the query (Ctrl+Enter or Enter). @@ -76,6 +90,7 @@ export default class ConsoleMessages { $welcomeMsg.children('[id^=instructions]').hide(); $welcomeMsg.children('#instructions-' + enterExecutes).show(); } + /** * Used for log new message * @@ -117,6 +132,7 @@ export default class ConsoleMessages { return { message_id: msgId, $message: $newMessage.appendTo('#pma_console .content .console_message_container') }; } + /** * Used for log new query * @@ -151,6 +167,7 @@ export default class ConsoleMessages { } return targetMessage; } + _msgEventBinds ($targetMessage) { var self = this; // Leave unbinded elements, remove binded. @@ -258,6 +275,12 @@ export default class ConsoleMessages { }); } } + + /** + * @param {string} msgId Id of the message + * @param {string} msgString Message string + * @param {string} msgType Type of message + */ msgAppend (msgId, msgString, msgType) { var $targetMessage = $('#pma_console').find('.content .console_message_container .message[msgid=' + msgId + ']'); if ($targetMessage.length === 0 || isNaN(parseInt(msgId)) || typeof(msgString) !== 'string') { @@ -265,6 +288,12 @@ export default class ConsoleMessages { } $targetMessage.append('<div>' + msgString + '</div>'); } + + /** + * @param {string} msgId Id of the message + * @param {bool} isSuccessed is update succeded + * @param {Object} queryData Data associated with the query + */ updateQuery (msgId, isSuccessed, queryData) { var $targetMessage = $('#pma_console').find('.console_message_container .message[msgid=' + parseInt(msgId) + ']'); if ($targetMessage.length === 0 || isNaN(parseInt(msgId))) { @@ -292,6 +321,7 @@ export default class ConsoleMessages { $targetMessage.addClass('failed'); } } + /** * Used for console messages initialize * diff --git a/js/src/classes/Server/ProcessList.js b/js/src/classes/Server/ProcessList.js index 23b7ec031d..b70004a084 100644 --- a/js/src/classes/Server/ProcessList.js +++ b/js/src/classes/Server/ProcessList.js @@ -1,12 +1,23 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import { $ } from '../../utils/JqueryExtended'; +import CommonParams from '../../variables/common_params'; +import { escapeHtml } from '../../utils/Sanitise'; import { PMA_ajaxShowMessage } from '../../utils/show_ajax_messages'; +import { PMA_getImage } from '../../functions/get_image'; import { PMA_highlightSQL } from '../../utils/sql'; import { PMA_Messages as messages } from '../../variables/export_variables'; -import CommonParams from '../../variables/common_params'; -import { PMA_getImage } from '../../functions/get_image'; -import { escapeHtml } from '../../utils/Sanitise'; -import { $ } from '../../utils/JqueryExtended'; -// object to store process list state information + +/** + * @class Object to store process list state information + */ class ProcessList { + /** + * @constructor Create a ProcessList + */ constructor () { // denotes whether auto refresh is on or off this.autoRefresh = false; @@ -19,6 +30,8 @@ class ProcessList { // the refresh URL (required to save last used option) // i.e. full or sorting url this.refreshUrl = null; + + // Bindings for methods this.init = this.init.bind(this); this.killProcessHandler = this.killProcessHandler.bind(this); this.refresh = this.refresh.bind(this); diff --git a/js/src/console.js b/js/src/console.js index b6a90fa379..ef2ff4cbef 100644 --- a/js/src/console.js +++ b/js/src/console.js @@ -1,14 +1,20 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + /** * Used in or for console * * @package phpMyAdmin-Console */ + +/** + * Module import + */ import ConsoleBookmarks from './classes/Console/PMA_consoleBookmarks'; import ConsoleDebug from './classes/Console/PMA_consoleDebug'; import ConsoleInput from './classes/Console/PMA_consoleInput'; import ConsoleMessages from './classes/Console/PMA_consoleMessages'; import ConsoleResizer from './classes/Console/PMA_ConsoleResizer'; + /** * Console object */ @@ -54,11 +60,27 @@ var Console = { * @access private */ isInitialized: false, + /** + * @var object, instance of PMA Console Resizer + */ pmaConsoleResizer: null, + /** + * @var object, instance of PMA Console Input + */ pmaConsoleInput: null, + /** + * @var object, instance of PMA Console Messages + */ pmaConsoleMessages: null, + /** + * @var object, instance of PMA Console Bookmaks + */ pmaConsoleBookmarks: null, + /** + * @var object, instance of PMA Console Debug + */ pmaConsoleDebug: null, + /** * Used for console initialize, reinit is ok, just some variable assignment * @@ -216,6 +238,7 @@ var Console = { Console.setConfig('Mode', 'info'); } }, + /** * Execute query and show results in console * @@ -251,6 +274,7 @@ var Console = { Console.pmaConsoleInput.clear(); PMA_reloadNavigation(); }, + ajaxCallback: function (data) { if (data && data.console_message_id) { Console.pmaConsoleMessages.updateQuery(data.console_message_id, data.success, @@ -262,6 +286,7 @@ var Console = { } } }, + /** * Change console to collapse mode * @@ -281,6 +306,7 @@ var Console = { }); Console.hideCard(); }, + /** * Show console * @@ -306,6 +332,7 @@ var Console = { } }); }, + /** * Change console to SQL information mode * this mode shows current SQL query @@ -317,6 +344,7 @@ var Console = { // Under construction Console.collapse(); }, + /** * Toggle console mode between collapse/show * Used for toggle buttons and shortcuts @@ -336,6 +364,7 @@ var Console = { PMA_consoleInitialize(); } }, + /** * Scroll console to bottom * @@ -344,6 +373,7 @@ var Console = { scrollBottom: function () { Console.$consoleContent.scrollTop(Console.$consoleContent.prop('scrollHeight')); }, + /** * Show card * @@ -373,6 +403,7 @@ var Console = { Console.showCard($card.parents('.card')); } }, + /** * Scroll console to bottom * @@ -389,6 +420,7 @@ var Console = { $targetCard.removeClass('show'); } }, + /** * Used for update console config * @@ -407,10 +439,12 @@ var Console = { $('#pma_console').find('>.content').removeClass('console_dark_theme'); } }, + setConfig: function (key, value) { Console.config[key] = value; configSet('Console/' + key, value); }, + isSelect: function (queryString) { var reg_exp = /^SELECT\s+/i; return reg_exp.test(queryString); diff --git a/js/src/db_central_columns.js b/js/src/db_central_columns.js index cd92967974..03a4ea8f98 100644 --- a/js/src/db_central_columns.js +++ b/js/src/db_central_columns.js @@ -1,10 +1,15 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from './utils/JqueryExtended'; import './plugins/jquery/jquery.tablesorter'; -import { PMA_Messages as PMA_messages } from './variables/export_variables'; -import { PMA_ajaxShowMessage } from './utils/show_ajax_messages'; -import PMA_commonParams from './variables/common_params'; import { AJAX } from './ajax'; +import CommonParams from './variables/common_params'; +import { PMA_ajaxShowMessage } from './utils/show_ajax_messages'; +import { PMA_Messages as messages } from './variables/export_variables'; + /** * @fileoverview events handling from central columns page * @name Central columns @@ -56,7 +61,7 @@ export function onloadDbCentralColumns () { event.preventDefault(); var multi_delete_columns = $('.checkall:checkbox:checked').serialize(); if (multi_delete_columns === '') { - PMA_ajaxShowMessage(PMA_messages.strRadioUnchecked); + PMA_ajaxShowMessage(messages.strRadioUnchecked); return false; } PMA_ajaxShowMessage(); @@ -67,11 +72,11 @@ export function onloadDbCentralColumns () { event.preventDefault(); var editColumnList = $('.checkall:checkbox:checked').serialize(); if (editColumnList === '') { - PMA_ajaxShowMessage(PMA_messages.strRadioUnchecked); + PMA_ajaxShowMessage(messages.strRadioUnchecked); return false; } - var argsep = PMA_commonParams.get('arg_separator'); - var editColumnData = editColumnList + '' + argsep + 'edit_central_columns_page=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + PMA_commonParams.get('db'); + var argsep = CommonParams.get('arg_separator'); + var editColumnData = editColumnList + '' + argsep + 'edit_central_columns_page=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + CommonParams.get('db'); PMA_ajaxShowMessage(); AJAX.source = $(this); $.get('db_central_columns.php', editColumnData, AJAX.responseHandler); @@ -79,8 +84,8 @@ export function onloadDbCentralColumns () { $('#multi_edit_central_columns').submit(function (event) { event.preventDefault(); event.stopPropagation(); - var argsep = PMA_commonParams.get('arg_separator'); - var multi_column_edit_data = $('#multi_edit_central_columns').serialize() + argsep + 'multi_edit_central_column_save=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + encodeURIComponent(PMA_commonParams.get('db')); + var argsep = CommonParams.get('arg_separator'); + var multi_column_edit_data = $('#multi_edit_central_columns').serialize() + argsep + 'multi_edit_central_column_save=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + encodeURIComponent(CommonParams.get('db')); PMA_ajaxShowMessage(); AJAX.source = $(this); $.post('db_central_columns.php', multi_column_edit_data, AJAX.responseHandler); @@ -122,7 +127,7 @@ export function onloadDbCentralColumns () { event.preventDefault(); event.stopPropagation(); var $td = $(this); - var question = PMA_messages.strDeleteCentralColumnWarning; + var question = messages.strDeleteCentralColumnWarning; $td.PMA_confirm(question, null, function (url) { var rownum = $td.data('rownum'); $('#del_col_name').val('selected_fld%5B%5D=' + $('#checkbox_row_' + rownum).val()); @@ -160,7 +165,7 @@ export function onloadDbCentralColumns () { $.ajax({ type: 'POST', url: 'db_central_columns.php', - data: datastring + PMA_commonParams.get('arg_separator') + 'ajax_request=true', + data: datastring + CommonParams.get('arg_separator') + 'ajax_request=true', dataType: 'json', success: function (data) { if (data.message !== '1') { @@ -190,7 +195,7 @@ export function onloadDbCentralColumns () { error: function () { PMA_ajaxShowMessage( '<div class="error">' + - PMA_messages.strErrorProcessingRequest + + messages.strErrorProcessingRequest + '</div>', false ); @@ -203,12 +208,12 @@ export function onloadDbCentralColumns () { var href = 'db_central_columns.php'; var params = { 'ajax_request' : true, - 'server' : PMA_commonParams.get('server'), - 'db' : PMA_commonParams.get('db'), + 'server' : CommonParams.get('server'), + 'db' : CommonParams.get('db'), 'selectedTable' : selectvalue, 'populateColumns' : true }; - $('#column-select').html('<option value="">' + PMA_messages.strLoading + '</option>'); + $('#column-select').html('<option value="">' + messages.strLoading + '</option>'); if (selectvalue !== '') { $.post(href, params, function (data) { $('#column-select').empty().append(default_column_select); diff --git a/js/src/db_operations.js b/js/src/db_operations.js index be2ec287a0..b45c1b038d 100644 --- a/js/src/db_operations.js +++ b/js/src/db_operations.js @@ -1,13 +1,18 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from './utils/JqueryExtended'; +import CommonParams from './variables/common_params'; import { PMA_commonActions } from './classes/CommonActions'; -import PMA_commonParams from './variables/common_params'; import { PMA_Messages as PMA_messages } from './variables/export_variables'; import { PMA_ajaxShowMessage } from './utils/show_ajax_messages'; import { escapeHtml } from './utils/Sanitise'; import { PMA_prepareForAjaxRequest } from './functions/AjaxRequest'; import { PMA_sprintf } from './utils/sprintf'; import { getJSConfirmCommonParam } from './functions/Common'; + /** * @fileoverview function used in server privilege pages * @name Database Operations @@ -45,7 +50,7 @@ export function onloadDbOperations () { $(document).on('submit', '#rename_db_form.ajax', function (event) { event.preventDefault(); - var old_db_name = PMA_commonParams.get('db'); + var old_db_name = CommonParams.get('db'); var new_db_name = $('#new_db_name').val(); if (new_db_name === old_db_name) { @@ -61,10 +66,10 @@ export function onloadDbOperations () { $form.PMA_confirm(question, $form.attr('action'), function (url) { PMA_ajaxShowMessage(PMA_messages.strRenamingDatabases, false); - $.post(url, $('#rename_db_form').serialize() + PMA_commonParams.get('arg_separator') + 'is_js_confirmed=1', function (data) { + $.post(url, $('#rename_db_form').serialize() + CommonParams.get('arg_separator') + 'is_js_confirmed=1', function (data) { if (typeof data !== 'undefined' && data.success === true) { PMA_ajaxShowMessage(data.message); - PMA_commonParams.set('db', data.newname); + CommonParams.set('db', data.newname); PMA_reloadNavigation(function () { $('#pma_navigation_tree') @@ -98,12 +103,12 @@ export function onloadDbOperations () { $('div.success, div.error').fadeOut(); if (typeof data !== 'undefined' && data.success === true) { if ($('#checkbox_switch').is(':checked')) { - PMA_commonParams.set('db', data.newname); + CommonParams.set('db', data.newname); PMA_commonActions.refreshMain(false, function () { PMA_ajaxShowMessage(data.message); }); } else { - PMA_commonParams.set('db', data.db); + CommonParams.set('db', data.db); PMA_ajaxShowMessage(data.message); } PMA_reloadNavigation(); @@ -129,7 +134,7 @@ export function onloadDbOperations () { var $form = $(this); PMA_prepareForAjaxRequest($form); PMA_ajaxShowMessage(PMA_messages.strChangingCharset); - $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'submitcollation=1', function (data) { + $.post($form.attr('action'), $form.serialize() + CommonParams.get('arg_separator') + 'submitcollation=1', function (data) { if (typeof data !== 'undefined' && data.success === true) { PMA_ajaxShowMessage(data.message); } else { @@ -150,7 +155,7 @@ export function onloadDbOperations () { var question = PMA_messages.strDropDatabaseStrongWarning + ' '; question += PMA_sprintf( PMA_messages.strDoYouReally, - 'DROP DATABASE `' + escapeHtml(PMA_commonParams.get('db') + '`') + 'DROP DATABASE `' + escapeHtml(CommonParams.get('db') + '`') ); var params = getJSConfirmCommonParam(this, $link.getPostData()); @@ -160,7 +165,7 @@ export function onloadDbOperations () { if (typeof data !== 'undefined' && data.success) { // Database deleted successfully, refresh both the frames PMA_reloadNavigation(); - PMA_commonParams.set('db', ''); + CommonParams.set('db', ''); PMA_commonActions.refreshMain( 'server_databases.php', function () { diff --git a/js/src/db_search.js b/js/src/db_search.js index 113f9b8958..62d8b29efc 100644 --- a/js/src/db_search.js +++ b/js/src/db_search.js @@ -1,4 +1,14 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import { $ } from './utils/JqueryExtended'; +import { PMA_Messages as messages } from './variables/export_variables'; +import { PMA_ajaxShowMessage, PMA_sprintf, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages'; +import CommonParams from './variables/common_params'; +import { PMA_makegrid } from './utils/makegrid'; + /** * JavaScript functions used on Database Search page * @@ -14,11 +24,6 @@ * Actions ajaxified here: * Retrieve result of SQL query */ -import { $ } from './utils/JqueryExtended'; -import { PMA_Messages as messages } from './variables/export_variables'; -import { PMA_ajaxShowMessage, PMA_sprintf, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages'; -import PMA_commonParams from './variables/common_params'; -import { PMA_makegrid } from './utils/makegrid'; /** * Unbind all event handlers before tearing down a page @@ -217,7 +222,7 @@ export function onloadDbSearch () { PMA_prepareForAjaxRequest($form); var url = `${$form.serialize()} - ${PMA_commonParams.get('arg_separator')}submit_search=${$('#buttonGo').val()}`; + ${CommonParams.get('arg_separator')}submit_search=${$('#buttonGo').val()}`; $.post($form.attr('action'), url, function (data) { if (typeof data !== 'undefined' && data.success === true) { // found results diff --git a/js/src/db_structure.js b/js/src/db_structure.js index a5bceaf31a..bb7bfd2897 100644 --- a/js/src/db_structure.js +++ b/js/src/db_structure.js @@ -1,6 +1,10 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from './utils/JqueryExtended'; -import { PMA_Messages as PMA_messages } from './variables/export_variables'; +import { PMA_Messages as messages } from './variables/export_variables'; import { PMA_sprintf } from './utils/sprintf'; import { escapeHtml } from './utils/Sanitise'; import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage, PMA_tooltip } from './utils/show_ajax_messages'; @@ -53,18 +57,18 @@ export function onloadDbStructure () { var dialogObj = $('<div class=\'hide\'>' + msg + '</div>'); $('body').append(dialogObj); var buttonOptions = {}; - buttonOptions[PMA_messages.strContinue] = function () { + buttonOptions[messages.strContinue] = function () { success(); $(this).dialog('close'); }; - buttonOptions[PMA_messages.strCancel] = function () { + buttonOptions[messages.strCancel] = function () { $(this).dialog('close'); $('#tablesForm')[0].reset(); }; $(dialogObj).dialog({ resizable: false, modal: true, - title: PMA_messages.confirmTitle, + title: messages.confirmTitle, buttons: buttonOptions }); }; @@ -77,7 +81,7 @@ export function onloadDbStructure () { event.preventDefault(); event.stopPropagation(); jqConfirm( - PMA_messages.makeConsistentMessage, function () { + messages.makeConsistentMessage, function () { $('#tablesForm').submit(); } ); @@ -91,13 +95,13 @@ export function onloadDbStructure () { var formData = $('#tablesForm').serialize(); var modalTitle = ''; if ($(this).val() === 'copy_tbl') { - modalTitle = PMA_messages.strCopyTablesTo; + modalTitle = messages.strCopyTablesTo; } else if ($(this).val() === 'add_prefix_tbl') { - modalTitle = PMA_messages.strAddPrefix; + modalTitle = messages.strAddPrefix; } else if ($(this).val() === 'replace_prefix_tbl') { - modalTitle = PMA_messages.strReplacePrefix; + modalTitle = messages.strReplacePrefix; } else if ($(this).val() === 'copy_tbl_change_prefix') { - modalTitle = PMA_messages.strCopyPrefix; + modalTitle = messages.strCopyPrefix; } $.ajax({ type: 'POST', @@ -109,11 +113,11 @@ export function onloadDbStructure () { var dialogObj = $('<div class=\'hide\'>' + data + '</div>'); $('body').append(dialogObj); var buttonOptions = {}; - buttonOptions[PMA_messages.strContinue] = function () { + buttonOptions[messages.strContinue] = function () { $('#ajax_form').submit(); $(this).dialog('close'); }; - buttonOptions[PMA_messages.strCancel] = function () { + buttonOptions[messages.strCancel] = function () { $(this).dialog('close'); $('#tablesForm')[0].reset(); }; @@ -149,12 +153,12 @@ export function onloadDbStructure () { /** * @var question String containing the question to be asked for confirmation */ - var question = PMA_messages.strTruncateTableStrongWarning + ' ' + - PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE `' + escapeHtml(curr_table_name) + '`') + + var question = messages.strTruncateTableStrongWarning + ' ' + + PMA_sprintf(messages.strDoYouReally, 'TRUNCATE `' + escapeHtml(curr_table_name) + '`') + getForeignKeyCheckboxLoader(); $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); + PMA_ajaxShowMessage(messages.strProcessingRequest); var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); @@ -175,7 +179,7 @@ export function onloadDbStructure () { .removeClass('truncate_table_anchor'); PMA_adjustTotals(); } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); + PMA_ajaxShowMessage(messages.strErrorProcessingRequest + ' : ' + data.error, false); } }); // end $.post() }, loadForeignKeyCheckbox); // end $.PMA_confirm() @@ -207,16 +211,16 @@ export function onloadDbStructure () { */ var question; if (! is_view) { - question = PMA_messages.strDropTableStrongWarning + ' ' + - PMA_sprintf(PMA_messages.strDoYouReally, 'DROP TABLE `' + escapeHtml(curr_table_name) + '`'); + question = messages.strDropTableStrongWarning + ' ' + + PMA_sprintf(messages.strDoYouReally, 'DROP TABLE `' + escapeHtml(curr_table_name) + '`'); } else { question = - PMA_sprintf(PMA_messages.strDoYouReally, 'DROP VIEW `' + escapeHtml(curr_table_name) + '`'); + PMA_sprintf(messages.strDoYouReally, 'DROP VIEW `' + escapeHtml(curr_table_name) + '`'); } question += getForeignKeyCheckboxLoader(); $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) { - var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); + var $msg = PMA_ajaxShowMessage(messages.strProcessingRequest); var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); @@ -228,7 +232,7 @@ export function onloadDbStructure () { PMA_reloadNavigation(); PMA_ajaxRemoveMessage($msg); } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); + PMA_ajaxShowMessage(messages.strErrorProcessingRequest + ' : ' + data.error, false); } }); // end $.post() }, loadForeignKeyCheckbox); // end $.PMA_confirm() @@ -255,7 +259,7 @@ export function onloadDbStructure () { /** * @var question String containing the question to be asked for confirmation */ - var question = PMA_messages.strOperationTakesLongTime; + var question = messages.strOperationTakesLongTime; $(this).PMA_confirm(question, '', function () { return true; diff --git a/js/src/db_tracking.js b/js/src/db_tracking.js index a61dbd124f..07f3be924e 100644 --- a/js/src/db_tracking.js +++ b/js/src/db_tracking.js @@ -1,9 +1,14 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from './utils/JqueryExtended'; import './plugins/jquery/jquery.tablesorter'; -import PMA_commonParams from './variables/common_params'; +import { AJAX } from './ajax'; +import CommonParams from './variables/common_params'; import { PMA_Messages as PMA_messages } from './variables/export_variables'; import { PMA_ajaxShowMessage } from './utils/show_ajax_messages'; -import { AJAX } from './ajax'; /** * Unbind all event handlers before tearing down the page @@ -50,7 +55,7 @@ export function onloadDbTracking () { e.preventDefault(); var $button = $(this); var $form = $button.parent('form'); - var argsep = PMA_commonParams.get('arg_separator'); + var argsep = CommonParams.get('arg_separator'); var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); if ($button.val() === 'delete_tracking') { @@ -74,7 +79,7 @@ export function onloadDbTracking () { e.preventDefault(); var $button = $(this); var $form = $button.parent('form'); - var argsep = PMA_commonParams.get('arg_separator'); + var argsep = CommonParams.get('arg_separator'); var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); PMA_ajaxShowMessage(); AJAX.source = $form; diff --git a/js/src/functions/Database/Structure.js b/js/src/functions/Database/Structure.js index 011d7177a0..03856ecab5 100644 --- a/js/src/functions/Database/Structure.js +++ b/js/src/functions/Database/Structure.js @@ -1,4 +1,9 @@ -import { PMA_Messages as PMA_messages } from '../../variables/export_variables'; +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import { PMA_Messages as messages } from '../../variables/export_variables'; import { PMA_sprintf } from '../../utils/sprintf'; import { PMA_ajaxShowMessage } from '../../utils/show_ajax_messages'; /** @@ -7,13 +12,13 @@ import { PMA_ajaxShowMessage } from '../../utils/show_ajax_messages'; */ export function PMA_adjustTotals () { var byteUnits = [ - PMA_messages.strB, - PMA_messages.strKiB, - PMA_messages.strMiB, - PMA_messages.strGiB, - PMA_messages.strTiB, - PMA_messages.strPiB, - PMA_messages.strEiB + messages.strB, + messages.strKiB, + messages.strMiB, + messages.strGiB, + messages.strTiB, + messages.strPiB, + messages.strEiB ]; /** * @var $allTr jQuery object that references all the rows in the list of tables @@ -97,7 +102,7 @@ export function PMA_adjustTotals () { // Update summary with new data var $summary = $('#tbl_summary_row'); - $summary.find('.tbl_num').text(PMA_sprintf(PMA_messages.strNTables, tableSum)); + $summary.find('.tbl_num').text(PMA_sprintf(messages.strNTables, tableSum)); if (rowSumApproximated) { $summary.find('.row_count_sum').text(strRowSum); } else { @@ -143,11 +148,11 @@ export function PMA_fetchRealRowCount ($target) { // Adjust the 'Sum' displayed at the bottom. PMA_adjustTotals(); } else { - PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount); + PMA_ajaxShowMessage(messages.strErrorRealRowCount); } }, error: function () { - PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount); + PMA_ajaxShowMessage(messages.strErrorRealRowCount); } }); } diff --git a/js/src/functions/Grid/Cell.js b/js/src/functions/Grid/Cell.js index c8acc0d31f..0cdb3a82da 100644 --- a/js/src/functions/Grid/Cell.js +++ b/js/src/functions/Grid/Cell.js @@ -1,3 +1,5 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + /** * Return value of a cell in a table. */ diff --git a/js/src/functions/Grid/GetFieldName.js b/js/src/functions/Grid/GetFieldName.js index 3338728be0..896ea3aadf 100644 --- a/js/src/functions/Grid/GetFieldName.js +++ b/js/src/functions/Grid/GetFieldName.js @@ -1,3 +1,5 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + /** * Get the field name for the current field. Required to construct the query * for grid editing diff --git a/js/src/functions/Grid/StickyColumns.js b/js/src/functions/Grid/StickyColumns.js index e941940d6c..059d2cacf7 100644 --- a/js/src/functions/Grid/StickyColumns.js +++ b/js/src/functions/Grid/StickyColumns.js @@ -1,3 +1,5 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + var prevScrollX = 0; /* * Set position, left, top, width of sticky_columns div diff --git a/js/src/functions/Server/ServerStatusMonitor.js b/js/src/functions/Server/ServerStatusMonitor.js index 623ad2b106..02f0b0423c 100644 --- a/js/src/functions/Server/ServerStatusMonitor.js +++ b/js/src/functions/Server/ServerStatusMonitor.js @@ -1,13 +1,24 @@ -import { PMA_Messages as PMA_messages } from '../../variables/export_variables'; -export function getOsDetail (server_os, presetCharts) { +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import { PMA_Messages as messages } from '../../variables/export_variables'; + +/** + * @param {string} serverOs Type of operating system + * + * @param {Object} presetCharts Charts already set + */ +export function getOsDetail (serverOs, presetCharts) { /* Add OS specific system info charts to the preset chart list */ - switch (server_os) { + switch (serverOs) { case 'WINNT': $.extend(presetCharts, { 'cpu': { - title: PMA_messages.strSystemCPUUsage, + title: messages.strSystemCPUUsage, series: [{ - label: PMA_messages.strAverageLoad + label: messages.strAverageLoad }], nodes: [{ dataPoints: [{ type: 'cpu', name: 'loadavg' }] @@ -16,13 +27,13 @@ export function getOsDetail (server_os, presetCharts) { }, 'memory': { - title: PMA_messages.strSystemMemory, + title: messages.strSystemMemory, series: [{ - label: PMA_messages.strTotalMemory, + label: messages.strTotalMemory, fill: true }, { dataType: 'memory', - label: PMA_messages.strUsedMemory, + label: messages.strUsedMemory, fill: true }], nodes: [{ dataPoints: [{ type: 'memory', name: 'MemTotal' }], valueDivisor: 1024 }, @@ -32,12 +43,12 @@ export function getOsDetail (server_os, presetCharts) { }, 'swap': { - title: PMA_messages.strSystemSwap, + title: messages.strSystemSwap, series: [{ - label: PMA_messages.strTotalSwap, + label: messages.strTotalSwap, fill: true }, { - label: PMA_messages.strUsedSwap, + label: messages.strUsedSwap, fill: true }], nodes: [{ dataPoints: [{ type: 'memory', name: 'SwapTotal' }] }, @@ -51,20 +62,20 @@ export function getOsDetail (server_os, presetCharts) { case 'Linux': $.extend(presetCharts, { 'cpu': { - title: PMA_messages.strSystemCPUUsage, + title: messages.strSystemCPUUsage, series: [{ - label: PMA_messages.strAverageLoad + label: messages.strAverageLoad }], nodes: [{ dataPoints: [{ type: 'cpu', name: 'irrelevant' }], transformFn: 'cpu-linux' }], maxYLabel: 0 }, 'memory': { - title: PMA_messages.strSystemMemory, + title: messages.strSystemMemory, series: [ - { label: PMA_messages.strBufferedMemory, fill: true }, - { label: PMA_messages.strUsedMemory, fill: true }, - { label: PMA_messages.strCachedMemory, fill: true }, - { label: PMA_messages.strFreeMemory, fill: true } + { label: messages.strBufferedMemory, fill: true }, + { label: messages.strUsedMemory, fill: true }, + { label: messages.strCachedMemory, fill: true }, + { label: messages.strFreeMemory, fill: true } ], nodes: [ { dataPoints: [{ type: 'memory', name: 'Buffers' }], valueDivisor: 1024 }, @@ -75,11 +86,11 @@ export function getOsDetail (server_os, presetCharts) { maxYLabel: 0 }, 'swap': { - title: PMA_messages.strSystemSwap, + title: messages.strSystemSwap, series: [ - { label: PMA_messages.strCachedSwap, fill: true }, - { label: PMA_messages.strUsedSwap, fill: true }, - { label: PMA_messages.strFreeSwap, fill: true } + { label: messages.strCachedSwap, fill: true }, + { label: messages.strUsedSwap, fill: true }, + { label: messages.strFreeSwap, fill: true } ], nodes: [ { dataPoints: [{ type: 'memory', name: 'SwapCached' }], valueDivisor: 1024 }, @@ -94,9 +105,9 @@ export function getOsDetail (server_os, presetCharts) { case 'SunOS': $.extend(presetCharts, { 'cpu': { - title: PMA_messages.strSystemCPUUsage, + title: messages.strSystemCPUUsage, series: [{ - label: PMA_messages.strAverageLoad + label: messages.strAverageLoad }], nodes: [{ dataPoints: [{ type: 'cpu', name: 'loadavg' }] @@ -104,10 +115,10 @@ export function getOsDetail (server_os, presetCharts) { maxYLabel: 0 }, 'memory': { - title: PMA_messages.strSystemMemory, + title: messages.strSystemMemory, series: [ - { label: PMA_messages.strUsedMemory, fill: true }, - { label: PMA_messages.strFreeMemory, fill: true } + { label: messages.strUsedMemory, fill: true }, + { label: messages.strFreeMemory, fill: true } ], nodes: [ { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }, @@ -116,10 +127,10 @@ export function getOsDetail (server_os, presetCharts) { maxYLabel: 0 }, 'swap': { - title: PMA_messages.strSystemSwap, + title: messages.strSystemSwap, series: [ - { label: PMA_messages.strUsedSwap, fill: true }, - { label: PMA_messages.strFreeSwap, fill: true } + { label: messages.strUsedSwap, fill: true }, + { label: messages.strFreeSwap, fill: true } ], nodes: [ { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 }, diff --git a/js/src/functions/Server/SeverStatusSorter.js b/js/src/functions/Server/ServerStatusSorter.js index 9cf7695961..d03c5eea74 100644 --- a/js/src/functions/Server/SeverStatusSorter.js +++ b/js/src/functions/Server/ServerStatusSorter.js @@ -5,6 +5,7 @@ */ import { $ } from '../../utils/JqueryExtended'; import '../../plugins/jquery/jquery.tablesorter'; + // TODO: tablesorter shouldn't sort already sorted columns /** * @access public diff --git a/js/src/functions/Table/CreateTable.js b/js/src/functions/Table/CreateTable.js index f1e3ddbb2f..cdfc18e948 100644 --- a/js/src/functions/Table/CreateTable.js +++ b/js/src/functions/Table/CreateTable.js @@ -1,5 +1,11 @@ -import PMA_commonParams from '../../variables/common_params'; +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import CommonParams from '../../variables/common_params'; import { PMA_Messages as PMA_messages } from '../../variables/export_variables'; + /** * Check if a form's element is empty. * An element containing only spaces is also considered empty @@ -81,7 +87,7 @@ export function PMA_checkReservedWordColumns ($form) { $.ajax({ type: 'POST', url: 'tbl_structure.php', - data: $form.serialize() + PMA_commonParams.get('arg_separator') + 'reserved_word_check=1', + data: $form.serialize() + CommonParams.get('arg_separator') + 'reserved_word_check=1', success: function (data) { if (typeof data.success !== 'undefined' && data.success === true) { is_confirmed = confirm(data.message); diff --git a/js/src/functions/Table/Relation.js b/js/src/functions/Table/Relation.js index a987a6867a..3fb16cad7f 100644 --- a/js/src/functions/Table/Relation.js +++ b/js/src/functions/Table/Relation.js @@ -1,7 +1,13 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from '../../utils/JqueryExtended'; +import CommonParams from '../../variables/common_params'; import { escapeHtml } from '../../utils/Sanitise'; -import PMA_commonParams from '../../variables/common_params'; import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from '../../utils/show_ajax_messages'; + /** * for tbl_relation.php * @@ -74,7 +80,7 @@ export function getDropdownValues ($dropdown) { } var $msgbox = PMA_ajaxShowMessage(); var $form = $dropdown.parents('form'); - var argsep = PMA_commonParams.get('arg_separator'); + var argsep = CommonParams.get('arg_separator'); var url = 'tbl_relation.php?getDropdownValues=true' + argsep + 'ajax_request=true' + argsep + 'db=' + $form.find('input[name="db"]').val() + argsep + 'table=' + $form.find('input[name="table"]').val() + diff --git a/js/src/functions/Table/TableChange.js b/js/src/functions/Table/TableChange.js index 3b9133de61..651e38e3ac 100644 --- a/js/src/functions/Table/TableChange.js +++ b/js/src/functions/Table/TableChange.js @@ -1,3 +1,8 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from '../../utils/JqueryExtended'; import { PMA_Messages as PMA_messages } from '../../variables/export_variables'; @@ -65,13 +70,13 @@ function fractionReplace (num) { return num >= 1 && num <= 9 ? '0' + num : '00'; } -/* function to check the validity of date -* The following patterns are accepted in this validation (accepted in mysql as well) -* 1) 2001-12-23 -* 2) 2001-1-2 -* 3) 02-12-23 -* 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues -*/ +/** function to check the validity of date + * The following patterns are accepted in this validation (accepted in mysql as well) + * 1) 2001-12-23 + * 2) 2001-1-2 + * 3) 02-12-23 + * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues + */ export function isDate (val, tmstmp) { val = val.replace(/[.|*|^|+|//|@]/g, '-'); var arrayVal = val.split('-'); @@ -110,12 +115,12 @@ export function isDate (val, tmstmp) { return true; } -/* function to check the validity of time -* The following patterns are accepted in this validation (accepted in mysql as well) -* 1) 2:3:4 -* 2) 2:23:43 -* 3) 2:23:43.123456 -*/ +/** function to check the validity of time + * The following patterns are accepted in this validation (accepted in mysql as well) + * 1) 2:3:4 + * 2) 2:23:43 + * 3) 2:23:43.123456 + */ export function isTime (val) { var arrayVal = val.split(':'); for (var a = 0, l = arrayVal.length; a < l; a++) { diff --git a/js/src/functions/Table/TableChart.js b/js/src/functions/Table/TableChart.js index e00a36c6b1..d58c41b9a5 100644 --- a/js/src/functions/Table/TableChart.js +++ b/js/src/functions/Table/TableChart.js @@ -1,3 +1,8 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from '../../utils/JqueryExtended'; import JQPlotChartFactory, { DataTable, ColumnType } from '../../classes/Chart'; import { escapeHtml } from '../../utils/Sanitise'; diff --git a/js/src/functions/Table/TableColumns.js b/js/src/functions/Table/TableColumns.js index eef47c540f..64578015ea 100644 --- a/js/src/functions/Table/TableColumns.js +++ b/js/src/functions/Table/TableColumns.js @@ -1,4 +1,10 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from '../../utils/JqueryExtended'; + /** * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected */ diff --git a/js/src/functions/Table/TableSelect.js b/js/src/functions/Table/TableSelect.js index 69302e9cab..b66a49e495 100644 --- a/js/src/functions/Table/TableSelect.js +++ b/js/src/functions/Table/TableSelect.js @@ -1,3 +1,8 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from '../../utils/JqueryExtended'; export function changeValueFieldType (elem, searchIndex) { diff --git a/js/src/functions/Table/TableStructure.js b/js/src/functions/Table/TableStructure.js new file mode 100644 index 0000000000..b67b1e96ad --- /dev/null +++ b/js/src/functions/Table/TableStructure.js @@ -0,0 +1,28 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import CommonParams from '../../variables/common_params'; + +/** + * Reload fields table + */ +export function reloadFieldForm () { + $.post($('#fieldsForm').attr('action'), $('#fieldsForm').serialize() + CommonParams.get('arg_separator') + 'ajax_request=true', function (form_data) { + var $temp_div = $('<div id=\'temp_div\'><div>').append(form_data.message); + $('#fieldsForm').replaceWith($temp_div.find('#fieldsForm')); + $('#addColumns').replaceWith($temp_div.find('#addColumns')); + $('#move_columns_dialog').find('ul').replaceWith($temp_div.find('#move_columns_dialog ul')); + $('#moveColumns').removeClass('move-active'); + }); + $('#page_content').show(); +} + +export function checkFirst () { + if ($('select[name=after_field] option:selected').data('pos') === 'first') { + $('input[name=field_where]').val('first'); + } else { + $('input[name=field_where]').val('after'); + } +} diff --git a/js/src/server_databases.js b/js/src/server_databases.js index 154b83967b..eafaf6a511 100644 --- a/js/src/server_databases.js +++ b/js/src/server_databases.js @@ -11,16 +11,16 @@ /** * Moduele import */ -import { PMA_sprintf } from './utils/sprintf'; import './variables/import_variables'; -import { PMA_ajaxShowMessage } from './utils/show_ajax_messages'; -import { escapeHtml } from './utils/Sanitise'; -import { PMA_Messages as messages } from './variables/export_variables'; import { $ } from './utils/JqueryExtended'; import { AJAX } from './ajax'; import CommonParams from './variables/common_params'; -import { PMA_reloadNavigation } from './functions/navigation'; +import { escapeHtml } from './utils/Sanitise'; import { getJSConfirmCommonParam } from './functions/Common'; +import { PMA_ajaxShowMessage } from './utils/show_ajax_messages'; +import { PMA_Messages as messages } from './variables/export_variables'; +import { PMA_reloadNavigation } from './functions/navigation'; +import { PMA_sprintf } from './utils/sprintf'; /** * @package PhpMyAdmin diff --git a/js/src/server_privileges.js b/js/src/server_privileges.js index 2c395e8ad3..a3f6fc1fa0 100644 --- a/js/src/server_privileges.js +++ b/js/src/server_privileges.js @@ -11,13 +11,13 @@ /** * Module import */ -import { PMA_sprintf } from './utils/sprintf'; +import { $ } from './utils/JqueryExtended'; import { checkPasswordStrength, displayPasswordGenerateButton } from './utils/password'; -import { PMA_Messages as messages } from './variables/export_variables'; -import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages'; import CommonParams from './variables/common_params'; -import { $ } from './utils/JqueryExtended'; +import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages'; import { PMA_getSQLEditor } from './functions/Sql/SqlEditor'; +import { PMA_Messages as messages } from './variables/export_variables'; +import { PMA_sprintf } from './utils/sprintf'; /** * @package PhpMyAdmin @@ -26,8 +26,6 @@ import { PMA_getSQLEditor } from './functions/Sql/SqlEditor'; */ /** - * AJAX scripts for server_privileges page. - * * Actions ajaxified here: * Add user * Revoke a user diff --git a/js/src/server_status_monitor.js b/js/src/server_status_monitor.js index d47d4de8e3..5d65da48e9 100644 --- a/js/src/server_status_monitor.js +++ b/js/src/server_status_monitor.js @@ -1,7 +1,12 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ -import { PMA_Messages as messages } from './variables/export_variables'; + +/** + * Module import + */ import { $ } from './utils/JqueryExtended'; +import { PMA_Messages as messages } from './variables/export_variables'; +// jQplot and related plugins import import 'updated-jqplot'; import './plugins/jquery/jquery.sortableTable'; @@ -14,12 +19,12 @@ import 'updated-jqplot/dist/plugins/jqplot.highlighter.js'; import 'updated-jqplot/dist/plugins/jqplot.cursor.js'; import './plugins/jqplot/jqplot.byteFormatter'; -import { getOsDetail } from './functions/Server/ServerStatusMonitor'; -import { isStorageSupported } from './functions/config'; -import { createProfilingChart } from './functions/chart'; import CommonParams from './variables/common_params'; +import { createProfilingChart } from './functions/chart'; import { escapeHtml } from './utils/Sanitise'; +import { getOsDetail } from './functions/Server/ServerStatusMonitor'; import { PMA_getImage } from './functions/get_image'; +import { isStorageSupported } from './functions/config'; var runtime = {}; var server_time_diff; diff --git a/js/src/server_status_queries.js b/js/src/server_status_queries.js index 44f0eca50d..8b0868aa41 100644 --- a/js/src/server_status_queries.js +++ b/js/src/server_status_queries.js @@ -3,9 +3,9 @@ /** * Module import */ -import { createProfilingChart } from './functions/chart'; import { $ } from './utils/JqueryExtended'; -import { initTableSorter } from './functions/Server/SeverStatusSorter'; +import { createProfilingChart } from './functions/chart'; +import { initTableSorter } from './functions/Server/ServerStatusSorter'; /** * @package PhpMyAdmin diff --git a/js/src/server_user_groups.js b/js/src/server_user_groups.js index bdc33b2c77..0c20812ddb 100644 --- a/js/src/server_user_groups.js +++ b/js/src/server_user_groups.js @@ -3,9 +3,9 @@ /** * Module import */ +import { escapeHtml } from './utils/Sanitise'; import { PMA_Messages as messages } from './variables/export_variables'; import { PMA_sprintf } from './utils/sprintf'; -import { escapeHtml } from './utils/Sanitise'; /** * @package PhpMyAdmin diff --git a/js/src/server_variables.js b/js/src/server_variables.js index f4ec19bf3d..0ae788ad6a 100644 --- a/js/src/server_variables.js +++ b/js/src/server_variables.js @@ -24,7 +24,6 @@ function teardownServerVariables () { * Binding event handlers on page load. */ function onloadServerVariables () { - // var $editLink = $('a.editLink'); var $saveLink = $('a.saveLink'); var $cancelLink = $('a.cancelLink'); @@ -39,6 +38,9 @@ function onloadServerVariables () { }); } +/** + * Module export + */ export { teardownServerVariables, onloadServerVariables diff --git a/js/src/shortcuts_handler.js b/js/src/shortcuts_handler.js index 376bbb7670..572d306e8f 100644 --- a/js/src/shortcuts_handler.js +++ b/js/src/shortcuts_handler.js @@ -49,6 +49,10 @@ $(document).ready(function () { } }); $(document).on('keydown', function (e) { + // disable the shortcuts when session has timed out. + if ($('#modalOverlay').length > 0) { + return; + } if (e.ctrlKey && e.altKey && e.keyCode === keyC) { Console.toggle(); } diff --git a/js/src/tbl_change.js b/js/src/tbl_change.js index 9868c2d425..13491b3b82 100644 --- a/js/src/tbl_change.js +++ b/js/src/tbl_change.js @@ -1,14 +1,13 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $, extendingValidatorMessages } from './utils/JqueryExtended'; -import { - isDate, - isTime, - nullify, - verificationsAfterFieldChange -} from './functions/Table/TableChange'; +import { AJAX } from './ajax'; +import * as TableChange from './functions/Table/TableChange'; import { PMA_Messages as PMA_messages } from './variables/export_variables'; import { addDateTimePicker } from './utils/DateTime'; -import { AJAX } from './ajax'; /** * @fileoverview function used in table data manipulation pages @@ -60,9 +59,9 @@ export function onloadTblChange () { var dt_value = value; var theType = options; if (theType === 'date') { - return isDate(dt_value); + return TableChange.isDate(dt_value); } else if (theType === 'time') { - return isTime(dt_value); + return TableChange.isTime(dt_value); } else if (theType === 'datetime' || theType === 'timestamp') { var tmstmp = false; dt_value = dt_value.trim(); @@ -77,11 +76,11 @@ export function onloadTblChange () { } var dv = dt_value.indexOf(' '); if (dv === -1) { // Only the date component, which is valid - return isDate(dt_value, tmstmp); + return TableChange.isDate(dt_value, tmstmp); } - return isDate(dt_value.substring(0, dv), tmstmp) && - isTime(dt_value.substring(dv + 1)); + return TableChange.isDate(dt_value.substring(0, dv), tmstmp) && + TableChange.isTime(dt_value.substring(dv + 1)); } }); /* @@ -137,7 +136,7 @@ export function onloadTblChange () { * */ $(document).on('click', 'input.checkbox_null', function () { - nullify( + TableChange.nullify( // use hidden fields populated by tbl_change.php $(this).siblings('.nullify_code').val(), $(this).closest('tr').find('input:hidden').first().val(), @@ -264,7 +263,7 @@ export function onloadTblChange () { .data('new_row_index', new_row_index) .on('change', function () { var $changed_element = $(this); - verificationsAfterFieldChange( + TableChange.verificationsAfterFieldChange( $changed_element.data('hashed_field'), $changed_element.data('new_row_index'), $changed_element.closest('tr').find('span.column_type').html() @@ -283,7 +282,7 @@ export function onloadTblChange () { .data('new_row_index', new_row_index) .on('click', function () { var $changed_element = $(this); - nullify( + TableChange.nullify( $changed_element.siblings('.nullify_code').val(), $this_element.closest('tr').find('input:hidden').first().val(), $changed_element.data('hashed_field'), diff --git a/js/src/tbl_chart.js b/js/src/tbl_chart.js index 81849e4dd7..595ba0279d 100644 --- a/js/src/tbl_chart.js +++ b/js/src/tbl_chart.js @@ -1,4 +1,8 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { TableChartEnum, drawChart, onDataSeriesChange, diff --git a/js/src/tbl_find_replace.js b/js/src/tbl_find_replace.js index 3da67f242d..cee33430e6 100644 --- a/js/src/tbl_find_replace.js +++ b/js/src/tbl_find_replace.js @@ -1,4 +1,9 @@ -import { PMA_Messages as PMA_messages } from './variables/export_variables'; +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import { PMA_Messages as messages } from './variables/export_variables'; import { PMA_prepareForAjaxRequest } from './functions/AjaxRequest'; import { PMA_ajaxRemoveMessage, PMA_ajaxShowMessage } from './utils/show_ajax_messages'; @@ -19,14 +24,14 @@ export function onloadTblFindReplace () { .hide(); $('#toggle_find') - .html(PMA_messages.strHideFindNReplaceCriteria) + .html(messages.strHideFindNReplaceCriteria) .on('click', function () { var $link = $(this); $('#find_replace_form').slideToggle(); - if ($link.text() === PMA_messages.strHideFindNReplaceCriteria) { - $link.text(PMA_messages.strShowFindNReplaceCriteria); + if ($link.text() === messages.strHideFindNReplaceCriteria) { + $link.text(messages.strShowFindNReplaceCriteria); } else { - $link.text(PMA_messages.strHideFindNReplaceCriteria); + $link.text(messages.strHideFindNReplaceCriteria); } return false; }); diff --git a/js/src/tbl_operations.js b/js/src/tbl_operations.js index 2845bab167..7c0eed08ef 100644 --- a/js/src/tbl_operations.js +++ b/js/src/tbl_operations.js @@ -1,4 +1,9 @@ -import { PMA_Messages as PMA_messages } from './variables/export_variables'; +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ +import { PMA_Messages as messages } from './variables/export_variables'; import PMA_commonParams from './variables/common_params'; import { PMA_commonActions } from './classes/CommonActions'; import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages'; @@ -98,7 +103,7 @@ export function onloadTblOperations () { var $tblCollationField = $form.find('select[name=tbl_collation]'); var collationOrigValue = $('select[name="tbl_collation"] option[selected]').val(); var $changeAllColumnCollationsCheckBox = $('#checkbox_change_all_collations'); - var question = PMA_messages.strChangeAllColumnCollationsWarning; + var question = messages.strChangeAllColumnCollationsWarning; if ($tblNameField.val() !== $tblNameField[0].defaultValue) { // reload page and navigation if the table has been renamed @@ -210,18 +215,18 @@ export function onloadTblOperations () { function submitPartitionMaintenance () { var argsep = PMA_commonParams.get('arg_separator'); var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true'; - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); + PMA_ajaxShowMessage(messages.strProcessingRequest); AJAX.source = $form; $.post($form.attr('action'), submitData, AJAX.responseHandler); } if ($('#partition_operation_DROP').is(':checked')) { - let question = PMA_messages.strDropPartitionWarning; + let question = messages.strDropPartitionWarning; $form.PMA_confirm(question, $form.attr('action'), function () { submitPartitionMaintenance(); }); } else if ($('#partition_operation_TRUNCATE').is(':checked')) { - let question = PMA_messages.strTruncatePartitionWarning; + let question = messages.strTruncatePartitionWarning; $form.PMA_confirm(question, $form.attr('action'), function () { submitPartitionMaintenance(); }); @@ -236,14 +241,14 @@ export function onloadTblOperations () { /** * @var question String containing the question to be asked for confirmation */ - var question = PMA_messages.strDropTableStrongWarning + ' '; + var question = messages.strDropTableStrongWarning + ' '; question += PMA_sprintf( - PMA_messages.strDoYouReally, + messages.strDoYouReally, 'DROP TABLE `' + escapeHtml(PMA_commonParams.get('db')) + '`.`' + escapeHtml(PMA_commonParams.get('table') + '`') ) + getForeignKeyCheckboxLoader(); $(this).PMA_confirm(question, $(this).attr('href'), function (url) { - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); + var $msgbox = PMA_ajaxShowMessage(messages.strProcessingRequest); var params = getJSConfirmCommonParam(this, $link.getPostData()); @@ -271,14 +276,14 @@ export function onloadTblOperations () { /** * @var question String containing the question to be asked for confirmation */ - var question = PMA_messages.strDropTableStrongWarning + ' '; + var question = messages.strDropTableStrongWarning + ' '; question += PMA_sprintf( - PMA_messages.strDoYouReally, + messages.strDoYouReally, 'DROP VIEW `' + escapeHtml(PMA_commonParams.get('table') + '`') ); $(this).PMA_confirm(question, $(this).attr('href'), function (url) { - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); + var $msgbox = PMA_ajaxShowMessage(messages.strProcessingRequest); var params = { 'is_js_confirmed': '1', 'ajax_request': true @@ -308,13 +313,13 @@ export function onloadTblOperations () { /** * @var question String containing the question to be asked for confirmation */ - var question = PMA_messages.strTruncateTableStrongWarning + ' '; + var question = messages.strTruncateTableStrongWarning + ' '; question += PMA_sprintf( - PMA_messages.strDoYouReally, + messages.strDoYouReally, 'TRUNCATE `' + escapeHtml(PMA_commonParams.get('db')) + '`.`' + escapeHtml(PMA_commonParams.get('table') + '`') ) + getForeignKeyCheckboxLoader(); $(this).PMA_confirm(question, $(this).attr('href'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); + PMA_ajaxShowMessage(messages.strProcessingRequest); var params = getJSConfirmCommonParam(this, $link.getPostData()); diff --git a/js/src/tbl_relation.js b/js/src/tbl_relation.js index 06afd6c2d6..cc61a8f38f 100644 --- a/js/src/tbl_relation.js +++ b/js/src/tbl_relation.js @@ -1,5 +1,9 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ -import { PMA_Messages as PMA_messages } from './variables/export_variables'; + +/** + * Module import + */ +import { PMA_Messages as messages } from './variables/export_variables'; import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages'; import { escapeHtml } from './utils/Sanitise'; import { PMA_commonActions } from './classes/CommonActions'; @@ -112,10 +116,10 @@ export function onloadTblRelation () { .val() ); - var question = PMA_sprintf(PMA_messages.strDoYouReally, drop_query); + var question = PMA_sprintf(messages.strDoYouReally, drop_query); $anchor.PMA_confirm(question, $anchor.attr('href'), function (url) { - var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingForeignKey, false); + var $msg = PMA_ajaxShowMessage(messages.strDroppingForeignKey, false); var params = getJSConfirmCommonParam(this, $anchor.getPostData()); $.post(url, params, function (data) { if (data.success === true) { @@ -124,7 +128,7 @@ export function onloadTblRelation () { // Do nothing }); } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); + PMA_ajaxShowMessage(messages.strErrorProcessingRequest + ' : ' + data.error, false); } }); // end $.post() }); // end $.PMA_confirm() diff --git a/js/src/tbl_select.js b/js/src/tbl_select.js index e6082c84ad..1d5340c757 100644 --- a/js/src/tbl_select.js +++ b/js/src/tbl_select.js @@ -1,6 +1,10 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from './utils/JqueryExtended'; -import { PMA_Messages as PMA_messages } from './variables/export_variables'; +import { PMA_Messages as messages } from './variables/export_variables'; import { changeValueFieldType, PMA_checkIfDataTypeNumericOrDate @@ -10,7 +14,7 @@ import { PMA_prepareForAjaxRequest } from './functions/AjaxRequest'; import { PMA_init_slider } from './utils/Slider'; import { PMA_highlightSQL } from './utils/sql'; import { PMA_addDatepicker } from './utils/DateTime'; -import { PMA_commonParams } from './variables/common_params'; +import CommonParams from './variables/common_params'; /** * @fileoverview JavaScript functions used on tbl_select.php @@ -48,14 +52,14 @@ export function onloadTblSelect () { .hide(); $('#togglesearchformlink') - .html(PMA_messages.strShowSearchCriteria) + .html(messages.strShowSearchCriteria) .on('click', function () { var $link = $(this); $('#tbl_search_form').slideToggle(); - if ($link.text() === PMA_messages.strHideSearchCriteria) { - $link.text(PMA_messages.strShowSearchCriteria); + if ($link.text() === messages.strHideSearchCriteria) { + $link.text(messages.strShowSearchCriteria); } else { - $link.text(PMA_messages.strHideSearchCriteria); + $link.text(messages.strHideSearchCriteria); } // avoid default click action return false; @@ -92,7 +96,7 @@ export function onloadTblSelect () { // empty previous search results while we are waiting for new results $('#sqlqueryresultsouter').empty(); - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strSearching, false); + var $msgbox = PMA_ajaxShowMessage(messages.strSearching, false); PMA_prepareForAjaxRequest($search_form); @@ -152,7 +156,7 @@ export function onloadTblSelect () { .hide(); $('#togglesearchformlink') // always start with the Show message - .text(PMA_messages.strShowSearchCriteria); + .text(messages.strShowSearchCriteria); $('#togglesearchformdiv') // now it's time to show the div containing the link .show(); @@ -285,7 +289,7 @@ export function onloadTblSelect () { url: 'tbl_select.php', type: 'POST', data: { - server: PMA_commonParams.get('server'), + server: CommonParams.get('server'), ajax_request: 1, db: $('input[name="db"]').val(), table: $('input[name="table"]').val(), @@ -297,16 +301,16 @@ export function onloadTblSelect () { if (response.success) { // Get the column min value. var min = response.column_data.min - ? '(' + PMA_messages.strColumnMin + + ? '(' + messages.strColumnMin + ' ' + response.column_data.min + ')' : ''; // Get the column max value. var max = response.column_data.max - ? '(' + PMA_messages.strColumnMax + + ? '(' + messages.strColumnMax + ' ' + response.column_data.max + ')' : ''; var button_options = {}; - button_options[PMA_messages.strGo] = function () { + button_options[messages.strGo] = function () { var min_value = $('#min_value').val(); var max_value = $('#max_value').val(); var final_value = ''; @@ -347,7 +351,7 @@ export function onloadTblSelect () { } $(this).dialog('close'); }; - button_options[PMA_messages.strCancel] = function () { + button_options[messages.strCancel] = function () { $(this).dialog('close'); }; @@ -355,11 +359,11 @@ export function onloadTblSelect () { $('<div/>').append( '<fieldset>' + '<legend>' + operator + '</legend>' + - '<label for="min_value">' + PMA_messages.strMinValue + + '<label for="min_value">' + messages.strMinValue + '</label>' + '<input type="text" id="min_value" />' + '<br>' + '<span class="small_font">' + min + '</span>' + '<br>' + - '<label for="max_value">' + PMA_messages.strMaxValue + + '<label for="max_value">' + messages.strMaxValue + '</label>' + '<input type="text" id="max_value" />' + '<br>' + '<span class="small_font">' + max + '</span>' + @@ -369,7 +373,7 @@ export function onloadTblSelect () { maxHeight: 400, modal: true, buttons: button_options, - title: PMA_messages.strRangeSearch, + title: messages.strRangeSearch, open: function () { // Add datepicker wherever required. PMA_addDatepicker($('#min_value'), data_type); @@ -384,7 +388,7 @@ export function onloadTblSelect () { } }, error: function (response) { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest); + PMA_ajaxShowMessage(messages.strErrorProcessingRequest); } }); } diff --git a/js/src/tbl_structure.js b/js/src/tbl_structure.js index f65d3a0be5..ef0cf44ce2 100644 --- a/js/src/tbl_structure.js +++ b/js/src/tbl_structure.js @@ -1,7 +1,11 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { PMA_Messages as PMA_messages } from './variables/export_variables'; import Indexes from './utils/IndexEnum'; -import PMA_commonParams from './variables/common_params'; +import CommonParams from './variables/common_params'; import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages'; import { PMA_highlightSQL } from './utils/sql'; import { PMA_prepareForAjaxRequest } from './functions/AjaxRequest'; @@ -13,6 +17,8 @@ import { escapeHtml } from './utils/Sanitise'; import { AJAX } from './ajax'; import { PMA_previewSQL } from './functions/Sql/PreviewSql'; import { printPreview } from './functions/Print'; +import { reloadFieldForm, checkFirst } from './functions/Table/TableStructure'; + /** * @fileoverview functions used on the table structure page * @name Table Structure @@ -32,27 +38,7 @@ import { printPreview } from './functions/Print'; * */ -/** - * Reload fields table - */ -function reloadFieldForm () { - $.post($('#fieldsForm').attr('action'), $('#fieldsForm').serialize() + PMA_commonParams.get('arg_separator') + 'ajax_request=true', function (form_data) { - var $temp_div = $('<div id=\'temp_div\'><div>').append(form_data.message); - $('#fieldsForm').replaceWith($temp_div.find('#fieldsForm')); - $('#addColumns').replaceWith($temp_div.find('#addColumns')); - $('#move_columns_dialog').find('ul').replaceWith($temp_div.find('#move_columns_dialog ul')); - $('#moveColumns').removeClass('move-active'); - }); - $('#page_content').show(); -} -function checkFirst () { - if ($('select[name=after_field] option:selected').data('pos') === 'first') { - $('input[name=field_where]').val('first'); - } else { - $('input[name=field_where]').val('after'); - } -} /** * Unbind all event handlers before tearing down a page */ @@ -89,7 +75,7 @@ export function onloadTblStructure () { function submitForm () { var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'do_save_data=1', function (data) { + $.post($form.attr('action'), $form.serialize() + CommonParams.get('arg_separator') + 'do_save_data=1', function (data) { if ($('.sqlqueryresults').length !== 0) { $('.sqlqueryresults').remove(); } else if ($('.error:not(.tab)').length !== 0) { @@ -198,7 +184,7 @@ export function onloadTblStructure () { $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) { var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false); var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); - params += PMA_commonParams.get('arg_separator') + 'ajax_page_request=1'; + params += CommonParams.get('arg_separator') + 'ajax_page_request=1'; $.post(url, params, function (data) { if (typeof data !== 'undefined' && data.success === true) { PMA_ajaxRemoveMessage($msg); @@ -284,7 +270,7 @@ export function onloadTblStructure () { AJAX.source = $this; var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); - params += PMA_commonParams.get('arg_separator') + 'ajax_page_request=1'; + params += CommonParams.get('arg_separator') + 'ajax_page_request=1'; $.post(url, params, AJAX.responseHandler); }); // end $.PMA_confirm() }); // end Add key @@ -317,7 +303,7 @@ export function onloadTblStructure () { $this.dialog('close'); return; } - $.post($form.prop('action'), serialized + PMA_commonParams.get('arg_separator') + 'ajax_request=true', function (data) { + $.post($form.prop('action'), serialized + CommonParams.get('arg_separator') + 'ajax_request=true', function (data) { if (data.success === false) { PMA_ajaxRemoveMessage($msgbox); $this @@ -423,7 +409,7 @@ export function onloadTblStructure () { e.preventDefault(); var $button = $(this); var $form = $button.parents('form'); - var argsep = PMA_commonParams.get('arg_separator'); + var argsep = CommonParams.get('arg_separator'); var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); PMA_ajaxShowMessage(); AJAX.source = $form; @@ -438,10 +424,7 @@ export function onloadTblStructure () { var $link = $(this); function submitPartitionAction (url) { - var params = { - 'ajax_request' : true, - 'ajax_page_request' : true - }; + var params = 'ajax_request=true&ajax_page_request=true&' + $link.getPostData(); PMA_ajaxShowMessage(); AJAX.source = $link; $.post(url, params, AJAX.responseHandler); diff --git a/js/src/tbl_tracking.js b/js/src/tbl_tracking.js index da6f8f7bcb..d50ca5795d 100644 --- a/js/src/tbl_tracking.js +++ b/js/src/tbl_tracking.js @@ -1,7 +1,12 @@ +/* vim: set expandtab sw=4 ts=4 sts=4: */ + +/** + * Module import + */ import { $ } from './utils/JqueryExtended'; import './plugins/jquery/jquery.tablesorter'; import { PMA_Messages as PMA_messages } from './variables/export_variables'; -import PMA_commonParams from './variables/common_params'; +import CommonParams from './variables/common_params'; import { PMA_ajaxShowMessage } from './utils/show_ajax_messages'; import { AJAX } from './ajax'; @@ -60,7 +65,7 @@ export function onloadTblTracking () { e.preventDefault(); var $button = $(this); var $form = $button.parent('form'); - var argsep = PMA_commonParams.get('arg_separator'); + var argsep = CommonParams.get('arg_separator'); var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); if ($button.val() === 'delete_version') { diff --git a/js/tbl_change.js b/js/tbl_change.js deleted file mode 100644 index 501ff3ba48..0000000000 --- a/js/tbl_change.js +++ /dev/null @@ -1,708 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview function used in table data manipulation pages - * - * @requires jQuery - * @requires jQueryUI - * @requires js/functions.js - * - */ - -/** - * Modify form controls when the "NULL" checkbox is checked - * - * @param theType string the MySQL field type - * @param urlField string the urlencoded field name - OBSOLETE - * @param md5Field string the md5 hashed field name - * @param multi_edit string the multi_edit row sequence number - * - * @return boolean always true - */ -function nullify (theType, urlField, md5Field, multi_edit) { - var rowForm = document.forms.insertForm; - - if (typeof(rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']']) !== 'undefined') { - rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1; - } - - // "ENUM" field with more than 20 characters - if (theType === 1) { - rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'][1].selectedIndex = -1; - // Other "ENUM" field - } else if (theType === 2) { - var elts = rowForm.elements['fields' + multi_edit + '[' + md5Field + ']']; - // when there is just one option in ENUM: - if (elts.checked) { - elts.checked = false; - } else { - var elts_cnt = elts.length; - for (var i = 0; i < elts_cnt; i++) { - elts[i].checked = false; - } // end for - } // end if - // "SET" field - } else if (theType === 3) { - rowForm.elements['fields' + multi_edit + '[' + md5Field + '][]'].selectedIndex = -1; - // Foreign key field (drop-down) - } else if (theType === 4) { - rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1; - // foreign key field (with browsing icon for foreign values) - } else if (theType === 6) { - rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = ''; - // Other field types - } else /* if (theType === 5)*/ { - rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = ''; - } // end if... else if... else - - return true; -} // end of the 'nullify()' function - - -/** - * javascript DateTime format validation. - * its used to prevent adding default (0000-00-00 00:00:00) to database when user enter wrong values - * Start of validation part - */ -// function checks the number of days in febuary -function daysInFebruary (year) { - return (((year % 4 === 0) && (((year % 100 !== 0)) || (year % 400 === 0))) ? 29 : 28); -} -// function to convert single digit to double digit -function fractionReplace (num) { - num = parseInt(num, 10); - return num >= 1 && num <= 9 ? '0' + num : '00'; -} - -/* function to check the validity of date -* The following patterns are accepted in this validation (accepted in mysql as well) -* 1) 2001-12-23 -* 2) 2001-1-2 -* 3) 02-12-23 -* 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues -*/ -function isDate (val, tmstmp) { - val = val.replace(/[.|*|^|+|//|@]/g, '-'); - var arrayVal = val.split('-'); - for (var a = 0; a < arrayVal.length; a++) { - if (arrayVal[a].length === 1) { - arrayVal[a] = fractionReplace(arrayVal[a]); - } - } - val = arrayVal.join('-'); - var pos = 2; - var dtexp = new RegExp(/^([0-9]{4})-(((01|03|05|07|08|10|12)-((0[0-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)-((0[0-9])|([1-2][0-9])|30))|((00)-(00)))$/); - if (val.length === 8) { - pos = 0; - } - if (dtexp.test(val)) { - var month = parseInt(val.substring(pos + 3, pos + 5), 10); - var day = parseInt(val.substring(pos + 6, pos + 8), 10); - var year = parseInt(val.substring(0, pos + 2), 10); - if (month === 2 && day > daysInFebruary(year)) { - return false; - } - if (val.substring(0, pos + 2).length === 2) { - year = parseInt('20' + val.substring(0, pos + 2), 10); - } - if (tmstmp === true) { - if (year < 1978) { - return false; - } - if (year > 2038 || (year > 2037 && day > 19 && month >= 1) || (year > 2037 && month > 1)) { - return false; - } - } - } else { - return false; - } - return true; -} - -/* function to check the validity of time -* The following patterns are accepted in this validation (accepted in mysql as well) -* 1) 2:3:4 -* 2) 2:23:43 -* 3) 2:23:43.123456 -*/ -function isTime (val) { - var arrayVal = val.split(':'); - for (var a = 0, l = arrayVal.length; a < l; a++) { - if (arrayVal[a].length === 1) { - arrayVal[a] = fractionReplace(arrayVal[a]); - } - } - val = arrayVal.join(':'); - var tmexp = new RegExp(/^(-)?(([0-7]?[0-9][0-9])|(8[0-2][0-9])|(83[0-8])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))(\.[0-9]{1,6}){0,1}$/); - return tmexp.test(val); -} - -/** - * To check whether insert section is ignored or not - */ -function checkForCheckbox (multi_edit) { - if ($('#insert_ignore_' + multi_edit).length) { - return $('#insert_ignore_' + multi_edit).is(':unchecked'); - } - return true; -} - -function verificationsAfterFieldChange (urlField, multi_edit, theType) { - var evt = window.event || arguments.callee.caller.arguments[0]; - var target = evt.target || evt.srcElement; - var $this_input = $(':input[name^=\'fields[multi_edit][' + multi_edit + '][' + - urlField + ']\']'); - // the function drop-down that corresponds to this input field - var $this_function = $('select[name=\'funcs[multi_edit][' + multi_edit + '][' + - urlField + ']\']'); - var function_selected = false; - if (typeof $this_function.val() !== 'undefined' && - $this_function.val() !== null && - $this_function.val().length > 0 - ) { - function_selected = true; - } - - // To generate the textbox that can take the salt - var new_salt_box = '<br><input type=text name=salt[multi_edit][' + multi_edit + '][' + urlField + ']' + - ' id=salt_' + target.id + ' placeholder=\'' + PMA_messages.strEncryptionKey + '\'>'; - - // If encrypting or decrypting functions that take salt as input is selected append the new textbox for salt - if (target.value === 'AES_ENCRYPT' || - target.value === 'AES_DECRYPT' || - target.value === 'DES_ENCRYPT' || - target.value === 'DES_DECRYPT' || - target.value === 'ENCRYPT') { - if (!($('#salt_' + target.id).length)) { - $this_input.after(new_salt_box); - } - } else { - // Remove the textbox for salt - $('#salt_' + target.id).prev('br').remove(); - $('#salt_' + target.id).remove(); - } - - if (target.value === 'AES_DECRYPT' - || target.value === 'AES_ENCRYPT' - || target.value === 'MD5') { - $('#' + target.id).rules('add', { - validationFunctionForFuns: { - param: $this_input, - depends: function () { - return checkForCheckbox(multi_edit); - } - } - }); - } - - // Unchecks the corresponding "NULL" control - $('input[name=\'fields_null[multi_edit][' + multi_edit + '][' + urlField + ']\']').prop('checked', false); - - // Unchecks the Ignore checkbox for the current row - $('input[name=\'insert_ignore_' + multi_edit + '\']').prop('checked', false); - - var charExceptionHandling; - if (theType.substring(0,4) === 'char') { - charExceptionHandling = theType.substring(5,6); - } else if (theType.substring(0,7) === 'varchar') { - charExceptionHandling = theType.substring(8,9); - } - if (function_selected) { - $this_input.removeAttr('min'); - $this_input.removeAttr('max'); - // @todo: put back attributes if corresponding function is deselected - } - - if ($this_input.data('rulesadded') === null && ! function_selected) { - // call validate before adding rules - $($this_input[0].form).validate(); - // validate for date time - if (theType === 'datetime' || theType === 'time' || theType === 'date' || theType === 'timestamp') { - $this_input.rules('add', { - validationFunctionForDateTime: { - param: theType, - depends: function () { - return checkForCheckbox(multi_edit); - } - } - }); - } - // validation for integer type - if ($this_input.data('type') === 'INT') { - var mini = parseInt($this_input.attr('min')); - var maxi = parseInt($this_input.attr('max')); - $this_input.rules('add', { - number: { - param : true, - depends: function () { - return checkForCheckbox(multi_edit); - } - }, - min: { - param: mini, - depends: function () { - if (isNaN($this_input.val())) { - return false; - } else { - return checkForCheckbox(multi_edit); - } - } - }, - max: { - param: maxi, - depends: function () { - if (isNaN($this_input.val())) { - return false; - } else { - return checkForCheckbox(multi_edit); - } - } - } - }); - // validation for CHAR types - } else if ($this_input.data('type') === 'CHAR') { - var maxlen = $this_input.data('maxlength'); - if (typeof maxlen !== 'undefined') { - if (maxlen <= 4) { - maxlen = charExceptionHandling; - } - $this_input.rules('add', { - maxlength: { - param: maxlen, - depends: function () { - return checkForCheckbox(multi_edit); - } - } - }); - } - // validate binary & blob types - } else if ($this_input.data('type') === 'HEX') { - $this_input.rules('add', { - validationFunctionForHex: { - param: true, - depends: function () { - return checkForCheckbox(multi_edit); - } - } - }); - } - $this_input.data('rulesadded', true); - } else if ($this_input.data('rulesadded') === true && function_selected) { - // remove any rules added - $this_input.rules('remove'); - // remove any error messages - $this_input - .removeClass('error') - .removeAttr('aria-invalid') - .siblings('.error') - .remove(); - $this_input.data('rulesadded', null); - } -} -/* End of fields validation*/ - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('tbl_change.js', function () { - $(document).off('click', 'span.open_gis_editor'); - $(document).off('click', 'input[name^=\'insert_ignore_\']'); - $(document).off('click', 'input[name=\'gis_data[save]\']'); - $(document).off('click', 'input.checkbox_null'); - $('select[name="submit_type"]').off('change'); - $(document).off('change', '#insert_rows'); -}); - -/** - * Ajax handlers for Change Table page - * - * Actions Ajaxified here: - * Submit Data to be inserted into the table. - * Restart insertion with 'N' rows. - */ -AJAX.registerOnload('tbl_change.js', function () { - if ($('#insertForm').length) { - // validate the comment form when it is submitted - $('#insertForm').validate(); - jQuery.validator.addMethod('validationFunctionForHex', function (value, element) { - return value.match(/^[a-f0-9]*$/i) !== null; - }); - - jQuery.validator.addMethod('validationFunctionForFuns', function (value, element, options) { - if (value.substring(0, 3) === 'AES' && options.data('type') !== 'HEX') { - return false; - } - - return !(value.substring(0, 3) === 'MD5' && - typeof options.data('maxlength') !== 'undefined' && - options.data('maxlength') < 32); - }); - - jQuery.validator.addMethod('validationFunctionForDateTime', function (value, element, options) { - var dt_value = value; - var theType = options; - if (theType === 'date') { - return isDate(dt_value); - } else if (theType === 'time') { - return isTime(dt_value); - } else if (theType === 'datetime' || theType === 'timestamp') { - var tmstmp = false; - dt_value = dt_value.trim(); - if (dt_value === 'CURRENT_TIMESTAMP' || dt_value === 'current_timestamp()') { - return true; - } - if (theType === 'timestamp') { - tmstmp = true; - } - if (dt_value === '0000-00-00 00:00:00') { - return true; - } - var dv = dt_value.indexOf(' '); - if (dv === -1) { // Only the date component, which is valid - return isDate(dt_value, tmstmp); - } - - return isDate(dt_value.substring(0, dv), tmstmp) && - isTime(dt_value.substring(dv + 1)); - } - }); - /* - * message extending script must be run - * after initiation of functions - */ - extendingValidatorMessages(); - } - - $.datepicker.initialized = false; - - $(document).on('click', 'span.open_gis_editor', function (event) { - event.preventDefault(); - - var $span = $(this); - // Current value - var value = $span.parent('td').children('input[type=\'text\']').val(); - // Field name - var field = $span.parents('tr').children('td:first').find('input[type=\'hidden\']').val(); - // Column type - var type = $span.parents('tr').find('span.column_type').text(); - // Names of input field and null checkbox - var input_name = $span.parent('td').children('input[type=\'text\']').attr('name'); - - openGISEditor(); - if (!gisEditorLoaded) { - loadJSAndGISEditor(value, field, type, input_name); - } else { - loadGISEditor(value, field, type, input_name); - } - }); - - /** - * Forced validation check of fields - */ - $(document).on('click','input[name^=\'insert_ignore_\']', function (event) { - $('#insertForm').valid(); - }); - - /** - * Uncheck the null checkbox as geometry data is placed on the input field - */ - $(document).on('click', 'input[name=\'gis_data[save]\']', function (event) { - var input_name = $('form#gis_data_editor_form').find('input[name=\'input_name\']').val(); - var $null_checkbox = $('input[name=\'' + input_name + '\']').parents('tr').find('.checkbox_null'); - $null_checkbox.prop('checked', false); - }); - - /** - * Handles all current checkboxes for Null; this only takes care of the - * checkboxes on currently displayed rows as the rows generated by - * "Continue insertion" are handled in the "Continue insertion" code - * - */ - $(document).on('click', 'input.checkbox_null', function () { - nullify( - // use hidden fields populated by tbl_change.php - $(this).siblings('.nullify_code').val(), - $(this).closest('tr').find('input:hidden').first().val(), - $(this).siblings('.hashed_field').val(), - $(this).siblings('.multi_edit').val() - ); - }); - - /** - * Reset the auto_increment column to 0 when selecting any of the - * insert options in submit_type-dropdown. Only perform the reset - * when we are in edit-mode, and not in insert-mode(no previous value - * available). - */ - $('select[name="submit_type"]').on('change', function () { - var thisElemSubmitTypeVal = $(this).val(); - var $table = $('table.insertRowTable'); - var auto_increment_column = $table.find('input[name^="auto_increment"]'); - auto_increment_column.each(function () { - var $thisElemAIField = $(this); - var thisElemName = $thisElemAIField.attr('name'); - - var prev_value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields_prev') + '"]'); - var value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields') + '"]'); - var previous_value = $(prev_value_field).val(); - if (previous_value !== undefined) { - if (thisElemSubmitTypeVal === 'insert' - || thisElemSubmitTypeVal === 'insertignore' - || thisElemSubmitTypeVal === 'showinsert' - ) { - $(value_field).val(0); - } else { - $(value_field).val(previous_value); - } - } - }); - }); - - /** - * Continue Insertion form - */ - $(document).on('change', '#insert_rows', function (event) { - event.preventDefault(); - /** - * @var columnCount Number of number of columns table has. - */ - var columnCount = $('table.insertRowTable:first').find('tr').has('input[name*=\'fields_name\']').length; - /** - * @var curr_rows Number of current insert rows already on page - */ - var curr_rows = $('table.insertRowTable').length; - /** - * @var target_rows Number of rows the user wants - */ - var target_rows = $('#insert_rows').val(); - - // remove all datepickers - $('input.datefield, input.datetimefield').each(function () { - $(this).datepicker('destroy'); - }); - - if (curr_rows < target_rows) { - var tempIncrementIndex = function () { - var $this_element = $(this); - /** - * Extract the index from the name attribute for all input/select fields and increment it - * name is of format funcs[multi_edit][10][<long random string of alphanum chars>] - */ - - /** - * @var this_name String containing name of the input/select elements - */ - var this_name = $this_element.attr('name'); - /** split {@link this_name} at [10], so we have the parts that can be concatenated later */ - var name_parts = this_name.split(/\[\d+\]/); - /** extract the [10] from {@link name_parts} */ - var old_row_index_string = this_name.match(/\[\d+\]/)[0]; - /** extract 10 - had to split into two steps to accomodate double digits */ - var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0], 10); - - /** calculate next index i.e. 11 */ - new_row_index = old_row_index + 1; - /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */ - var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1]; - - var hashed_field = name_parts[1].match(/\[(.+)\]/)[1]; - $this_element.attr('name', new_name); - - /** If element is select[name*='funcs'], update id */ - if ($this_element.is('select[name*=\'funcs\']')) { - var this_id = $this_element.attr('id'); - var id_parts = this_id.split(/\_/); - var old_id_index = id_parts[1]; - var prevSelectedValue = $('#field_' + old_id_index + '_1').val(); - var new_id_index = parseInt(old_id_index) + columnCount; - var new_id = 'field_' + new_id_index + '_1'; - $this_element.attr('id', new_id); - $this_element.find('option').filter(function () { - return $(this).text() === prevSelectedValue; - }).attr('selected','selected'); - - // If salt field is there then update its id. - var nextSaltInput = $this_element.parent().next('td').next('td').find('input[name*=\'salt\']'); - if (nextSaltInput.length !== 0) { - nextSaltInput.attr('id', 'salt_' + new_id); - } - } - - // handle input text fields and textareas - if ($this_element.is('.textfield') || $this_element.is('.char') || $this_element.is('textarea')) { - // do not remove the 'value' attribute for ENUM columns - // special handling for radio fields after updating ids to unique - see below - if ($this_element.closest('tr').find('span.column_type').html() !== 'enum') { - $this_element.val($this_element.closest('tr').find('span.default_value').html()); - } - $this_element - .off('change') - // Remove onchange attribute that was placed - // by tbl_change.php; it refers to the wrong row index - .attr('onchange', null) - // Keep these values to be used when the element - // will change - .data('hashed_field', hashed_field) - .data('new_row_index', new_row_index) - .on('change', function () { - var $changed_element = $(this); - verificationsAfterFieldChange( - $changed_element.data('hashed_field'), - $changed_element.data('new_row_index'), - $changed_element.closest('tr').find('span.column_type').html() - ); - }); - } - - if ($this_element.is('.checkbox_null')) { - $this_element - // this event was bound earlier by jQuery but - // to the original row, not the cloned one, so unbind() - .off('click') - // Keep these values to be used when the element - // will be clicked - .data('hashed_field', hashed_field) - .data('new_row_index', new_row_index) - .on('click', function () { - var $changed_element = $(this); - nullify( - $changed_element.siblings('.nullify_code').val(), - $this_element.closest('tr').find('input:hidden').first().val(), - $changed_element.data('hashed_field'), - '[multi_edit][' + $changed_element.data('new_row_index') + ']' - ); - }); - } - }; - - var tempReplaceAnchor = function () { - var $anchor = $(this); - var new_value = 'rownumber=' + new_row_index; - // needs improvement in case something else inside - // the href contains this pattern - var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value); - $anchor.attr('href', new_href); - }; - - while (curr_rows < target_rows) { - /** - * @var $last_row Object referring to the last row - */ - var $last_row = $('#insertForm').find('.insertRowTable:last'); - - // need to access this at more than one level - // (also needs improvement because it should be calculated - // just once per cloned row, not once per column) - var new_row_index = 0; - - // Clone the insert tables - $last_row - .clone(true, true) - .insertBefore('#actions_panel') - .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]') - .each(tempIncrementIndex) - .end() - .find('.foreign_values_anchor') - .each(tempReplaceAnchor); - - // Insert/Clone the ignore checkboxes - if (curr_rows === 1) { - $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />') - .insertBefore('table.insertRowTable:last') - .after('<label for="insert_ignore_1">' + PMA_messages.strIgnore + '</label>'); - } else { - /** - * @var $last_checkbox Object reference to the last checkbox in #insertForm - */ - var $last_checkbox = $('#insertForm').children('input:checkbox:last'); - - /** name of {@link $last_checkbox} */ - var last_checkbox_name = $last_checkbox.attr('name'); - /** index of {@link $last_checkbox} */ - var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/), 10); - /** name of new {@link $last_checkbox} */ - var new_name = last_checkbox_name.replace(/\d+/, last_checkbox_index + 1); - - $('<br/><div class="clearfloat"></div>') - .insertBefore('table.insertRowTable:last'); - - $last_checkbox - .clone() - .attr({ 'id': new_name, 'name': new_name }) - .prop('checked', true) - .insertBefore('table.insertRowTable:last'); - - $('label[for^=insert_ignore]:last') - .clone() - .attr('for', new_name) - .insertBefore('table.insertRowTable:last'); - - $('<br/>') - .insertBefore('table.insertRowTable:last'); - } - curr_rows++; - } - // recompute tabindex for text fields and other controls at footer; - // IMO it's not really important to handle the tabindex for - // function and Null - var tabindex = 0; - $('.textfield, .char, textarea') - .each(function () { - tabindex++; - $(this).attr('tabindex', tabindex); - // update the IDs of textfields to ensure that they are unique - $(this).attr('id', 'field_' + tabindex + '_3'); - - // special handling for radio fields after updating ids to unique - if ($(this).closest('tr').find('span.column_type').html() === 'enum') { - if ($(this).val() === $(this).closest('tr').find('span.default_value').html()) { - $(this).prop('checked', true); - } else { - $(this).prop('checked', false); - } - } - }); - $('.control_at_footer') - .each(function () { - tabindex++; - $(this).attr('tabindex', tabindex); - }); - } else if (curr_rows > target_rows) { - /** - * Displays alert if data loss possible on decrease - * of rows. - */ - var checkLock = jQuery.isEmptyObject(AJAX.lockedTargets); - if (checkLock || confirm(PMA_messages.strConfirmRowChange) === true) { - while (curr_rows > target_rows) { - $('input[id^=insert_ignore]:last') - .nextUntil('fieldset') - .addBack() - .remove(); - curr_rows--; - } - } else { - document.getElementById('insert_rows').value = curr_rows; - } - } - // Add all the required datepickers back - addDateTimePicker(); - }); -}); - -function changeValueFieldType (elem, searchIndex) { - var fieldsValue = $('select#fieldID_' + searchIndex); - if (0 === fieldsValue.size()) { - return; - } - - var type = $(elem).val(); - if ('IN (...)' === type || - 'NOT IN (...)' === type || - 'BETWEEN' === type || - 'NOT BETWEEN' === type - ) { - $('#fieldID_' + searchIndex).attr('multiple', ''); - } else { - $('#fieldID_' + searchIndex).removeAttr('multiple'); - } -} diff --git a/js/tbl_chart.js b/js/tbl_chart.js deleted file mode 100644 index 30688716aa..0000000000 --- a/js/tbl_chart.js +++ /dev/null @@ -1,423 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ - -var chart_data = {}; -var temp_chart_title; - -var currentChart = null; -var currentSettings = null; - -var dateTimeCols = []; -var numericCols = []; - -function extractDate (dateString) { - var matches; - var match; - var dateTimeRegExp = /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/; - var dateRegExp = /[0-9]{4}-[0-9]{2}-[0-9]{2}/; - - matches = dateTimeRegExp.exec(dateString); - if (matches !== null && matches.length > 0) { - match = matches[0]; - return new Date(match.substr(0, 4), parseInt(match.substr(5, 2), 10) - 1, match.substr(8, 2), match.substr(11, 2), match.substr(14, 2), match.substr(17, 2)); - } else { - matches = dateRegExp.exec(dateString); - if (matches !== null && matches.length > 0) { - match = matches[0]; - return new Date(match.substr(0, 4), parseInt(match.substr(5, 2), 10) - 1, match.substr(8, 2)); - } - } - return null; -} - -function PMA_queryChart (data, columnNames, settings) { - if ($('#querychart').length === 0) { - return; - } - - var plotSettings = { - title : { - text : settings.title, - escapeHtml: true - }, - grid : { - drawBorder : false, - shadow : false, - background : 'rgba(0,0,0,0)' - }, - legend : { - show : true, - placement : 'outsideGrid', - location : 'e', - rendererOptions: { - numberColumns: 2 - } - }, - axes : { - xaxis : { - label : escapeHtml(settings.xaxisLabel) - }, - yaxis : { - label : settings.yaxisLabel - } - }, - stackSeries : settings.stackSeries - }; - - // create the chart - var factory = new JQPlotChartFactory(); - var chart = factory.createChart(settings.type, 'querychart'); - - // create the data table and add columns - var dataTable = new DataTable(); - if (settings.type === 'timeline') { - dataTable.addColumn(ColumnType.DATE, columnNames[settings.mainAxis]); - } else if (settings.type === 'scatter') { - dataTable.addColumn(ColumnType.NUMBER, columnNames[settings.mainAxis]); - } else { - dataTable.addColumn(ColumnType.STRING, columnNames[settings.mainAxis]); - } - - var i; - if (settings.seriesColumn === null) { - $.each(settings.selectedSeries, function (index, element) { - dataTable.addColumn(ColumnType.NUMBER, columnNames[element]); - }); - - // set data to the data table - var columnsToExtract = [settings.mainAxis]; - $.each(settings.selectedSeries, function (index, element) { - columnsToExtract.push(element); - }); - var values = []; - var newRow; - var row; - var col; - for (i = 0; i < data.length; i++) { - row = data[i]; - newRow = []; - for (var j = 0; j < columnsToExtract.length; j++) { - col = columnNames[columnsToExtract[j]]; - if (j === 0) { - if (settings.type === 'timeline') { // first column is date type - newRow.push(extractDate(row[col])); - } else if (settings.type === 'scatter') { - newRow.push(parseFloat(row[col])); - } else { // first column is string type - newRow.push(row[col]); - } - } else { // subsequent columns are of type, number - newRow.push(parseFloat(row[col])); - } - } - values.push(newRow); - } - dataTable.setData(values); - } else { - var seriesNames = {}; - var seriesNumber = 1; - var seriesColumnName = columnNames[settings.seriesColumn]; - for (i = 0; i < data.length; i++) { - if (! seriesNames[data[i][seriesColumnName]]) { - seriesNames[data[i][seriesColumnName]] = seriesNumber; - seriesNumber++; - } - } - - $.each(seriesNames, function (seriesName, seriesNumber) { - dataTable.addColumn(ColumnType.NUMBER, seriesName); - }); - - var valueMap = {}; - var xValue; - var value; - var mainAxisName = columnNames[settings.mainAxis]; - var valueColumnName = columnNames[settings.valueColumn]; - for (i = 0; i < data.length; i++) { - xValue = data[i][mainAxisName]; - value = valueMap[xValue]; - if (! value) { - value = [xValue]; - valueMap[xValue] = value; - } - seriesNumber = seriesNames[data[i][seriesColumnName]]; - value[seriesNumber] = parseFloat(data[i][valueColumnName]); - } - - var values = []; - $.each(valueMap, function (index, value) { - values.push(value); - }); - dataTable.setData(values); - } - - // draw the chart and return the chart object - chart.draw(dataTable, plotSettings); - return chart; -} - -function drawChart () { - currentSettings.width = $('#resizer').width() - 20; - currentSettings.height = $('#resizer').height() - 20; - - // TODO: a better way using .redraw() ? - if (currentChart !== null) { - currentChart.destroy(); - } - - var columnNames = []; - $('select[name="chartXAxis"] option').each(function () { - columnNames.push(escapeHtml($(this).text())); - }); - try { - currentChart = PMA_queryChart(chart_data, columnNames, currentSettings); - if (currentChart !== null) { - $('#saveChart').attr('href', currentChart.toImageString()); - } - } catch (err) { - PMA_ajaxShowMessage(err.message, false); - } -} - -function getSelectedSeries () { - var val = $('select[name="chartSeries"]').val() || []; - var ret = []; - $.each(val, function (i, v) { - ret.push(parseInt(v, 10)); - }); - return ret; -} - -function onXAxisChange () { - var $xAxisSelect = $('select[name="chartXAxis"]'); - currentSettings.mainAxis = parseInt($xAxisSelect.val(), 10); - if (dateTimeCols.indexOf(currentSettings.mainAxis) !== -1) { - $('span.span_timeline').show(); - } else { - $('span.span_timeline').hide(); - if (currentSettings.type === 'timeline') { - $('input#radio_line').prop('checked', true); - currentSettings.type = 'line'; - } - } - if (numericCols.indexOf(currentSettings.mainAxis) !== -1) { - $('span.span_scatter').show(); - } else { - $('span.span_scatter').hide(); - if (currentSettings.type === 'scatter') { - $('input#radio_line').prop('checked', true); - currentSettings.type = 'line'; - } - } - var xaxis_title = $xAxisSelect.children('option:selected').text(); - $('input[name="xaxis_label"]').val(xaxis_title); - currentSettings.xaxisLabel = xaxis_title; -} - -function onDataSeriesChange () { - var $seriesSelect = $('select[name="chartSeries"]'); - currentSettings.selectedSeries = getSelectedSeries(); - var yaxis_title; - if (currentSettings.selectedSeries.length === 1) { - $('span.span_pie').show(); - yaxis_title = $seriesSelect.children('option:selected').text(); - } else { - $('span.span_pie').hide(); - if (currentSettings.type === 'pie') { - $('input#radio_line').prop('checked', true); - currentSettings.type = 'line'; - } - yaxis_title = PMA_messages.strYValues; - } - $('input[name="yaxis_label"]').val(yaxis_title); - currentSettings.yaxisLabel = yaxis_title; -} - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('tbl_chart.js', function () { - $('input[name="chartType"]').off('click'); - $('input[name="barStacked"]').off('click'); - $('input[name="chkAlternative"]').off('click'); - $('input[name="chartTitle"]').off('focus').off('keyup').off('blur'); - $('select[name="chartXAxis"]').off('change'); - $('select[name="chartSeries"]').off('change'); - $('select[name="chartSeriesColumn"]').off('change'); - $('select[name="chartValueColumn"]').off('change'); - $('input[name="xaxis_label"]').off('keyup'); - $('input[name="yaxis_label"]').off('keyup'); - $('#resizer').off('resizestop'); - $('#tblchartform').off('submit'); -}); - -AJAX.registerOnload('tbl_chart.js', function () { - // handle manual resize - $('#resizer').on('resizestop', function (event, ui) { - // make room so that the handle will still appear - $('#querychart').height($('#resizer').height() * 0.96); - $('#querychart').width($('#resizer').width() * 0.96); - if (currentChart !== null) { - currentChart.redraw({ - resetAxes : true - }); - } - }); - - // handle chart type changes - $('input[name="chartType"]').on('click', function () { - var type = currentSettings.type = $(this).val(); - if (type === 'bar' || type === 'column' || type === 'area') { - $('span.barStacked').show(); - } else { - $('input[name="barStacked"]').prop('checked', false); - $.extend(true, currentSettings, { stackSeries : false }); - $('span.barStacked').hide(); - } - drawChart(); - }); - - // handle chosing alternative data format - $('input[name="chkAlternative"]').on('click', function () { - var $seriesColumn = $('select[name="chartSeriesColumn"]'); - var $valueColumn = $('select[name="chartValueColumn"]'); - var $chartSeries = $('select[name="chartSeries"]'); - if ($(this).is(':checked')) { - $seriesColumn.prop('disabled', false); - $valueColumn.prop('disabled', false); - $chartSeries.prop('disabled', true); - currentSettings.seriesColumn = parseInt($seriesColumn.val(), 10); - currentSettings.valueColumn = parseInt($valueColumn.val(), 10); - } else { - $seriesColumn.prop('disabled', true); - $valueColumn.prop('disabled', true); - $chartSeries.prop('disabled', false); - currentSettings.seriesColumn = null; - currentSettings.valueColumn = null; - } - drawChart(); - }); - - // handle stacking for bar, column and area charts - $('input[name="barStacked"]').on('click', function () { - if ($(this).is(':checked')) { - $.extend(true, currentSettings, { stackSeries : true }); - } else { - $.extend(true, currentSettings, { stackSeries : false }); - } - drawChart(); - }); - - // handle changes in chart title - $('input[name="chartTitle"]') - .focus(function () { - temp_chart_title = $(this).val(); - }) - .on('keyup', function () { - currentSettings.title = $('input[name="chartTitle"]').val(); - drawChart(); - }) - .blur(function () { - if ($(this).val() !== temp_chart_title) { - drawChart(); - } - }); - - // handle changing the x-axis - $('select[name="chartXAxis"]').on('change', function () { - onXAxisChange(); - drawChart(); - }); - - // handle changing the selected data series - $('select[name="chartSeries"]').on('change', function () { - onDataSeriesChange(); - drawChart(); - }); - - // handle changing the series column - $('select[name="chartSeriesColumn"]').on('change', function () { - currentSettings.seriesColumn = parseInt($(this).val(), 10); - drawChart(); - }); - - // handle changing the value column - $('select[name="chartValueColumn"]').on('change', function () { - currentSettings.valueColumn = parseInt($(this).val(), 10); - drawChart(); - }); - - // handle manual changes to the chart x-axis labels - $('input[name="xaxis_label"]').on('keyup', function () { - currentSettings.xaxisLabel = $(this).val(); - drawChart(); - }); - - // handle manual changes to the chart y-axis labels - $('input[name="yaxis_label"]').on('keyup', function () { - currentSettings.yaxisLabel = $(this).val(); - drawChart(); - }); - - // handler for ajax form submission - $('#tblchartform').submit(function (event) { - var $form = $(this); - if (codemirror_editor) { - $form[0].elements.sql_query.value = codemirror_editor.getValue(); - } - if (!checkSqlQuery($form[0])) { - return false; - } - - var $msgbox = PMA_ajaxShowMessage(); - PMA_prepareForAjaxRequest($form); - $.post($form.attr('action'), $form.serialize(), function (data) { - if (typeof data !== 'undefined' && - data.success === true && - typeof data.chartData !== 'undefined') { - chart_data = JSON.parse(data.chartData); - drawChart(); - PMA_ajaxRemoveMessage($msgbox); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }, 'json'); // end $.post() - - return false; - }); - - // from jQuery UI - $('#resizer').resizable({ - minHeight: 240, - minWidth: 300 - }) - .width($('#div_view_options').width() - 50) - .trigger('resizestop'); - - currentSettings = { - type : 'line', - width : $('#resizer').width() - 20, - height : $('#resizer').height() - 20, - xaxisLabel : $('input[name="xaxis_label"]').val(), - yaxisLabel : $('input[name="yaxis_label"]').val(), - title : $('input[name="chartTitle"]').val(), - stackSeries : false, - mainAxis : parseInt($('select[name="chartXAxis"]').val(), 10), - selectedSeries : getSelectedSeries(), - seriesColumn : null - }; - - var vals = $('input[name="dateTimeCols"]').val().split(' '); - $.each(vals, function (i, v) { - dateTimeCols.push(parseInt(v, 10)); - }); - - vals = $('input[name="numericCols"]').val().split(' '); - $.each(vals, function (i, v) { - numericCols.push(parseInt(v, 10)); - }); - - onXAxisChange(); - onDataSeriesChange(); - - $('#tblchartform').submit(); -}); diff --git a/js/tbl_find_replace.js b/js/tbl_find_replace.js deleted file mode 100644 index 09d4042072..0000000000 --- a/js/tbl_find_replace.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('tbl_find_replace.js', function () { - $('#find_replace_form').off('submit'); - $('#toggle_find').off('click'); -}); - -/** - * Bind events - */ -AJAX.registerOnload('tbl_find_replace.js', function () { - $('<div id="toggle_find_div"><a id="toggle_find"></a></div>') - .insertAfter('#find_replace_form') - .hide(); - - $('#toggle_find') - .html(PMA_messages.strHideFindNReplaceCriteria) - .on('click', function () { - var $link = $(this); - $('#find_replace_form').slideToggle(); - if ($link.text() === PMA_messages.strHideFindNReplaceCriteria) { - $link.text(PMA_messages.strShowFindNReplaceCriteria); - } else { - $link.text(PMA_messages.strHideFindNReplaceCriteria); - } - return false; - }); - - $('#find_replace_form').submit(function (e) { - e.preventDefault(); - var findReplaceForm = $('#find_replace_form'); - PMA_prepareForAjaxRequest(findReplaceForm); - var $msgbox = PMA_ajaxShowMessage(); - $.post(findReplaceForm.attr('action'), findReplaceForm.serialize(), function (data) { - PMA_ajaxRemoveMessage($msgbox); - if (data.success === true) { - $('#toggle_find_div').show(); - $('#toggle_find').trigger('click'); - $('#sqlqueryresultsouter').html(data.preview); - } else { - $('#sqlqueryresultsouter').html(data.error); - } - }); - }); -}); diff --git a/js/tbl_operations.js b/js/tbl_operations.js deleted file mode 100644 index 59b8c534e7..0000000000 --- a/js/tbl_operations.js +++ /dev/null @@ -1,325 +0,0 @@ -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('tbl_operations.js', function () { - $(document).off('submit', '#copyTable.ajax'); - $(document).off('submit', '#moveTableForm'); - $(document).off('submit', '#tableOptionsForm'); - $(document).off('submit', '#partitionsForm'); - $(document).off('click', '#tbl_maintenance li a.maintain_action.ajax'); - $(document).off('click', '#drop_tbl_anchor.ajax'); - $(document).off('click', '#drop_view_anchor.ajax'); - $(document).off('click', '#truncate_tbl_anchor.ajax'); -}); - -/** - * jQuery coding for 'Table operations'. Used on tbl_operations.php - * Attach Ajax Event handlers for Table operations - */ -AJAX.registerOnload('tbl_operations.js', function () { - /** - *Ajax action for submitting the "Copy table" - **/ - $(document).on('submit', '#copyTable.ajax', function (event) { - event.preventDefault(); - var $form = $(this); - PMA_prepareForAjaxRequest($form); - var argsep = PMA_commonParams.get('arg_separator'); - $.post($form.attr('action'), $form.serialize() + argsep + 'submit_copy=Go', function (data) { - if (typeof data !== 'undefined' && data.success === true) { - if ($form.find('input[name=\'switch_to_new\']').prop('checked')) { - PMA_commonParams.set( - 'db', - $form.find('select[name=\'target_db\']').val() - ); - PMA_commonParams.set( - 'table', - $form.find('input[name=\'new_name\']').val() - ); - PMA_commonActions.refreshMain(false, function () { - PMA_ajaxShowMessage(data.message); - }); - } else { - PMA_ajaxShowMessage(data.message); - } - // Refresh navigation when the table is copied - PMA_reloadNavigation(); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - });// end of copyTable ajax submit - - /** - *Ajax action for submitting the "Move table" - */ - $(document).on('submit', '#moveTableForm', function (event) { - event.preventDefault(); - var $form = $(this); - PMA_prepareForAjaxRequest($form); - var argsep = PMA_commonParams.get('arg_separator'); - $.post($form.attr('action'), $form.serialize() + argsep + 'submit_move=1', function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_commonParams.set('db', data._params.db); - PMA_commonParams.set('table', data._params.tbl); - PMA_commonActions.refreshMain(false, function () { - PMA_ajaxShowMessage(data.message); - }); - // Refresh navigation when the table is copied - PMA_reloadNavigation(); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }); - - /** - * Ajax action for submitting the "Table options" - */ - $(document).on('submit', '#tableOptionsForm', function (event) { - event.preventDefault(); - event.stopPropagation(); - var $form = $(this); - var $tblNameField = $form.find('input[name=new_name]'); - var $tblCollationField = $form.find('select[name=tbl_collation]'); - var collationOrigValue = $('select[name="tbl_collation"] option[selected]').val(); - var $changeAllColumnCollationsCheckBox = $('#checkbox_change_all_collations'); - var question = PMA_messages.strChangeAllColumnCollationsWarning; - - if ($tblNameField.val() !== $tblNameField[0].defaultValue) { - // reload page and navigation if the table has been renamed - PMA_prepareForAjaxRequest($form); - - if ($tblCollationField.val() !== collationOrigValue && $changeAllColumnCollationsCheckBox.is(':checked')) { - $form.PMA_confirm(question, $form.attr('action'), function (url) { - submitOptionsForm(); - }); - } else { - submitOptionsForm(); - } - } else { - if ($tblCollationField.val() !== collationOrigValue && $changeAllColumnCollationsCheckBox.is(':checked')) { - $form.PMA_confirm(question, $form.attr('action'), function (url) { - $form.removeClass('ajax').submit().addClass('ajax'); - }); - } else { - $form.removeClass('ajax').submit().addClass('ajax'); - } - } - - function submitOptionsForm () { - $.post($form.attr('action'), $form.serialize(), function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_commonParams.set('table', data._params.table); - PMA_commonActions.refreshMain(false, function () { - $('#page_content').html(data.message); - PMA_highlightSQL($('#page_content')); - }); - // Refresh navigation when the table is renamed - PMA_reloadNavigation(); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - } - }); - - /** - *Ajax events for actions in the "Table maintenance" - **/ - $(document).on('click', '#tbl_maintenance li a.maintain_action.ajax', function (event) { - event.preventDefault(); - var $link = $(this); - - if ($('.sqlqueryresults').length !== 0) { - $('.sqlqueryresults').remove(); - } - if ($('.result_query').length !== 0) { - $('.result_query').remove(); - } - // variables which stores the common attributes - var params = $.param({ - ajax_request: 1, - server: PMA_commonParams.get('server') - }); - var postData = $link.getPostData(); - if (postData) { - params += PMA_commonParams.get('arg_separator') + postData; - } - - $.post($link.attr('href'), params, function (data) { - function scrollToTop () { - $('html, body').animate({ scrollTop: 0 }); - } - var $temp_div; - if (typeof data !== 'undefined' && data.success === true && data.sql_query !== undefined) { - PMA_ajaxShowMessage(data.message); - $('<div class=\'sqlqueryresults ajax\'></div>').prependTo('#page_content'); - $('.sqlqueryresults').html(data.sql_query); - PMA_highlightSQL($('#page_content')); - scrollToTop(); - } else if (typeof data !== 'undefined' && data.success === true) { - $temp_div = $('<div id=\'temp_div\'></div>'); - $temp_div.html(data.message); - var $success = $temp_div.find('.result_query .success'); - PMA_ajaxShowMessage($success); - $('<div class=\'sqlqueryresults ajax\'></div>').prependTo('#page_content'); - $('.sqlqueryresults').html(data.message); - PMA_highlightSQL($('#page_content')); - PMA_init_slider(); - $('.sqlqueryresults').children('fieldset,br').remove(); - scrollToTop(); - } else { - $temp_div = $('<div id=\'temp_div\'></div>'); - $temp_div.html(data.error); - - var $error; - if ($temp_div.find('.error code').length !== 0) { - $error = $temp_div.find('.error code').addClass('error'); - } else { - $error = $temp_div; - } - - PMA_ajaxShowMessage($error, false); - } - }); // end $.post() - });// end of table maintenance ajax click - - /** - * Ajax action for submitting the "Partition Maintenance" - * Also, asks for confirmation when DROP partition is submitted - */ - $(document).on('submit', '#partitionsForm', function (event) { - event.preventDefault(); - var $form = $(this); - - function submitPartitionMaintenance () { - var argsep = PMA_commonParams.get('arg_separator'); - var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true'; - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - AJAX.source = $form; - $.post($form.attr('action'), submitData, AJAX.responseHandler); - } - - if ($('#partition_operation_DROP').is(':checked')) { - var question = PMA_messages.strDropPartitionWarning; - $form.PMA_confirm(question, $form.attr('action'), function (url) { - submitPartitionMaintenance(); - }); - } else if ($('#partition_operation_TRUNCATE').is(':checked')) { - var question = PMA_messages.strTruncatePartitionWarning; - $form.PMA_confirm(question, $form.attr('action'), function (url) { - submitPartitionMaintenance(); - }); - } else { - submitPartitionMaintenance(); - } - }); - - $(document).on('click', '#drop_tbl_anchor.ajax', function (event) { - event.preventDefault(); - var $link = $(this); - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_messages.strDropTableStrongWarning + ' '; - question += PMA_sprintf( - PMA_messages.strDoYouReally, - 'DROP TABLE `' + escapeHtml(PMA_commonParams.get('db')) + '`.`' + escapeHtml(PMA_commonParams.get('table') + '`') - ) + getForeignKeyCheckboxLoader(); - - $(this).PMA_confirm(question, $(this).attr('href'), function (url) { - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - - var params = getJSConfirmCommonParam(this, $link.getPostData()); - - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxRemoveMessage($msgbox); - // Table deleted successfully, refresh both the frames - PMA_reloadNavigation(); - PMA_commonParams.set('table', ''); - PMA_commonActions.refreshMain( - PMA_commonParams.get('opendb_url'), - function () { - PMA_ajaxShowMessage(data.message); - } - ); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }, loadForeignKeyCheckbox); // end $.PMA_confirm() - }); // end of Drop Table Ajax action - - $(document).on('click', '#drop_view_anchor.ajax', function (event) { - event.preventDefault(); - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_messages.strDropTableStrongWarning + ' '; - question += PMA_sprintf( - PMA_messages.strDoYouReally, - 'DROP VIEW `' + escapeHtml(PMA_commonParams.get('table') + '`') - ); - - $(this).PMA_confirm(question, $(this).attr('href'), function (url) { - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - var params = { - 'is_js_confirmed': '1', - 'ajax_request': true - }; - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxRemoveMessage($msgbox); - // Table deleted successfully, refresh both the frames - PMA_reloadNavigation(); - PMA_commonParams.set('table', ''); - PMA_commonActions.refreshMain( - PMA_commonParams.get('opendb_url'), - function () { - PMA_ajaxShowMessage(data.message); - } - ); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }); // end $.PMA_confirm() - }); // end of Drop View Ajax action - - $(document).on('click', '#truncate_tbl_anchor.ajax', function (event) { - event.preventDefault(); - var $link = $(this); - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_messages.strTruncateTableStrongWarning + ' '; - question += PMA_sprintf( - PMA_messages.strDoYouReally, - 'TRUNCATE `' + escapeHtml(PMA_commonParams.get('db')) + '`.`' + escapeHtml(PMA_commonParams.get('table') + '`') - ) + getForeignKeyCheckboxLoader(); - $(this).PMA_confirm(question, $(this).attr('href'), function (url) { - PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - - var params = getJSConfirmCommonParam(this, $link.getPostData()); - - $.post(url, params, function (data) { - if ($('.sqlqueryresults').length !== 0) { - $('.sqlqueryresults').remove(); - } - if ($('.result_query').length !== 0) { - $('.result_query').remove(); - } - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxShowMessage(data.message); - $('<div class=\'sqlqueryresults ajax\'></div>').prependTo('#page_content'); - $('.sqlqueryresults').html(data.sql_query); - PMA_highlightSQL($('#page_content')); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - }, loadForeignKeyCheckbox); // end $.PMA_confirm() - }); // end of Truncate Table Ajax action -}); // end $(document).ready for 'Table operations' diff --git a/js/tbl_relation.js b/js/tbl_relation.js deleted file mode 100644 index 6446b8b1e6..0000000000 --- a/js/tbl_relation.js +++ /dev/null @@ -1,241 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * for tbl_relation.php - * - */ -function show_hide_clauses ($thisDropdown) { - if ($thisDropdown.val() === '') { - $thisDropdown.parent().nextAll('span').hide(); - } else { - if ($thisDropdown.is('select[name^="destination_foreign_column"]')) { - $thisDropdown.parent().nextAll('span').show(); - } - } -} - -/** - * Sets dropdown options to values - */ -function setDropdownValues ($dropdown, values, selectedValue) { - $dropdown.empty(); - var optionsAsString = ''; - // add an empty string to the beginning for empty selection - values.unshift(''); - $.each(values, function () { - optionsAsString += '<option value=\'' + escapeHtml(this) + '\'' + (selectedValue === escapeHtml(this) ? ' selected=\'selected\'' : '') + '>' + escapeHtml(this) + '</option>'; - }); - $dropdown.append($(optionsAsString)); -} - -/** - * Retrieves and populates dropdowns to the left based on the selected value - * - * @param $dropdown the dropdown whose value got changed - */ -function getDropdownValues ($dropdown) { - var foreignDb = null; - var foreignTable = null; - var $databaseDd; - var $tableDd; - var $columnDd; - var foreign = ''; - // if the changed dropdown is for foreign key constraints - if ($dropdown.is('select[name^="destination_foreign"]')) { - $databaseDd = $dropdown.parent().parent().parent().find('select[name^="destination_foreign_db"]'); - $tableDd = $dropdown.parent().parent().parent().find('select[name^="destination_foreign_table"]'); - $columnDd = $dropdown.parent().parent().parent().find('select[name^="destination_foreign_column"]'); - foreign = '_foreign'; - } else { // internal relations - $databaseDd = $dropdown.parent().find('select[name^="destination_db"]'); - $tableDd = $dropdown.parent().find('select[name^="destination_table"]'); - $columnDd = $dropdown.parent().find('select[name^="destination_column"]'); - } - - // if the changed dropdown is a database selector - if ($dropdown.is('select[name^="destination' + foreign + '_db"]')) { - foreignDb = $dropdown.val(); - // if no database is selected empty table and column dropdowns - if (foreignDb === '') { - setDropdownValues($tableDd, []); - setDropdownValues($columnDd, []); - return; - } - } else { // if a table selector - foreignDb = $databaseDd.val(); - foreignTable = $dropdown.val(); - // if no table is selected empty the column dropdown - if (foreignTable === '') { - setDropdownValues($columnDd, []); - return; - } - } - var $msgbox = PMA_ajaxShowMessage(); - var $form = $dropdown.parents('form'); - var argsep = PMA_commonParams.get('arg_separator'); - var url = 'tbl_relation.php?getDropdownValues=true' + argsep + 'ajax_request=true' + - argsep + 'db=' + $form.find('input[name="db"]').val() + - argsep + 'table=' + $form.find('input[name="table"]').val() + - argsep + 'foreign=' + (foreign !== '') + - argsep + 'foreignDb=' + encodeURIComponent(foreignDb) + - (foreignTable !== null ? - argsep + 'foreignTable=' + encodeURIComponent(foreignTable) : '' - ); - var $server = $form.find('input[name="server"]'); - if ($server.length > 0) { - url += argsep + 'server=' + $form.find('input[name="server"]').val(); - } - $.ajax({ - url: url, - datatype: 'json', - success: function (data) { - PMA_ajaxRemoveMessage($msgbox); - if (typeof data !== 'undefined' && data.success) { - // if the changed dropdown is a database selector - if (foreignTable === null) { - // set values for table and column dropdowns - setDropdownValues($tableDd, data.tables); - setDropdownValues($columnDd, []); - } else { // if a table selector - // set values for the column dropdown - var primary = null; - if (typeof data.primary !== 'undefined' - && 1 === data.primary.length - ) { - primary = data.primary[0]; - } - setDropdownValues($columnDd.first(), data.columns, primary); - setDropdownValues($columnDd.slice(1), data.columns); - } - } else { - PMA_ajaxShowMessage(data.error, false); - } - } - }); -} - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('tbl_relation.js', function () { - $('body').off('change', - 'select[name^="destination_db"], ' + - 'select[name^="destination_table"], ' + - 'select[name^="destination_foreign_db"], ' + - 'select[name^="destination_foreign_table"]' - ); - $('body').off('click', 'a.add_foreign_key_field'); - $('body').off('click', 'a.add_foreign_key'); - $('a.drop_foreign_key_anchor.ajax').off('click'); -}); - -AJAX.registerOnload('tbl_relation.js', function () { - /** - * Ajax event handler to fetch table/column dropdown values. - */ - $('body').on('change', - 'select[name^="destination_db"], ' + - 'select[name^="destination_table"], ' + - 'select[name^="destination_foreign_db"], ' + - 'select[name^="destination_foreign_table"]', - function () { - getDropdownValues($(this)); - } - ); - - /** - * Ajax event handler to add a column to a foreign key constraint. - */ - $('body').on('click', 'a.add_foreign_key_field', function (event) { - event.preventDefault(); - event.stopPropagation(); - - // Add field. - $(this) - .prev('span') - .clone(true, true) - .insertBefore($(this)) - .find('select') - .val(''); - - // Add foreign field. - var $source_elem = $('select[name^="destination_foreign_column[' + - $(this).attr('data-index') + ']"]:last').parent(); - $source_elem - .clone(true, true) - .insertAfter($source_elem) - .find('select') - .val(''); - }); - - /** - * Ajax event handler to add a foreign key constraint. - */ - $('body').on('click', 'a.add_foreign_key', function (event) { - event.preventDefault(); - event.stopPropagation(); - - var $prev_row = $(this).closest('tr').prev('tr'); - var $newRow = $prev_row.clone(true, true); - - // Update serial number. - var curr_index = $newRow - .find('a.add_foreign_key_field') - .attr('data-index'); - var new_index = parseInt(curr_index) + 1; - $newRow.find('a.add_foreign_key_field').attr('data-index', new_index); - - // Update form parameter names. - $newRow.find('select[name^="foreign_key_fields_name"]:not(:first), ' + - 'select[name^="destination_foreign_column"]:not(:first)' - ).each(function () { - $(this).parent().remove(); - }); - $newRow.find('input, select').each(function () { - $(this).attr('name', - $(this).attr('name').replace(/\d/, new_index) - ); - }); - $newRow.find('input[type="text"]').each(function () { - $(this).val(''); - }); - // Finally add the row. - $newRow.insertAfter($prev_row); - }); - - /** - * Ajax Event handler for 'Drop Foreign key' - */ - $('a.drop_foreign_key_anchor.ajax').on('click', function (event) { - event.preventDefault(); - var $anchor = $(this); - - // Object containing reference to the current field's row - var $curr_row = $anchor.parents('tr'); - - var drop_query = escapeHtml( - $curr_row.children('td') - .children('.drop_foreign_key_msg') - .val() - ); - - var question = PMA_sprintf(PMA_messages.strDoYouReally, drop_query); - - $anchor.PMA_confirm(question, $anchor.attr('href'), function (url) { - var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingForeignKey, false); - var params = getJSConfirmCommonParam(this, $anchor.getPostData()); - $.post(url, params, function (data) { - if (data.success === true) { - PMA_ajaxRemoveMessage($msg); - PMA_commonActions.refreshMain(false, function () { - // Do nothing - }); - } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); - } - }); // end $.post() - }); // end $.PMA_confirm() - }); // end Drop Foreign key - - var windowwidth = $(window).width(); - $('.jsresponsive').css('max-width', (windowwidth - 35) + 'px'); -}); diff --git a/js/tbl_select.js b/js/tbl_select.js deleted file mode 100644 index 1e44db695b..0000000000 --- a/js/tbl_select.js +++ /dev/null @@ -1,413 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview JavaScript functions used on tbl_select.php - * - * @requires jQuery - * @requires js/functions.js - */ - -/** - * Ajax event handlers for this page - * - * Actions ajaxified here: - * Table search - */ - -/** - * Checks if given data-type is numeric or date. - * - * @param string data_type Column data-type - * - * @return bool|string - */ -function PMA_checkIfDataTypeNumericOrDate (data_type) { - // To test for numeric data-types. - var numeric_re = new RegExp( - 'TINYINT|SMALLINT|MEDIUMINT|INT|BIGINT|DECIMAL|FLOAT|DOUBLE|REAL', - 'i' - ); - - // To test for date data-types. - var date_re = new RegExp( - 'DATETIME|DATE|TIMESTAMP|TIME|YEAR', - 'i' - ); - - // Return matched data-type - if (numeric_re.test(data_type)) { - return numeric_re.exec(data_type)[0]; - } - - if (date_re.test(data_type)) { - return date_re.exec(data_type)[0]; - } - - return false; -} - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('tbl_select.js', function () { - $('#togglesearchformlink').off('click'); - $(document).off('submit', '#tbl_search_form.ajax'); - $('select.geom_func').off('change'); - $(document).off('click', 'span.open_search_gis_editor'); - $('body').off('change', 'select[name*="criteriaColumnOperators"]'); // Fix for bug #13778, changed 'click' to 'change' -}); - -AJAX.registerOnload('tbl_select.js', function () { - /** - * Prepare a div containing a link, otherwise it's incorrectly displayed - * after a couple of clicks - */ - $('<div id="togglesearchformdiv"><a id="togglesearchformlink"></a></div>') - .insertAfter('#tbl_search_form') - // don't show it until we have results on-screen - .hide(); - - $('#togglesearchformlink') - .html(PMA_messages.strShowSearchCriteria) - .on('click', function () { - var $link = $(this); - $('#tbl_search_form').slideToggle(); - if ($link.text() === PMA_messages.strHideSearchCriteria) { - $link.text(PMA_messages.strShowSearchCriteria); - } else { - $link.text(PMA_messages.strHideSearchCriteria); - } - // avoid default click action - return false; - }); - - var tableRows = $('#fieldset_table_qbe select'); - $.each(tableRows, function (index, item) { - $(item).on('change', function () { - changeValueFieldType(this, index); - }); - }); - - /** - * Ajax event handler for Table search - */ - $(document).on('submit', '#tbl_search_form.ajax', function (event) { - var unaryFunctions = [ - 'IS NULL', - 'IS NOT NULL', - '= \'\'', - '!= \'\'' - ]; - - var geomUnaryFunctions = [ - 'IsEmpty', - 'IsSimple', - 'IsRing', - 'IsClosed', - ]; - - // jQuery object to reuse - var $search_form = $(this); - event.preventDefault(); - - // empty previous search results while we are waiting for new results - $('#sqlqueryresultsouter').empty(); - var $msgbox = PMA_ajaxShowMessage(PMA_messages.strSearching, false); - - PMA_prepareForAjaxRequest($search_form); - - var values = {}; - $search_form.find(':input').each(function () { - var $input = $(this); - if ($input.attr('type') === 'checkbox' || $input.attr('type') === 'radio') { - if ($input.is(':checked')) { - values[this.name] = $input.val(); - } - } else { - values[this.name] = $input.val(); - } - }); - var columnCount = $('select[name="columnsToDisplay[]"] option').length; - // Submit values only for the columns that have unary column operator or a search criteria - for (var a = 0; a < columnCount; a++) { - if ($.inArray(values['criteriaColumnOperators[' + a + ']'], unaryFunctions) >= 0) { - continue; - } - - if (values['geom_func[' + a + ']'] && - $.isArray(values['geom_func[' + a + ']'], geomUnaryFunctions) >= 0) { - continue; - } - - if (values['criteriaValues[' + a + ']'] === '' || values['criteriaValues[' + a + ']'] === null) { - delete values['criteriaValues[' + a + ']']; - delete values['criteriaColumnOperators[' + a + ']']; - delete values['criteriaColumnNames[' + a + ']']; - delete values['criteriaColumnTypes[' + a + ']']; - delete values['criteriaColumnCollations[' + a + ']']; - } - } - // If all columns are selected, use a single parameter to indicate that - if (values['columnsToDisplay[]'] !== null) { - if (values['columnsToDisplay[]'].length === columnCount) { - delete values['columnsToDisplay[]']; - values.displayAllColumns = true; - } - } else { - values.displayAllColumns = true; - } - - $.post($search_form.attr('action'), values, function (data) { - PMA_ajaxRemoveMessage($msgbox); - if (typeof data !== 'undefined' && data.success === true) { - if (typeof data.sql_query !== 'undefined') { // zero rows - $('#sqlqueryresultsouter').html(data.sql_query); - } else { // results found - $('#sqlqueryresultsouter').html(data.message); - $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns'); - } - $('#tbl_search_form') - // workaround for bug #3168569 - Issue on toggling the "Hide search criteria" in chrome. - .slideToggle() - .hide(); - $('#togglesearchformlink') - // always start with the Show message - .text(PMA_messages.strShowSearchCriteria); - $('#togglesearchformdiv') - // now it's time to show the div containing the link - .show(); - // needed for the display options slider in the results - PMA_init_slider(); - $('html, body').animate({ scrollTop: 0 }, 'fast'); - } else { - $('#sqlqueryresultsouter').html(data.error); - } - PMA_highlightSQL($('#sqlqueryresultsouter')); - }); // end $.post() - }); - - // Following section is related to the 'function based search' for geometry data types. - // Initialy hide all the open_gis_editor spans - $('span.open_search_gis_editor').hide(); - - $('select.geom_func').bind('change', function () { - var $geomFuncSelector = $(this); - - var binaryFunctions = [ - 'Contains', - 'Crosses', - 'Disjoint', - 'Equals', - 'Intersects', - 'Overlaps', - 'Touches', - 'Within', - 'MBRContains', - 'MBRDisjoint', - 'MBREquals', - 'MBRIntersects', - 'MBROverlaps', - 'MBRTouches', - 'MBRWithin', - 'ST_Contains', - 'ST_Crosses', - 'ST_Disjoint', - 'ST_Equals', - 'ST_Intersects', - 'ST_Overlaps', - 'ST_Touches', - 'ST_Within' - ]; - - var tempArray = [ - 'Envelope', - 'EndPoint', - 'StartPoint', - 'ExteriorRing', - 'Centroid', - 'PointOnSurface' - ]; - var outputGeomFunctions = binaryFunctions.concat(tempArray); - - // If the chosen function takes two geometry objects as parameters - var $operator = $geomFuncSelector.parents('tr').find('td:nth-child(5)').find('select'); - if ($.inArray($geomFuncSelector.val(), binaryFunctions) >= 0) { - $operator.prop('readonly', true); - } else { - $operator.prop('readonly', false); - } - - // if the chosen function's output is a geometry, enable GIS editor - var $editorSpan = $geomFuncSelector.parents('tr').find('span.open_search_gis_editor'); - if ($.inArray($geomFuncSelector.val(), outputGeomFunctions) >= 0) { - $editorSpan.show(); - } else { - $editorSpan.hide(); - } - }); - - $(document).on('click', 'span.open_search_gis_editor', function (event) { - event.preventDefault(); - - var $span = $(this); - // Current value - var value = $span.parent('td').children('input[type=\'text\']').val(); - // Field name - var field = 'Parameter'; - // Column type - var geom_func = $span.parents('tr').find('.geom_func').val(); - var type; - if (geom_func === 'Envelope') { - type = 'polygon'; - } else if (geom_func === 'ExteriorRing') { - type = 'linestring'; - } else { - type = 'point'; - } - // Names of input field and null checkbox - var input_name = $span.parent('td').children('input[type=\'text\']').attr('name'); - // Token - - openGISEditor(); - if (!gisEditorLoaded) { - loadJSAndGISEditor(value, field, type, input_name); - } else { - loadGISEditor(value, field, type, input_name); - } - }); - - /** - * Ajax event handler for Range-Search. - */ - $('body').on('change', 'select[name*="criteriaColumnOperators"]', function () { // Fix for bug #13778, changed 'click' to 'change' - $source_select = $(this); - // Get the column name. - var column_name = $(this) - .closest('tr') - .find('th:first') - .text(); - - // Get the data-type of column excluding size. - var data_type = $(this) - .closest('tr') - .find('td[data-type]') - .attr('data-type'); - data_type = PMA_checkIfDataTypeNumericOrDate(data_type); - - // Get the operator. - var operator = $(this).val(); - - if ((operator === 'BETWEEN' || operator === 'NOT BETWEEN') - && data_type - ) { - var $msgbox = PMA_ajaxShowMessage(); - $.ajax({ - url: 'tbl_select.php', - type: 'POST', - data: { - server: PMA_commonParams.get('server'), - ajax_request: 1, - db: $('input[name="db"]').val(), - table: $('input[name="table"]').val(), - column: column_name, - range_search: 1 - }, - success: function (response) { - PMA_ajaxRemoveMessage($msgbox); - if (response.success) { - // Get the column min value. - var min = response.column_data.min - ? '(' + PMA_messages.strColumnMin + - ' ' + response.column_data.min + ')' - : ''; - // Get the column max value. - var max = response.column_data.max - ? '(' + PMA_messages.strColumnMax + - ' ' + response.column_data.max + ')' - : ''; - var button_options = {}; - button_options[PMA_messages.strGo] = function () { - var min_value = $('#min_value').val(); - var max_value = $('#max_value').val(); - var final_value = ''; - if (min_value.length && max_value.length) { - final_value = min_value + ', ' + - max_value; - } - var $target_field = $source_select.closest('tr') - .find('[name*="criteriaValues"]'); - - // If target field is a select list. - if ($target_field.is('select')) { - $target_field.val(final_value); - var $options = $target_field.find('option'); - var $closest_min = null; - var $closest_max = null; - // Find closest min and max value. - $options.each(function () { - if ( - $closest_min === null - || Math.abs($(this).val() - min_value) < Math.abs($closest_min.val() - min_value) - ) { - $closest_min = $(this); - } - - if ( - $closest_max === null - || Math.abs($(this).val() - max_value) < Math.abs($closest_max.val() - max_value) - ) { - $closest_max = $(this); - } - }); - - $closest_min.attr('selected', 'selected'); - $closest_max.attr('selected', 'selected'); - } else { - $target_field.val(final_value); - } - $(this).dialog('close'); - }; - button_options[PMA_messages.strCancel] = function () { - $(this).dialog('close'); - }; - - // Display dialog box. - $('<div/>').append( - '<fieldset>' + - '<legend>' + operator + '</legend>' + - '<label for="min_value">' + PMA_messages.strMinValue + - '</label>' + - '<input type="text" id="min_value" />' + '<br>' + - '<span class="small_font">' + min + '</span>' + '<br>' + - '<label for="max_value">' + PMA_messages.strMaxValue + - '</label>' + - '<input type="text" id="max_value" />' + '<br>' + - '<span class="small_font">' + max + '</span>' + - '</fieldset>' - ).dialog({ - minWidth: 500, - maxHeight: 400, - modal: true, - buttons: button_options, - title: PMA_messages.strRangeSearch, - open: function () { - // Add datepicker wherever required. - PMA_addDatepicker($('#min_value'), data_type); - PMA_addDatepicker($('#max_value'), data_type); - }, - close: function () { - $(this).remove(); - } - }); - } else { - PMA_ajaxShowMessage(response.error); - } - }, - error: function (response) { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest); - } - }); - } - }); - var windowwidth = $(window).width(); - $('.jsresponsive').css('max-width', (windowwidth - 69) + 'px'); -}); diff --git a/js/tbl_structure.js b/js/tbl_structure.js deleted file mode 100644 index c1affbc186..0000000000 --- a/js/tbl_structure.js +++ /dev/null @@ -1,506 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ -/** - * @fileoverview functions used on the table structure page - * @name Table Structure - * - * @requires jQuery - * @requires jQueryUI - * @required js/functions.js - */ - -/** - * AJAX scripts for tbl_structure.php - * - * Actions ajaxified here: - * Drop Column - * Add Primary Key - * Drop Primary Key/Index - * - */ - -/** - * Reload fields table - */ -function reloadFieldForm () { - $.post($('#fieldsForm').attr('action'), $('#fieldsForm').serialize() + PMA_commonParams.get('arg_separator') + 'ajax_request=true', function (form_data) { - var $temp_div = $('<div id=\'temp_div\'><div>').append(form_data.message); - $('#fieldsForm').replaceWith($temp_div.find('#fieldsForm')); - $('#addColumns').replaceWith($temp_div.find('#addColumns')); - $('#move_columns_dialog').find('ul').replaceWith($temp_div.find('#move_columns_dialog ul')); - $('#moveColumns').removeClass('move-active'); - }); - $('#page_content').show(); -} - -function checkFirst () { - if ($('select[name=after_field] option:selected').data('pos') === 'first') { - $('input[name=field_where]').val('first'); - } else { - $('input[name=field_where]').val('after'); - } -} -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('tbl_structure.js', function () { - $(document).off('click', 'a.drop_column_anchor.ajax'); - $(document).off('click', 'a.add_key.ajax'); - $(document).off('click', '#move_columns_anchor'); - $(document).off('click', '#printView'); - $(document).off('submit', '.append_fields_form.ajax'); - $('body').off('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]'); - $(document).off('click', 'a[name^=partition_action].ajax'); - $(document).off('click', '#remove_partitioning.ajax'); -}); - -AJAX.registerOnload('tbl_structure.js', function () { - // Re-initialize variables. - primary_indexes = []; - indexes = []; - fulltext_indexes = []; - spatial_indexes = []; - - /** - *Ajax action for submitting the "Column Change" and "Add Column" form - */ - $('.append_fields_form.ajax').off(); - $(document).on('submit', '.append_fields_form.ajax', function (event) { - event.preventDefault(); - /** - * @var the_form object referring to the export form - */ - var $form = $(this); - var field_cnt = $form.find('input[name=orig_num_fields]').val(); - - - function submitForm () { - $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest); - $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'do_save_data=1', function (data) { - if ($('.sqlqueryresults').length !== 0) { - $('.sqlqueryresults').remove(); - } else if ($('.error:not(.tab)').length !== 0) { - $('.error:not(.tab)').remove(); - } - if (typeof data.success !== 'undefined' && data.success === true) { - $('#page_content') - .empty() - .append(data.message) - .show(); - PMA_highlightSQL($('#page_content')); - $('.result_query .notice').remove(); - reloadFieldForm(); - $form.remove(); - PMA_ajaxRemoveMessage($msg); - PMA_init_slider(); - PMA_reloadNavigation(); - } else { - PMA_ajaxShowMessage(data.error, false); - } - }); // end $.post() - } - - function checkIfConfirmRequired ($form, $field_cnt) { - var i = 0; - var id; - var elm; - var val; - var name_orig; - var elm_orig; - var val_orig; - var checkRequired = false; - for (i = 0; i < field_cnt; i++) { - id = '#field_' + i + '_5'; - elm = $(id); - val = elm.val(); - - name_orig = 'input[name=field_collation_orig\\[' + i + '\\]]'; - elm_orig = $form.find(name_orig); - val_orig = elm_orig.val(); - - if (val && val_orig && val !== val_orig) { - checkRequired = true; - break; - } - } - return checkRequired; - } - - /* - * First validate the form; if there is a problem, avoid submitting it - * - * checkTableEditForm() needs a pure element and not a jQuery object, - * this is why we pass $form[0] as a parameter (the jQuery object - * is actually an array of DOM elements) - */ - if (checkTableEditForm($form[0], field_cnt)) { - // OK, form passed validation step - - PMA_prepareForAjaxRequest($form); - if (PMA_checkReservedWordColumns($form)) { - // User wants to submit the form - - // If Collation is changed, Warn and Confirm - if (checkIfConfirmRequired($form, field_cnt)) { - var question = sprintf( - PMA_messages.strChangeColumnCollation, 'https://wiki.phpmyadmin.net/pma/Garbled_data' - ); - $form.PMA_confirm(question, $form.attr('action'), function (url) { - submitForm(); - }); - } else { - submitForm(); - } - } - } - }); // end change table button "do_save_data" - - /** - * Attach Event Handler for 'Drop Column' - */ - $(document).on('click', 'a.drop_column_anchor.ajax', function (event) { - event.preventDefault(); - /** - * @var curr_table_name String containing the name of the current table - */ - var curr_table_name = $(this).closest('form').find('input[name=table]').val(); - /** - * @var curr_row Object reference to the currently selected row (i.e. field in the table) - */ - var $curr_row = $(this).parents('tr'); - /** - * @var curr_column_name String containing name of the field referred to by {@link curr_row} - */ - var curr_column_name = $curr_row.children('th').children('label').text().trim(); - curr_column_name = escapeHtml(curr_column_name); - /** - * @var $after_field_item Corresponding entry in the 'After' field. - */ - var $after_field_item = $('select[name=\'after_field\'] option[value=\'' + curr_column_name + '\']'); - /** - * @var question String containing the question to be asked for confirmation - */ - var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;'); - var $this_anchor = $(this); - $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) { - var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false); - var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); - params += PMA_commonParams.get('arg_separator') + 'ajax_page_request=1'; - $.post(url, params, function (data) { - if (typeof data !== 'undefined' && data.success === true) { - PMA_ajaxRemoveMessage($msg); - if ($('.result_query').length) { - $('.result_query').remove(); - } - if (data.sql_query) { - $('<div class="result_query"></div>') - .html(data.sql_query) - .prependTo('#structure_content'); - PMA_highlightSQL($('#page_content')); - } - // Adjust the row numbers - for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) { - var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1; - $row.find('td:nth-child(2)').text(new_val); - } - $after_field_item.remove(); - $curr_row.hide('medium').remove(); - - // Remove the dropped column from select menu for 'after field' - $('select[name=after_field]').find( - '[value="' + curr_column_name + '"]' - ).remove(); - - // by default select the (new) last option to add new column - // (in case last column is dropped) - $('select[name=after_field] option:last').attr('selected','selected'); - - // refresh table stats - if (data.tableStat) { - $('#tablestatistics').html(data.tableStat); - } - // refresh the list of indexes (comes from sql.php) - $('.index_info').replaceWith(data.indexes_list); - PMA_reloadNavigation(); - } else { - PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false); - } - }); // end $.post() - }); // end $.PMA_confirm() - }); // end of Drop Column Anchor action - - /** - * Attach Event Handler for 'Print' link - */ - $(document).on('click', '#printView', function (event) { - event.preventDefault(); - - // Take to preview mode - printPreview(); - }); // end of Print View action - - /** - * Ajax Event handler for adding keys - */ - $(document).on('click', 'a.add_key.ajax', function (event) { - event.preventDefault(); - - var $this = $(this); - var curr_table_name = $this.closest('form').find('input[name=table]').val(); - var curr_column_name = $this.parents('tr').children('th').children('label').text().trim(); - - var add_clause = ''; - if ($this.is('.add_primary_key_anchor')) { - add_clause = 'ADD PRIMARY KEY'; - } else if ($this.is('.add_index_anchor')) { - add_clause = 'ADD INDEX'; - } else if ($this.is('.add_unique_anchor')) { - add_clause = 'ADD UNIQUE'; - } else if ($this.is('.add_spatial_anchor')) { - add_clause = 'ADD SPATIAL'; - } else if ($this.is('.add_fulltext_anchor')) { - add_clause = 'ADD FULLTEXT'; - } - var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + - escapeHtml(curr_table_name) + '` ' + add_clause + '(`' + escapeHtml(curr_column_name) + '`);'); - - var $this_anchor = $(this); - - $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) { - PMA_ajaxShowMessage(); - AJAX.source = $this; - - var params = getJSConfirmCommonParam(this, $this_anchor.getPostData()); - params += PMA_commonParams.get('arg_separator') + 'ajax_page_request=1'; - $.post(url, params, AJAX.responseHandler); - }); // end $.PMA_confirm() - }); // end Add key - - /** - * Inline move columns - **/ - $(document).on('click', '#move_columns_anchor', function (e) { - e.preventDefault(); - - if ($(this).hasClass('move-active')) { - return; - } - - /** - * @var button_options Object that stores the options passed to jQueryUI - * dialog - */ - var button_options = {}; - - button_options[PMA_messages.strGo] = function (event) { - event.preventDefault(); - var $msgbox = PMA_ajaxShowMessage(); - var $this = $(this); - var $form = $this.find('form'); - var serialized = $form.serialize(); - // check if any columns were moved at all - if (serialized === $form.data('serialized-unmoved')) { - PMA_ajaxRemoveMessage($msgbox); - $this.dialog('close'); - return; - } - $.post($form.prop('action'), serialized + PMA_commonParams.get('arg_separator') + 'ajax_request=true', function (data) { - if (data.success === false) { - PMA_ajaxRemoveMessage($msgbox); - $this - .clone() - .html(data.error) - .dialog({ - title: $(this).prop('title'), - height: 230, - width: 900, - modal: true, - buttons: button_options_error - }); // end dialog options - } else { - // sort the fields table - var $fields_table = $('table#tablestructure tbody'); - // remove all existing rows and remember them - var $rows = $fields_table.find('tr').remove(); - // loop through the correct order - for (var i in data.columns) { - var the_column = data.columns[i]; - var $the_row = $rows - .find('input:checkbox[value=\'' + the_column + '\']') - .closest('tr'); - // append the row for this column to the table - $fields_table.append($the_row); - } - var $firstrow = $fields_table.find('tr').eq(0); - // Adjust the row numbers and colors - for (var $row = $firstrow; $row.length > 0; $row = $row.next()) { - $row - .find('td:nth-child(2)') - .text($row.index() + 1) - .end() - .removeClass('odd even') - .addClass($row.index() % 2 === 0 ? 'odd' : 'even'); - } - PMA_ajaxShowMessage(data.message); - $this.dialog('close'); - } - }); - }; - button_options[PMA_messages.strPreviewSQL] = function () { - // Function for Previewing SQL - var $form = $('#move_column_form'); - PMA_previewSQL($form); - }; - button_options[PMA_messages.strCancel] = function () { - $(this).dialog('close'); - }; - - var button_options_error = {}; - button_options_error[PMA_messages.strOK] = function () { - $(this).dialog('close').remove(); - }; - - var columns = []; - - $('#tablestructure').find('tbody tr').each(function () { - var col_name = $(this).find('input:checkbox').eq(0).val(); - var hidden_input = $('<input/>') - .prop({ - name: 'move_columns[]', - type: 'hidden' - }) - .val(col_name); - columns[columns.length] = $('<li/>') - .addClass('placeholderDrag') - .text(col_name) - .append(hidden_input); - }); - - var col_list = $('#move_columns_dialog').find('ul') - .find('li').remove().end(); - for (var i in columns) { - col_list.append(columns[i]); - } - col_list.sortable({ - axis: 'y', - containment: $('#move_columns_dialog').find('div'), - tolerance: 'pointer' - }).disableSelection(); - var $form = $('#move_columns_dialog').find('form'); - $form.data('serialized-unmoved', $form.serialize()); - - $('#move_columns_dialog').dialog({ - modal: true, - buttons: button_options, - open: function () { - if ($('#move_columns_dialog').parents('.ui-dialog').height() > $(window).height()) { - $('#move_columns_dialog').dialog('option', 'height', $(window).height()); - } - }, - beforeClose: function () { - $('#move_columns_anchor').removeClass('move-active'); - } - }); - }); - - /** - * Handles multi submits in table structure page such as change, browse, drop, primary etc. - */ - $('body').on('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]', function (e) { - e.preventDefault(); - var $button = $(this); - var $form = $button.parents('form'); - var argsep = PMA_commonParams.get('arg_separator'); - var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); - PMA_ajaxShowMessage(); - AJAX.source = $form; - $.post($form.attr('action'), submitData, AJAX.responseHandler); - }); - - /** - * Handles clicks on Action links in partition table - */ - $(document).on('click', 'a[name^=partition_action].ajax', function (e) { - e.preventDefault(); - var $link = $(this); - - function submitPartitionAction (url) { - var params = { - 'ajax_request' : true, - 'ajax_page_request' : true - }; - PMA_ajaxShowMessage(); - AJAX.source = $link; - $.post(url, params, AJAX.responseHandler); - } - - if ($link.is('#partition_action_DROP')) { - var question = PMA_messages.strDropPartitionWarning; - $link.PMA_confirm(question, $link.attr('href'), function (url) { - submitPartitionAction(url); - }); - } else if ($link.is('#partition_action_TRUNCATE')) { - var question = PMA_messages.strTruncatePartitionWarning; - $link.PMA_confirm(question, $link.attr('href'), function (url) { - submitPartitionAction(url); - }); - } else { - submitPartitionAction($link.attr('href')); - } - }); - - /** - * Handles remove partitioning - */ - $(document).on('click', '#remove_partitioning.ajax', function (e) { - e.preventDefault(); - var $link = $(this); - var question = PMA_messages.strRemovePartitioningWarning; - $link.PMA_confirm(question, $link.attr('href'), function (url) { - var params = { - 'ajax_request' : true, - 'ajax_page_request' : true - }; - PMA_ajaxShowMessage(); - AJAX.source = $link; - $.post(url, params, AJAX.responseHandler); - }); - }); - - $(document).on('change', 'select[name=after_field]', function () { - checkFirst(); - }); -}); - -/** Handler for "More" dropdown in structure table rows */ -AJAX.registerOnload('tbl_structure.js', function () { - var windowwidth = $(window).width(); - if (windowwidth > 768) { - if (! $('#fieldsForm').hasClass('HideStructureActions')) { - $('.table-structure-actions').width(function () { - var width = 5; - $(this).find('li').each(function () { - width += $(this).outerWidth(true); - }); - return width; - }); - } - } - - $('.jsresponsive').css('max-width', (windowwidth - 35) + 'px'); - var tableRows = $('.central_columns'); - $.each(tableRows, function (index, item) { - if ($(item).hasClass('add_button')) { - $(item).on('click', function () { - $('input:checkbox').prop('checked', false); - $('#checkbox_row_' + (index + 1)).prop('checked', true); - $('button[value=add_to_central_columns]').trigger('click'); - }); - } else { - $(item).on('click', function () { - $('input:checkbox').prop('checked', false); - $('#checkbox_row_' + (index + 1)).prop('checked', true); - $('button[value=remove_from_central_columns]').trigger('click'); - }); - } - }); -}); diff --git a/js/tbl_tracking.js b/js/tbl_tracking.js deleted file mode 100644 index 9415f37a66..0000000000 --- a/js/tbl_tracking.js +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Unbind all event handlers before tearing down the page - */ -AJAX.registerTeardown('tbl_tracking.js', function () { - $('body').off('click', '#versionsForm.ajax button[name="submit_mult"], #versionsForm.ajax input[name="submit_mult"]'); - $('body').off('click', 'a.delete_version_anchor.ajax'); - $('body').off('click', 'a.delete_entry_anchor.ajax'); -}); - -/** - * Bind event handlers - */ -AJAX.registerOnload('tbl_tracking.js', function () { - $('#versions tr:first th').append($('<div class="sorticon"></div>')); - $('#versions').tablesorter({ - sortList: [[1, 0]], - headers: { - 0: { sorter: false }, - 1: { sorter: 'integer' }, - 5: { sorter: false }, - 6: { sorter: false } - } - }); - - if ($('#ddl_versions tbody tr').length > 0) { - $('#ddl_versions tr:first th').append($('<div class="sorticon"></div>')); - $('#ddl_versions').tablesorter({ - sortList: [[0, 0]], - headers: { - 0: { sorter: 'integer' }, - 3: { sorter: false }, - 4: { sorter: false } - } - }); - } - - if ($('#dml_versions tbody tr').length > 0) { - $('#dml_versions tr:first th').append($('<div class="sorticon"></div>')); - $('#dml_versions').tablesorter({ - sortList: [[0, 0]], - headers: { - 0: { sorter: 'integer' }, - 3: { sorter: false }, - 4: { sorter: false } - } - }); - } - - /** - * Handles multi submit for tracking versions - */ - $('body').on('click', '#versionsForm.ajax button[name="submit_mult"], #versionsForm.ajax input[name="submit_mult"]', function (e) { - e.preventDefault(); - var $button = $(this); - var $form = $button.parent('form'); - var argsep = PMA_commonParams.get('arg_separator'); - var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val(); - - if ($button.val() === 'delete_version') { - var question = PMA_messages.strDeleteTrackingVersionMultiple; - $button.PMA_confirm(question, $form.attr('action'), function (url) { - PMA_ajaxShowMessage(); - AJAX.source = $form; - $.post(url, submitData, AJAX.responseHandler); - }); - } else { - PMA_ajaxShowMessage(); - AJAX.source = $form; - $.post($form.attr('action'), submitData, AJAX.responseHandler); - } - }); - - /** - * Ajax Event handler for 'Delete version' - */ - $('body').on('click', 'a.delete_version_anchor.ajax', function (e) { - e.preventDefault(); - var $anchor = $(this); - var question = PMA_messages.strDeleteTrackingVersion; - $anchor.PMA_confirm(question, $anchor.attr('href'), function (url) { - PMA_ajaxShowMessage(); - AJAX.source = $anchor; - var params = { - 'ajax_page_request': true, - 'ajax_request': true - }; - $.post(url, params, AJAX.responseHandler); - }); - }); - - /** - * Ajax Event handler for 'Delete tracking report entry' - */ - $('body').on('click', 'a.delete_entry_anchor.ajax', function (e) { - e.preventDefault(); - var $anchor = $(this); - var question = PMA_messages.strDeletingTrackingEntry; - $anchor.PMA_confirm(question, $anchor.attr('href'), function (url) { - PMA_ajaxShowMessage(); - AJAX.source = $anchor; - var params = { - 'ajax_page_request': true, - 'ajax_request': true - }; - $.post(url, params, AJAX.responseHandler); - }); - }); -}); diff --git a/libraries/tbl_columns_definition_form.inc.php b/libraries/tbl_columns_definition_form.inc.php index b35cb52c59..9939eae5cf 100644 --- a/libraries/tbl_columns_definition_form.inc.php +++ b/libraries/tbl_columns_definition_form.inc.php @@ -501,10 +501,5 @@ $html = $template->render('columns_definitions/column_definitions_form', [ unset($form_params); $response = Response::getInstance(); -$response->getHeader()->getScripts()->addFiles( - [ - 'vendor/jquery/jquery.uitablefilter.js', - 'indexes.js' - ] -); +$response->getHeader()->getScripts()->addFiles('indexes'); $response->addHTML($html); diff --git a/tbl_addfield.php b/tbl_addfield.php index 04ecb80dad..7ec1d9323a 100644 --- a/tbl_addfield.php +++ b/tbl_addfield.php @@ -22,7 +22,7 @@ require_once 'libraries/common.inc.php'; $response = Response::getInstance(); $header = $response->getHeader(); $scripts = $header->getScripts(); -$scripts->addFile('tbl_structure.js'); +$scripts->addFile('tbl_structure'); // Check parameters Util::checkParameters(['db', 'table']); |