From d1e44771911b78bdfc033bbe150b68cd11eb4d31 Mon Sep 17 00:00:00 2001 From: Piyush Vijay Date: Mon, 20 Aug 2018 06:40:10 +0530 Subject: [PATCH 1/8] Sync the branch with master. Remove server related files for code cleanup. Signed-Off-By: Piyush Vijay --- js/server_databases.js | 149 --- js/server_plugins.js | 16 - js/server_privileges.js | 426 ------- js/server_status_advisor.js | 101 -- js/server_status_monitor.js | 2180 --------------------------------- js/server_status_processes.js | 187 --- js/server_status_queries.js | 34 - js/server_status_sorter.js | 70 -- js/server_status_variables.js | 100 -- js/server_user_groups.js | 41 - js/server_variables.js | 112 -- 11 files changed, 3416 deletions(-) delete mode 100644 js/server_databases.js delete mode 100644 js/server_plugins.js delete mode 100644 js/server_privileges.js delete mode 100644 js/server_status_advisor.js delete mode 100644 js/server_status_monitor.js delete mode 100644 js/server_status_processes.js delete mode 100644 js/server_status_queries.js delete mode 100644 js/server_status_sorter.js delete mode 100644 js/server_status_variables.js delete mode 100644 js/server_user_groups.js delete mode 100644 js/server_variables.js 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( - $('
').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('
')); - - 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('
'); -}); 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 = $('
') - .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 = $('
') - .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 = $('
') - .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 = $('
    ').prop('id', 'topmenu2'); - - $('#edit_user_dialog .submenu-item').each(function () { - submenu_label = $(this).find('legend[data-submenu-label]').data('submenu-label'); - - submenu_link = $('') - .prop('href', '#') - .html(submenu_label); - - $('
  • ') - .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 = $('
    ').attr('id', 'advisorDialog'); - var $instructionsDialog = $('
    ') - .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('Rules file not well formed, following errors were found:
    - '); - $cnt.append(data.parse.errors.join('
    - ')); - $cnt.append('

    '); - } - - if (data.run.errors.length > 0) { - $cnt.append('Errors occurred while executing rule expressions:
    - '); - $cnt.append(data.run.errors.join('
    - ')); - $cnt.append('

    '); - } - - if (data.run.fired.length > 0) { - $cnt.append('

    ' + PMA_messages.strPerformanceIssues + '

    '); - $cnt.append('' + - '
    ' + PMA_messages.strIssuse + '' + PMA_messages.strRecommendation + - '
    '); - $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($('
    ').html(value.recommendation).text()); - $tbody.append($tr = $('' + - value.issue + '' + rc_stripped + ' ')); - even = !even; - $tr.data('rule', value); - - $tr.on('click', function () { - var rule = $(this).data('rule'); - $dialog - .dialog({ title: PMA_messages.strRuleDetails }) - .html( - '

    ' + PMA_messages.strIssuse + ':
    ' + rule.issue + '

    ' + - '

    ' + PMA_messages.strRecommendation + ':
    ' + rule.recommendation + '

    ' + - '

    ' + PMA_messages.strJustification + ':
    ' + rule.justification + '

    ' + - '

    ' + PMA_messages.strFormula + ':
    ' + rule.formula + '

    ' + - '

    ' + PMA_messages.strTest + ':
    ' + rule.test + '

    ' - ); - - 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 () { - $('
    ') - .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.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(''); - }); - $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('' + PMA_messages.strNone + ''); - - 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 + ':
    ' + - '
    '); - - 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 = '' + PMA_messages.strCurrentSettings + '
    '; - str += icon + msg + '
    '; - - if (logVars.log_output !== 'TABLE') { - str += PMA_getImage('s_error') + ' ' + PMA_messages.strLogOutNotTable + '
    '; - } else { - str += PMA_getImage('s_success') + ' ' + PMA_messages.strLogOutIsTable + '
    '; - } - - 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 += '
    '; - } - - if (logVars.long_query_time < 2) { - str += PMA_getImage('s_success') + ' '; - str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time); - str += '
    '; - } - } - - str += '
    '; - - if (is_superuser) { - str += '

    ' + PMA_messages.strChangeSettings + ''; - str += '
    '; - - $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('' + PMA_messages.strNone + ''); - 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) + '
    '); - 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(''); - 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(''); - } - - // 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(''); - } - - if (!chartSize) { - calculateChartSize(); - } - $('#chartGrid').find('tr:last').append( - '
    ' + - '
    ' + - '
    ' - ); - } - - // 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 = '
    '; - // x value i.e. time - var timeValue = str.split(',')[0]; - var seriesValue; - tooltipHtml += 'Time: ' + timeValue; - tooltipHtml += ''; - // 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 += '
    ' + - seriesLabel + ': ' + seriesValue + ''; - } - tooltipHtml += '
    '; - 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 = $('
    ').css('padding', '0.5em'); - for (i in chartObj.chart.series) { - $legend.append( - $('
    ').append( - $('
    ').css({ - width: '1em', - height: '1em', - background: chartObj.chart.seriesColors[i] - }).addClass('floatleft') - ).append( - $('
    ').text( - chartObj.chart.series[i].label - ).addClass('floatleft') - ).append( - $('
    ') - ).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 = $('
    '); - $(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 + - ' '); - 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('

    ' + PMA_messages.strNoDataFound + '

    '); - - 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('

    ' + PMA_messages.strLogDataLoaded + '

    '); - $.each(logData.sum, function (key, value) { - key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase(); - if (key === 'Total') { - key = '' + key + ''; - } - $('#emptyDialog').append(key + ': ' + value + '
    '); - }); - - /* Add filter options if more than a bunch of rows there to filter */ - if (logData.numRows > 12) { - $('#logTable').prepend( - '
    ' + - ' ' + PMA_messages.strFiltersForLogTable + '' + - '
    ' + - ' ' + - ' ' + - '
    ' + - ((logData.numRows > 250) ? '
    ' : '') + - '
    ' + - ' ' + - ' ' + - ' ' - ); - - $('#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>/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>)/gi, '')); - columnSums[query][1] += timeToSec(cells[3].replace(/(|<\/td>)/gi, '')); - // rows_examind and rows_sent are just numbers - columnSums[query][2] += parseInt(cells[4].replace(/(|<\/td>)/gi, ''), 10); - columnSums[query][3] += parseInt(cells[5].replace(/(|<\/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('' + - PMA_messages.strSumRows + ' ' + rowSum + '' + - PMA_messages.strTotal + '' + totalSum + ''); - } - } - - /* 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 = $('
    '); - 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('' + - '' + cols.join('') + '' + - '' - ); - - $table.append($tBody = $('')); - } - - $tBody.append($tRow = $('')); - 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 = $('' + formatValue(cols[j], rows[i][cols[j]]) + '')); - $tCell.on('click', openQueryAnalyzer); - } else { - $tRow.append('' + formatValue(cols[j], rows[i][cols[j]]) + ''); - } - - $tRow.data('query', rows[i]); - } - } - - $table.append('' + - '' + PMA_messages.strSumRows + - ' ' + data.numRows + '' + PMA_messages.strTotal + - '' + data.sum.TOTAL + ''); - - // 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 += '

    ' + PMA_messages.strMoreCountColumnExplanation + '

    '; - } - - PMA_tooltip( - $('img.qroupedQueryInfoIcon'), - 'img', - tooltipContent - ); - } - - $('#logTable').find('table').tablesorter({ - sortList: [[cols.length - 1, 1]], - widgets: ['fast-zebra'] - }); - - $('#logTable').find('table thead th') - .append('
    '); - - 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 + ' '); - - $.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('
    ' + data.error + '
    '); - return; - } - var totalTime = 0; - // Float sux, I'll use table :( - $('#queryAnalyzerDialog').find('div.placeHolder') - .html('
    '); - - var explain = '' + PMA_messages.strExplainOutput + ' ' + $('#explain_docu').html(); - if (data.explain.length > 1) { - explain += ' ('; - for (i = 0; i < data.explain.length; i++) { - if (i > 0) { - explain += ', '; - } - explain += '' + i + ''; - } - explain += ')'; - } - explain += '

    '; - - var tempExplain = function (key, value) { - value = (value === null) ? 'null' : escapeHtml(value); - - if (key === 'type' && value.toLowerCase() === 'all') { - value = '' + value + ''; - } - if (key === 'Extra') { - value = value.replace(/(using (temporary|filesort))/gi, '$1'); - } - explain += key + ': ' + value + '
    '; - }; - - for (i = 0, l = data.explain.length; i < l; i++) { - explain += '
    0 ? 'style="display:none;"' : '') + '>'; - $.each(data.explain[i], tempExplain); - explain += '
    '; - } - - explain += '

    ' + PMA_messages.strAffectedRows + ' ' + 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 = ''; - var duration; - var otherTime = 0; - - for (i = 0, l = data.profiling.length; i < l; i++) { - duration = parseFloat(data.profiling[i].duration); - - totalTime += duration; - - numberTable += ''; - } - - // 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 += ''; - numberTable += '
    ' + PMA_messages.strStatus + '' + PMA_messages.strTime + '
    ' + data.profiling[i].state + ' ' + PMA_prettyProfilingNum(duration, 2) + '
    ' + PMA_messages.strTotalTime + '' + PMA_prettyProfilingNum(totalTime, 2) + '
    '; - - $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append( - '' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + ' ' + - '(' + PMA_messages.strTable + ', ' + PMA_messages.strChart + ')
    ' + - numberTable + '

    '); - - $('#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('
    '); -} - -$(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>/); - 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'); - }; - $('
    ') - .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 = $('
    ') - .append($myCancelLink) - .append('   ') - .append($mySaveLink); - var $editor = $('
    ', { 'class': 'serverVariableEditor' }) - .append( - $('
    ').append( - $('', { 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); - } - }); - } -}); From f7b33b00e94a0e95e78088030623171388689644 Mon Sep 17 00:00:00 2001 From: Piyush Vijay Date: Mon, 20 Aug 2018 06:53:01 +0530 Subject: [PATCH 2/8] Code restructuring and comments for serve related files. Signed-Off-By: Piyush Vijay --- js/src/classes/Server/ProcessList.js | 23 ++++-- .../functions/Server/ServerStatusMonitor.js | 71 +++++++++++-------- ...rStatusSorter.js => ServerStatusSorter.js} | 1 + js/src/server_databases.js | 10 +-- js/src/server_privileges.js | 12 ++-- js/src/server_status_monitor.js | 15 ++-- js/src/server_status_queries.js | 4 +- js/src/server_user_groups.js | 2 +- js/src/server_variables.js | 4 +- 9 files changed, 86 insertions(+), 56 deletions(-) rename js/src/functions/Server/{SeverStatusSorter.js => ServerStatusSorter.js} (99%) 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/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 similarity index 99% rename from js/src/functions/Server/SeverStatusSorter.js rename to 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/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 { 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 { checkPasswordStrength, displayPasswordGenerateButton } from './utils/password'; +import CommonParams from './variables/common_params'; +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'; -import { $ } from './utils/JqueryExtended'; +/** + * 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 From 181bfb58494e7bede25a00c5185db558e49611e7 Mon Sep 17 00:00:00 2001 From: Piyush Vijay Date: Tue, 21 Aug 2018 05:25:53 +0530 Subject: [PATCH 3/8] Remove table related files not needed in modular code. Signed-Off-By: Piyush Vijay --- js/src/tbl_structure.js | 5 +- js/tbl_change.js | 708 ---------------------------------------- js/tbl_chart.js | 423 ------------------------ js/tbl_find_replace.js | 46 --- js/tbl_operations.js | 325 ------------------ js/tbl_relation.js | 241 -------------- js/tbl_select.js | 413 ----------------------- js/tbl_structure.js | 506 ---------------------------- js/tbl_tracking.js | 108 ------ 9 files changed, 1 insertion(+), 2774 deletions(-) delete mode 100644 js/tbl_change.js delete mode 100644 js/tbl_chart.js delete mode 100644 js/tbl_find_replace.js delete mode 100644 js/tbl_operations.js delete mode 100644 js/tbl_relation.js delete mode 100644 js/tbl_select.js delete mode 100644 js/tbl_structure.js delete mode 100644 js/tbl_tracking.js diff --git a/js/src/tbl_structure.js b/js/src/tbl_structure.js index f65d3a0be5..03ae2cfdf9 100644 --- a/js/src/tbl_structure.js +++ b/js/src/tbl_structure.js @@ -438,10 +438,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/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 = '
    '; - - // 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][] - */ - - /** - * @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) { - $('') - .insertBefore('table.insertRowTable:last') - .after(''); - } 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); - - $('
    ') - .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'); - - $('
    ') - .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 () { - $('
    ') - .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); - $('
    ').prependTo('#page_content'); - $('.sqlqueryresults').html(data.sql_query); - PMA_highlightSQL($('#page_content')); - scrollToTop(); - } else if (typeof data !== 'undefined' && data.success === true) { - $temp_div = $('
    '); - $temp_div.html(data.message); - var $success = $temp_div.find('.result_query .success'); - PMA_ajaxShowMessage($success); - $('
    ').prependTo('#page_content'); - $('.sqlqueryresults').html(data.message); - PMA_highlightSQL($('#page_content')); - PMA_init_slider(); - $('.sqlqueryresults').children('fieldset,br').remove(); - scrollToTop(); - } else { - $temp_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); - $('
    ').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 += ''; - }); - $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 - */ - $('
    ') - .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. - $('
    ').append( - '
    ' + - '' + operator + '' + - '' + - '' + '
    ' + - '' + min + '' + '
    ' + - '' + - '' + '
    ' + - '' + max + '' + - '
    ' - ).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 = $('
    ').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) { - $('
    ') - .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 = $('') - .prop({ - name: 'move_columns[]', - type: 'hidden' - }) - .val(col_name); - columns[columns.length] = $('
  • ') - .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($('
    ')); - $('#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($('
    ')); - $('#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($('
    ')); - $('#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); - }); - }); -}); From bb72bc2ddcb74d88ae1fa4367b394266123b1b96 Mon Sep 17 00:00:00 2001 From: Piyush Vijay Date: Tue, 21 Aug 2018 05:44:55 +0530 Subject: [PATCH 4/8] Some code structuring for table related files. Signed-Off-By: Piyush Vijay --- js/src/functions/Table/CreateTable.js | 10 +++++-- js/src/functions/Table/Relation.js | 10 +++++-- js/src/functions/Table/TableChange.js | 31 +++++++++++-------- js/src/functions/Table/TableChart.js | 5 ++++ js/src/functions/Table/TableColumns.js | 6 ++++ js/src/functions/Table/TableSelect.js | 5 ++++ js/src/functions/Table/TableStructure.js | 28 +++++++++++++++++ js/src/tbl_change.js | 29 +++++++++--------- js/src/tbl_chart.js | 4 +++ js/src/tbl_find_replace.js | 15 ++++++---- js/src/tbl_operations.js | 33 +++++++++++--------- js/src/tbl_relation.js | 12 +++++--- js/src/tbl_select.js | 38 +++++++++++++----------- js/src/tbl_structure.js | 38 ++++++++---------------- js/src/tbl_tracking.js | 9 ++++-- 15 files changed, 173 insertions(+), 100 deletions(-) create mode 100644 js/src/functions/Table/TableStructure.js 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 = $('
    ').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/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 () { $('
    ').append( '
    ' + '' + operator + '' + - '