From 5bf66662a9bdd62c5bccab15e607cd95cfb8fcab Mon Sep 17 00:00:00 2001 From: Charles Cabergs Date: Mon, 27 Jul 2020 10:05:23 +0200 Subject: Removed wordpress and phpmyadmin, my server doesn't handle it well and it brings shame on my familly --- srcs/phpmyadmin/js/functions.js | 5148 --------------------------------------- 1 file changed, 5148 deletions(-) delete mode 100644 srcs/phpmyadmin/js/functions.js (limited to 'srcs/phpmyadmin/js/functions.js') diff --git a/srcs/phpmyadmin/js/functions.js b/srcs/phpmyadmin/js/functions.js deleted file mode 100644 index cf973b5..0000000 --- a/srcs/phpmyadmin/js/functions.js +++ /dev/null @@ -1,5148 +0,0 @@ -/* vim: set expandtab sw=4 ts=4 sts=4: */ - -/* global isStorageSupported */ // js/config.js -/* global ChartType, ColumnType, DataTable, JQPlotChartFactory */ // js/chart.js -/* global DatabaseStructure */ // js/database/structure.js -/* global mysqlDocBuiltin, mysqlDocKeyword */ // js/doclinks.js -/* global Indexes */ // js/indexes.js -/* global maxInputVars, mysqlDocTemplate, pmaThemeImage */ // js/messages.php -/* global MicroHistory */ // js/microhistory.js -/* global checkPasswordStrength */ // js/server/privileges.js -/* global sprintf */ // js/vendor/sprintf.js -/* global Int32Array */ // ES6 - -/** - * general function, usually for data manipulation pages - * - */ -var Functions = {}; - -/** - * @var sqlBoxLocked lock for the sqlbox textarea in the querybox - */ -// eslint-disable-next-line no-unused-vars -var sqlBoxLocked = false; - -/** - * @var {array} holds elements which content should only selected once - */ -var onlyOnceElements = []; - -/** - * @var {int} ajaxMessageCount Number of AJAX messages shown since page load - */ -var ajaxMessageCount = 0; - -/** - * @var codeMirrorEditor object containing CodeMirror editor of the query editor in SQL tab - */ -var codeMirrorEditor = false; - -/** - * @var codeMirrorInlineEditor object containing CodeMirror editor of the inline query editor - */ -var codeMirrorInlineEditor = false; - -/** - * @var {boolean} sqlAutoCompleteInProgress shows if Table/Column name autocomplete AJAX is in progress - */ -var sqlAutoCompleteInProgress = false; - -/** - * @var sqlAutoComplete object containing list of columns in each table - */ -var sqlAutoComplete = false; - -/** - * @var {string} sqlAutoCompleteDefaultTable string containing default table to autocomplete columns - */ -var sqlAutoCompleteDefaultTable = ''; - -/** - * @var {array} centralColumnList array to hold the columns in central list per db. - */ -var centralColumnList = []; - -/** - * @var {array} primaryIndexes array to hold 'Primary' index columns. - */ -// eslint-disable-next-line no-unused-vars -var primaryIndexes = []; - -/** - * @var {array} uniqueIndexes array to hold 'Unique' index columns. - */ -// eslint-disable-next-line no-unused-vars -var uniqueIndexes = []; - -/** - * @var {array} indexes array to hold 'Index' columns. - */ -// eslint-disable-next-line no-unused-vars -var indexes = []; - -/** - * @var {array} fulltextIndexes array to hold 'Fulltext' columns. - */ -// eslint-disable-next-line no-unused-vars -var fulltextIndexes = []; - -/** - * @var {array} spatialIndexes array to hold 'Spatial' columns. - */ -// eslint-disable-next-line no-unused-vars -var spatialIndexes = []; - -/** - * Make sure that ajax requests will not be cached - * by appending a random variable to their parameters - */ -$.ajaxPrefilter(function (options, originalOptions) { - var nocache = new Date().getTime() + '' + Math.floor(Math.random() * 1000000); - if (typeof options.data === 'string') { - options.data += '&_nocache=' + nocache + '&token=' + encodeURIComponent(CommonParams.get('token')); - } else if (typeof options.data === 'object') { - options.data = $.extend(originalOptions.data, { '_nocache' : nocache, 'token': CommonParams.get('token') }); - } -}); - -/** - * Adds a date/time picker to an element - * - * @param {object} $thisElement a jQuery object pointing to the element - */ -Functions.addDatepicker = function ($thisElement, type, options) { - if (type !== 'date' && type !== 'time' && type !== 'datetime' && type !== 'timestamp') { - return; - } - - var showTimepicker = true; - if (type === 'date') { - showTimepicker = false; - } - - // Getting the current Date and time - var currentDateTime = new Date(); - - var defaultOptions = { - timeInput : true, - hour: currentDateTime.getHours(), - minute: currentDateTime.getMinutes(), - second: currentDateTime.getSeconds(), - showOn: 'button', - buttonImage: pmaThemeImage + 'b_calendar.png', - buttonImageOnly: true, - stepMinutes: 1, - stepHours: 1, - showSecond: true, - showMillisec: true, - showMicrosec: true, - showTimepicker: showTimepicker, - showButtonPanel: false, - dateFormat: 'yy-mm-dd', // yy means year with four digits - timeFormat: 'HH:mm:ss.lc', - constrainInput: false, - altFieldTimeOnly: false, - showAnim: '', - beforeShow: function (input, inst) { - // Remember that we came from the datepicker; this is used - // in table/change.js by verificationsAfterFieldChange() - $thisElement.data('comes_from', 'datepicker'); - if ($(input).closest('.cEdit').length > 0) { - setTimeout(function () { - inst.dpDiv.css({ - top: 0, - left: 0, - position: 'relative' - }); - }, 0); - } - setTimeout(function () { - // Fix wrong timepicker z-index, doesn't work without timeout - $('#ui-timepicker-div').css('z-index', $('#ui-datepicker-div').css('z-index')); - // Integrate tooltip text into dialog - var tooltip = $thisElement.tooltip('instance'); - if (typeof tooltip !== 'undefined') { - tooltip.disable(); - var $note = $('

'); - $note.text(tooltip.option('content')); - $('div.ui-datepicker').append($note); - } - }, 0); - }, - onSelect: function () { - $thisElement.data('datepicker').inline = true; - }, - onClose: function () { - // The value is no more from the date picker - $thisElement.data('comes_from', ''); - if (typeof $thisElement.data('datepicker') !== 'undefined') { - $thisElement.data('datepicker').inline = false; - } - var tooltip = $thisElement.tooltip('instance'); - if (typeof tooltip !== 'undefined') { - tooltip.enable(); - } - } - }; - if (type === 'time') { - $thisElement.timepicker($.extend(defaultOptions, options)); - // Add a tip regarding entering MySQL allowed-values for TIME data-type - Functions.tooltip($thisElement, 'input', Messages.strMysqlAllowedValuesTipTime); - } else { - $thisElement.datetimepicker($.extend(defaultOptions, options)); - } -}; - -/** - * Add a date/time picker to each element that needs it - * (only when jquery-ui-timepicker-addon.js is loaded) - */ -Functions.addDateTimePicker = function () { - if ($.timepicker !== undefined) { - $('input.timefield, input.datefield, input.datetimefield').each(function () { - var decimals = $(this).parent().attr('data-decimals'); - var type = $(this).parent().attr('data-type'); - - var showMillisec = false; - var showMicrosec = false; - var timeFormat = 'HH:mm:ss'; - var hourMax = 23; - // check for decimal places of seconds - if (decimals > 0 && type.indexOf('time') !== -1) { - if (decimals > 3) { - showMillisec = true; - showMicrosec = true; - timeFormat = 'HH:mm:ss.lc'; - } else { - showMillisec = true; - timeFormat = 'HH:mm:ss.l'; - } - } - if (type === 'time') { - hourMax = 99; - } - Functions.addDatepicker($(this), type, { - showMillisec: showMillisec, - showMicrosec: showMicrosec, - timeFormat: timeFormat, - hourMax: hourMax - }); - // Add a tip regarding entering MySQL allowed-values - // for TIME and DATE data-type - if ($(this).hasClass('timefield')) { - Functions.tooltip($(this), 'input', Messages.strMysqlAllowedValuesTipTime); - } else if ($(this).hasClass('datefield')) { - Functions.tooltip($(this), 'input', Messages.strMysqlAllowedValuesTipDate); - } - }); - } -}; - -/** - * Handle redirect and reload flags sent as part of AJAX requests - * - * @param data ajax response data - */ -Functions.handleRedirectAndReload = function (data) { - if (parseInt(data.redirect_flag) === 1) { - // add one more GET param to display session expiry msg - if (window.location.href.indexOf('?') === -1) { - window.location.href += '?session_expired=1'; - } else { - window.location.href += CommonParams.get('arg_separator') + 'session_expired=1'; - } - window.location.reload(); - } else if (parseInt(data.reload_flag) === 1) { - window.location.reload(); - } -}; - -/** - * Creates an SQL editor which supports auto completing etc. - * - * @param $textarea jQuery object wrapping the textarea to be made the editor - * @param options optional options for CodeMirror - * @param resize optional resizing ('vertical', 'horizontal', 'both') - * @param lintOptions additional options for lint - */ -Functions.getSqlEditor = function ($textarea, options, resize, lintOptions) { - var resizeType = resize; - if ($textarea.length > 0 && typeof CodeMirror !== 'undefined') { - // merge options for CodeMirror - var defaults = { - lineNumbers: true, - matchBrackets: true, - extraKeys: { 'Ctrl-Space': 'autocomplete' }, - hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true }, - indentUnit: 4, - mode: 'text/x-mysql', - lineWrapping: true - }; - - if (CodeMirror.sqlLint) { - $.extend(defaults, { - gutters: ['CodeMirror-lint-markers'], - lint: { - 'getAnnotations': CodeMirror.sqlLint, - 'async': true, - 'lintOptions': lintOptions - } - }); - } - - $.extend(true, defaults, options); - - // create CodeMirror editor - var codemirrorEditor = CodeMirror.fromTextArea($textarea[0], defaults); - // allow resizing - if (! resizeType) { - resizeType = 'vertical'; - } - var handles = ''; - if (resizeType === 'vertical') { - handles = 's'; - } - if (resizeType === 'both') { - handles = 'all'; - } - if (resizeType === 'horizontal') { - handles = 'e, w'; - } - $(codemirrorEditor.getWrapperElement()) - .css('resize', resizeType) - .resizable({ - handles: handles, - resize: function () { - codemirrorEditor.setSize($(this).width(), $(this).height()); - } - }); - // enable autocomplete - codemirrorEditor.on('inputRead', Functions.codeMirrorAutoCompleteOnInputRead); - - // page locking - codemirrorEditor.on('change', function (e) { - e.data = { - value: 3, - content: codemirrorEditor.isClean(), - }; - AJAX.lockPageHandler(e); - }); - - return codemirrorEditor; - } - return null; -}; - -/** - * Clear text selection - */ -Functions.clearSelection = function () { - if (document.selection && document.selection.empty) { - document.selection.empty(); - } else if (window.getSelection) { - var sel = window.getSelection(); - if (sel.empty) { - sel.empty(); - } - if (sel.removeAllRanges) { - sel.removeAllRanges(); - } - } -}; - -/** - * Create a jQuery UI tooltip - * - * @param $elements jQuery object representing the elements - * @param item the item - * (see https://api.jqueryui.com/tooltip/#option-items) - * @param myContent content of the tooltip - * @param additionalOptions to override the default options - * - */ -Functions.tooltip = function ($elements, item, myContent, additionalOptions) { - if ($('#no_hint').length > 0) { - return; - } - - var defaultOptions = { - content: myContent, - items: item, - tooltipClass: 'tooltip', - track: true, - show: false, - hide: false - }; - - $elements.tooltip($.extend(true, defaultOptions, additionalOptions)); -}; - -/** - * HTML escaping - */ -Functions.escapeHtml = function (unsafe) { - if (typeof(unsafe) !== 'undefined') { - return unsafe - .toString() - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); - } else { - return false; - } -}; - -Functions.escapeJsString = function (unsafe) { - if (typeof(unsafe) !== 'undefined') { - return unsafe - .toString() - .replace('\x00', '') - .replace('\\', '\\\\') - .replace('\'', '\\\'') - .replace(''', '\\'') - .replace('"', '\\"') - .replace('"', '\\"') - .replace('\n', '\n') - .replace('\r', '\r') - .replace(/<\/script/gi, ''); - } -}; - -/** - * Generate a new password and copy it to the password input areas - * - * @param {object} passwordForm the form that holds the password fields - * - * @return {boolean} always true - */ -Functions.suggestPassword = function (passwordForm) { - // restrict the password to just letters and numbers to avoid problems: - // "editors and viewers regard the password as multiple words and - // things like double click no longer work" - var pwchars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ'; - var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :) - var passwd = passwordForm.generated_pw; - var randomWords = new Int32Array(passwordlength); - - passwd.value = ''; - - var i; - - // First we're going to try to use a built-in CSPRNG - if (window.crypto && window.crypto.getRandomValues) { - window.crypto.getRandomValues(randomWords); - } else if (window.msCrypto && window.msCrypto.getRandomValues) { - // Because of course IE calls it msCrypto instead of being standard - window.msCrypto.getRandomValues(randomWords); - } else { - // Fallback to Math.random - for (i = 0; i < passwordlength; i++) { - randomWords[i] = Math.floor(Math.random() * pwchars.length); - } - } - - for (i = 0; i < passwordlength; i++) { - passwd.value += pwchars.charAt(Math.abs(randomWords[i]) % pwchars.length); - } - - var $jQueryPasswordForm = $(passwordForm); - - passwordForm.elements.pma_pw.value = passwd.value; - passwordForm.elements.pma_pw2.value = passwd.value; - var meterObj = $jQueryPasswordForm.find('meter[name="pw_meter"]').first(); - var meterObjLabel = $jQueryPasswordForm.find('span[name="pw_strength"]').first(); - checkPasswordStrength(passwd.value, meterObj, meterObjLabel); - return true; -}; - -/** - * Version string to integer conversion. - */ -Functions.parseVersionString = function (str) { - if (typeof(str) !== 'string') { - return false; - } - var add = 0; - // Parse possible alpha/beta/rc/ - var state = str.split('-'); - if (state.length >= 2) { - if (state[1].substr(0, 2) === 'rc') { - add = - 20 - parseInt(state[1].substr(2), 10); - } else if (state[1].substr(0, 4) === 'beta') { - add = - 40 - parseInt(state[1].substr(4), 10); - } else if (state[1].substr(0, 5) === 'alpha') { - add = - 60 - parseInt(state[1].substr(5), 10); - } else if (state[1].substr(0, 3) === 'dev') { - /* We don't handle dev, it's git snapshot */ - add = 0; - } - } - // Parse version - var x = str.split('.'); - // Use 0 for non existing parts - var maj = parseInt(x[0], 10) || 0; - var min = parseInt(x[1], 10) || 0; - var pat = parseInt(x[2], 10) || 0; - var hotfix = parseInt(x[3], 10) || 0; - return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add; -}; - -/** - * Indicates current available version on main page. - */ -Functions.currentVersion = function (data) { - if (data && data.version && data.date) { - var current = Functions.parseVersionString($('span.version').text()); - var latest = Functions.parseVersionString(data.version); - var url = 'https://www.phpmyadmin.net/files/' + Functions.escapeHtml(encodeURIComponent(data.version)) + '/'; - var versionInformationMessage = document.createElement('span'); - versionInformationMessage.className = 'latest'; - var versionInformationMessageLink = document.createElement('a'); - versionInformationMessageLink.href = url; - versionInformationMessageLink.className = 'disableAjax'; - var versionInformationMessageLinkText = document.createTextNode(data.version); - versionInformationMessageLink.appendChild(versionInformationMessageLinkText); - var prefixMessage = document.createTextNode(Messages.strLatestAvailable + ' '); - versionInformationMessage.appendChild(prefixMessage); - versionInformationMessage.appendChild(versionInformationMessageLink); - if (latest > current) { - var message = Functions.sprintf( - Messages.strNewerVersion, - Functions.escapeHtml(data.version), - Functions.escapeHtml(data.date) - ); - var htmlClass = 'notice'; - if (Math.floor(latest / 10000) === Math.floor(current / 10000)) { - /* Security update */ - htmlClass = 'error'; - } - $('#newer_version_notice').remove(); - var mainContainerDiv = document.createElement('div'); - mainContainerDiv.id = 'newer_version_notice'; - mainContainerDiv.className = htmlClass; - var mainContainerDivLink = document.createElement('a'); - mainContainerDivLink.href = url; - mainContainerDivLink.className = 'disableAjax'; - var mainContainerDivLinkText = document.createTextNode(message); - mainContainerDivLink.appendChild(mainContainerDivLinkText); - mainContainerDiv.appendChild(mainContainerDivLink); - $('#maincontainer').append($(mainContainerDiv)); - } - if (latest === current) { - versionInformationMessage = document.createTextNode(' (' + Messages.strUpToDate + ')'); - } - /* Remove extra whitespace */ - var versionInfo = $('#li_pma_version').contents().get(2); - if (typeof versionInfo !== 'undefined') { - versionInfo.textContent = $.trim(versionInfo.textContent); - } - var $liPmaVersion = $('#li_pma_version'); - $liPmaVersion.find('span.latest').remove(); - $liPmaVersion.append($(versionInformationMessage)); - } -}; - -/** - * Loads Git revision data from ajax for index.php - */ -Functions.displayGitRevision = function () { - $('#is_git_revision').remove(); - $('#li_pma_version_git').remove(); - $.get( - 'index.php', - { - 'server': CommonParams.get('server'), - 'git_revision': true, - 'ajax_request': true, - 'no_debug': true - }, - function (data) { - if (typeof data !== 'undefined' && data.success === true) { - $(data.message).insertAfter('#li_pma_version'); - } - } - ); -}; - -/** - * for PhpMyAdmin\Display\ChangePassword - * libraries/user_password.php - * - */ -Functions.displayPasswordGenerateButton = function () { - var generatePwdRow = $('').addClass('vmiddle'); - $('').html(Messages.strGeneratePassword).appendTo(generatePwdRow); - var pwdCell = $('').appendTo(generatePwdRow); - var pwdButton = $('') - .attr({ type: 'button', id: 'button_generate_password', value: Messages.strGenerate }) - .addClass('btn btn-secondary button') - .on('click', function () { - Functions.suggestPassword(this.form); - }); - var pwdTextbox = $('') - .attr({ type: 'text', name: 'generated_pw', id: 'generated_pw' }); - pwdCell.append(pwdButton).append(pwdTextbox); - - if (document.getElementById('button_generate_password') === null) { - $('#tr_element_before_generate_password').parent().append(generatePwdRow); - } - - var generatePwdDiv = $('

').addClass('item'); - $('').attr({ for: 'button_generate_password' }) - .html(Messages.strGeneratePassword + ':') - .appendTo(generatePwdDiv); - var optionsSpan = $('').addClass('options') - .appendTo(generatePwdDiv); - pwdButton.clone(true).appendTo(optionsSpan); - pwdTextbox.clone(true).appendTo(generatePwdDiv); - - if (document.getElementById('button_generate_password') === null) { - $('#div_element_before_generate_password').parent().append(generatePwdDiv); - } -}; - -/** - * selects the content of a given object, f.e. a textarea - * - * @param {object} element element of which the content will be selected - * @param {var} lock variable which holds the lock for this element or true, if no lock exists - * @param {boolean} onlyOnce boolean if true this is only done once f.e. only on first focus - */ -Functions.selectContent = function (element, lock, onlyOnce) { - if (onlyOnce && onlyOnceElements[element.name]) { - return; - } - - onlyOnceElements[element.name] = true; - - if (lock) { - return; - } - - element.select(); -}; - -/** - * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query. - * This function is called while clicking links - * - * @param theLink object the link - * @param theSqlQuery object the sql query to submit - * - * @return boolean whether to run the query or not - */ -Functions.confirmLink = function (theLink, theSqlQuery) { - // Confirmation is not required in the configuration file - // or browser is Opera (crappy js implementation) - if (Messages.strDoYouReally === '' || typeof(window.opera) !== 'undefined') { - return true; - } - - var isConfirmed = confirm(Functions.sprintf(Messages.strDoYouReally, theSqlQuery)); - if (isConfirmed) { - if (typeof(theLink.href) !== 'undefined') { - theLink.href += CommonParams.get('arg_separator') + 'is_js_confirmed=1'; - } else if (typeof(theLink.form) !== 'undefined') { - theLink.form.action += '?is_js_confirmed=1'; - } - } - - return isConfirmed; -}; - -/** - * Confirms a "DROP/DELETE/ALTER" query before - * submitting it if required. - * This function is called by the 'Functions.checkSqlQuery()' js function. - * - * @param theForm1 object the form - * @param sqlQuery1 string the sql query string - * - * @return boolean whether to run the query or not - * - * @see Functions.checkSqlQuery() - */ -Functions.confirmQuery = function (theForm1, sqlQuery1) { - // Confirmation is not required in the configuration file - if (Messages.strDoYouReally === '') { - return true; - } - - // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement - // - // TODO: find a way (if possible) to use the parser-analyser - // for this kind of verification - // For now, I just added a ^ to check for the statement at - // beginning of expression - - var doConfirmRegExp0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|PROCEDURE)\\s', 'i'); - var doConfirmRegExp1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i'); - var doConfirmRegExp2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i'); - var doConfirmRegExp3 = new RegExp('^\\s*TRUNCATE\\s', 'i'); - var doConfirmRegExp4 = new RegExp('^(?=.*UPDATE\\b)^((?!WHERE).)*$', 'i'); - - if (doConfirmRegExp0.test(sqlQuery1) || - doConfirmRegExp1.test(sqlQuery1) || - doConfirmRegExp2.test(sqlQuery1) || - doConfirmRegExp3.test(sqlQuery1) || - doConfirmRegExp4.test(sqlQuery1)) { - var message; - if (sqlQuery1.length > 100) { - message = sqlQuery1.substr(0, 100) + '\n ...'; - } else { - message = sqlQuery1; - } - var isConfirmed = confirm(Functions.sprintf(Messages.strDoYouReally, message)); - // statement is confirmed -> update the - // "is_js_confirmed" form field so the confirm test won't be - // run on the server side and allows to submit the form - if (isConfirmed) { - theForm1.elements.is_js_confirmed.value = 1; - return true; - } else { - // statement is rejected -> do not submit the form - window.focus(); - return false; - } // end if (handle confirm box result) - } // end if (display confirm box) - - return true; -}; - -/** - * Displays an error message if the user submitted the sql query form with no - * sql query, else checks for "DROP/DELETE/ALTER" statements - * - * @param theForm object the form - * - * @return boolean always false - * - * @see Functions.confirmQuery() - */ -Functions.checkSqlQuery = function (theForm) { - // get the textarea element containing the query - var sqlQuery; - if (codeMirrorEditor) { - codeMirrorEditor.save(); - sqlQuery = codeMirrorEditor.getValue(); - } else { - sqlQuery = theForm.elements.sql_query.value; - } - var spaceRegExp = new RegExp('\\s+'); - if (typeof(theForm.elements.sql_file) !== 'undefined' && - theForm.elements.sql_file.value.replace(spaceRegExp, '') !== '') { - return true; - } - if (typeof(theForm.elements.id_bookmark) !== 'undefined' && - (theForm.elements.id_bookmark.value !== null || theForm.elements.id_bookmark.value !== '') && - theForm.elements.id_bookmark.selectedIndex !== 0) { - return true; - } - var result = false; - // Checks for "DROP/DELETE/ALTER" statements - if (sqlQuery.replace(spaceRegExp, '') !== '') { - result = Functions.confirmQuery(theForm, sqlQuery); - } else { - alert(Messages.strFormEmpty); - } - - if (codeMirrorEditor) { - codeMirrorEditor.focus(); - } else if (codeMirrorInlineEditor) { - codeMirrorInlineEditor.focus(); - } - return result; -}; - -/** - * Check if a form's element is empty. - * An element containing only spaces is also considered empty - * - * @param {object} theForm the form - * @param {string} theFieldName the name of the form field to put the focus on - * - * @return {boolean} whether the form field is empty or not - */ -Functions.emptyCheckTheField = function (theForm, theFieldName) { - var theField = theForm.elements[theFieldName]; - var spaceRegExp = new RegExp('\\s+'); - return theField.value.replace(spaceRegExp, '') === ''; -}; - -/** - * Ensures a value submitted in a form is numeric and is in a range - * - * @param object the form - * @param string the name of the form field to check - * @param integer the minimum authorized value - * @param integer the maximum authorized value - * - * @return boolean whether a valid number has been submitted or not - */ -Functions.checkFormElementInRange = function (theForm, theFieldName, message, minimum, maximum) { - var theField = theForm.elements[theFieldName]; - var val = parseInt(theField.value, 10); - var min = minimum; - var max = maximum; - - if (typeof(min) === 'undefined') { - min = 0; - } - if (typeof(max) === 'undefined') { - max = Number.MAX_VALUE; - } - - if (isNaN(val)) { - theField.select(); - alert(Messages.strEnterValidNumber); - theField.focus(); - return false; - } else if (val < min || val > max) { - theField.select(); - alert(Functions.sprintf(message, val)); - theField.focus(); - return false; - } else { - theField.value = val; - } - return true; -}; - -Functions.checkTableEditForm = function (theForm, fieldsCnt) { - // TODO: avoid sending a message if user just wants to add a line - // on the form but has not completed at least one field name - - var atLeastOneField = 0; - var i; - var elm; - var elm2; - var elm3; - var val; - var id; - - for (i = 0; i < fieldsCnt; i++) { - id = '#field_' + i + '_2'; - elm = $(id); - val = elm.val(); - if (val === 'VARCHAR' || val === 'CHAR' || val === 'BIT' || val === 'VARBINARY' || val === 'BINARY') { - elm2 = $('#field_' + i + '_3'); - val = parseInt(elm2.val(), 10); - elm3 = $('#field_' + i + '_1'); - if (isNaN(val) && elm3.val() !== '') { - elm2.select(); - alert(Messages.strEnterValidLength); - elm2.focus(); - return false; - } - } - - if (atLeastOneField === 0) { - id = 'field_' + i + '_1'; - if (!Functions.emptyCheckTheField(theForm, id)) { - atLeastOneField = 1; - } - } - } - if (atLeastOneField === 0) { - var theField = theForm.elements.field_0_1; - alert(Messages.strFormEmpty); - theField.focus(); - return false; - } - - // at least this section is under jQuery - var $input = $('input.textfield[name=\'table\']'); - if ($input.val() === '') { - alert(Messages.strFormEmpty); - $input.focus(); - return false; - } - - return true; -}; - -/** - * True if last click is to check a row. - */ -var lastClickChecked = false; - -/** - * Zero-based index of last clicked row. - * Used to handle the shift + click event in the code above. - */ -var lastClickedRow = -1; - -/** - * Zero-based index of last shift clicked row. - */ -var lastShiftClickedRow = -1; - -var idleSecondsCounter = 0; -var incInterval; -var updateTimeout; -AJAX.registerTeardown('functions.js', function () { - clearTimeout(updateTimeout); - clearInterval(incInterval); - $(document).off('mousemove'); -}); - -AJAX.registerOnload('functions.js', function () { - document.onclick = function () { - idleSecondsCounter = 0; - }; - $(document).on('mousemove',function () { - idleSecondsCounter = 0; - }); - document.onkeypress = function () { - idleSecondsCounter = 0; - }; - function guid () { - function s4 () { - return Math.floor((1 + Math.random()) * 0x10000) - .toString(16) - .substring(1); - } - return s4() + s4() + '-' + s4() + '-' + s4() + '-' + - s4() + '-' + s4() + s4() + s4(); - } - - function SetIdleTime () { - idleSecondsCounter++; - } - function UpdateIdleTime () { - var href = 'index.php'; - var guid = 'default'; - if (isStorageSupported('sessionStorage')) { - guid = window.sessionStorage.guid; - } - var params = { - 'ajax_request' : true, - 'server' : CommonParams.get('server'), - 'db' : CommonParams.get('db'), - 'guid': guid, - 'access_time': idleSecondsCounter, - 'check_timeout': 1 - }; - $.ajax({ - type: 'POST', - url: href, - data: params, - success: function (data) { - if (data.success) { - if (CommonParams.get('LoginCookieValidity') - idleSecondsCounter < 0) { - /* There is other active window, let's reset counter */ - idleSecondsCounter = 0; - } - var remaining = Math.min( - /* Remaining login validity */ - CommonParams.get('LoginCookieValidity') - idleSecondsCounter, - /* Remaining time till session GC */ - CommonParams.get('session_gc_maxlifetime') - ); - var interval = 1000; - if (remaining > 5) { - // max value for setInterval() function - interval = Math.min((remaining - 1) * 1000, Math.pow(2, 31) - 1); - } - updateTimeout = window.setTimeout(UpdateIdleTime, interval); - } else { // timeout occurred - clearInterval(incInterval); - if (isStorageSupported('sessionStorage')) { - window.sessionStorage.clear(); - } - // append the login form on the page, disable all the forms which were not disabled already, close all the open jqueryui modal boxes - if (!$('#modalOverlay').length) { - $('fieldset').not(':disabled').attr('disabled', 'disabled').addClass('disabled_for_expiration'); - $('body').append(data.error); - $('.ui-dialog').each(function () { - $('#' + $(this).attr('aria-describedby')).dialog('close'); - }); - $('#input_username').trigger('focus'); - } else { - CommonParams.set('token', data.new_token); - $('input[name=token]').val(data.new_token); - } - idleSecondsCounter = 0; - Functions.handleRedirectAndReload(data); - } - } - }); - } - if (CommonParams.get('logged_in')) { - incInterval = window.setInterval(SetIdleTime, 1000); - var sessionTimeout = Math.min( - CommonParams.get('LoginCookieValidity'), - CommonParams.get('session_gc_maxlifetime') - ); - if (isStorageSupported('sessionStorage')) { - window.sessionStorage.setItem('guid', guid()); - } - var interval = (sessionTimeout - 5) * 1000; - if (interval > Math.pow(2, 31) - 1) { // max value for setInterval() function - interval = Math.pow(2, 31) - 1; - } - updateTimeout = window.setTimeout(UpdateIdleTime, interval); - } -}); -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('functions.js', function () { - $(document).off('click', 'input:checkbox.checkall'); -}); - -AJAX.registerOnload('functions.js', function () { - /** - * Row marking in horizontal mode (use "on" so that it works also for - * next pages reached via AJAX); a tr may have the class noclick to remove - * this behavior. - */ - - $(document).on('click', 'input:checkbox.checkall', function (e) { - var $this = $(this); - var $tr = $this.closest('tr'); - var $table = $this.closest('table'); - - if (!e.shiftKey || lastClickedRow === -1) { - // usual click - - var $checkbox = $tr.find(':checkbox.checkall'); - var checked = $this.prop('checked'); - $checkbox.prop('checked', checked).trigger('change'); - if (checked) { - $tr.addClass('marked'); - } else { - $tr.removeClass('marked'); - } - lastClickChecked = checked; - - // remember the last clicked row - lastClickedRow = lastClickChecked ? $table.find('tbody tr:not(.noclick)').index($tr) : -1; - lastShiftClickedRow = -1; - } else { - // handle the shift click - Functions.clearSelection(); - var start; - var end; - - // clear last shift click result - if (lastShiftClickedRow >= 0) { - if (lastShiftClickedRow >= lastClickedRow) { - start = lastClickedRow; - end = lastShiftClickedRow; - } else { - start = lastShiftClickedRow; - end = lastClickedRow; - } - $tr.parent().find('tr:not(.noclick)') - .slice(start, end + 1) - .removeClass('marked') - .find(':checkbox') - .prop('checked', false) - .trigger('change'); - } - - // handle new shift click - var currRow = $table.find('tbody tr:not(.noclick)').index($tr); - if (currRow >= lastClickedRow) { - start = lastClickedRow; - end = currRow; - } else { - start = currRow; - end = lastClickedRow; - } - $tr.parent().find('tr:not(.noclick)') - .slice(start, end + 1) - .addClass('marked') - .find(':checkbox') - .prop('checked', true) - .trigger('change'); - - // remember the last shift clicked row - lastShiftClickedRow = currRow; - } - }); - - Functions.addDateTimePicker(); - - /** - * Add attribute to text boxes for iOS devices (based on bugID: 3508912) - */ - if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) { - $('input[type=text]').attr('autocapitalize', 'off').attr('autocorrect', 'off'); - } -}); - -/** - * Checks/unchecks all options of a '); - } - } else { - if ($simulateDml.length) { - $simulateDml.remove(); - } - } -}; - -/** - * Create quick sql statements. - * - */ -Functions.insertQuery = function (queryType) { - if (queryType === 'clear') { - Functions.setQuery(''); - return; - } else if (queryType === 'format') { - if (codeMirrorEditor) { - $('#querymessage').html(Messages.strFormatting + - ' '); - var href = 'db_sql_format.php'; - var params = { - 'ajax_request': true, - 'sql': codeMirrorEditor.getValue(), - 'server': CommonParams.get('server') - }; - $.ajax({ - type: 'POST', - url: href, - data: params, - success: function (data) { - if (data.success) { - codeMirrorEditor.setValue(data.sql); - } - $('#querymessage').html(''); - } - }); - } - return; - } else if (queryType === 'saved') { - if (isStorageSupported('localStorage') && typeof window.localStorage.autoSavedSql !== 'undefined') { - Functions.setQuery(window.localStorage.autoSavedSql); - } else if (Cookies.get('autoSavedSql')) { - Functions.setQuery(Cookies.get('autoSavedSql')); - } else { - Functions.ajaxShowMessage(Messages.strNoAutoSavedQuery); - } - return; - } - - var query = ''; - var myListBox = document.sqlform.dummy; - var table = document.sqlform.table.value; - - if (myListBox.options.length > 0) { - sqlBoxLocked = true; - var columnsList = ''; - var valDis = ''; - var editDis = ''; - var NbSelect = 0; - for (var i = 0; i < myListBox.options.length; i++) { - NbSelect++; - if (NbSelect > 1) { - columnsList += ', '; - valDis += ','; - editDis += ','; - } - columnsList += myListBox.options[i].value; - valDis += '[value-' + NbSelect + ']'; - editDis += myListBox.options[i].value + '=[value-' + NbSelect + ']'; - } - if (queryType === 'selectall') { - query = 'SELECT * FROM `' + table + '` WHERE 1'; - } else if (queryType === 'select') { - query = 'SELECT ' + columnsList + ' FROM `' + table + '` WHERE 1'; - } else if (queryType === 'insert') { - query = 'INSERT INTO `' + table + '`(' + columnsList + ') VALUES (' + valDis + ')'; - } else if (queryType === 'update') { - query = 'UPDATE `' + table + '` SET ' + editDis + ' WHERE 1'; - } else if (queryType === 'delete') { - query = 'DELETE FROM `' + table + '` WHERE 0'; - } - Functions.setQuery(query); - sqlBoxLocked = false; - } -}; - -/** - * Inserts multiple fields. - * - */ -Functions.insertValueQuery = function () { - var myQuery = document.sqlform.sql_query; - var myListBox = document.sqlform.dummy; - - if (myListBox.options.length > 0) { - sqlBoxLocked = true; - var columnsList = ''; - var NbSelect = 0; - for (var i = 0; i < myListBox.options.length; i++) { - if (myListBox.options[i].selected) { - NbSelect++; - if (NbSelect > 1) { - columnsList += ', '; - } - columnsList += myListBox.options[i].value; - } - } - - /* CodeMirror support */ - if (codeMirrorEditor) { - codeMirrorEditor.replaceSelection(columnsList); - codeMirrorEditor.focus(); - // IE support - } else if (document.selection) { - myQuery.focus(); - var sel = document.selection.createRange(); - sel.text = columnsList; - // MOZILLA/NETSCAPE support - } else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart === '0') { - var startPos = document.sqlform.sql_query.selectionStart; - var endPos = document.sqlform.sql_query.selectionEnd; - var SqlString = document.sqlform.sql_query.value; - - myQuery.value = SqlString.substring(0, startPos) + columnsList + SqlString.substring(endPos, SqlString.length); - myQuery.focus(); - } else { - myQuery.value += columnsList; - } - sqlBoxLocked = false; - } -}; - -/** - * Updates the input fields for the parameters based on the query - */ -Functions.updateQueryParameters = function () { - if ($('#parameterized').is(':checked')) { - var query = codeMirrorEditor ? codeMirrorEditor.getValue() : $('#sqlquery').val(); - - var allParameters = query.match(/:[a-zA-Z0-9_]+/g); - var parameters = []; - // get unique parameters - if (allParameters) { - $.each(allParameters, function (i, parameter) { - if ($.inArray(parameter, parameters) === -1) { - parameters.push(parameter); - } - }); - } else { - $('#parametersDiv').text(Messages.strNoParam); - return; - } - - var $temp = $('
'); - $temp.append($('#parametersDiv').children()); - $('#parametersDiv').empty(); - - $.each(parameters, function (i, parameter) { - var paramName = parameter.substring(1); - var $param = $temp.find('#paramSpan_' + paramName); - if (! $param.length) { - $param = $(''); - $('').text(parameter).appendTo($param); - $('').appendTo($param); - } - $('#parametersDiv').append($param); - }); - } else { - $('#parametersDiv').empty(); - } -}; - -/** - * Refresh/resize the WYSIWYG scratchboard - */ -Functions.refreshLayout = function () { - var $elm = $('#pdflayout'); - var orientation = $('#orientation_opt').val(); - var paper = 'A4'; - var $paperOpt = $('#paper_opt'); - if ($paperOpt.length === 1) { - paper = $paperOpt.val(); - } - var posa = 'y'; - var posb = 'x'; - if (orientation === 'P') { - posa = 'x'; - posb = 'y'; - } - $elm.css('width', Functions.pdfPaperSize(paper, posa) + 'px'); - $elm.css('height', Functions.pdfPaperSize(paper, posb) + 'px'); -}; - -/** - * Initializes positions of elements. - */ -Functions.tableDragInit = function () { - $('.pdflayout_table').each(function () { - var $this = $(this); - var number = $this.data('number'); - var x = $('#c_table_' + number + '_x').val(); - var y = $('#c_table_' + number + '_y').val(); - $this.css('left', x + 'px'); - $this.css('top', y + 'px'); - /* Make elements draggable */ - $this.draggable({ - containment: 'parent', - drag: function (evt, ui) { - var number = $this.data('number'); - $('#c_table_' + number + '_x').val(parseInt(ui.position.left, 10)); - $('#c_table_' + number + '_y').val(parseInt(ui.position.top, 10)); - } - }); - }); -}; - -/** - * Resets drag and drop positions. - */ -Functions.resetDrag = function () { - $('.pdflayout_table').each(function () { - var $this = $(this); - var x = $this.data('x'); - var y = $this.data('y'); - $this.css('left', x + 'px'); - $this.css('top', y + 'px'); - }); -}; - -/** - * User schema handlers. - */ -$(function () { - /* Move in scratchboard on manual change */ - $(document).on('change', '.position-change', function () { - var $this = $(this); - var $elm = $('#table_' + $this.data('number')); - $elm.css($this.data('axis'), $this.val() + 'px'); - }); - /* Refresh on paper size/orientation change */ - $(document).on('change', '.paper-change', function () { - var $elm = $('#pdflayout'); - if ($elm.css('visibility') === 'visible') { - Functions.refreshLayout(); - Functions.tableDragInit(); - } - }); - /* Show/hide the WYSIWYG scratchboard */ - $(document).on('click', '#toggle-dragdrop', function () { - var $elm = $('#pdflayout'); - if ($elm.css('visibility') === 'hidden') { - Functions.refreshLayout(); - Functions.tableDragInit(); - $elm.css('visibility', 'visible'); - $elm.css('display', 'block'); - $('#showwysiwyg').val('1'); - } else { - $elm.css('visibility', 'hidden'); - $elm.css('display', 'none'); - $('#showwysiwyg').val('0'); - } - }); - /* Reset scratchboard */ - $(document).on('click', '#reset-dragdrop', function () { - Functions.resetDrag(); - }); -}); - -/** - * Returns paper sizes for a given format - */ -Functions.pdfPaperSize = function (format, axis) { - switch (format.toUpperCase()) { - case '4A0': - if (axis === 'x') { - return 4767.87; - } - return 6740.79; - case '2A0': - if (axis === 'x') { - return 3370.39; - } - return 4767.87; - case 'A0': - if (axis === 'x') { - return 2383.94; - } - return 3370.39; - case 'A1': - if (axis === 'x') { - return 1683.78; - } - return 2383.94; - case 'A2': - if (axis === 'x') { - return 1190.55; - } - return 1683.78; - case 'A3': - if (axis === 'x') { - return 841.89; - } - return 1190.55; - case 'A4': - if (axis === 'x') { - return 595.28; - } - return 841.89; - case 'A5': - if (axis === 'x') { - return 419.53; - } - return 595.28; - case 'A6': - if (axis === 'x') { - return 297.64; - } - return 419.53; - case 'A7': - if (axis === 'x') { - return 209.76; - } - return 297.64; - case 'A8': - if (axis === 'x') { - return 147.40; - } - return 209.76; - case 'A9': - if (axis === 'x') { - return 104.88; - } - return 147.40; - case 'A10': - if (axis === 'x') { - return 73.70; - } - return 104.88; - case 'B0': - if (axis === 'x') { - return 2834.65; - } - return 4008.19; - case 'B1': - if (axis === 'x') { - return 2004.09; - } - return 2834.65; - case 'B2': - if (axis === 'x') { - return 1417.32; - } - return 2004.09; - case 'B3': - if (axis === 'x') { - return 1000.63; - } - return 1417.32; - case 'B4': - if (axis === 'x') { - return 708.66; - } - return 1000.63; - case 'B5': - if (axis === 'x') { - return 498.90; - } - return 708.66; - case 'B6': - if (axis === 'x') { - return 354.33; - } - return 498.90; - case 'B7': - if (axis === 'x') { - return 249.45; - } - return 354.33; - case 'B8': - if (axis === 'x') { - return 175.75; - } - return 249.45; - case 'B9': - if (axis === 'x') { - return 124.72; - } - return 175.75; - case 'B10': - if (axis === 'x') { - return 87.87; - } - return 124.72; - case 'C0': - if (axis === 'x') { - return 2599.37; - } - return 3676.54; - case 'C1': - if (axis === 'x') { - return 1836.85; - } - return 2599.37; - case 'C2': - if (axis === 'x') { - return 1298.27; - } - return 1836.85; - case 'C3': - if (axis === 'x') { - return 918.43; - } - return 1298.27; - case 'C4': - if (axis === 'x') { - return 649.13; - } - return 918.43; - case 'C5': - if (axis === 'x') { - return 459.21; - } - return 649.13; - case 'C6': - if (axis === 'x') { - return 323.15; - } - return 459.21; - case 'C7': - if (axis === 'x') { - return 229.61; - } - return 323.15; - case 'C8': - if (axis === 'x') { - return 161.57; - } - return 229.61; - case 'C9': - if (axis === 'x') { - return 113.39; - } - return 161.57; - case 'C10': - if (axis === 'x') { - return 79.37; - } - return 113.39; - case 'RA0': - if (axis === 'x') { - return 2437.80; - } - return 3458.27; - case 'RA1': - if (axis === 'x') { - return 1729.13; - } - return 2437.80; - case 'RA2': - if (axis === 'x') { - return 1218.90; - } - return 1729.13; - case 'RA3': - if (axis === 'x') { - return 864.57; - } - return 1218.90; - case 'RA4': - if (axis === 'x') { - return 609.45; - } - return 864.57; - case 'SRA0': - if (axis === 'x') { - return 2551.18; - } - return 3628.35; - case 'SRA1': - if (axis === 'x') { - return 1814.17; - } - return 2551.18; - case 'SRA2': - if (axis === 'x') { - return 1275.59; - } - return 1814.17; - case 'SRA3': - if (axis === 'x') { - return 907.09; - } - return 1275.59; - case 'SRA4': - if (axis === 'x') { - return 637.80; - } - return 907.09; - case 'LETTER': - if (axis === 'x') { - return 612.00; - } - return 792.00; - case 'LEGAL': - if (axis === 'x') { - return 612.00; - } - return 1008.00; - case 'EXECUTIVE': - if (axis === 'x') { - return 521.86; - } - return 756.00; - case 'FOLIO': - if (axis === 'x') { - return 612.00; - } - return 936.00; - } - return 0; -}; - -/** - * Get checkbox for foreign key checks - * - * @return string - */ -Functions.getForeignKeyCheckboxLoader = function () { - var html = ''; - html += '
'; - html += '
'; - html += Functions.getImage('ajax_clock_small'); - html += '
'; - html += '
'; - return html; -}; - -Functions.loadForeignKeyCheckbox = function () { - // Load default foreign key check value - var params = { - 'ajax_request': true, - 'server': CommonParams.get('server'), - 'get_default_fk_check_value': true - }; - $.get('sql.php', params, function (data) { - var html = '' + - '' + - ''; - $('.load-default-fk-check-value').replaceWith(html); - }); -}; - -Functions.getJsConfirmCommonParam = function (elem, parameters) { - var $elem = $(elem); - var params = parameters; - var sep = CommonParams.get('arg_separator'); - if (params) { - // Strip possible leading ? - if (params.substring(0,1) === '?') { - params = params.substr(1); - } - params += sep; - } else { - params = ''; - } - params += 'is_js_confirmed=1' + sep + 'ajax_request=true' + sep + 'fk_checks=' + ($elem.find('#fk_checks').is(':checked') ? 1 : 0); - return params; -}; - -/** - * Unbind all event handlers before tearing down a page - */ -AJAX.registerTeardown('functions.js', function () { - $(document).off('click', 'a.inline_edit_sql'); - $(document).off('click', 'input#sql_query_edit_save'); - $(document).off('click', 'input#sql_query_edit_discard'); - $('input.sqlbutton').off('click'); - if (codeMirrorEditor) { - codeMirrorEditor.off('blur'); - } else { - $(document).off('blur', '#sqlquery'); - } - $(document).off('change', '#parameterized'); - $(document).off('click', 'input.sqlbutton'); - $('#sqlquery').off('keydown'); - $('#sql_query_edit').off('keydown'); - - if (codeMirrorInlineEditor) { - // Copy the sql query to the text area to preserve it. - $('#sql_query_edit').text(codeMirrorInlineEditor.getValue()); - $(codeMirrorInlineEditor.getWrapperElement()).off('keydown'); - codeMirrorInlineEditor.toTextArea(); - codeMirrorInlineEditor = false; - } - if (codeMirrorEditor) { - $(codeMirrorEditor.getWrapperElement()).off('keydown'); - } -}); - -/** - * Jquery Coding for inline editing SQL_QUERY - */ -AJAX.registerOnload('functions.js', function () { - // If we are coming back to the page by clicking forward button - // of the browser, bind the code mirror to inline query editor. - Functions.bindCodeMirrorToInlineEditor(); - $(document).on('click', 'a.inline_edit_sql', function () { - if ($('#sql_query_edit').length) { - // An inline query editor is already open, - // we don't want another copy of it - return false; - } - - var $form = $(this).prev('form'); - var sqlQuery = $form.find('input[name=\'sql_query\']').val().trim(); - var $innerSql = $(this).parent().prev().find('code.sql'); - - var newContent = '\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: 'import.php', 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; - } - $('.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 href = 'db_sql_autocomplete.php'; - var params = { - 'ajax_request': true, - 'server': CommonParams.get('server'), - 'db': CommonParams.get('db'), - 'no_debug': true - }; - - var columnHintRender = function (elem, self, data) { - $('
') - .text(data.columnName) - .appendTo(elem); - $('
') - .text(data.columnHint) - .appendTo(elem); - }; - - $.ajax({ - type: 'POST', - url: href, - data: params, - success: function (data) { - if (data.success) { - var tables = JSON