One Hat Cyber Team
  • Dir : ~/proc/self/root/usr/share/phpmyadmin/js/dist/
  • View File Name : functions.js
    \n'; newContent += Functions.getForeignKeyCheckboxLoader(); newContent += '\n'; newContent += '\n'; var $editorArea = $('div#inline_editor'); if ($editorArea.length === 0) { $editorArea = $('
    '); $editorArea.insertBefore($innerSql); } $editorArea.html(newContent); Functions.loadForeignKeyCheckbox(); $innerSql.hide(); Functions.bindCodeMirrorToInlineEditor(); return false; }); $(document).on('click', 'input#sql_query_edit_save', function () { // hide already existing success message var sqlQuery; if (codeMirrorInlineEditor) { codeMirrorInlineEditor.save(); sqlQuery = codeMirrorInlineEditor.getValue(); } else { sqlQuery = $(this).parent().find('#sql_query_edit').val(); } var fkCheck = $(this).parent().find('#fk_checks').is(':checked'); var $form = $('a.inline_edit_sql').prev('form'); var $fakeForm = $('
    ', { action: 'index.php?route=/import', method: 'post' }).append($form.find('input[name=server], input[name=db], input[name=table], input[name=token]').clone()).append($('', { type: 'hidden', name: 'show_query', value: 1 })).append($('', { type: 'hidden', name: 'is_js_confirmed', value: 0 })).append($('', { type: 'hidden', name: 'sql_query', value: sqlQuery })).append($('', { type: 'hidden', name: 'fk_checks', value: fkCheck ? 1 : 0 })); if (!Functions.checkSqlQuery($fakeForm[0])) { return false; } $('.alert-success').hide(); $fakeForm.appendTo($('body')).trigger('submit'); }); $(document).on('click', 'input#sql_query_edit_discard', function () { var $divEditor = $('div#inline_editor_outer'); $divEditor.siblings('code.sql').show(); $divEditor.remove(); }); $(document).on('click', 'input.sqlbutton', function (evt) { Functions.insertQuery(evt.target.id); Functions.handleSimulateQueryButton(); return false; }); $(document).on('change', '#parameterized', Functions.updateQueryParameters); var $inputUsername = $('#input_username'); if ($inputUsername) { if ($inputUsername.val() === '') { $inputUsername.trigger('focus'); } else { $('#input_password').trigger('focus'); } } }); /** * "inputRead" event handler for CodeMirror SQL query editors for autocompletion */ Functions.codeMirrorAutoCompleteOnInputRead = function (instance) { if (!sqlAutoCompleteInProgress && (!instance.options.hintOptions.tables || !sqlAutoComplete)) { if (!sqlAutoComplete) { // Reset after teardown instance.options.hintOptions.tables = false; instance.options.hintOptions.defaultTable = ''; sqlAutoCompleteInProgress = true; var params = { 'ajax_request': true, 'server': CommonParams.get('server'), 'db': CommonParams.get('db'), 'no_debug': true }; var columnHintRender = function columnHintRender(elem, self, data) { $('
    ').text(data.columnName).appendTo(elem); $('
    ').text(data.columnHint).appendTo(elem); }; $.ajax({ type: 'POST', url: 'index.php?route=/database/sql/autocomplete', data: params, success: function success(data) { if (data.success) { var tables = JSON.parse(data.tables); sqlAutoCompleteDefaultTable = CommonParams.get('table'); sqlAutoComplete = []; for (var table in tables) { if (tables.hasOwnProperty(table)) { var columns = tables[table]; table = { text: table, columns: [] }; for (var column in columns) { if (columns.hasOwnProperty(column)) { var displayText = columns[column].Type; if (columns[column].Key === 'PRI') { displayText += ' | Primary'; } else if (columns[column].Key === 'UNI') { displayText += ' | Unique'; } table.columns.push({ text: column, displayText: column + ' | ' + displayText, columnName: column, columnHint: displayText, render: columnHintRender }); } } } sqlAutoComplete.push(table); } instance.options.hintOptions.tables = sqlAutoComplete; instance.options.hintOptions.defaultTable = sqlAutoCompleteDefaultTable; } }, complete: function complete() { sqlAutoCompleteInProgress = false; } }); } else { instance.options.hintOptions.tables = sqlAutoComplete; instance.options.hintOptions.defaultTable = sqlAutoCompleteDefaultTable; } } if (instance.state.completionActive) { return; } var cur = instance.getCursor(); var token = instance.getTokenAt(cur); var string = ''; if (token.string.match(/^[.`\w@]\w*$/)) { string = token.string; } if (string.length > 0) { CodeMirror.commands.autocomplete(instance); } }; /** * Remove autocomplete information before tearing down a page */ AJAX.registerTeardown('functions.js', function () { sqlAutoComplete = false; sqlAutoCompleteDefaultTable = ''; }); /** * Binds the CodeMirror to the text area used to inline edit a query. */ Functions.bindCodeMirrorToInlineEditor = function () { var $inlineEditor = $('#sql_query_edit'); if ($inlineEditor.length > 0) { if (typeof CodeMirror !== 'undefined') { var height = $inlineEditor.css('height'); codeMirrorInlineEditor = Functions.getSqlEditor($inlineEditor); codeMirrorInlineEditor.getWrapperElement().style.height = height; codeMirrorInlineEditor.refresh(); codeMirrorInlineEditor.focus(); $(codeMirrorInlineEditor.getWrapperElement()).on('keydown', Functions.catchKeypressesFromSqlInlineEdit); } else { $inlineEditor.trigger('focus').on('keydown', Functions.catchKeypressesFromSqlInlineEdit); } } }; Functions.catchKeypressesFromSqlInlineEdit = function (event) { // ctrl-enter is 10 in chrome and ie, but 13 in ff if ((event.ctrlKey || event.metaKey) && (event.keyCode === 13 || event.keyCode === 10)) { $('#sql_query_edit_save').trigger('click'); } }; /** * Adds doc link to single highlighted SQL element */ Functions.documentationAdd = function ($elm, params) { if (typeof mysqlDocTemplate === 'undefined') { return; } var url = Functions.sprintf(decodeURIComponent(mysqlDocTemplate), params[0]); if (params.length > 1) { url += '#' + params[1]; } var content = $elm.text(); $elm.text(''); $elm.append('' + content + ''); }; /** * Generates doc links for keywords inside highlighted SQL */ Functions.documentationKeyword = function (idx, elm) { var $elm = $(elm); /* Skip already processed ones */ if ($elm.find('a').length > 0) { return; } var keyword = $elm.text().toUpperCase(); var $next = $elm.next('.cm-keyword'); if ($next) { var nextKeyword = $next.text().toUpperCase(); var full = keyword + ' ' + nextKeyword; var $next2 = $next.next('.cm-keyword'); if ($next2) { var next2Keyword = $next2.text().toUpperCase(); var full2 = full + ' ' + next2Keyword; if (full2 in mysqlDocKeyword) { Functions.documentationAdd($elm, mysqlDocKeyword[full2]); Functions.documentationAdd($next, mysqlDocKeyword[full2]); Functions.documentationAdd($next2, mysqlDocKeyword[full2]); return; } } if (full in mysqlDocKeyword) { Functions.documentationAdd($elm, mysqlDocKeyword[full]); Functions.documentationAdd($next, mysqlDocKeyword[full]); return; } } if (keyword in mysqlDocKeyword) { Functions.documentationAdd($elm, mysqlDocKeyword[keyword]); } }; /** * Generates doc links for builtins inside highlighted SQL */ Functions.documentationBuiltin = function (idx, elm) { var $elm = $(elm); var builtin = $elm.text().toUpperCase(); if (builtin in mysqlDocBuiltin) { Functions.documentationAdd($elm, mysqlDocBuiltin[builtin]); } }; /** * Higlights SQL using CodeMirror. */ Functions.highlightSql = function ($base) { var $elm = $base.find('code.sql'); $elm.each(function () { var $sql = $(this); var $pre = $sql.find('pre'); /* We only care about visible elements to avoid double processing */ if ($pre.is(':visible')) { var $highlight = $('
    '); $sql.append($highlight); if (typeof CodeMirror !== 'undefined') { CodeMirror.runMode($sql.text(), 'text/x-mysql', $highlight[0]); $pre.hide(); $highlight.find('.cm-keyword').each(Functions.documentationKeyword); $highlight.find('.cm-builtin').each(Functions.documentationBuiltin); } } }); }; /** * Updates an element containing code. * * @param jQuery Object $base base element which contains the raw and the * highlighted code. * * @param string htmlValue code in HTML format, displayed if code cannot be * highlighted * * @param string rawValue raw code, used as a parameter for highlighter * * @return bool whether content was updated or not */ Functions.updateCode = function ($base, htmlValue, rawValue) { var $code = $base.find('code'); if ($code.length === 0) { return false; } // Determines the type of the content and appropriate CodeMirror mode. var type = ''; var mode = ''; if ($code.hasClass('json')) { type = 'json'; mode = 'application/json'; } else if ($code.hasClass('sql')) { type = 'sql'; mode = 'text/x-mysql'; } else if ($code.hasClass('xml')) { type = 'xml'; mode = 'application/xml'; } else { return false; } // Element used to display unhighlighted code. var $notHighlighted = $('
    ' + htmlValue + '
    '); // Tries to highlight code using CodeMirror. if (typeof CodeMirror !== 'undefined') { var $highlighted = $('
    '); CodeMirror.runMode(rawValue, mode, $highlighted[0]); $notHighlighted.hide(); $code.html('').append($notHighlighted, $highlighted[0]); } else { $code.html('').append($notHighlighted); } return true; }; /** * Show a message on the top of the page for an Ajax request * * Sample usage: * * 1) var $msg = Functions.ajaxShowMessage(); * This will show a message that reads "Loading...". Such a message will not * disappear automatically and cannot be dismissed by the user. To remove this * message either the Functions.ajaxRemoveMessage($msg) function must be called or * another message must be show with Functions.ajaxShowMessage() function. * * 2) var $msg = Functions.ajaxShowMessage(Messages.strProcessingRequest); * This is a special case. The behaviour is same as above, * just with a different message * * 3) var $msg = Functions.ajaxShowMessage('The operation was successful'); * This will show a message that will disappear automatically and it can also * be dismissed by the user. * * 4) var $msg = Functions.ajaxShowMessage('Some error', false); * This will show a message that will not disappear automatically, but it * can be dismissed by the user after they have finished reading it. * * @param string message string containing the message to be shown. * optional, defaults to 'Loading...' * @param mixed timeout number of milliseconds for the message to be visible * optional, defaults to 5000. If set to 'false', the * notification will never disappear * @param string type string to dictate the type of message shown. * optional, defaults to normal notification. * If set to 'error', the notification will show message * with red background. * If set to 'success', the notification will show with * a green background. * @return jQuery object jQuery Element that holds the message div * this object can be passed to Functions.ajaxRemoveMessage() * to remove the notification */ Functions.ajaxShowMessage = function (message, timeout, type) { var msg = message; var newTimeOut = timeout; /** * @var self_closing Whether the notification will automatically disappear */ var selfClosing = true; /** * @var dismissable Whether the user will be able to remove * the notification by clicking on it */ var dismissable = true; // Handle the case when a empty data.message is passed. // We don't want the empty message if (msg === '') { return true; } else if (!msg) { // If the message is undefined, show the default msg = Messages.strLoading; dismissable = false; selfClosing = false; } else if (msg === Messages.strProcessingRequest) { // This is another case where the message should not disappear dismissable = false; selfClosing = false; } // Figure out whether (or after how long) to remove the notification if (newTimeOut === undefined) { newTimeOut = 5000; } else if (newTimeOut === false) { selfClosing = false; } // Determine type of message, add styling as required if (type === 'error') { msg = ''; } else if (type === 'success') { msg = ''; } // Create a parent element for the AJAX messages, if necessary if ($('#loading_parent').length === 0) { $('
    ').prependTo('#page_content'); } // Update message count to create distinct message elements every time ajaxMessageCount++; // Remove all old messages, if any $('span.ajax_notification[id^=ajax_message_num]').remove(); /** * @var $retval a jQuery object containing the reference * to the created AJAX message */ var $retval = $('').hide().appendTo('#loading_parent').html(msg).show(); // If the notification is self-closing we should create a callback to remove it if (selfClosing) { $retval.delay(newTimeOut).fadeOut('medium', function () { if ($(this).is(':data(tooltip)')) { $(this).tooltip('destroy'); } // Remove the notification $(this).remove(); }); } // If the notification is dismissable we need to add the relevant class to it // and add a tooltip so that the users know that it can be removed if (dismissable) { $retval.addClass('dismissable').css('cursor', 'pointer'); /** * Add a tooltip to the notification to let the user know that they * can dismiss the ajax notification by clicking on it. */ Functions.tooltip($retval, 'span', Messages.strDismiss); } // Hide spinner if this is not a loading message if (msg !== Messages.strLoading) { $retval.css('background-image', 'none'); } Functions.highlightSql($retval); return $retval; }; /** * Removes the message shown for an Ajax operation when it's completed * * @param jQuery object jQuery Element that holds the notification * * @return nothing */ Functions.ajaxRemoveMessage = function ($thisMessageBox) { if ($thisMessageBox !== undefined && $thisMessageBox instanceof jQuery) { $thisMessageBox.stop(true, true).fadeOut('medium'); if ($thisMessageBox.is(':data(tooltip)')) { $thisMessageBox.tooltip('destroy'); } else { $thisMessageBox.remove(); } } }; /** * Requests SQL for previewing before executing. * * @param jQuery Object $form Form containing query data * * @return void */ Functions.previewSql = function ($form) { var formUrl = $form.attr('action'); var sep = CommonParams.get('arg_separator'); var formData = $form.serialize() + sep + 'do_save_data=1' + sep + 'preview_sql=1' + sep + 'ajax_request=1'; var $messageBox = Functions.ajaxShowMessage(); $.ajax({ type: 'POST', url: formUrl, data: formData, success: function success(response) { Functions.ajaxRemoveMessage($messageBox); if (response.success) { var $dialogContent = $('
    ').append(response.sql_data); var buttonOptions = {}; buttonOptions[Messages.strClose] = function () { $(this).dialog('close'); }; $dialogContent.dialog({ minWidth: 550, maxHeight: 400, modal: true, buttons: buttonOptions, title: Messages.strPreviewSQL, close: function close() { $(this).remove(); }, open: function open() { // Pretty SQL printing. Functions.highlightSql($(this)); } }); } else { Functions.ajaxShowMessage(response.message); } }, error: function error() { Functions.ajaxShowMessage(Messages.strErrorProcessingRequest); } }); }; /** * Callback called when submit/"OK" is clicked on sql preview/confirm modal * * @callback onSubmitCallback * @param {string} url The url */ /** * * @param {string} sqlData Sql query to preview * @param {string} url Url to be sent to callback * @param {onSubmitCallback} callback On submit callback function * * @return void */ Functions.confirmPreviewSql = function (sqlData, url, callback) { var $dialogContent = $('
    ' + sqlData + '
    '); var buttonOptions = [{ text: Messages.strOK, class: 'submitOK', click: function click() { callback(url); } }, { text: Messages.strCancel, class: 'submitCancel', click: function click() { $(this).dialog('close'); } }]; $dialogContent.dialog({ minWidth: 550, maxHeight: 400, modal: true, buttons: buttonOptions, title: Messages.strPreviewSQL, close: function close() { $(this).remove(); }, open: function open() { // Pretty SQL printing. Functions.highlightSql($(this)); } }); }; /** * check for reserved keyword column name * * @param jQuery Object $form Form * * @returns true|false */ Functions.checkReservedWordColumns = function ($form) { var isConfirmed = true; $.ajax({ type: 'POST', url: 'index.php?route=/table/structure/reserved-word-check', data: $form.serialize(), success: function success(data) { if (typeof data.success !== 'undefined' && data.success === true) { isConfirmed = confirm(data.message); } }, async: false }); return isConfirmed; }; // This event only need to be fired once after the initial page load $(function () { /** * Allows the user to dismiss a notification * created with Functions.ajaxShowMessage() */ var holdStarter = null; $(document).on('mousedown', 'span.ajax_notification.dismissable', function () { holdStarter = setTimeout(function () { holdStarter = null; }, 250); }); $(document).on('mouseup', 'span.ajax_notification.dismissable', function (event) { if (holdStarter && event.which === 1) { clearTimeout(holdStarter); Functions.ajaxRemoveMessage($(this)); } }); /** * The below two functions hide the "Dismiss notification" tooltip when a user * is hovering a link or button that is inside an ajax message */ $(document).on('mouseover', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () { if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) { $(this).parents('span.ajax_notification').tooltip('disable'); } }); $(document).on('mouseout', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () { if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) { $(this).parents('span.ajax_notification').tooltip('enable'); } }); /** * Copy text to clipboard * * @param text to copy to clipboard * * @returns bool true|false */ function copyToClipboard(text) { var $temp = $(''); $temp.css({ 'position': 'fixed', 'width': '2em', 'border': 0, 'top': 0, 'left': 0, 'padding': 0, 'background': 'transparent' }); $('body').append($temp); $temp.val(text).trigger('select'); try { var res = document.execCommand('copy'); $temp.remove(); return res; } catch (e) { $temp.remove(); return false; } } $(document).on('click', 'a.copyQueryBtn', function (event) { event.preventDefault(); var res = copyToClipboard($(this).attr('data-text')); if (res) { $(this).after(' (' + Messages.strCopyQueryButtonSuccess + ')'); } else { $(this).after(' (' + Messages.strCopyQueryButtonFailure + ')'); } setTimeout(function () { $('#copyStatus').remove(); }, 2000); }); }); /** * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected */ Functions.showNoticeForEnum = function (selectElement) { var enumNoticeId = selectElement.attr('id').split('_')[1]; enumNoticeId += '_' + (parseInt(selectElement.attr('id').split('_')[2], 10) + 1); var selectedType = selectElement.val(); if (selectedType === 'ENUM' || selectedType === 'SET') { $('p#enum_notice_' + enumNoticeId).show(); } else { $('p#enum_notice_' + enumNoticeId).hide(); } }; /** * Creates a Profiling Chart. Used in sql.js * and in server/status/monitor.js */ Functions.createProfilingChart = function (target, data) { // create the chart var factory = new JQPlotChartFactory(); var chart = factory.createChart(ChartType.PIE, target); // create the data table and add columns var dataTable = new DataTable(); dataTable.addColumn(ColumnType.STRING, ''); dataTable.addColumn(ColumnType.NUMBER, ''); dataTable.setData(data); var windowWidth = $(window).width(); var location = 's'; if (windowWidth > 768) { location = 'se'; } // draw the chart and return the chart object chart.draw(dataTable, { seriesDefaults: { rendererOptions: { showDataLabels: true } }, highlighter: { tooltipLocation: 'se', sizeAdjust: 0, tooltipAxes: 'pieref', formatString: '%s, %.9Ps' }, legend: { show: true, location: location, rendererOptions: { numberColumns: 2 } }, // from https://web.archive.org/web/20190321233412/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines seriesColors: ['#fce94f', '#fcaf3e', '#e9b96e', '#8ae234', '#729fcf', '#ad7fa8', '#ef2929', '#888a85', '#c4a000', '#ce5c00', '#8f5902', '#4e9a06', '#204a87', '#5c3566', '#a40000', '#babdb6', '#2e3436'] }); return chart; }; /** * Formats a profiling duration nicely (in us and ms time). * Used in server/status/monitor.js * * @param integer Number to be formatted, should be in the range of microsecond to second * @param integer Accuracy, how many numbers right to the comma should be * @return string The formatted number */ Functions.prettyProfilingNum = function (number, accuracy) { var num = number; var acc = accuracy; if (!acc) { acc = 2; } acc = Math.pow(10, acc); if (num * 1000 < 0.1) { num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ'; } else if (num < 0.1) { num = Math.round(acc * (num * 1000)) / acc + 'm'; } else { num = Math.round(acc * num) / acc; } return num + 's'; }; /** * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode! * * @param string Query to be formatted * @return string The formatted query */ Functions.sqlPrettyPrint = function (string) { if (typeof CodeMirror === 'undefined') { return string; } var mode = CodeMirror.getMode({}, 'text/x-mysql'); var stream = new CodeMirror.StringStream(string); var state = mode.startState(); var token; var tokens = []; var output = ''; var tabs = function tabs(cnt) { var ret = ''; for (var i = 0; i < 4 * cnt; i++) { ret += ' '; } return ret; }; // "root-level" statements var statements = { 'select': ['select', 'from', 'on', 'where', 'having', 'limit', 'order by', 'group by'], 'update': ['update', 'set', 'where'], 'insert into': ['insert into', 'values'] }; // don't put spaces before these tokens var spaceExceptionsBefore = { ';': true, ',': true, '.': true, '(': true }; // don't put spaces after these tokens var spaceExceptionsAfter = { '.': true }; // Populate tokens array while (!stream.eol()) { stream.start = stream.pos; token = mode.token(stream, state); if (token !== null) { tokens.push([token, stream.current().toLowerCase()]); } } var currentStatement = tokens[0][1]; if (!statements[currentStatement]) { return string; } // Holds all currently opened code blocks (statement, function or generic) var blockStack = []; // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock var newBlock; var endBlock; // How much to indent in the current line var indentLevel = 0; // Holds the "root-level" statements var statementPart; var lastStatementPart = statements[currentStatement][0]; blockStack.unshift('statement'); // Iterate through every token and format accordingly for (var i = 0; i < tokens.length; i++) { // New block => push to stack if (tokens[i][1] === '(') { if (i < tokens.length - 1 && tokens[i + 1][0] === 'statement-verb') { blockStack.unshift(newBlock = 'statement'); } else if (i > 0 && tokens[i - 1][0] === 'builtin') { blockStack.unshift(newBlock = 'function'); } else { blockStack.unshift(newBlock = 'generic'); } } else { newBlock = null; } // Block end => pop from stack if (tokens[i][1] === ')') { endBlock = blockStack[0]; blockStack.shift(); } else { endBlock = null; } // A subquery is starting if (i > 0 && newBlock === 'statement') { indentLevel++; output += '\n' + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i + 1][1].toUpperCase() + '\n' + tabs(indentLevel + 1); currentStatement = tokens[i + 1][1]; i++; continue; } // A subquery is ending if (endBlock === 'statement' && indentLevel > 0) { output += '\n' + tabs(indentLevel); indentLevel--; } // One less indentation for statement parts (from, where, order by, etc.) and a newline statementPart = statements[currentStatement].indexOf(tokens[i][1]); if (statementPart !== -1) { if (i > 0) { output += '\n'; } output += tabs(indentLevel) + tokens[i][1].toUpperCase(); output += '\n' + tabs(indentLevel + 1); lastStatementPart = tokens[i][1]; // Normal indentation and spaces for everything else } else { if (!spaceExceptionsBefore[tokens[i][1]] && !(i > 0 && spaceExceptionsAfter[tokens[i - 1][1]]) && output.charAt(output.length - 1) !== ' ') { output += ' '; } if (tokens[i][0] === 'keyword') { output += tokens[i][1].toUpperCase(); } else { output += tokens[i][1]; } } // split columns in select and 'update set' clauses, but only inside statements blocks if ((lastStatementPart === 'select' || lastStatementPart === 'where' || lastStatementPart === 'set') && tokens[i][1] === ',' && blockStack[0] === 'statement') { output += '\n' + tabs(indentLevel + 1); } // split conditions in where clauses, but only inside statements blocks if (lastStatementPart === 'where' && (tokens[i][1] === 'and' || tokens[i][1] === 'or' || tokens[i][1] === 'xor')) { if (blockStack[0] === 'statement') { output += '\n' + tabs(indentLevel + 1); } // Todo: Also split and or blocks in newlines & indentation++ // if (blockStack[0] === 'generic') // output += ... } } return output; }; /** * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not * return a jQuery object yet and hence cannot be chained * * @param string question * @param string url URL to be passed to the callbackFn to make * an Ajax call to * @param function callbackFn callback to execute after user clicks on OK * @param function openCallback optional callback to run when dialog is shown */ Functions.confirm = function (question, url, callbackFn, openCallback) { var confirmState = CommonParams.get('confirm'); if (!confirmState) { // user does not want to confirm if (typeof callbackFn === 'function') { callbackFn.call(this, url); return true; } } if (Messages.strDoYouReally === '') { return true; } /** * @var button_options Object that stores the options passed to jQueryUI * dialog */ var buttonOptions = [{ text: Messages.strOK, 'class': 'submitOK', click: function click() { $(this).dialog('close'); if (typeof callbackFn === 'function') { callbackFn.call(this, url); } } }, { text: Messages.strCancel, 'class': 'submitCancel', click: function click() { $(this).dialog('close'); } }]; $('
    ', { 'id': 'confirm_dialog', 'title': Messages.strConfirm }).prepend(question).dialog({ buttons: buttonOptions, close: function close() { $(this).remove(); }, open: openCallback, modal: true }); }; jQuery.fn.confirm = Functions.confirm; /** * jQuery function to sort a table's body after a new row has been appended to it. * * @param string text_selector string to select the sortKey's text * * @return jQuery Object for chaining purposes */ Functions.sortTable = function (textSelector) { return this.each(function () { /** * @var table_body Object referring to the table's element */ var tableBody = $(this); /** * @var rows Object referring to the collection of rows in {@link tableBody} */ var rows = $(this).find('tr').get(); // get the text of the field that we will sort by $.each(rows, function (index, row) { row.sortKey = $(row).find(textSelector).text().toLowerCase().trim(); }); // get the sorted order rows.sort(function (a, b) { if (a.sortKey < b.sortKey) { return -1; } if (a.sortKey > b.sortKey) { return 1; } return 0; }); // pull out each row from the table and then append it according to it's order $.each(rows, function (index, row) { $(tableBody).append(row); row.sortKey = null; }); }); }; jQuery.fn.sortTable = Functions.sortTable; /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('functions.js', function () { $(document).off('submit', '#create_table_form_minimal.ajax'); $(document).off('submit', 'form.create_table_form.ajax'); $(document).off('click', 'form.create_table_form.ajax input[name=submit_num_fields]'); $(document).off('keyup', 'form.create_table_form.ajax input'); $(document).off('change', 'input[name=partition_count],input[name=subpartition_count],select[name=partition_by]'); }); /** * jQuery coding for 'Create Table'. Used on /database/operations, * /database/structure and /database/tracking (i.e., wherever * PhpMyAdmin\Display\CreateTable is used) * * Attach Ajax Event handlers for Create Table */ AJAX.registerOnload('functions.js', function () { /** * Attach event handler for submission of create table form (save) */ $(document).on('submit', 'form.create_table_form.ajax', function (event) { event.preventDefault(); /** * @var the_form object referring to the create table form */ var $form = $(this); /* * First validate the form; if there is a problem, avoid submitting it * * Functions.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 (Functions.checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) { Functions.prepareForAjaxRequest($form); if (Functions.checkReservedWordColumns($form)) { Functions.ajaxShowMessage(Messages.strProcessingRequest); // User wants to submit the form $.post($form.attr('action'), $form.serialize() + CommonParams.get('arg_separator') + 'do_save_data=1', function (data) { if (typeof data !== 'undefined' && data.success === true) { $('#properties_message').removeClass('alert-danger').html(''); Functions.ajaxShowMessage(data.message); // Only if the create table dialog (distinct panel) exists var $createTableDialog = $('#create_table_dialog'); if ($createTableDialog.length > 0) { $createTableDialog.dialog('close').remove(); } $('#tableslistcontainer').before(data.formatted_sql); /** * @var tables_table Object referring to the element that holds the list of tables */ var tablesTable = $('#tablesForm').find('tbody').not('#tbl_summary_row'); // this is the first table created in this db if (tablesTable.length === 0) { CommonActions.refreshMain(CommonParams.get('opendb_url')); } else { /** * @var curr_last_row Object referring to the last element in {@link tablesTable} */ var currLastRow = $(tablesTable).find('tr').last(); /** * @var curr_last_row_index_string String containing the index of {@link currLastRow} */ var currLastRowIndexString = $(currLastRow).find('input:checkbox').attr('id').match(/\d+/)[0]; /** * @var curr_last_row_index Index of {@link currLastRow} */ var currLastRowIndex = parseFloat(currLastRowIndexString); /** * @var new_last_row_index Index of the new row to be appended to {@link tablesTable} */ var newLastRowIndex = currLastRowIndex + 1; /** * @var new_last_row_id String containing the id of the row to be appended to {@link tablesTable} */ var newLastRowId = 'checkbox_tbl_' + newLastRowIndex; data.newTableString = data.newTableString.replace(/checkbox_tbl_/, newLastRowId); // append to table $(data.newTableString).appendTo(tablesTable); // Sort the table $(tablesTable).sortTable('th'); // Adjust summary row DatabaseStructure.adjustTotals(); } // Refresh navigation as a new table has been added Navigation.reload(); // Redirect to table structure page on creation of new table var argsep = CommonParams.get('arg_separator'); var params12 = 'ajax_request=true' + argsep + 'ajax_page_request=true'; if (!(history && history.pushState)) { params12 += MicroHistory.menus.getRequestParam(); } var tableStructureUrl = 'index.php?route=/table/structure' + argsep + 'server=' + data.params.server + argsep + 'db=' + data.params.db + argsep + 'token=' + data.params.token + argsep + 'goto=' + encodeURIComponent('index.php?route=/database/structure') + argsep + 'table=' + data.params.table + ''; $.get(tableStructureUrl, params12, AJAX.responseHandler); } else { Functions.ajaxShowMessage('', false); } }); // end $.post() } } }); // end create table form (save) /** * Submits the intermediate changes in the table creation form * to refresh the UI accordingly */ function submitChangesInCreateTableForm(actionParam) { /** * @var the_form object referring to the create table form */ var $form = $('form.create_table_form.ajax'); var $msgbox = Functions.ajaxShowMessage(Messages.strProcessingRequest); Functions.prepareForAjaxRequest($form); // User wants to add more fields to the table $.post($form.attr('action'), $form.serialize() + '&' + actionParam, function (data) { if (typeof data !== 'undefined' && data.success) { var $pageContent = $('#page_content'); $pageContent.html(data.message); Functions.highlightSql($pageContent); Functions.verifyColumnsProperties(); Functions.hideShowConnection($('.create_table_form select[name=tbl_storage_engine]')); Functions.ajaxRemoveMessage($msgbox); } else { Functions.ajaxShowMessage(data.error); } }); // end $.post() } /** * Attach event handler for create table form (add fields) */ $(document).on('click', 'form.create_table_form.ajax input[name=submit_num_fields]', function (event) { event.preventDefault(); submitChangesInCreateTableForm('submit_num_fields=1'); }); // end create table form (add fields) $(document).on('keydown', 'form.create_table_form.ajax input[name=added_fields]', function (event) { if (event.keyCode === 13) { event.preventDefault(); event.stopImmediatePropagation(); $(this).closest('form').find('input[name=submit_num_fields]').trigger('click'); } }); /** * Attach event handler to manage changes in number of partitions and subpartitions */ $(document).on('change', 'input[name=partition_count],input[name=subpartition_count],select[name=partition_by]', function () { var $this = $(this); var $form = $this.parents('form'); if ($form.is('.create_table_form.ajax')) { submitChangesInCreateTableForm('submit_partition_change=1'); } else { $form.trigger('submit'); } }); $(document).on('change', 'input[value=AUTO_INCREMENT]', function () { if (this.checked) { var col = /\d/.exec($(this).attr('name')); col = col[0]; var $selectFieldKey = $('select[name="field_key[' + col + ']"]'); if ($selectFieldKey.val() === 'none_' + col) { $selectFieldKey.val('primary_' + col).trigger('change', [false]); } } }); $('body').off('click', 'input.preview_sql').on('click', 'input.preview_sql', function () { var $form = $(this).closest('form'); Functions.previewSql($form); }); }); /** * Validates the password field in a form * * @see Messages.strPasswordEmpty * @see Messages.strPasswordNotSame * @param {object} $theForm The form to be validated * @return bool */ Functions.checkPassword = function ($theForm) { // Did the user select 'no password'? if ($theForm.find('#nopass_1').is(':checked')) { return true; } else { var $pred = $theForm.find('#select_pred_password'); if ($pred.length && ($pred.val() === 'none' || $pred.val() === 'keep')) { return true; } } var $password = $theForm.find('input[name=pma_pw]'); var $passwordRepeat = $theForm.find('input[name=pma_pw2]'); var alertMessage = false; if ($password.val() === '') { alertMessage = Messages.strPasswordEmpty; } else if ($password.val() !== $passwordRepeat.val()) { alertMessage = Messages.strPasswordNotSame; } if (alertMessage) { alert(alertMessage); $password.val(''); $passwordRepeat.val(''); $password.trigger('focus'); return false; } return true; }; /** * Attach Ajax event handlers for 'Change Password' on index.php */ AJAX.registerOnload('functions.js', function () { /* Handler for hostname type */ $(document).on('change', '#select_pred_hostname', function () { var hostname = $('#pma_hostname'); if (this.value === 'any') { hostname.val('%'); } else if (this.value === 'localhost') { hostname.val('localhost'); } else if (this.value === 'thishost' && $(this).data('thishost')) { hostname.val($(this).data('thishost')); } else if (this.value === 'hosttable') { hostname.val('').prop('required', false); } else if (this.value === 'userdefined') { hostname.trigger('focus').select().prop('required', true); } }); /* Handler for editing hostname */ $(document).on('change', '#pma_hostname', function () { $('#select_pred_hostname').val('userdefined'); $('#pma_hostname').prop('required', true); }); /* Handler for username type */ $(document).on('change', '#select_pred_username', function () { if (this.value === 'any') { $('#pma_username').val('').prop('required', false); $('#user_exists_warning').css('display', 'none'); } else if (this.value === 'userdefined') { $('#pma_username').trigger('focus').trigger('select').prop('required', true); } }); /* Handler for editing username */ $(document).on('change', '#pma_username', function () { $('#select_pred_username').val('userdefined'); $('#pma_username').prop('required', true); }); /* Handler for password type */ $(document).on('change', '#select_pred_password', function () { if (this.value === 'none') { $('#text_pma_pw2').prop('required', false).val(''); $('#text_pma_pw').prop('required', false).val(''); } else if (this.value === 'userdefined') { $('#text_pma_pw2').prop('required', true); $('#text_pma_pw').prop('required', true).trigger('focus').trigger('select'); } else { $('#text_pma_pw2').prop('required', false); $('#text_pma_pw').prop('required', false); } }); /* Handler for editing password */ $(document).on('change', '#text_pma_pw,#text_pma_pw2', function () { $('#select_pred_password').val('userdefined'); $('#text_pma_pw2').prop('required', true); $('#text_pma_pw').prop('required', true); }); /** * Unbind all event handlers before tearing down a page */ $(document).off('click', '#change_password_anchor.ajax'); /** * Attach Ajax event handler on the change password anchor */ $(document).on('click', '#change_password_anchor.ajax', function (event) { event.preventDefault(); var $msgbox = Functions.ajaxShowMessage(); /** * @var button_options Object containing options to be passed to jQueryUI's dialog */ var buttonOptions = {}; buttonOptions[Messages.strGo] = function () { event.preventDefault(); /** * @var $the_form Object referring to the change password form */ var $theForm = $('#change_password_form'); if (!Functions.checkPassword($theForm)) { return false; } /** * @var this_value String containing the value of the submit button. * Need to append this for the change password form on Server Privileges * page to work */ var thisValue = $(this).val(); var $msgbox = Functions.ajaxShowMessage(Messages.strProcessingRequest); $theForm.append(''); $.post($theForm.attr('action'), $theForm.serialize() + CommonParams.get('arg_separator') + 'change_pw=' + thisValue, function (data) { if (typeof data === 'undefined' || data.success !== true) { Functions.ajaxShowMessage(data.error, false); return; } var $pageContent = $('#page_content'); $pageContent.prepend(data.message); Functions.highlightSql($pageContent); $('#change_password_dialog').hide().remove(); $('#edit_user_dialog').dialog('close').remove(); Functions.ajaxRemoveMessage($msgbox); }); // end $.post() }; buttonOptions[Messages.strCancel] = function () { $(this).dialog('close'); }; $.get($(this).attr('href'), { 'ajax_request': true }, function (data) { if (typeof data === 'undefined' || !data.success) { Functions.ajaxShowMessage(data.error, false); return; } if (data.scripts) { AJAX.scriptHandler.load(data.scripts); } $('
    ').dialog({ title: Messages.strChangePassword, width: 600, close: function close() { $(this).remove(); }, buttons: buttonOptions, modal: true }).append(data.message); // for this dialog, we remove the fieldset wrapping due to double headings $('fieldset#fieldset_change_password').find('legend').remove().end().find('table.noclick').unwrap().addClass('some-margin').find('input#text_pma_pw').trigger('focus'); $('#fieldset_change_password_footer').hide(); Functions.ajaxRemoveMessage($msgbox); Functions.displayPasswordGenerateButton(); $('#change_password_form').on('submit', function (e) { e.preventDefault(); $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane .ui-button').first().trigger('click'); }); }); // end $.get() }); // end handler for change password anchor }); // end $() for Change Password /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('functions.js', function () { $(document).off('change', 'select.column_type'); $(document).off('change', 'select.default_type'); $(document).off('change', 'select.virtuality'); $(document).off('change', 'input.allow_null'); $(document).off('change', '.create_table_form select[name=tbl_storage_engine]'); }); /** * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when * the page loads and when the selected data type changes */ AJAX.registerOnload('functions.js', function () { // is called here for normal page loads and also when opening // the Create table dialog Functions.verifyColumnsProperties(); // // needs on() to work also in the Create Table dialog $(document).on('change', 'select.column_type', function () { Functions.showNoticeForEnum($(this)); }); $(document).on('change', 'select.default_type', function () { Functions.hideShowDefaultValue($(this)); }); $(document).on('change', 'select.virtuality', function () { Functions.hideShowExpression($(this)); }); $(document).on('change', 'input.allow_null', function () { Functions.validateDefaultValue($(this)); }); $(document).on('change', '.create_table_form select[name=tbl_storage_engine]', function () { Functions.hideShowConnection($(this)); }); }); /** * If the chosen storage engine is FEDERATED show connection field. Hide otherwise * * @param $engineSelector storage engine selector */ Functions.hideShowConnection = function ($engineSelector) { var $connection = $('.create_table_form input[name=connection]'); var $labelTh = $('.create_table_form #storage-engine-connection'); if ($engineSelector.val() !== 'FEDERATED') { $connection.prop('disabled', true).parent('td').hide(); $labelTh.hide(); } else { $connection.prop('disabled', false).parent('td').show(); $labelTh.show(); } }; /** * If the column does not allow NULL values, makes sure that default is not NULL */ Functions.validateDefaultValue = function ($nullCheckbox) { if (!$nullCheckbox.prop('checked')) { var $default = $nullCheckbox.closest('tr').find('.default_type'); if ($default.val() === 'NULL') { $default.val('NONE'); } } }; /** * function to populate the input fields on picking a column from central list * * @param string input_id input id of the name field for the column to be populated * @param integer offset of the selected column in central list of columns */ Functions.autoPopulate = function (inputId, offset) { var db = CommonParams.get('db'); var table = CommonParams.get('table'); var newInputId = inputId.substring(0, inputId.length - 1); $('#' + newInputId + '1').val(centralColumnList[db + '_' + table][offset].col_name); var colType = centralColumnList[db + '_' + table][offset].col_type.toUpperCase(); $('#' + newInputId + '2').val(colType); var $input3 = $('#' + newInputId + '3'); $input3.val(centralColumnList[db + '_' + table][offset].col_length); if (colType === 'ENUM' || colType === 'SET') { $input3.next().show(); } else { $input3.next().hide(); } var colDefault = centralColumnList[db + '_' + table][offset].col_default.toUpperCase(); var $input4 = $('#' + newInputId + '4'); if (colDefault !== '' && colDefault !== 'NULL' && colDefault !== 'CURRENT_TIMESTAMP' && colDefault !== 'CURRENT_TIMESTAMP()') { $input4.val('USER_DEFINED'); $input4.next().next().show(); $input4.next().next().val(centralColumnList[db + '_' + table][offset].col_default); } else { $input4.val(centralColumnList[db + '_' + table][offset].col_default); $input4.next().next().hide(); } $('#' + newInputId + '5').val(centralColumnList[db + '_' + table][offset].col_collation); var $input6 = $('#' + newInputId + '6'); $input6.val(centralColumnList[db + '_' + table][offset].col_attribute); if (centralColumnList[db + '_' + table][offset].col_extra === 'on update CURRENT_TIMESTAMP') { $input6.val(centralColumnList[db + '_' + table][offset].col_extra); } if (centralColumnList[db + '_' + table][offset].col_extra.toUpperCase() === 'AUTO_INCREMENT') { $('#' + newInputId + '9').prop('checked', true).trigger('change'); } else { $('#' + newInputId + '9').prop('checked', false); } if (centralColumnList[db + '_' + table][offset].col_isNull !== '0') { $('#' + newInputId + '7').prop('checked', true); } else { $('#' + newInputId + '7').prop('checked', false); } }; /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('functions.js', function () { $(document).off('click', 'a.open_enum_editor'); $(document).off('click', 'input.add_value'); $(document).off('click', '#enum_editor td.drop'); $(document).off('click', 'a.central_columns_dialog'); }); /** * @var $enumEditorDialog An object that points to the jQuery * dialog of the ENUM/SET editor */ var $enumEditorDialog = null; /** * Opens the ENUM/SET editor and controls its functions */ AJAX.registerOnload('functions.js', function () { $(document).on('click', 'a.open_enum_editor', function () { // Get the name of the column that is being edited var colname = $(this).closest('tr').find('input').first().val(); var title; var i; // And use it to make up a title for the page if (colname.length < 1) { title = Messages.enum_newColumnVals; } else { title = Messages.enum_columnVals.replace(/%s/, '"' + Functions.escapeHtml(decodeURIComponent(colname)) + '"'); } // Get the values as a string var inputstring = $(this).closest('td').find('input').val(); // Escape html entities inputstring = $('
    ').text(inputstring).html(); // Parse the values, escaping quotes and // slashes on the fly, into an array var values = []; var inString = false; var curr; var next; var buffer = ''; for (i = 0; i < inputstring.length; i++) { curr = inputstring.charAt(i); next = i === inputstring.length ? '' : inputstring.charAt(i + 1); if (!inString && curr === '\'') { inString = true; } else if (inString && curr === '\\' && next === '\\') { buffer += '\'; i++; } else if (inString && next === '\'' && (curr === '\'' || curr === '\\')) { buffer += '''; i++; } else if (inString && curr === '\'') { inString = false; values.push(buffer); buffer = ''; } else if (inString) { buffer += curr; } } if (buffer.length > 0) { // The leftovers in the buffer are the last value (if any) values.push(buffer); } var fields = ''; // If there are no values, maybe the user is about to make a // new list so we add a few for them to get started with. if (values.length === 0) { values.push('', '', '', ''); } // Add the parsed values to the editor var dropIcon = Functions.getImage('b_drop'); for (i = 0; i < values.length; i++) { fields += '' + '' + '' + dropIcon + ''; } /** * @var dialog HTML code for the ENUM/SET dialog */ var dialog = '
    ' + '
    ' + '' + title + '' + '

    ' + Functions.getImage('s_notice') + Messages.enum_hint + '

    ' + '' + fields + '
    ' + '
    ' + '
    ' + '
    ' + '
    ' + '
    ' + '
    ' + '' + '
    ' + '
    '; /** * @var {object} buttonOptions Defines functions to be called when the buttons in * the buttonOptions jQuery dialog bar are pressed */ var buttonOptions = {}; buttonOptions[Messages.strGo] = function () { // When the submit button is clicked, // put the data back into the original form var valueArray = []; $(this).find('.values input').each(function (index, elm) { var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, '\'\''); valueArray.push('\'' + val + '\''); }); // get the Length/Values text field where this value belongs var valuesId = $(this).find('input[type=\'hidden\']').val(); $('input#' + valuesId).val(valueArray.join(',')); $(this).dialog('close'); }; buttonOptions[Messages.strClose] = function () { $(this).dialog('close'); }; // Show the dialog var width = parseInt(parseInt($('html').css('font-size'), 10) / 13 * 340, 10); if (!width) { width = 340; } $enumEditorDialog = $(dialog).dialog({ minWidth: width, maxHeight: 450, modal: true, title: Messages.enum_editor, buttons: buttonOptions, open: function open() { // Focus the "Go" button after opening the dialog $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button').first().trigger('focus'); }, close: function close() { $(this).remove(); } }); // slider for choosing how many fields to add $enumEditorDialog.find('.slider').slider({ animate: true, range: 'min', value: 1, min: 1, max: 9, slide: function slide(event, ui) { $(this).closest('table').find('input[type=submit]').val(Functions.sprintf(Messages.enum_addValue, ui.value)); } }); // Focus the slider, otherwise it looks nearly transparent $('a.ui-slider-handle').addClass('ui-state-focus'); return false; }); $(document).on('click', 'a.central_columns_dialog', function () { var href = 'index.php?route=/database/central-columns'; var db = CommonParams.get('db'); var table = CommonParams.get('table'); var maxRows = $(this).data('maxrows'); var pick = $(this).data('pick'); if (pick !== false) { pick = true; } var params = { 'ajax_request': true, 'server': CommonParams.get('server'), 'db': CommonParams.get('db'), 'cur_table': CommonParams.get('table'), 'getColumnList': true }; var colid = $(this).closest('td').find('input').attr('id'); var fields = ''; if (!(db + '_' + table in centralColumnList)) { centralColumnList.push(db + '_' + table); $.ajax({ type: 'POST', url: href, data: params, success: function success(data) { centralColumnList[db + '_' + table] = data.message; }, async: false }); } var i = 0; var listSize = centralColumnList[db + '_' + table].length; var min = listSize <= maxRows ? listSize : maxRows; for (i = 0; i < min; i++) { fields += '
    ' + Functions.escapeHtml(centralColumnList[db + '_' + table][i].col_name) + '
    ' + centralColumnList[db + '_' + table][i].col_type; if (centralColumnList[db + '_' + table][i].col_attribute !== '') { fields += '(' + Functions.escapeHtml(centralColumnList[db + '_' + table][i].col_attribute) + ') '; } if (centralColumnList[db + '_' + table][i].col_length !== '') { fields += '(' + Functions.escapeHtml(centralColumnList[db + '_' + table][i].col_length) + ') '; } fields += Functions.escapeHtml(centralColumnList[db + '_' + table][i].col_extra) + '' + '
    '; if (pick) { fields += ''; } fields += ''; } var resultPointer = i; var searchIn = ''; if (fields === '') { fields = Functions.sprintf(Messages.strEmptyCentralList, '\'' + Functions.escapeHtml(db) + '\''); searchIn = ''; } var seeMore = ''; if (listSize > maxRows) { seeMore = '
    ' + '' + Messages.seeMore + '
    '; } var centralColumnsDialog = '
    ' + '
    ' + searchIn + '' + fields + '
    ' + '
    ' + seeMore + '
    '; var width = parseInt(parseInt($('html').css('font-size'), 10) / 13 * 500, 10); if (!width) { width = 500; } var buttonOptions = {}; var $centralColumnsDialog = $(centralColumnsDialog).dialog({ minWidth: width, maxHeight: 450, modal: true, title: Messages.pickColumnTitle, buttons: buttonOptions, open: function open() { $('#col_list').on('click', '.pick', function () { $centralColumnsDialog.remove(); }); $('.filter_rows').on('keyup', function () { $.uiTableFilter($('#col_list'), $(this).val()); }); $('#seeMore').on('click', function () { fields = ''; min = listSize <= maxRows + resultPointer ? listSize : maxRows + resultPointer; for (i = resultPointer; i < min; i++) { fields += '
    ' + centralColumnList[db + '_' + table][i].col_name + '
    ' + centralColumnList[db + '_' + table][i].col_type; if (centralColumnList[db + '_' + table][i].col_attribute !== '') { fields += '(' + centralColumnList[db + '_' + table][i].col_attribute + ') '; } if (centralColumnList[db + '_' + table][i].col_length !== '') { fields += '(' + centralColumnList[db + '_' + table][i].col_length + ') '; } fields += centralColumnList[db + '_' + table][i].col_extra + '' + '
    '; if (pick) { fields += ''; } fields += ''; } $('#col_list').append(fields); resultPointer = i; if (resultPointer === listSize) { $('#seeMore').hide(); } return false; }); $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button').first().trigger('focus'); }, close: function close() { $('#col_list').off('click', '.pick'); $('.filter_rows').off('keyup'); $(this).remove(); } }); return false; }); // $(document).on('click', 'a.show_central_list',function(e) { // }); // When "add a new value" is clicked, append an empty text field $(document).on('click', 'input.add_value', function (e) { e.preventDefault(); var numNewRows = $enumEditorDialog.find('div.slider').slider('value'); while (numNewRows--) { $enumEditorDialog.find('.values').append('' + '' + '' + Functions.getImage('b_drop') + '').find('tr').last().show('fast'); } }); // Removes the specified row from the enum editor $(document).on('click', '#enum_editor td.drop', function () { $(this).closest('tr').hide('fast', function () { $(this).remove(); }); }); }); /** * Ensures indexes names are valid according to their type and, for a primary * key, lock index name to 'PRIMARY' * @param string form_id Variable which parses the form name as * the input * @return boolean false if there is no index form, true else */ Functions.checkIndexName = function (formId) { if ($('#' + formId).length === 0) { return false; } // Gets the elements pointers var $theIdxName = $('#input_index_name'); var $theIdxChoice = $('#select_index_choice'); // Index is a primary key if ($theIdxChoice.find('option:selected').val() === 'PRIMARY') { $theIdxName.val('PRIMARY'); $theIdxName.prop('disabled', true); } else { if ($theIdxName.val() === 'PRIMARY') { $theIdxName.val(''); } $theIdxName.prop('disabled', false); } return true; }; AJAX.registerTeardown('functions.js', function () { $(document).off('click', '#index_frm input[type=submit]'); }); AJAX.registerOnload('functions.js', function () { /** * Handler for adding more columns to an index in the editor */ $(document).on('click', '#index_frm input[type=submit]', function (event) { event.preventDefault(); var hadAddButtonHidden = $(this).closest('fieldset').find('.add_fields').hasClass('hide'); if (hadAddButtonHidden === false) { var rowsToAdd = $(this).closest('fieldset').find('.slider').slider('value'); var tempEmptyVal = function tempEmptyVal() { $(this).val(''); }; var tempSetFocus = function tempSetFocus() { if ($(this).find('option:selected').val() === '') { return true; } $(this).closest('tr').find('input').trigger('focus'); }; while (rowsToAdd--) { var $indexColumns = $('#index_columns'); var $newrow = $indexColumns.find('tbody > tr').first().clone().appendTo($indexColumns.find('tbody')); $newrow.find(':input').each(tempEmptyVal); // focus index size input on column picked $newrow.find('select').on('change', tempSetFocus); } } }); }); Functions.indexDialogModal = function (routeUrl, url, title, callbackSuccess, callbackFailure) { /* Remove the hidden dialogs if there are*/ var $editIndexDialog = $('#edit_index_dialog'); if ($editIndexDialog.length !== 0) { $editIndexDialog.remove(); } var $div = $('
    '); /** * @var button_options Object that stores the options * passed to jQueryUI dialog */ var buttonOptions = {}; buttonOptions[Messages.strGo] = function () { /** * @var the_form object referring to the export form */ var $form = $('#index_frm'); Functions.ajaxShowMessage(Messages.strProcessingRequest); Functions.prepareForAjaxRequest($form); // User wants to submit the form $.post($form.attr('action'), $form.serialize() + CommonParams.get('arg_separator') + 'do_save_data=1', function (data) { var $sqlqueryresults = $('.sqlqueryresults'); if ($sqlqueryresults.length !== 0) { $sqlqueryresults.remove(); } if (typeof data !== 'undefined' && data.success === true) { Functions.ajaxShowMessage(data.message); Functions.highlightSql($('.result_query')); $('.result_query .alert').remove(); /* Reload the field form*/ $('#table_index').remove(); $('
    ').append(data.index_table).find('#table_index').insertAfter('#index_header'); var $editIndexDialog = $('#edit_index_dialog'); if ($editIndexDialog.length > 0) { $editIndexDialog.dialog('close'); } $('div.no_indexes_defined').hide(); if (callbackSuccess) { callbackSuccess(data); } Navigation.reload(); } else { var $tempDiv = $('
    ').append(data.error); var $error; if ($tempDiv.find('.error code').length !== 0) { $error = $tempDiv.find('.error code').addClass('error'); } else { $error = $tempDiv; } if (callbackFailure) { callbackFailure(); } Functions.ajaxShowMessage($error, false); } }); // end $.post() }; buttonOptions[Messages.strPreviewSQL] = function () { // Function for Previewing SQL var $form = $('#index_frm'); Functions.previewSql($form); }; buttonOptions[Messages.strCancel] = function () { $(this).dialog('close'); }; var $msgbox = Functions.ajaxShowMessage(); $.post(routeUrl, url, function (data) { if (typeof data !== 'undefined' && data.success === false) { // in the case of an error, show the error message returned. Functions.ajaxShowMessage(data.error, false); } else { Functions.ajaxRemoveMessage($msgbox); // Show dialog if the request was successful $div.append(data.message).dialog({ title: title, width: 'auto', open: Functions.verifyColumnsProperties, modal: true, buttons: buttonOptions, close: function close() { $(this).remove(); } }); $div.find('.tblFooters').remove(); Functions.showIndexEditDialog($div); } }); // end $.get() }; Functions.indexEditorDialog = function (url, title, callbackSuccess, callbackFailure) { Functions.indexDialogModal('index.php?route=/table/indexes', url, title, callbackSuccess, callbackFailure); }; Functions.indexRenameDialog = function (url, title, callbackSuccess, callbackFailure) { Functions.indexDialogModal('index.php?route=/table/indexes/rename', url, title, callbackSuccess, callbackFailure); }; Functions.showIndexEditDialog = function ($outer) { Indexes.checkIndexType(); Functions.checkIndexName('index_frm'); var $indexColumns = $('#index_columns'); $indexColumns.find('td').each(function () { $(this).css('width', $(this).width() + 'px'); }); $indexColumns.find('tbody').sortable({ axis: 'y', containment: $indexColumns.find('tbody'), tolerance: 'pointer' }); Functions.showHints($outer); Functions.initSlider(); // Add a slider for selecting how many columns to add to the index $outer.find('.slider').slider({ animate: true, value: 1, min: 1, max: 16, slide: function slide(event, ui) { $(this).closest('fieldset').find('input[type=submit]').val(Functions.sprintf(Messages.strAddToIndex, ui.value)); } }); $('div.add_fields').removeClass('hide'); // focus index size input on column picked $outer.find('table#index_columns select').on('change', function () { if ($(this).find('option:selected').val() === '') { return true; } $(this).closest('tr').find('input').trigger('focus'); }); // Focus the slider, otherwise it looks nearly transparent $('a.ui-slider-handle').addClass('ui-state-focus'); // set focus on index name input, if empty var input = $outer.find('input#input_index_name'); if (!input.val()) { input.trigger('focus'); } }; /** * Function to display tooltips that were * generated on the PHP side by PhpMyAdmin\Util::showHint() * * @param object $div a div jquery object which specifies the * domain for searching for tooltips. If we * omit this parameter the function searches * in the whole body **/ Functions.showHints = function ($div) { var $newDiv = $div; if ($newDiv === undefined || !($newDiv instanceof jQuery) || $newDiv.length === 0) { $newDiv = $('body'); } $newDiv.find('.pma_hint').each(function () { Functions.tooltip($(this).children('img'), 'img', $(this).children('span').html()); }); }; AJAX.registerOnload('functions.js', function () { Functions.showHints(); }); Functions.mainMenuResizerCallback = function () { // 5 px margin for jumping menu in Chrome return $(document.body).width() - 5; }; // This must be fired only once after the initial page load $(function () { // Initialise the menu resize plugin $('#topmenu').menuResizer(Functions.mainMenuResizerCallback); // register resize event $(window).on('resize', function () { $('#topmenu').menuResizer('resize'); }); }); /** * Changes status of slider */ Functions.setStatusLabel = function ($element) { var text; if ($element.css('display') === 'none') { text = '+ '; } else { text = '- '; } $element.closest('.slide-wrapper').prev().find('span').text(text); }; /** * var toggleButton This is a function that creates a toggle * sliding button given a jQuery reference * to the correct DOM element */ Functions.toggleButton = function ($obj) { // In rtl mode the toggle switch is flipped horizontally // so we need to take that into account var right; if ($('span.text_direction', $obj).text() === 'ltr') { right = 'right'; } else { right = 'left'; } /** * var h Height of the button, used to scale the * background image and position the layers */ var h = $obj.height(); $('img', $obj).height(h); $('table', $obj).css('bottom', h - 1); /** * var on Width of the "ON" part of the toggle switch * var off Width of the "OFF" part of the toggle switch */ var on = $('td.toggleOn', $obj).width(); var off = $('td.toggleOff', $obj).width(); // Make the "ON" and "OFF" parts of the switch the same size // + 2 pixels to avoid overflowed $('td.toggleOn > div', $obj).width(Math.max(on, off) + 2); $('td.toggleOff > div', $obj).width(Math.max(on, off) + 2); /** * var w Width of the central part of the switch */ var w = parseInt($('img', $obj).height() / 16 * 22, 10); // Resize the central part of the switch on the top // layer to match the background $($obj).find('table td').eq(1).children('div').width(w); /** * var imgw Width of the background image * var tblw Width of the foreground layer * var offset By how many pixels to move the background * image, so that it matches the top layer */ var imgw = $('img', $obj).width(); var tblw = $('table', $obj).width(); var offset = parseInt((imgw - tblw) / 2, 10); // Move the background to match the layout of the top layer $obj.find('img').css(right, offset); /** * var offw Outer width of the "ON" part of the toggle switch * var btnw Outer width of the central part of the switch */ var offw = $('td.toggleOff', $obj).outerWidth(); var btnw = $($obj).find('table td').eq(1).outerWidth(); // Resize the main div so that exactly one side of // the switch plus the central part fit into it. $obj.width(offw + btnw + 2); /** * var move How many pixels to move the * switch by when toggling */ var move = $('td.toggleOff', $obj).outerWidth(); // If the switch is initialized to the // OFF state we need to move it now. if ($('div.toggle-container', $obj).hasClass('off')) { if (right === 'right') { $('div.toggle-container', $obj).animate({ 'left': '-=' + move + 'px' }, 0); } else { $('div.toggle-container', $obj).animate({ 'left': '+=' + move + 'px' }, 0); } } // Attach an 'onclick' event to the switch $('div.toggle-container', $obj).on('click', function () { if ($(this).hasClass('isActive')) { return false; } else { $(this).addClass('isActive'); } var $msg = Functions.ajaxShowMessage(); var $container = $(this); var callback = $('span.callback', this).text(); var operator; var url; var removeClass; var addClass; // Perform the actual toggle if ($(this).hasClass('on')) { if (right === 'right') { operator = '-='; } else { operator = '+='; } url = $(this).find('td.toggleOff > span').text(); removeClass = 'on'; addClass = 'off'; } else { if (right === 'right') { operator = '+='; } else { operator = '-='; } url = $(this).find('td.toggleOn > span').text(); removeClass = 'off'; addClass = 'on'; } var parts = url.split('?'); $.post(parts[0], parts[1] + '&ajax_request=true', function (data) { if (typeof data !== 'undefined' && data.success === true) { Functions.ajaxRemoveMessage($msg); $container.removeClass(removeClass).addClass(addClass).animate({ 'left': operator + move + 'px' }, function () { $container.removeClass('isActive'); }); // eslint-disable-next-line no-eval eval(callback); } else { Functions.ajaxShowMessage(data.error, false); $container.removeClass('isActive'); } }); }); }; /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('functions.js', function () { $('div.toggle-container').off('click'); }); /** * Initialise all toggle buttons */ AJAX.registerOnload('functions.js', function () { $('div.toggleAjax').each(function () { var $button = $(this).show(); $button.find('img').each(function () { if (this.complete) { Functions.toggleButton($button); } else { $(this).on('load', function () { Functions.toggleButton($button); }); } }); }); }); /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('functions.js', function () { $(document).off('change', 'select.pageselector'); $('#update_recent_tables').off('ready'); $('#sync_favorite_tables').off('ready'); }); AJAX.registerOnload('functions.js', function () { /** * Autosubmit page selector */ $(document).on('change', 'select.pageselector', function (event) { event.stopPropagation(); // Check where to load the new content if ($(this).closest('#pma_navigation').length === 0) { // For the main page we don't need to do anything, $(this).closest('form').trigger('submit'); } else { // but for the navigation we need to manually replace the content Navigation.treePagination($(this)); } }); /** * Load version information asynchronously. */ if ($('li.jsversioncheck').length > 0) { $.ajax({ dataType: 'json', url: 'index.php?route=/version-check', method: 'POST', data: { 'server': CommonParams.get('server') }, success: Functions.currentVersion }); } if ($('#is_git_revision').length > 0) { setTimeout(Functions.displayGitRevision, 10); } /** * Slider effect. */ Functions.initSlider(); var $updateRecentTables = $('#update_recent_tables'); if ($updateRecentTables.length) { $.get($updateRecentTables.attr('href'), { 'no_debug': true }, function (data) { if (typeof data !== 'undefined' && data.success === true) { $('#pma_recent_list').html(data.list); } }); } // Sync favorite tables from localStorage to pmadb. if ($('#sync_favorite_tables').length) { $.ajax({ url: $('#sync_favorite_tables').attr('href'), cache: false, type: 'POST', data: { 'favoriteTables': isStorageSupported('localStorage') && typeof window.localStorage.favoriteTables !== 'undefined' ? window.localStorage.favoriteTables : '', 'server': CommonParams.get('server'), 'no_debug': true }, success: function success(data) { // Update localStorage. if (isStorageSupported('localStorage')) { window.localStorage.favoriteTables = data.favoriteTables; } $('#pma_favorite_list').html(data.list); } }); } }); // end of $() /** * Initializes slider effect. */ Functions.initSlider = function () { $('div.pma_auto_slider').each(function () { var $this = $(this); if ($this.data('slider_init_done')) { return; } var $wrapper = $('
    ', { 'class': 'slide-wrapper' }); $wrapper.toggle($this.is(':visible')); $('', { href: '#' + this.id, 'class': 'ajax' }).text($this.attr('title')).prepend($('')).insertBefore($this).on('click', function () { var $wrapper = $this.closest('.slide-wrapper'); var visible = $this.is(':visible'); if (!visible) { $wrapper.show(); } $this[visible ? 'hide' : 'show']('blind', function () { $wrapper.toggle(!visible); $wrapper.parent().toggleClass('print_ignore', visible); Functions.setStatusLabel($this); }); return false; }); $this.wrap($wrapper); $this.removeAttr('title'); Functions.setStatusLabel($this); $this.data('slider_init_done', 1); }); }; /** * Initializes slider effect. */ AJAX.registerOnload('functions.js', function () { Functions.initSlider(); }); /** * Restores sliders to the state they were in before initialisation. */ AJAX.registerTeardown('functions.js', function () { $('div.pma_auto_slider').each(function () { var $this = $(this); $this.removeData(); $this.parent().replaceWith($this); $this.parent().children('a').remove(); }); }); /** * Creates a message inside an object with a sliding effect * * @param msg A string containing the text to display * @param $obj a jQuery object containing the reference * to the element where to put the message * This is optional, if no element is * provided, one will be created below the * navigation links at the top of the page * * @return bool True on success, false on failure */ Functions.slidingMessage = function (msg, $object) { var $obj = $object; if (msg === undefined || msg.length === 0) { // Don't show an empty message return false; } if ($obj === undefined || !($obj instanceof jQuery) || $obj.length === 0) { // If the second argument was not supplied, // we might have to create a new DOM node. if ($('#PMA_slidingMessage').length === 0) { $('#page_content').prepend(''); } $obj = $('#PMA_slidingMessage'); } if ($obj.has('div').length > 0) { // If there already is a message inside the // target object, we must get rid of it $obj.find('div').first().fadeOut(function () { $obj.children().remove(); $obj.append('
    ' + msg + '
    '); // highlight any sql before taking height; Functions.highlightSql($obj); $obj.find('div').first().hide(); $obj.animate({ height: $obj.find('div').first().height() }).find('div').first().fadeIn(); }); } else { // Object does not already have a message // inside it, so we simply slide it down $obj.width('100%').html('
    ' + msg + '
    '); // highlight any sql before taking height; Functions.highlightSql($obj); var h = $obj.find('div').first().hide().height(); $obj.find('div').first().css('height', 0).show().animate({ height: h }, function () { // Set the height of the parent // to the height of the child $obj.height($obj.find('div').first().height()); }); } return true; }; /** * Attach CodeMirror2 editor to SQL edit area. */ AJAX.registerOnload('functions.js', function () { var $elm = $('#sqlquery'); if ($elm.siblings().filter('.CodeMirror').length > 0) { return; } if ($elm.length > 0) { if (typeof CodeMirror !== 'undefined') { codeMirrorEditor = Functions.getSqlEditor($elm); codeMirrorEditor.focus(); codeMirrorEditor.on('blur', Functions.updateQueryParameters); } else { // without codemirror $elm.trigger('focus').on('blur', Functions.updateQueryParameters); } } Functions.highlightSql($('body')); }); AJAX.registerTeardown('functions.js', function () { if (codeMirrorEditor) { $('#sqlquery').text(codeMirrorEditor.getValue()); codeMirrorEditor.toTextArea(); codeMirrorEditor = false; } }); AJAX.registerOnload('functions.js', function () { // initializes all lock-page elements lock-id and // val-hash data property $('#page_content form.lock-page textarea, ' + '#page_content form.lock-page input[type="text"], ' + '#page_content form.lock-page input[type="number"], ' + '#page_content form.lock-page select').each(function (i) { $(this).data('lock-id', i); // val-hash is the hash of default value of the field // so that it can be compared with new value hash // to check whether field was modified or not. $(this).data('val-hash', AJAX.hash($(this).val())); }); // initializes lock-page elements (input types checkbox and radio buttons) // lock-id and val-hash data property $('#page_content form.lock-page input[type="checkbox"], ' + '#page_content form.lock-page input[type="radio"]').each(function (i) { $(this).data('lock-id', i); $(this).data('val-hash', AJAX.hash($(this).is(':checked'))); }); }); /** * jQuery plugin to correctly filter input fields by value, needed * because some nasty values may break selector syntax */ (function ($) { $.fn.filterByValue = function (value) { return this.filter(function () { return $(this).val() === value; }); }; })(jQuery); /** * Return value of a cell in a table. */ Functions.getCellValue = function (td) { var $td = $(td); if ($td.is('.null')) { return ''; } else if ((!$td.is('.to_be_saved') || $td.is('.set')) && $td.data('original_data')) { return $td.data('original_data'); } else { return $td.text(); } }; $(window).on('popstate', function () { $('#printcss').attr('media', 'print'); return true; }); /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('functions.js', function () { $(document).off('click', 'a.themeselect'); $(document).off('change', '.autosubmit'); $('a.take_theme').off('click'); }); AJAX.registerOnload('functions.js', function () { /** * Theme selector. */ $(document).on('click', 'a.themeselect', function (e) { window.open(e.target, 'themes', 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'); return false; }); /** * Automatic form submission on change. */ $(document).on('change', '.autosubmit', function () { $(this).closest('form').trigger('submit'); }); /** * Theme changer. */ $('a.take_theme').on('click', function () { var what = this.name; /* eslint-disable compat/compat */ if (window.opener && window.opener.document.forms.setTheme.elements.set_theme) { window.opener.document.forms.setTheme.elements.set_theme.value = what; window.opener.document.forms.setTheme.submit(); window.close(); return false; } /* eslint-enable compat/compat */ return true; }); }); /** * Produce print preview */ Functions.printPreview = function () { $('#printcss').attr('media', 'all'); Functions.createPrintAndBackButtons(); }; /** * Create print and back buttons in preview page */ Functions.createPrintAndBackButtons = function () { var backButton = $('', { type: 'button', value: Messages.back, class: 'btn btn-secondary', id: 'back_button_print_view' }); backButton.on('click', Functions.removePrintAndBackButton); backButton.appendTo('#page_content'); var printButton = $('', { type: 'button', value: Messages.print, class: 'btn btn-primary', id: 'print_button_print_view' }); printButton.on('click', Functions.printPage); printButton.appendTo('#page_content'); }; /** * Remove print and back buttons and revert to normal view */ Functions.removePrintAndBackButton = function () { $('#printcss').attr('media', 'print'); $('#back_button_print_view').remove(); $('#print_button_print_view').remove(); }; /** * Print page */ Functions.printPage = function () { if (typeof window.print !== 'undefined') { window.print(); } }; /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('functions.js', function () { $('input#print').off('click'); $(document).off('click', 'a.create_view.ajax'); $(document).off('keydown', '#createViewDialog input, #createViewDialog select'); $(document).off('change', '#fkc_checkbox'); }); AJAX.registerOnload('functions.js', function () { $('input#print').on('click', Functions.printPage); $('.logout').on('click', function () { var form = $('
    ' + '' + '
    '); $('body').append(form); form.submit(); sessionStorage.clear(); return false; }); /** * Ajaxification for the "Create View" action */ $(document).on('click', 'a.create_view.ajax', function (e) { e.preventDefault(); Functions.createViewDialog($(this)); }); /** * Attach Ajax event handlers for input fields in the editor * and used to submit the Ajax request when the ENTER key is pressed. */ if ($('#createViewDialog').length !== 0) { $(document).on('keydown', '#createViewDialog input, #createViewDialog select', function (e) { if (e.which === 13) { // 13 is the ENTER key e.preventDefault(); // with preventing default, selection by