1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * general function, usually for data manipulation pages
8 * @var sql_box_locked lock for the sqlbox textarea in the querybox
10 var sql_box_locked = false;
13 * @var array holds elements which content should only selected once
15 var only_once_elements = [];
18 * @var int ajax_message_count Number of AJAX messages shown since page load
20 var ajax_message_count = 0;
23 * @var codemirror_editor object containing CodeMirror editor of the query editor in SQL tab
25 var codemirror_editor = false;
28 * @var codemirror_editor object containing CodeMirror editor of the inline query editor
30 var codemirror_inline_editor = false;
33 * @var sql_autocomplete_in_progress bool shows if Table/Column name autocomplete AJAX is in progress
35 var sql_autocomplete_in_progress = false;
38 * @var sql_autocomplete object containing list of columns in each table
40 var sql_autocomplete = false;
43 * @var sql_autocomplete_default_table string containing default table to autocomplete columns
45 var sql_autocomplete_default_table = '';
48 * @var central_column_list array to hold the columns in central list per db.
50 var central_column_list = [];
53 * @var primary_indexes array to hold 'Primary' index columns.
55 var primary_indexes = [];
58 * @var unique_indexes array to hold 'Unique' index columns.
60 var unique_indexes = [];
63 * @var indexes array to hold 'Index' columns.
68 * @var fulltext_indexes array to hold 'Fulltext' columns.
70 var fulltext_indexes = [];
73 * @var spatial_indexes array to hold 'Spatial' columns.
75 var spatial_indexes = [];
78 * Make sure that ajax requests will not be cached
79 * by appending a random variable to their parameters
81 $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
82 var nocache = new Date().getTime() + '' + Math.floor(Math.random() * 1000000);
83 if (typeof options.data === 'string') {
84 options.data += '&_nocache=' + nocache + '&token=' + encodeURIComponent(PMA_commonParams.get('token'));
85 } else if (typeof options.data === 'object') {
86 options.data = $.extend(originalOptions.data, { '_nocache' : nocache, 'token': PMA_commonParams.get('token') });
91 * Adds a date/time picker to an element
93 * @param object $this_element a jQuery object pointing to the element
95 function PMA_addDatepicker ($this_element, type, options) {
96 var showTimepicker = true;
97 if (type === 'date') {
98 showTimepicker = false;
101 var defaultOptions = {
103 buttonImage: themeCalendarImage, // defined in js/messages.php
104 buttonImageOnly: true,
110 showTimepicker: showTimepicker,
111 showButtonPanel: false,
112 dateFormat: 'yy-mm-dd', // yy means year with four digits
113 timeFormat: 'HH:mm:ss.lc',
114 constrainInput: false,
115 altFieldTimeOnly: false,
117 beforeShow: function (input, inst) {
118 // Remember that we came from the datepicker; this is used
119 // in tbl_change.js by verificationsAfterFieldChange()
120 $this_element.data('comes_from', 'datepicker');
121 if ($(input).closest('.cEdit').length > 0) {
122 setTimeout(function () {
130 setTimeout(function () {
131 // Fix wrong timepicker z-index, doesn't work without timeout
132 $('#ui-timepicker-div').css('z-index', $('#ui-datepicker-div').css('z-index'));
133 // Integrate tooltip text into dialog
134 var tooltip = $this_element.tooltip('instance');
135 if (typeof tooltip !== 'undefined') {
137 var $note = $('<p class="note"></div>');
138 $note.text(tooltip.option('content'));
139 $('div.ui-datepicker').append($note);
143 onSelect: function () {
144 $this_element.data('datepicker').inline = true;
146 onClose: function (dateText, dp_inst) {
147 // The value is no more from the date picker
148 $this_element.data('comes_from', '');
149 if (typeof $this_element.data('datepicker') !== 'undefined') {
150 $this_element.data('datepicker').inline = false;
152 var tooltip = $this_element.tooltip('instance');
153 if (typeof tooltip !== 'undefined') {
158 if (type == 'time') {
159 $this_element.timepicker($.extend(defaultOptions, options));
160 // Add a tip regarding entering MySQL allowed-values for TIME data-type
161 PMA_tooltip($this_element, 'input', PMA_messages.strMysqlAllowedValuesTipTime);
163 $this_element.datetimepicker($.extend(defaultOptions, options));
168 * Add a date/time picker to each element that needs it
169 * (only when jquery-ui-timepicker-addon.js is loaded)
171 function addDateTimePicker () {
172 if ($.timepicker !== undefined) {
173 $('input.timefield, input.datefield, input.datetimefield').each(function () {
174 var decimals = $(this).parent().attr('data-decimals');
175 var type = $(this).parent().attr('data-type');
177 var showMillisec = false;
178 var showMicrosec = false;
179 var timeFormat = 'HH:mm:ss';
181 // check for decimal places of seconds
182 if (decimals > 0 && type.indexOf('time') !== -1) {
186 timeFormat = 'HH:mm:ss.lc';
189 timeFormat = 'HH:mm:ss.l';
192 if (type === 'time') {
195 PMA_addDatepicker($(this), type, {
196 showMillisec: showMillisec,
197 showMicrosec: showMicrosec,
198 timeFormat: timeFormat,
201 // Add a tip regarding entering MySQL allowed-values
202 // for TIME and DATE data-type
203 if ($(this).hasClass('timefield')) {
204 PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipTime);
205 } else if ($(this).hasClass('datefield')) {
206 PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipDate);
213 * Handle redirect and reload flags sent as part of AJAX requests
215 * @param data ajax response data
217 function PMA_handleRedirectAndReload (data) {
218 if (parseInt(data.redirect_flag) === 1) {
219 // add one more GET param to display session expiry msg
220 if (window.location.href.indexOf('?') === -1) {
221 window.location.href += '?session_expired=1';
223 window.location.href += PMA_commonParams.get('arg_separator') + 'session_expired=1';
225 window.location.reload();
226 } else if (parseInt(data.reload_flag) === 1) {
227 window.location.reload();
232 * Creates an SQL editor which supports auto completing etc.
234 * @param $textarea jQuery object wrapping the textarea to be made the editor
235 * @param options optional options for CodeMirror
236 * @param resize optional resizing ('vertical', 'horizontal', 'both')
237 * @param lintOptions additional options for lint
239 function PMA_getSQLEditor ($textarea, options, resize, lintOptions) {
240 if ($textarea.length > 0 && typeof CodeMirror !== 'undefined') {
241 // merge options for CodeMirror
245 extraKeys: { 'Ctrl-Space': 'autocomplete' },
246 hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true },
248 mode: 'text/x-mysql',
252 if (CodeMirror.sqlLint) {
254 gutters: ['CodeMirror-lint-markers'],
256 'getAnnotations': CodeMirror.sqlLint,
258 'lintOptions': lintOptions
263 $.extend(true, defaults, options);
265 // create CodeMirror editor
266 var codemirrorEditor = CodeMirror.fromTextArea($textarea[0], defaults);
272 if (resize === 'vertical') {
275 if (resize === 'both') {
278 if (resize === 'horizontal') {
281 $(codemirrorEditor.getWrapperElement())
282 .css('resize', resize)
285 resize: function () {
286 codemirrorEditor.setSize($(this).width(), $(this).height());
289 // enable autocomplete
290 codemirrorEditor.on('inputRead', codemirrorAutocompleteOnInputRead);
293 codemirrorEditor.on('change', function (e) {
296 content: codemirrorEditor.isClean(),
298 AJAX.lockPageHandler(e);
301 return codemirrorEditor;
307 * Clear text selection
309 function PMA_clearSelection () {
310 if (document.selection && document.selection.empty) {
311 document.selection.empty();
312 } else if (window.getSelection) {
313 var sel = window.getSelection();
317 if (sel.removeAllRanges) {
318 sel.removeAllRanges();
324 * Create a jQuery UI tooltip
326 * @param $elements jQuery object representing the elements
327 * @param item the item
328 * (see https://api.jqueryui.com/tooltip/#option-items)
329 * @param myContent content of the tooltip
330 * @param additionalOptions to override the default options
333 function PMA_tooltip ($elements, item, myContent, additionalOptions) {
334 if ($('#no_hint').length > 0) {
338 var defaultOptions = {
341 tooltipClass: 'tooltip',
347 $elements.tooltip($.extend(true, defaultOptions, additionalOptions));
354 function escapeHtml (unsafe) {
355 if (typeof(unsafe) !== 'undefined') {
358 .replace(/&/g, '&')
359 .replace(/</g, '<')
360 .replace(/>/g, '>')
361 .replace(/"/g, '"')
362 .replace(/'/g, ''');
368 function escapeJsString (unsafe) {
369 if (typeof(unsafe) !== 'undefined') {
373 .replace('\\', '\\\\')
374 .replace('\'', '\\\'')
375 .replace(''', '\\\'')
377 .replace('"', '\"')
380 .replace(/<\/script/gi, '</\' + \'script');
387 function escapeBacktick (s) {
388 return s.replace('`', '``');
391 function escapeSingleQuote (s) {
392 return s.replace('\\', '\\\\').replace('\'', '\\\'');
395 function PMA_sprintf () {
396 return sprintf.apply(this, arguments);
400 * Hides/shows the default value input field, depending on the default type
401 * Ticks the NULL checkbox if NULL is chosen as default value.
403 function PMA_hideShowDefaultValue ($default_type) {
404 if ($default_type.val() === 'USER_DEFINED') {
405 $default_type.siblings('.default_value').show().focus();
407 $default_type.siblings('.default_value').hide();
408 if ($default_type.val() === 'NULL') {
409 var $null_checkbox = $default_type.closest('tr').find('.allow_null');
410 $null_checkbox.prop('checked', true);
416 * Hides/shows the input field for column expression based on whether
417 * VIRTUAL/PERSISTENT is selected
419 * @param $virtuality virtuality dropdown
421 function PMA_hideShowExpression ($virtuality) {
422 if ($virtuality.val() === '') {
423 $virtuality.siblings('.expression').hide();
425 $virtuality.siblings('.expression').show();
430 * Show notices for ENUM columns; add/hide the default value
433 function PMA_verifyColumnsProperties () {
434 $('select.column_type').each(function () {
435 PMA_showNoticeForEnum($(this));
437 $('select.default_type').each(function () {
438 PMA_hideShowDefaultValue($(this));
440 $('select.virtuality').each(function () {
441 PMA_hideShowExpression($(this));
446 * Add a hidden field to the form to indicate that this will be an
447 * Ajax request (only if this hidden field does not exist)
449 * @param $form object the form
451 function PMA_prepareForAjaxRequest ($form) {
452 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
453 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
458 * Generate a new password and copy it to the password input areas
460 * @param passwd_form object the form that holds the password fields
462 * @return boolean always true
464 function suggestPassword (passwd_form) {
465 // restrict the password to just letters and numbers to avoid problems:
466 // "editors and viewers regard the password as multiple words and
467 // things like double click no longer work"
468 var pwchars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ';
469 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
470 var passwd = passwd_form.generated_pw;
471 var randomWords = new Int32Array(passwordlength);
475 // First we're going to try to use a built-in CSPRNG
476 if (window.crypto && window.crypto.getRandomValues) {
477 window.crypto.getRandomValues(randomWords);
478 } else if (window.msCrypto && window.msCrypto.getRandomValues) {
479 // Because of course IE calls it msCrypto instead of being standard
480 window.msCrypto.getRandomValues(randomWords);
482 // Fallback to Math.random
483 for (var i = 0; i < passwordlength; i++) {
484 randomWords[i] = Math.floor(Math.random() * pwchars.length);
488 for (var i = 0; i < passwordlength; i++) {
489 passwd.value += pwchars.charAt(Math.abs(randomWords[i]) % pwchars.length);
492 $jquery_passwd_form = $(passwd_form);
494 passwd_form.elements.pma_pw.value = passwd.value;
495 passwd_form.elements.pma_pw2.value = passwd.value;
496 meter_obj = $jquery_passwd_form.find('meter[name="pw_meter"]').first();
497 meter_obj_label = $jquery_passwd_form.find('span[name="pw_strength"]').first();
498 checkPasswordStrength(passwd.value, meter_obj, meter_obj_label);
503 * Version string to integer conversion.
505 function parseVersionString (str) {
506 if (typeof(str) !== 'string') {
510 // Parse possible alpha/beta/rc/
511 var state = str.split('-');
512 if (state.length >= 2) {
513 if (state[1].substr(0, 2) === 'rc') {
514 add = - 20 - parseInt(state[1].substr(2), 10);
515 } else if (state[1].substr(0, 4) === 'beta') {
516 add = - 40 - parseInt(state[1].substr(4), 10);
517 } else if (state[1].substr(0, 5) === 'alpha') {
518 add = - 60 - parseInt(state[1].substr(5), 10);
519 } else if (state[1].substr(0, 3) === 'dev') {
520 /* We don't handle dev, it's git snapshot */
525 var x = str.split('.');
526 // Use 0 for non existing parts
527 var maj = parseInt(x[0], 10) || 0;
528 var min = parseInt(x[1], 10) || 0;
529 var pat = parseInt(x[2], 10) || 0;
530 var hotfix = parseInt(x[3], 10) || 0;
531 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
535 * Indicates current available version on main page.
537 function PMA_current_version (data) {
538 if (data && data.version && data.date) {
539 var current = parseVersionString($('span.version').text());
540 var latest = parseVersionString(data.version);
541 var url = 'https://www.phpmyadmin.net/files/' + escapeHtml(encodeURIComponent(data.version)) + '/';
542 var version_information_message = document.createElement('span');
543 version_information_message.className = 'latest';
544 var version_information_message_link = document.createElement('a');
545 version_information_message_link.href = url;
546 version_information_message_link.className = 'disableAjax';
547 version_information_message_link_text = document.createTextNode(data.version);
548 version_information_message_link.appendChild(version_information_message_link_text);
549 var prefix_message = document.createTextNode(PMA_messages.strLatestAvailable + ' ');
550 version_information_message.appendChild(prefix_message);
551 version_information_message.appendChild(version_information_message_link);
552 if (latest > current) {
553 var message = PMA_sprintf(
554 PMA_messages.strNewerVersion,
555 escapeHtml(data.version),
556 escapeHtml(data.date)
558 var htmlClass = 'notice';
559 if (Math.floor(latest / 10000) === Math.floor(current / 10000)) {
560 /* Security update */
563 $('#newer_version_notice').remove();
564 var maincontainer_div = document.createElement('div');
565 maincontainer_div.id = 'newer_version_notice';
566 maincontainer_div.className = htmlClass;
567 var maincontainer_div_link = document.createElement('a');
568 maincontainer_div_link.href = url;
569 maincontainer_div_link.className = 'disableAjax';
570 maincontainer_div_link_text = document.createTextNode(message);
571 maincontainer_div_link.appendChild(maincontainer_div_link_text);
572 maincontainer_div.appendChild(maincontainer_div_link);
573 $('#maincontainer').append($(maincontainer_div));
575 if (latest === current) {
576 version_information_message = document.createTextNode(' (' + PMA_messages.strUpToDate + ')');
578 /* Remove extra whitespace */
579 var version_info = $('#li_pma_version').contents().get(2);
580 if (typeof version_info !== 'undefined') {
581 version_info.textContent = $.trim(version_info.textContent);
583 var $liPmaVersion = $('#li_pma_version');
584 $liPmaVersion.find('span.latest').remove();
585 $liPmaVersion.append($(version_information_message));
590 * Loads Git revision data from ajax for index.php
592 function PMA_display_git_revision () {
593 $('#is_git_revision').remove();
594 $('#li_pma_version_git').remove();
598 'server': PMA_commonParams.get('server'),
599 'git_revision': true,
600 'ajax_request': true,
604 if (typeof data !== 'undefined' && data.success === true) {
605 $(data.message).insertAfter('#li_pma_version');
612 * for PhpMyAdmin\Display\ChangePassword
613 * libraries/user_password.php
617 function displayPasswordGenerateButton () {
618 var generatePwdRow = $('<tr />').addClass('vmiddle');
619 var titleCell = $('<td />').html(PMA_messages.strGeneratePassword).appendTo(generatePwdRow);
620 var pwdCell = $('<td />').appendTo(generatePwdRow);
621 var pwdButton = $('<input />')
622 .attr({ type: 'button', id: 'button_generate_password', value: PMA_messages.strGenerate })
624 .on('click', function () {
625 suggestPassword(this.form);
627 var pwdTextbox = $('<input />')
628 .attr({ type: 'text', name: 'generated_pw', id: 'generated_pw' });
629 pwdCell.append(pwdButton).append(pwdTextbox);
631 if (document.getElementById('button_generate_password') === null) {
632 $('#tr_element_before_generate_password').parent().append(generatePwdRow);
635 var generatePwdDiv = $('<div />').addClass('item');
636 var titleLabel = $('<label />').attr({ for: 'button_generate_password' })
637 .html(PMA_messages.strGeneratePassword + ':')
638 .appendTo(generatePwdDiv);
639 var optionsSpan = $('<span/>').addClass('options')
640 .appendTo(generatePwdDiv);
641 pwdButton.clone(true).appendTo(optionsSpan);
642 pwdTextbox.clone(true).appendTo(generatePwdDiv);
644 if (document.getElementById('button_generate_password') === null) {
645 $('#div_element_before_generate_password').parent().append(generatePwdDiv);
650 * selects the content of a given object, f.e. a textarea
652 * @param element object element of which the content will be selected
653 * @param lock var variable which holds the lock for this element
654 * or true, if no lock exists
655 * @param only_once boolean if true this is only done once
656 * f.e. only on first focus
658 function selectContent (element, lock, only_once) {
659 if (only_once && only_once_elements[element.name]) {
663 only_once_elements[element.name] = true;
673 * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
674 * This function is called while clicking links
676 * @param theLink object the link
677 * @param theSqlQuery object the sql query to submit
679 * @return boolean whether to run the query or not
681 function confirmLink (theLink, theSqlQuery) {
682 // Confirmation is not required in the configuration file
683 // or browser is Opera (crappy js implementation)
684 if (PMA_messages.strDoYouReally === '' || typeof(window.opera) !== 'undefined') {
688 var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, theSqlQuery));
690 if (typeof(theLink.href) !== 'undefined') {
691 theLink.href += PMA_commonParams.get('arg_separator') + 'is_js_confirmed=1';
692 } else if (typeof(theLink.form) !== 'undefined') {
693 theLink.form.action += '?is_js_confirmed=1';
698 } // end of the 'confirmLink()' function
701 * Confirms a "DROP/DELETE/ALTER" query before
702 * submitting it if required.
703 * This function is called by the 'checkSqlQuery()' js function.
705 * @param theForm1 object the form
706 * @param sqlQuery1 string the sql query string
708 * @return boolean whether to run the query or not
710 * @see checkSqlQuery()
712 function confirmQuery (theForm1, sqlQuery1) {
713 // Confirmation is not required in the configuration file
714 if (PMA_messages.strDoYouReally === '') {
718 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
720 // TODO: find a way (if possible) to use the parser-analyser
721 // for this kind of verification
722 // For now, I just added a ^ to check for the statement at
723 // beginning of expression
725 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|PROCEDURE)\\s', 'i');
726 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
727 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
728 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
730 if (do_confirm_re_0.test(sqlQuery1) ||
731 do_confirm_re_1.test(sqlQuery1) ||
732 do_confirm_re_2.test(sqlQuery1) ||
733 do_confirm_re_3.test(sqlQuery1)) {
735 if (sqlQuery1.length > 100) {
736 message = sqlQuery1.substr(0, 100) + '\n ...';
740 var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, message));
741 // statement is confirmed -> update the
742 // "is_js_confirmed" form field so the confirm test won't be
743 // run on the server side and allows to submit the form
745 theForm1.elements.is_js_confirmed.value = 1;
748 // statement is rejected -> do not submit the form
751 } // end if (handle confirm box result)
752 } // end if (display confirm box)
755 } // end of the 'confirmQuery()' function
758 * Displays an error message if the user submitted the sql query form with no
759 * sql query, else checks for "DROP/DELETE/ALTER" statements
761 * @param theForm object the form
763 * @return boolean always false
765 * @see confirmQuery()
767 function checkSqlQuery (theForm) {
768 // get the textarea element containing the query
770 if (codemirror_editor) {
771 codemirror_editor.save();
772 sqlQuery = codemirror_editor.getValue();
774 sqlQuery = theForm.elements.sql_query.value;
776 var space_re = new RegExp('\\s+');
777 if (typeof(theForm.elements.sql_file) !== 'undefined' &&
778 theForm.elements.sql_file.value.replace(space_re, '') !== '') {
781 if (typeof(theForm.elements.id_bookmark) !== 'undefined' &&
782 (theForm.elements.id_bookmark.value !== null || theForm.elements.id_bookmark.value !== '') &&
783 theForm.elements.id_bookmark.selectedIndex !== 0) {
787 // Checks for "DROP/DELETE/ALTER" statements
788 if (sqlQuery.replace(space_re, '') !== '') {
789 result = confirmQuery(theForm, sqlQuery);
791 alert(PMA_messages.strFormEmpty);
794 if (codemirror_editor) {
795 codemirror_editor.focus();
796 } else if (codemirror_inline_editor) {
797 codemirror_inline_editor.focus();
800 } // end of the 'checkSqlQuery()' function
803 * Check if a form's element is empty.
804 * An element containing only spaces is also considered empty
806 * @param object the form
807 * @param string the name of the form field to put the focus on
809 * @return boolean whether the form field is empty or not
811 function emptyCheckTheField (theForm, theFieldName) {
812 var theField = theForm.elements[theFieldName];
813 var space_re = new RegExp('\\s+');
814 return theField.value.replace(space_re, '') === '';
815 } // end of the 'emptyCheckTheField()' function
818 * Ensures a value submitted in a form is numeric and is in a range
820 * @param object the form
821 * @param string the name of the form field to check
822 * @param integer the minimum authorized value
823 * @param integer the maximum authorized value
825 * @return boolean whether a valid number has been submitted or not
827 function checkFormElementInRange (theForm, theFieldName, message, min, max) {
828 var theField = theForm.elements[theFieldName];
829 var val = parseInt(theField.value, 10);
831 if (typeof(min) === 'undefined') {
834 if (typeof(max) === 'undefined') {
835 max = Number.MAX_VALUE;
840 alert(PMA_messages.strEnterValidNumber);
843 } else if (val < min || val > max) {
845 alert(PMA_sprintf(message, val));
849 theField.value = val;
852 } // end of the 'checkFormElementInRange()' function
855 function checkTableEditForm (theForm, fieldsCnt) {
856 // TODO: avoid sending a message if user just wants to add a line
857 // on the form but has not completed at least one field name
859 var atLeastOneField = 0;
867 for (i = 0; i < fieldsCnt; i++) {
868 id = '#field_' + i + '_2';
871 if (val === 'VARCHAR' || val === 'CHAR' || val === 'BIT' || val === 'VARBINARY' || val === 'BINARY') {
872 elm2 = $('#field_' + i + '_3');
873 val = parseInt(elm2.val(), 10);
874 elm3 = $('#field_' + i + '_1');
875 if (isNaN(val) && elm3.val() !== '') {
877 alert(PMA_messages.strEnterValidLength);
883 if (atLeastOneField === 0) {
884 id = 'field_' + i + '_1';
885 if (!emptyCheckTheField(theForm, id)) {
890 if (atLeastOneField === 0) {
891 var theField = theForm.elements.field_0_1;
892 alert(PMA_messages.strFormEmpty);
897 // at least this section is under jQuery
898 var $input = $('input.textfield[name=\'table\']');
899 if ($input.val() === '') {
900 alert(PMA_messages.strFormEmpty);
906 } // enf of the 'checkTableEditForm()' function
909 * True if last click is to check a row.
911 var last_click_checked = false;
914 * Zero-based index of last clicked row.
915 * Used to handle the shift + click event in the code above.
917 var last_clicked_row = -1;
920 * Zero-based index of last shift clicked row.
922 var last_shift_clicked_row = -1;
924 var _idleSecondsCounter = 0;
927 AJAX.registerTeardown('functions.js', function () {
928 clearTimeout(updateTimeout);
929 clearInterval(IncInterval);
930 $(document).off('mousemove');
933 AJAX.registerOnload('functions.js', function () {
934 document.onclick = function () {
935 _idleSecondsCounter = 0;
937 $(document).on('mousemove',function () {
938 _idleSecondsCounter = 0;
940 document.onkeypress = function () {
941 _idleSecondsCounter = 0;
945 return Math.floor((1 + Math.random()) * 0x10000)
949 return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
950 s4() + '-' + s4() + s4() + s4();
953 function SetIdleTime () {
954 _idleSecondsCounter++;
956 function UpdateIdleTime () {
957 var href = 'index.php';
958 var guid = 'default';
959 if (isStorageSupported('sessionStorage')) {
960 guid = window.sessionStorage.guid;
963 'ajax_request' : true,
964 'server' : PMA_commonParams.get('server'),
965 'db' : PMA_commonParams.get('db'),
967 'access_time':_idleSecondsCounter
973 success: function (data) {
975 if (PMA_commonParams.get('LoginCookieValidity') - _idleSecondsCounter < 0) {
976 /* There is other active window, let's reset counter */
977 _idleSecondsCounter = 0;
979 var remaining = Math.min(
980 /* Remaining login validity */
981 PMA_commonParams.get('LoginCookieValidity') - _idleSecondsCounter,
982 /* Remaining time till session GC */
983 PMA_commonParams.get('session_gc_maxlifetime')
987 // max value for setInterval() function
988 interval = Math.min((remaining - 1) * 1000, Math.pow(2, 31) - 1);
990 updateTimeout = window.setTimeout(UpdateIdleTime, interval);
991 } else { // timeout occurred
992 clearInterval(IncInterval);
993 if (isStorageSupported('sessionStorage')) {
994 window.sessionStorage.clear();
996 window.location.reload(true);
1001 if (PMA_commonParams.get('logged_in')) {
1002 IncInterval = window.setInterval(SetIdleTime, 1000);
1003 var session_timeout = Math.min(
1004 PMA_commonParams.get('LoginCookieValidity'),
1005 PMA_commonParams.get('session_gc_maxlifetime')
1007 if (isStorageSupported('sessionStorage')) {
1008 window.sessionStorage.setItem('guid', guid());
1010 var interval = (session_timeout - 5) * 1000;
1011 if (interval > Math.pow(2, 31) - 1) { // max value for setInterval() function
1012 interval = Math.pow(2, 31) - 1;
1014 updateTimeout = window.setTimeout(UpdateIdleTime, interval);
1018 * Unbind all event handlers before tearing down a page
1020 AJAX.registerTeardown('functions.js', function () {
1021 $(document).off('click', 'input:checkbox.checkall');
1023 AJAX.registerOnload('functions.js', function () {
1025 * Row marking in horizontal mode (use "on" so that it works also for
1026 * next pages reached via AJAX); a tr may have the class noclick to remove
1030 $(document).on('click', 'input:checkbox.checkall', function (e) {
1032 var $tr = $this.closest('tr');
1033 var $table = $this.closest('table');
1035 if (!e.shiftKey || last_clicked_row === -1) {
1038 var $checkbox = $tr.find(':checkbox.checkall');
1039 var checked = $this.prop('checked');
1040 $checkbox.prop('checked', checked).trigger('change');
1042 $tr.addClass('marked');
1044 $tr.removeClass('marked');
1046 last_click_checked = checked;
1048 // remember the last clicked row
1049 last_clicked_row = last_click_checked ? $table.find('tr:not(.noclick)').index($tr) : -1;
1050 last_shift_clicked_row = -1;
1052 // handle the shift click
1053 PMA_clearSelection();
1057 // clear last shift click result
1058 if (last_shift_clicked_row >= 0) {
1059 if (last_shift_clicked_row >= last_clicked_row) {
1060 start = last_clicked_row;
1061 end = last_shift_clicked_row;
1063 start = last_shift_clicked_row;
1064 end = last_clicked_row;
1066 $tr.parent().find('tr:not(.noclick)')
1067 .slice(start, end + 1)
1068 .removeClass('marked')
1070 .prop('checked', false)
1074 // handle new shift click
1075 var curr_row = $table.find('tr:not(.noclick)').index($tr);
1076 if (curr_row >= last_clicked_row) {
1077 start = last_clicked_row;
1081 end = last_clicked_row;
1083 $tr.parent().find('tr:not(.noclick)')
1087 .prop('checked', true)
1090 // remember the last shift clicked row
1091 last_shift_clicked_row = curr_row;
1095 addDateTimePicker();
1098 * Add attribute to text boxes for iOS devices (based on bugID: 3508912)
1100 if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) {
1101 $('input[type=text]').attr('autocapitalize', 'off').attr('autocorrect', 'off');
1106 * Checks/unchecks all options of a <select> element
1108 * @param string the form name
1109 * @param string the element name
1110 * @param boolean whether to check or to uncheck options
1112 * @return boolean always true
1114 function setSelectOptions (the_form, the_select, do_check) {
1115 $('form[name=\'' + the_form + '\'] select[name=\'' + the_select + '\']').find('option').prop('selected', do_check);
1117 } // end of the 'setSelectOptions()' function
1120 * Sets current value for query box.
1122 function setQuery (query) {
1123 if (codemirror_editor) {
1124 codemirror_editor.setValue(query);
1125 codemirror_editor.focus();
1127 document.sqlform.sql_query.value = query;
1128 document.sqlform.sql_query.focus();
1133 * Handles 'Simulate query' button on SQL query box.
1137 function PMA_handleSimulateQueryButton () {
1138 var update_re = new RegExp('^\\s*UPDATE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+SET\\s', 'i');
1139 var delete_re = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
1142 if (codemirror_editor) {
1143 query = codemirror_editor.getValue();
1145 query = $('#sqlquery').val();
1148 var $simulateDml = $('#simulate_dml');
1149 if (update_re.test(query) || delete_re.test(query)) {
1150 if (! $simulateDml.length) {
1151 $('#button_submit_query')
1152 .before('<input type="button" id="simulate_dml"' +
1153 'tabindex="199" value="' +
1154 PMA_messages.strSimulateDML +
1158 if ($simulateDml.length) {
1159 $simulateDml.remove();
1165 * Create quick sql statements.
1168 function insertQuery (queryType) {
1169 if (queryType === 'clear') {
1172 } else if (queryType === 'format') {
1173 if (codemirror_editor) {
1174 $('#querymessage').html(PMA_messages.strFormatting +
1175 ' <img class="ajaxIcon" src="' +
1176 pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1177 var href = 'db_sql_format.php';
1179 'ajax_request': true,
1180 'sql': codemirror_editor.getValue(),
1181 'server': PMA_commonParams.get('server')
1187 success: function (data) {
1189 codemirror_editor.setValue(data.sql);
1191 $('#querymessage').html('');
1196 } else if (queryType === 'saved') {
1197 if (isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql !== 'undefined') {
1198 setQuery(window.localStorage.auto_saved_sql);
1199 } else if (Cookies.get('auto_saved_sql')) {
1200 setQuery(Cookies.get('auto_saved_sql'));
1202 PMA_ajaxShowMessage(PMA_messages.strNoAutoSavedQuery);
1208 var myListBox = document.sqlform.dummy;
1209 var table = document.sqlform.table.value;
1211 if (myListBox.options.length > 0) {
1212 sql_box_locked = true;
1213 var columnsList = '';
1217 for (var i = 0; i < myListBox.options.length; i++) {
1220 columnsList += ', ';
1224 columnsList += myListBox.options[i].value;
1225 valDis += '[value-' + NbSelect + ']';
1226 editDis += myListBox.options[i].value + '=[value-' + NbSelect + ']';
1228 if (queryType === 'selectall') {
1229 query = 'SELECT * FROM `' + table + '` WHERE 1';
1230 } else if (queryType === 'select') {
1231 query = 'SELECT ' + columnsList + ' FROM `' + table + '` WHERE 1';
1232 } else if (queryType === 'insert') {
1233 query = 'INSERT INTO `' + table + '`(' + columnsList + ') VALUES (' + valDis + ')';
1234 } else if (queryType === 'update') {
1235 query = 'UPDATE `' + table + '` SET ' + editDis + ' WHERE 1';
1236 } else if (queryType === 'delete') {
1237 query = 'DELETE FROM `' + table + '` WHERE 0';
1240 sql_box_locked = false;
1246 * Inserts multiple fields.
1249 function insertValueQuery () {
1250 var myQuery = document.sqlform.sql_query;
1251 var myListBox = document.sqlform.dummy;
1253 if (myListBox.options.length > 0) {
1254 sql_box_locked = true;
1255 var columnsList = '';
1257 for (var i = 0; i < myListBox.options.length; i++) {
1258 if (myListBox.options[i].selected) {
1261 columnsList += ', ';
1263 columnsList += myListBox.options[i].value;
1267 /* CodeMirror support */
1268 if (codemirror_editor) {
1269 codemirror_editor.replaceSelection(columnsList);
1270 codemirror_editor.focus();
1272 } else if (document.selection) {
1274 var sel = document.selection.createRange();
1275 sel.text = columnsList;
1276 // MOZILLA/NETSCAPE support
1277 } else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart === '0') {
1278 var startPos = document.sqlform.sql_query.selectionStart;
1279 var endPos = document.sqlform.sql_query.selectionEnd;
1280 var SqlString = document.sqlform.sql_query.value;
1282 myQuery.value = SqlString.substring(0, startPos) + columnsList + SqlString.substring(endPos, SqlString.length);
1285 myQuery.value += columnsList;
1287 sql_box_locked = false;
1292 * Updates the input fields for the parameters based on the query
1294 function updateQueryParameters () {
1295 if ($('#parameterized').is(':checked')) {
1296 var query = codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val();
1298 var allParameters = query.match(/:[a-zA-Z0-9_]+/g);
1299 var parameters = [];
1300 // get unique parameters
1301 if (allParameters) {
1302 $.each(allParameters, function (i, parameter) {
1303 if ($.inArray(parameter, parameters) === -1) {
1304 parameters.push(parameter);
1308 $('#parametersDiv').text(PMA_messages.strNoParam);
1312 var $temp = $('<div />');
1313 $temp.append($('#parametersDiv').children());
1314 $('#parametersDiv').empty();
1316 $.each(parameters, function (i, parameter) {
1317 var paramName = parameter.substring(1);
1318 var $param = $temp.find('#paramSpan_' + paramName);
1319 if (! $param.length) {
1320 $param = $('<span class="parameter" id="paramSpan_' + paramName + '" />');
1321 $('<label for="param_' + paramName + '" />').text(parameter).appendTo($param);
1322 $('<input type="text" name="parameters[' + parameter + ']" id="param_' + paramName + '" />').appendTo($param);
1324 $('#parametersDiv').append($param);
1327 $('#parametersDiv').empty();
1332 * Refresh/resize the WYSIWYG scratchboard
1334 function refreshLayout () {
1335 var $elm = $('#pdflayout');
1336 var orientation = $('#orientation_opt').val();
1338 var $paperOpt = $('#paper_opt');
1339 if ($paperOpt.length === 1) {
1340 paper = $paperOpt.val();
1344 if (orientation === 'P') {
1348 $elm.css('width', pdfPaperSize(paper, posa) + 'px');
1349 $elm.css('height', pdfPaperSize(paper, posb) + 'px');
1353 * Initializes positions of elements.
1355 function TableDragInit () {
1356 $('.pdflayout_table').each(function () {
1357 var $this = $(this);
1358 var number = $this.data('number');
1359 var x = $('#c_table_' + number + '_x').val();
1360 var y = $('#c_table_' + number + '_y').val();
1361 $this.css('left', x + 'px');
1362 $this.css('top', y + 'px');
1363 /* Make elements draggable */
1365 containment: 'parent',
1366 drag: function (evt, ui) {
1367 var number = $this.data('number');
1368 $('#c_table_' + number + '_x').val(parseInt(ui.position.left, 10));
1369 $('#c_table_' + number + '_y').val(parseInt(ui.position.top, 10));
1376 * Resets drag and drop positions.
1378 function resetDrag () {
1379 $('.pdflayout_table').each(function () {
1380 var $this = $(this);
1381 var x = $this.data('x');
1382 var y = $this.data('y');
1383 $this.css('left', x + 'px');
1384 $this.css('top', y + 'px');
1389 * User schema handlers.
1392 /* Move in scratchboard on manual change */
1393 $(document).on('change', '.position-change', function () {
1394 var $this = $(this);
1395 var $elm = $('#table_' + $this.data('number'));
1396 $elm.css($this.data('axis'), $this.val() + 'px');
1398 /* Refresh on paper size/orientation change */
1399 $(document).on('change', '.paper-change', function () {
1400 var $elm = $('#pdflayout');
1401 if ($elm.css('visibility') === 'visible') {
1406 /* Show/hide the WYSIWYG scratchboard */
1407 $(document).on('click', '#toggle-dragdrop', function () {
1408 var $elm = $('#pdflayout');
1409 if ($elm.css('visibility') === 'hidden') {
1412 $elm.css('visibility', 'visible');
1413 $elm.css('display', 'block');
1414 $('#showwysiwyg').val('1');
1416 $elm.css('visibility', 'hidden');
1417 $elm.css('display', 'none');
1418 $('#showwysiwyg').val('0');
1421 /* Reset scratchboard */
1422 $(document).on('click', '#reset-dragdrop', function () {
1428 * Returns paper sizes for a given format
1430 function pdfPaperSize (format, axis) {
1431 switch (format.toUpperCase()) {
1781 * Get checkbox for foreign key checks
1785 function getForeignKeyCheckboxLoader () {
1788 html += '<div class="load-default-fk-check-value">';
1789 html += PMA_getImage('ajax_clock_small');
1795 function loadForeignKeyCheckbox () {
1796 // Load default foreign key check value
1798 'ajax_request': true,
1799 'server': PMA_commonParams.get('server'),
1800 'get_default_fk_check_value': true
1802 $.get('sql.php', params, function (data) {
1803 var html = '<input type="hidden" name="fk_checks" value="0" />' +
1804 '<input type="checkbox" name="fk_checks" id="fk_checks"' +
1805 (data.default_fk_check_value ? ' checked="checked"' : '') + ' />' +
1806 '<label for="fk_checks">' + PMA_messages.strForeignKeyCheck + '</label>';
1807 $('.load-default-fk-check-value').replaceWith(html);
1811 function getJSConfirmCommonParam (elem, params) {
1812 var $elem = $(elem);
1813 var sep = PMA_commonParams.get('arg_separator');
1815 // Strip possible leading ?
1816 if (params.substring(0,1) == '?') {
1817 params = params.substr(1);
1823 params += 'is_js_confirmed=1' + sep + 'ajax_request=true' + sep + 'fk_checks=' + ($elem.find('#fk_checks').is(':checked') ? 1 : 0);
1828 * Unbind all event handlers before tearing down a page
1830 AJAX.registerTeardown('functions.js', function () {
1831 $(document).off('click', 'a.inline_edit_sql');
1832 $(document).off('click', 'input#sql_query_edit_save');
1833 $(document).off('click', 'input#sql_query_edit_discard');
1834 $('input.sqlbutton').off('click');
1835 if (codemirror_editor) {
1836 codemirror_editor.off('blur');
1838 $(document).off('blur', '#sqlquery');
1840 $(document).off('change', '#parameterized');
1841 $(document).off('click', 'input.sqlbutton');
1842 $('#sqlquery').off('keydown');
1843 $('#sql_query_edit').off('keydown');
1845 if (codemirror_inline_editor) {
1846 // Copy the sql query to the text area to preserve it.
1847 $('#sql_query_edit').text(codemirror_inline_editor.getValue());
1848 $(codemirror_inline_editor.getWrapperElement()).off('keydown');
1849 codemirror_inline_editor.toTextArea();
1850 codemirror_inline_editor = false;
1852 if (codemirror_editor) {
1853 $(codemirror_editor.getWrapperElement()).off('keydown');
1858 * Jquery Coding for inline editing SQL_QUERY
1860 AJAX.registerOnload('functions.js', function () {
1861 // If we are coming back to the page by clicking forward button
1862 // of the browser, bind the code mirror to inline query editor.
1863 bindCodeMirrorToInlineEditor();
1864 $(document).on('click', 'a.inline_edit_sql', function () {
1865 if ($('#sql_query_edit').length) {
1866 // An inline query editor is already open,
1867 // we don't want another copy of it
1871 var $form = $(this).prev('form');
1872 var sql_query = $form.find('input[name=\'sql_query\']').val().trim();
1873 var $inner_sql = $(this).parent().prev().find('code.sql');
1874 var old_text = $inner_sql.html();
1876 var new_content = '<textarea name="sql_query_edit" id="sql_query_edit">' + escapeHtml(sql_query) + '</textarea>\n';
1877 new_content += getForeignKeyCheckboxLoader();
1878 new_content += '<input type="submit" id="sql_query_edit_save" class="button btnSave" value="' + PMA_messages.strGo + '"/>\n';
1879 new_content += '<input type="button" id="sql_query_edit_discard" class="button btnDiscard" value="' + PMA_messages.strCancel + '"/>\n';
1880 var $editor_area = $('div#inline_editor');
1881 if ($editor_area.length === 0) {
1882 $editor_area = $('<div id="inline_editor_outer"></div>');
1883 $editor_area.insertBefore($inner_sql);
1885 $editor_area.html(new_content);
1886 loadForeignKeyCheckbox();
1889 bindCodeMirrorToInlineEditor();
1893 $(document).on('click', 'input#sql_query_edit_save', function () {
1894 // hide already existing success message
1896 if (codemirror_inline_editor) {
1897 codemirror_inline_editor.save();
1898 sql_query = codemirror_inline_editor.getValue();
1900 sql_query = $(this).parent().find('#sql_query_edit').val();
1902 var fk_check = $(this).parent().find('#fk_checks').is(':checked');
1904 var $form = $('a.inline_edit_sql').prev('form');
1905 var $fake_form = $('<form>', { action: 'import.php', method: 'post' })
1906 .append($form.find('input[name=server], input[name=db], input[name=table], input[name=token]').clone())
1907 .append($('<input/>', { type: 'hidden', name: 'show_query', value: 1 }))
1908 .append($('<input/>', { type: 'hidden', name: 'is_js_confirmed', value: 0 }))
1909 .append($('<input/>', { type: 'hidden', name: 'sql_query', value: sql_query }))
1910 .append($('<input/>', { type: 'hidden', name: 'fk_checks', value: fk_check ? 1 : 0 }));
1911 if (! checkSqlQuery($fake_form[0])) {
1914 $('.success').hide();
1915 $fake_form.appendTo($('body')).submit();
1918 $(document).on('click', 'input#sql_query_edit_discard', function () {
1919 var $divEditor = $('div#inline_editor_outer');
1920 $divEditor.siblings('code.sql').show();
1921 $divEditor.remove();
1924 $(document).on('click', 'input.sqlbutton', function (evt) {
1925 insertQuery(evt.target.id);
1926 PMA_handleSimulateQueryButton();
1930 $(document).on('change', '#parameterized', updateQueryParameters);
1932 var $inputUsername = $('#input_username');
1933 if ($inputUsername) {
1934 if ($inputUsername.val() === '') {
1935 $inputUsername.trigger('focus');
1937 $('#input_password').trigger('focus');
1943 * "inputRead" event handler for CodeMirror SQL query editors for autocompletion
1945 function codemirrorAutocompleteOnInputRead (instance) {
1946 if (!sql_autocomplete_in_progress
1947 && (!instance.options.hintOptions.tables || !sql_autocomplete)) {
1948 if (!sql_autocomplete) {
1949 // Reset after teardown
1950 instance.options.hintOptions.tables = false;
1951 instance.options.hintOptions.defaultTable = '';
1953 sql_autocomplete_in_progress = true;
1955 var href = 'db_sql_autocomplete.php';
1957 'ajax_request': true,
1958 'server': PMA_commonParams.get('server'),
1959 'db': PMA_commonParams.get('db'),
1963 var columnHintRender = function (elem, self, data) {
1964 $('<div class="autocomplete-column-name">')
1965 .text(data.columnName)
1967 $('<div class="autocomplete-column-hint">')
1968 .text(data.columnHint)
1976 success: function (data) {
1978 var tables = JSON.parse(data.tables);
1979 sql_autocomplete_default_table = PMA_commonParams.get('table');
1980 sql_autocomplete = [];
1981 for (var table in tables) {
1982 if (tables.hasOwnProperty(table)) {
1983 var columns = tables[table];
1988 for (var column in columns) {
1989 if (columns.hasOwnProperty(column)) {
1990 var displayText = columns[column].Type;
1991 if (columns[column].Key === 'PRI') {
1992 displayText += ' | Primary';
1993 } else if (columns[column].Key === 'UNI') {
1994 displayText += ' | Unique';
1996 table.columns.push({
1998 displayText: column + ' | ' + displayText,
2000 columnHint: displayText,
2001 render: columnHintRender
2006 sql_autocomplete.push(table);
2008 instance.options.hintOptions.tables = sql_autocomplete;
2009 instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
2012 complete: function () {
2013 sql_autocomplete_in_progress = false;
2017 instance.options.hintOptions.tables = sql_autocomplete;
2018 instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
2021 if (instance.state.completionActive) {
2024 var cur = instance.getCursor();
2025 var token = instance.getTokenAt(cur);
2027 if (token.string.match(/^[.`\w@]\w*$/)) {
2028 string = token.string;
2030 if (string.length > 0) {
2031 CodeMirror.commands.autocomplete(instance);
2036 * Remove autocomplete information before tearing down a page
2038 AJAX.registerTeardown('functions.js', function () {
2039 sql_autocomplete = false;
2040 sql_autocomplete_default_table = '';
2044 * Binds the CodeMirror to the text area used to inline edit a query.
2046 function bindCodeMirrorToInlineEditor () {
2047 var $inline_editor = $('#sql_query_edit');
2048 if ($inline_editor.length > 0) {
2049 if (typeof CodeMirror !== 'undefined') {
2050 var height = $inline_editor.css('height');
2051 codemirror_inline_editor = PMA_getSQLEditor($inline_editor);
2052 codemirror_inline_editor.getWrapperElement().style.height = height;
2053 codemirror_inline_editor.refresh();
2054 codemirror_inline_editor.focus();
2055 $(codemirror_inline_editor.getWrapperElement())
2056 .on('keydown', catchKeypressesFromSqlInlineEdit);
2060 .on('keydown', catchKeypressesFromSqlInlineEdit);
2065 function catchKeypressesFromSqlInlineEdit (event) {
2066 // ctrl-enter is 10 in chrome and ie, but 13 in ff
2067 if ((event.ctrlKey || event.metaKey) && (event.keyCode === 13 || event.keyCode === 10)) {
2068 $('#sql_query_edit_save').trigger('click');
2073 * Adds doc link to single highlighted SQL element
2075 function PMA_doc_add ($elm, params) {
2076 if (typeof mysql_doc_template === 'undefined') {
2080 var url = PMA_sprintf(
2081 decodeURIComponent(mysql_doc_template),
2084 if (params.length > 1) {
2085 url += '#' + params[1];
2087 var content = $elm.text();
2089 $elm.append('<a target="mysql_doc" class="cm-sql-doc" href="' + url + '">' + content + '</a>');
2093 * Generates doc links for keywords inside highlighted SQL
2095 function PMA_doc_keyword (idx, elm) {
2097 /* Skip already processed ones */
2098 if ($elm.find('a').length > 0) {
2101 var keyword = $elm.text().toUpperCase();
2102 var $next = $elm.next('.cm-keyword');
2104 var next_keyword = $next.text().toUpperCase();
2105 var full = keyword + ' ' + next_keyword;
2107 var $next2 = $next.next('.cm-keyword');
2109 var next2_keyword = $next2.text().toUpperCase();
2110 var full2 = full + ' ' + next2_keyword;
2111 if (full2 in mysql_doc_keyword) {
2112 PMA_doc_add($elm, mysql_doc_keyword[full2]);
2113 PMA_doc_add($next, mysql_doc_keyword[full2]);
2114 PMA_doc_add($next2, mysql_doc_keyword[full2]);
2118 if (full in mysql_doc_keyword) {
2119 PMA_doc_add($elm, mysql_doc_keyword[full]);
2120 PMA_doc_add($next, mysql_doc_keyword[full]);
2124 if (keyword in mysql_doc_keyword) {
2125 PMA_doc_add($elm, mysql_doc_keyword[keyword]);
2130 * Generates doc links for builtins inside highlighted SQL
2132 function PMA_doc_builtin (idx, elm) {
2134 var builtin = $elm.text().toUpperCase();
2135 if (builtin in mysql_doc_builtin) {
2136 PMA_doc_add($elm, mysql_doc_builtin[builtin]);
2141 * Higlights SQL using CodeMirror.
2143 function PMA_highlightSQL ($base) {
2144 var $elm = $base.find('code.sql');
2145 $elm.each(function () {
2147 var $pre = $sql.find('pre');
2148 /* We only care about visible elements to avoid double processing */
2149 if ($pre.is(':visible')) {
2150 var $highlight = $('<div class="sql-highlight cm-s-default"></div>');
2151 $sql.append($highlight);
2152 if (typeof CodeMirror !== 'undefined') {
2153 CodeMirror.runMode($sql.text(), 'text/x-mysql', $highlight[0]);
2155 $highlight.find('.cm-keyword').each(PMA_doc_keyword);
2156 $highlight.find('.cm-builtin').each(PMA_doc_builtin);
2163 * Updates an element containing code.
2165 * @param jQuery Object $base base element which contains the raw and the
2168 * @param string htmlValue code in HTML format, displayed if code cannot be
2171 * @param string rawValue raw code, used as a parameter for highlighter
2173 * @return bool whether content was updated or not
2175 function PMA_updateCode ($base, htmlValue, rawValue) {
2176 var $code = $base.find('code');
2177 if ($code.length === 0) {
2181 // Determines the type of the content and appropriate CodeMirror mode.
2184 if ($code.hasClass('json')) {
2186 mode = 'application/json';
2187 } else if ($code.hasClass('sql')) {
2189 mode = 'text/x-mysql';
2190 } else if ($code.hasClass('xml')) {
2192 mode = 'application/xml';
2197 // Element used to display unhighlighted code.
2198 var $notHighlighted = $('<pre>' + htmlValue + '</pre>');
2200 // Tries to highlight code using CodeMirror.
2201 if (typeof CodeMirror !== 'undefined') {
2202 var $highlighted = $('<div class="' + type + '-highlight cm-s-default"></div>');
2203 CodeMirror.runMode(rawValue, mode, $highlighted[0]);
2204 $notHighlighted.hide();
2205 $code.html('').append($notHighlighted, $highlighted[0]);
2207 $code.html('').append($notHighlighted);
2214 * Show a message on the top of the page for an Ajax request
2218 * 1) var $msg = PMA_ajaxShowMessage();
2219 * This will show a message that reads "Loading...". Such a message will not
2220 * disappear automatically and cannot be dismissed by the user. To remove this
2221 * message either the PMA_ajaxRemoveMessage($msg) function must be called or
2222 * another message must be show with PMA_ajaxShowMessage() function.
2224 * 2) var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2225 * This is a special case. The behaviour is same as above,
2226 * just with a different message
2228 * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
2229 * This will show a message that will disappear automatically and it can also
2230 * be dismissed by the user.
2232 * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
2233 * This will show a message that will not disappear automatically, but it
2234 * can be dismissed by the user after he has finished reading it.
2236 * @param string message string containing the message to be shown.
2237 * optional, defaults to 'Loading...'
2238 * @param mixed timeout number of milliseconds for the message to be visible
2239 * optional, defaults to 5000. If set to 'false', the
2240 * notification will never disappear
2241 * @param string type string to dictate the type of message shown.
2242 * optional, defaults to normal notification.
2243 * If set to 'error', the notification will show message
2244 * with red background.
2245 * If set to 'success', the notification will show with
2246 * a green background.
2247 * @return jQuery object jQuery Element that holds the message div
2248 * this object can be passed to PMA_ajaxRemoveMessage()
2249 * to remove the notification
2251 function PMA_ajaxShowMessage (message, timeout, type) {
2253 * @var self_closing Whether the notification will automatically disappear
2255 var self_closing = true;
2257 * @var dismissable Whether the user will be able to remove
2258 * the notification by clicking on it
2260 var dismissable = true;
2261 // Handle the case when a empty data.message is passed.
2262 // We don't want the empty message
2263 if (message === '') {
2265 } else if (! message) {
2266 // If the message is undefined, show the default
2267 message = PMA_messages.strLoading;
2268 dismissable = false;
2269 self_closing = false;
2270 } else if (message === PMA_messages.strProcessingRequest) {
2271 // This is another case where the message should not disappear
2272 dismissable = false;
2273 self_closing = false;
2275 // Figure out whether (or after how long) to remove the notification
2276 if (timeout === undefined) {
2278 } else if (timeout === false) {
2279 self_closing = false;
2281 // Determine type of message, add styling as required
2282 if (type === 'error') {
2283 message = '<div class="error">' + message + '</div>';
2284 } else if (type === 'success') {
2285 message = '<div class="success">' + message + '</div>';
2287 // Create a parent element for the AJAX messages, if necessary
2288 if ($('#loading_parent').length === 0) {
2289 $('<div id="loading_parent"></div>')
2290 .prependTo('#page_content');
2292 // Update message count to create distinct message elements every time
2293 ajax_message_count++;
2294 // Remove all old messages, if any
2295 $('span.ajax_notification[id^=ajax_message_num]').remove();
2297 * @var $retval a jQuery object containing the reference
2298 * to the created AJAX message
2301 '<span class="ajax_notification" id="ajax_message_num_' +
2302 ajax_message_count +
2306 .appendTo('#loading_parent')
2309 // If the notification is self-closing we should create a callback to remove it
2313 .fadeOut('medium', function () {
2314 if ($(this).is(':data(tooltip)')) {
2315 $(this).tooltip('destroy');
2317 // Remove the notification
2321 // If the notification is dismissable we need to add the relevant class to it
2322 // and add a tooltip so that the users know that it can be removed
2324 $retval.addClass('dismissable').css('cursor', 'pointer');
2326 * Add a tooltip to the notification to let the user know that (s)he
2327 * can dismiss the ajax notification by clicking on it.
2332 PMA_messages.strDismiss
2335 PMA_highlightSQL($retval);
2341 * Removes the message shown for an Ajax operation when it's completed
2343 * @param jQuery object jQuery Element that holds the notification
2347 function PMA_ajaxRemoveMessage ($this_msgbox) {
2348 if ($this_msgbox !== undefined && $this_msgbox instanceof jQuery) {
2352 if ($this_msgbox.is(':data(tooltip)')) {
2353 $this_msgbox.tooltip('destroy');
2355 $this_msgbox.remove();
2361 * Requests SQL for previewing before executing.
2363 * @param jQuery Object $form Form containing query data
2367 function PMA_previewSQL ($form) {
2368 var form_url = $form.attr('action');
2369 var sep = PMA_commonParams.get('arg_separator');
2370 var form_data = $form.serialize() +
2371 sep + 'do_save_data=1' +
2372 sep + 'preview_sql=1' +
2373 sep + 'ajax_request=1';
2374 var $msgbox = PMA_ajaxShowMessage();
2379 success: function (response) {
2380 PMA_ajaxRemoveMessage($msgbox);
2381 if (response.success) {
2382 var $dialog_content = $('<div/>')
2383 .append(response.sql_data);
2384 var button_options = {};
2385 button_options[PMA_messages.strClose] = function () {
2386 $(this).dialog('close');
2388 var $response_dialog = $dialog_content.dialog({
2392 buttons: button_options,
2393 title: PMA_messages.strPreviewSQL,
2394 close: function () {
2398 // Pretty SQL printing.
2399 PMA_highlightSQL($(this));
2403 PMA_ajaxShowMessage(response.message);
2406 error: function () {
2407 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
2413 * Callback called when submit/"OK" is clicked on sql preview/confirm modal
2415 * @callback onSubmitCallback
2416 * @param {string} url The url
2421 * @param {string} sql_data Sql query to preview
2422 * @param {string} url Url to be sent to callback
2423 * @param {onSubmitCallback} callback On submit callback function
2427 function PMA_confirmPreviewSQL (sql_data, url, callback) {
2428 var $dialog_content = $('<div class="preview_sql"><code class="sql"><pre>'
2430 + '</pre></code></div>'
2432 var button_options = [
2434 text: PMA_messages.strOK,
2436 click: function () {
2441 text: PMA_messages.strCancel,
2442 class: 'submitCancel',
2443 click: function () {
2444 $(this).dialog('close');
2448 var $response_dialog = $dialog_content.dialog({
2452 buttons: button_options,
2453 title: PMA_messages.strPreviewSQL,
2454 close: function () {
2458 // Pretty SQL printing.
2459 PMA_highlightSQL($(this));
2465 * check for reserved keyword column name
2467 * @param jQuery Object $form Form
2469 * @returns true|false
2472 function PMA_checkReservedWordColumns ($form) {
2473 var is_confirmed = true;
2476 url: 'tbl_structure.php',
2477 data: $form.serialize() + PMA_commonParams.get('arg_separator') + 'reserved_word_check=1',
2478 success: function (data) {
2479 if (typeof data.success !== 'undefined' && data.success === true) {
2480 is_confirmed = confirm(data.message);
2485 return is_confirmed;
2488 // This event only need to be fired once after the initial page load
2491 * Allows the user to dismiss a notification
2492 * created with PMA_ajaxShowMessage()
2494 $(document).on('click', 'span.ajax_notification.dismissable', function () {
2495 PMA_ajaxRemoveMessage($(this));
2498 * The below two functions hide the "Dismiss notification" tooltip when a user
2499 * is hovering a link or button that is inside an ajax message
2501 $(document).on('mouseover', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
2502 if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
2503 $(this).parents('span.ajax_notification').tooltip('disable');
2506 $(document).on('mouseout', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
2507 if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
2508 $(this).parents('span.ajax_notification').tooltip('enable');
2514 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
2516 function PMA_showNoticeForEnum (selectElement) {
2517 var enum_notice_id = selectElement.attr('id').split('_')[1];
2518 enum_notice_id += '_' + (parseInt(selectElement.attr('id').split('_')[2], 10) + 1);
2519 var selectedType = selectElement.val();
2520 if (selectedType === 'ENUM' || selectedType === 'SET') {
2521 $('p#enum_notice_' + enum_notice_id).show();
2523 $('p#enum_notice_' + enum_notice_id).hide();
2528 * Creates a Profiling Chart. Used in sql.js
2529 * and in server_status_monitor.js
2531 function PMA_createProfilingChart (target, data) {
2533 var factory = new JQPlotChartFactory();
2534 var chart = factory.createChart(ChartType.PIE, target);
2536 // create the data table and add columns
2537 var dataTable = new DataTable();
2538 dataTable.addColumn(ColumnType.STRING, '');
2539 dataTable.addColumn(ColumnType.NUMBER, '');
2540 dataTable.setData(data);
2542 var windowWidth = $(window).width();
2544 if (windowWidth > 768) {
2545 var location = 'se';
2548 // draw the chart and return the chart object
2549 chart.draw(dataTable, {
2552 showDataLabels: true
2556 tooltipLocation: 'se',
2558 tooltipAxes: 'pieref',
2559 formatString: '%s, %.9Ps'
2568 // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
2593 * Formats a profiling duration nicely (in us and ms time).
2594 * Used in server_status_monitor.js
2596 * @param integer Number to be formatted, should be in the range of microsecond to second
2597 * @param integer Accuracy, how many numbers right to the comma should be
2598 * @return string The formatted number
2600 function PMA_prettyProfilingNum (num, acc) {
2604 acc = Math.pow(10, acc);
2605 if (num * 1000 < 0.1) {
2606 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
2607 } else if (num < 0.1) {
2608 num = Math.round(acc * (num * 1000)) / acc + 'm';
2610 num = Math.round(acc * num) / acc;
2618 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
2620 * @param string Query to be formatted
2621 * @return string The formatted query
2623 function PMA_SQLPrettyPrint (string) {
2624 if (typeof CodeMirror === 'undefined') {
2628 var mode = CodeMirror.getMode({}, 'text/x-mysql');
2629 var stream = new CodeMirror.StringStream(string);
2630 var state = mode.startState();
2634 var tabs = function (cnt) {
2636 for (var i = 0; i < 4 * cnt; i++) {
2642 // "root-level" statements
2644 'select': ['select', 'from', 'on', 'where', 'having', 'limit', 'order by', 'group by'],
2645 'update': ['update', 'set', 'where'],
2646 'insert into': ['insert into', 'values']
2648 // don't put spaces before these tokens
2649 var spaceExceptionsBefore = { ';': true, ',': true, '.': true, '(': true };
2650 // don't put spaces after these tokens
2651 var spaceExceptionsAfter = { '.': true };
2653 // Populate tokens array
2655 while (! stream.eol()) {
2656 stream.start = stream.pos;
2657 token = mode.token(stream, state);
2658 if (token !== null) {
2659 tokens.push([token, stream.current().toLowerCase()]);
2663 var currentStatement = tokens[0][1];
2665 if (! statements[currentStatement]) {
2668 // Holds all currently opened code blocks (statement, function or generic)
2669 var blockStack = [];
2670 // Holds the type of block from last iteration (the current is in blockStack[0])
2672 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
2675 // How much to indent in the current line
2676 var indentLevel = 0;
2677 // Holds the "root-level" statements
2679 var lastStatementPart = statements[currentStatement][0];
2681 blockStack.unshift('statement');
2683 // Iterate through every token and format accordingly
2684 for (var i = 0; i < tokens.length; i++) {
2685 previousBlock = blockStack[0];
2687 // New block => push to stack
2688 if (tokens[i][1] === '(') {
2689 if (i < tokens.length - 1 && tokens[i + 1][0] === 'statement-verb') {
2690 blockStack.unshift(newBlock = 'statement');
2691 } else if (i > 0 && tokens[i - 1][0] === 'builtin') {
2692 blockStack.unshift(newBlock = 'function');
2694 blockStack.unshift(newBlock = 'generic');
2700 // Block end => pop from stack
2701 if (tokens[i][1] === ')') {
2702 endBlock = blockStack[0];
2708 // A subquery is starting
2709 if (i > 0 && newBlock === 'statement') {
2711 output += '\n' + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i + 1][1].toUpperCase() + '\n' + tabs(indentLevel + 1);
2712 currentStatement = tokens[i + 1][1];
2717 // A subquery is ending
2718 if (endBlock === 'statement' && indentLevel > 0) {
2719 output += '\n' + tabs(indentLevel);
2723 // One less indentation for statement parts (from, where, order by, etc.) and a newline
2724 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
2725 if (statementPart !== -1) {
2729 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
2730 output += '\n' + tabs(indentLevel + 1);
2731 lastStatementPart = tokens[i][1];
2732 // Normal indentation and spaces for everything else
2734 if (! spaceExceptionsBefore[tokens[i][1]] &&
2735 ! (i > 0 && spaceExceptionsAfter[tokens[i - 1][1]]) &&
2736 output.charAt(output.length - 1) !== ' ') {
2739 if (tokens[i][0] === 'keyword') {
2740 output += tokens[i][1].toUpperCase();
2742 output += tokens[i][1];
2746 // split columns in select and 'update set' clauses, but only inside statements blocks
2747 if ((lastStatementPart === 'select' || lastStatementPart === 'where' || lastStatementPart === 'set') &&
2748 tokens[i][1] === ',' && blockStack[0] === 'statement') {
2749 output += '\n' + tabs(indentLevel + 1);
2752 // split conditions in where clauses, but only inside statements blocks
2753 if (lastStatementPart === 'where' &&
2754 (tokens[i][1] === 'and' || tokens[i][1] === 'or' || tokens[i][1] === 'xor')) {
2755 if (blockStack[0] === 'statement') {
2756 output += '\n' + tabs(indentLevel + 1);
2758 // Todo: Also split and or blocks in newlines & indentation++
2759 // if (blockStack[0] === 'generic')
2767 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
2768 * return a jQuery object yet and hence cannot be chained
2770 * @param string question
2771 * @param string url URL to be passed to the callbackFn to make
2773 * @param function callbackFn callback to execute after user clicks on OK
2774 * @param function openCallback optional callback to run when dialog is shown
2777 jQuery.fn.PMA_confirm = function (question, url, callbackFn, openCallback) {
2778 var confirmState = PMA_commonParams.get('confirm');
2779 if (! confirmState) {
2780 // user does not want to confirm
2781 if ($.isFunction(callbackFn)) {
2782 callbackFn.call(this, url);
2786 if (PMA_messages.strDoYouReally === '') {
2791 * @var button_options Object that stores the options passed to jQueryUI
2794 var button_options = [
2796 text: PMA_messages.strOK,
2797 'class': 'submitOK',
2798 click: function () {
2799 $(this).dialog('close');
2800 if ($.isFunction(callbackFn)) {
2801 callbackFn.call(this, url);
2806 text: PMA_messages.strCancel,
2807 'class': 'submitCancel',
2808 click: function () {
2809 $(this).dialog('close');
2814 $('<div/>', { 'id': 'confirm_dialog', 'title': PMA_messages.strConfirm })
2817 buttons: button_options,
2818 close: function () {
2827 * jQuery function to sort a table's body after a new row has been appended to it.
2829 * @param string text_selector string to select the sortKey's text
2831 * @return jQuery Object for chaining purposes
2833 jQuery.fn.PMA_sort_table = function (text_selector) {
2834 return this.each(function () {
2836 * @var table_body Object referring to the table's <tbody> element
2838 var table_body = $(this);
2840 * @var rows Object referring to the collection of rows in {@link table_body}
2842 var rows = $(this).find('tr').get();
2844 // get the text of the field that we will sort by
2845 $.each(rows, function (index, row) {
2846 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
2849 // get the sorted order
2850 rows.sort(function (a, b) {
2851 if (a.sortKey < b.sortKey) {
2854 if (a.sortKey > b.sortKey) {
2860 // pull out each row from the table and then append it according to it's order
2861 $.each(rows, function (index, row) {
2862 $(table_body).append(row);
2869 * Unbind all event handlers before tearing down a page
2871 AJAX.registerTeardown('functions.js', function () {
2872 $(document).off('submit', '#create_table_form_minimal.ajax');
2873 $(document).off('submit', 'form.create_table_form.ajax');
2874 $(document).off('click', 'form.create_table_form.ajax input[name=submit_num_fields]');
2875 $(document).off('keyup', 'form.create_table_form.ajax input');
2876 $(document).off('change', 'input[name=partition_count],input[name=subpartition_count],select[name=partition_by]');
2880 * jQuery coding for 'Create Table'. Used on db_operations.php,
2881 * db_structure.php and db_tracking.php (i.e., wherever
2882 * PhpMyAdmin\Display\CreateTable is used)
2884 * Attach Ajax Event handlers for Create Table
2886 AJAX.registerOnload('functions.js', function () {
2888 * Attach event handler for submission of create table form (save)
2890 $(document).on('submit', 'form.create_table_form.ajax', function (event) {
2891 event.preventDefault();
2894 * @var the_form object referring to the create table form
2896 var $form = $(this);
2899 * First validate the form; if there is a problem, avoid submitting it
2901 * checkTableEditForm() needs a pure element and not a jQuery object,
2902 * this is why we pass $form[0] as a parameter (the jQuery object
2903 * is actually an array of DOM elements)
2906 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2907 PMA_prepareForAjaxRequest($form);
2908 if (PMA_checkReservedWordColumns($form)) {
2909 PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2910 // User wants to submit the form
2911 $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'do_save_data=1', function (data) {
2912 if (typeof data !== 'undefined' && data.success === true) {
2913 $('#properties_message')
2914 .removeClass('error')
2916 PMA_ajaxShowMessage(data.message);
2917 // Only if the create table dialog (distinct panel) exists
2918 var $createTableDialog = $('#create_table_dialog');
2919 if ($createTableDialog.length > 0) {
2920 $createTableDialog.dialog('close').remove();
2922 $('#tableslistcontainer').before(data.formatted_sql);
2925 * @var tables_table Object referring to the <tbody> element that holds the list of tables
2927 var tables_table = $('#tablesForm').find('tbody').not('#tbl_summary_row');
2928 // this is the first table created in this db
2929 if (tables_table.length === 0) {
2930 PMA_commonActions.refreshMain(
2931 PMA_commonParams.get('opendb_url')
2935 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
2937 var curr_last_row = $(tables_table).find('tr:last');
2939 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
2941 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2943 * @var curr_last_row_index Index of {@link curr_last_row}
2945 var curr_last_row_index = parseFloat(curr_last_row_index_string);
2947 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
2949 var new_last_row_index = curr_last_row_index + 1;
2951 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2953 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2955 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2957 $(data.new_table_string)
2958 .appendTo(tables_table);
2961 $(tables_table).PMA_sort_table('th');
2963 // Adjust summary row
2967 // Refresh navigation as a new table has been added
2968 PMA_reloadNavigation();
2969 // Redirect to table structure page on creation of new table
2970 var argsep = PMA_commonParams.get('arg_separator');
2971 var params_12 = 'ajax_request=true' + argsep + 'ajax_page_request=true';
2972 if (! (history && history.pushState)) {
2973 params_12 += PMA_MicroHistory.menus.getRequestParam();
2975 tblStruct_url = 'tbl_structure.php?server=' + data._params.server +
2976 argsep + 'db=' + data._params.db + argsep + 'token=' + data._params.token +
2977 argsep + 'goto=db_structure.php' + argsep + 'table=' + data._params.table + '';
2978 $.get(tblStruct_url, params_12, AJAX.responseHandler);
2980 PMA_ajaxShowMessage(
2981 '<div class="error">' + data.error + '</div>',
2987 } // end if (checkTableEditForm() )
2988 }); // end create table form (save)
2991 * Submits the intermediate changes in the table creation form
2992 * to refresh the UI accordingly
2994 function submitChangesInCreateTableForm (actionParam) {
2996 * @var the_form object referring to the create table form
2998 var $form = $('form.create_table_form.ajax');
3000 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
3001 PMA_prepareForAjaxRequest($form);
3003 // User wants to add more fields to the table
3004 $.post($form.attr('action'), $form.serialize() + '&' + actionParam, function (data) {
3005 if (typeof data !== 'undefined' && data.success) {
3006 var $pageContent = $('#page_content');
3007 $pageContent.html(data.message);
3008 PMA_highlightSQL($pageContent);
3009 PMA_verifyColumnsProperties();
3010 PMA_hideShowConnection($('.create_table_form select[name=tbl_storage_engine]'));
3011 PMA_ajaxRemoveMessage($msgbox);
3013 PMA_ajaxShowMessage(data.error);
3019 * Attach event handler for create table form (add fields)
3021 $(document).on('click', 'form.create_table_form.ajax input[name=submit_num_fields]', function (event) {
3022 event.preventDefault();
3023 submitChangesInCreateTableForm('submit_num_fields=1');
3024 }); // end create table form (add fields)
3026 $(document).on('keydown', 'form.create_table_form.ajax input[name=added_fields]', function (event) {
3027 if (event.keyCode === 13) {
3028 event.preventDefault();
3029 event.stopImmediatePropagation();
3032 .find('input[name=submit_num_fields]')
3038 * Attach event handler to manage changes in number of partitions and subpartitions
3040 $(document).on('change', 'input[name=partition_count],input[name=subpartition_count],select[name=partition_by]', function (event) {
3042 $form = $this.parents('form');
3043 if ($form.is('.create_table_form.ajax')) {
3044 submitChangesInCreateTableForm('submit_partition_change=1');
3050 $(document).on('change', 'input[value=AUTO_INCREMENT]', function () {
3052 var col = /\d/.exec($(this).attr('name'));
3054 var $selectFieldKey = $('select[name="field_key[' + col + ']"]');
3055 if ($selectFieldKey.val() === 'none_' + col) {
3056 $selectFieldKey.val('primary_' + col).change();
3061 .off('click', 'input.preview_sql')
3062 .on('click', 'input.preview_sql', function () {
3063 var $form = $(this).closest('form');
3064 PMA_previewSQL($form);
3070 * Validates the password field in a form
3072 * @see PMA_messages.strPasswordEmpty
3073 * @see PMA_messages.strPasswordNotSame
3074 * @param object $the_form The form to be validated
3077 function PMA_checkPassword ($the_form) {
3078 // Did the user select 'no password'?
3079 if ($the_form.find('#nopass_1').is(':checked')) {
3082 var $pred = $the_form.find('#select_pred_password');
3083 if ($pred.length && ($pred.val() === 'none' || $pred.val() === 'keep')) {
3088 var $password = $the_form.find('input[name=pma_pw]');
3089 var $password_repeat = $the_form.find('input[name=pma_pw2]');
3090 var alert_msg = false;
3092 if ($password.val() === '') {
3093 alert_msg = PMA_messages.strPasswordEmpty;
3094 } else if ($password.val() !== $password_repeat.val()) {
3095 alert_msg = PMA_messages.strPasswordNotSame;
3101 $password_repeat.val('');
3109 * Attach Ajax event handlers for 'Change Password' on index.php
3111 AJAX.registerOnload('functions.js', function () {
3112 /* Handler for hostname type */
3113 $(document).on('change', '#select_pred_hostname', function () {
3114 var hostname = $('#pma_hostname');
3115 if (this.value === 'any') {
3117 } else if (this.value === 'localhost') {
3118 hostname.val('localhost');
3119 } else if (this.value === 'thishost' && $(this).data('thishost')) {
3120 hostname.val($(this).data('thishost'));
3121 } else if (this.value === 'hosttable') {
3122 hostname.val('').prop('required', false);
3123 } else if (this.value === 'userdefined') {
3124 hostname.focus().select().prop('required', true);
3128 /* Handler for editing hostname */
3129 $(document).on('change', '#pma_hostname', function () {
3130 $('#select_pred_hostname').val('userdefined');
3131 $('#pma_hostname').prop('required', true);
3134 /* Handler for username type */
3135 $(document).on('change', '#select_pred_username', function () {
3136 if (this.value === 'any') {
3137 $('#pma_username').val('').prop('required', false);
3138 $('#user_exists_warning').css('display', 'none');
3139 } else if (this.value === 'userdefined') {
3140 $('#pma_username').focus().select().prop('required', true);
3144 /* Handler for editing username */
3145 $(document).on('change', '#pma_username', function () {
3146 $('#select_pred_username').val('userdefined');
3147 $('#pma_username').prop('required', true);
3150 /* Handler for password type */
3151 $(document).on('change', '#select_pred_password', function () {
3152 if (this.value === 'none') {
3153 $('#text_pma_pw2').prop('required', false).val('');
3154 $('#text_pma_pw').prop('required', false).val('');
3155 } else if (this.value === 'userdefined') {
3156 $('#text_pma_pw2').prop('required', true);
3157 $('#text_pma_pw').prop('required', true).focus().select();
3159 $('#text_pma_pw2').prop('required', false);
3160 $('#text_pma_pw').prop('required', false);
3164 /* Handler for editing password */
3165 $(document).on('change', '#text_pma_pw,#text_pma_pw2', function () {
3166 $('#select_pred_password').val('userdefined');
3167 $('#text_pma_pw2').prop('required', true);
3168 $('#text_pma_pw').prop('required', true);
3172 * Unbind all event handlers before tearing down a page
3174 $(document).off('click', '#change_password_anchor.ajax');
3177 * Attach Ajax event handler on the change password anchor
3180 $(document).on('click', '#change_password_anchor.ajax', function (event) {
3181 event.preventDefault();
3183 var $msgbox = PMA_ajaxShowMessage();
3186 * @var button_options Object containing options to be passed to jQueryUI's dialog
3188 var button_options = {};
3189 button_options[PMA_messages.strGo] = function () {
3190 event.preventDefault();
3193 * @var $the_form Object referring to the change password form
3195 var $the_form = $('#change_password_form');
3197 if (! PMA_checkPassword($the_form)) {
3202 * @var this_value String containing the value of the submit button.
3203 * Need to append this for the change password form on Server Privileges
3206 var this_value = $(this).val();
3208 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
3209 $the_form.append('<input type="hidden" name="ajax_request" value="true" />');
3211 $.post($the_form.attr('action'), $the_form.serialize() + PMA_commonParams.get('arg_separator') + 'change_pw=' + this_value, function (data) {
3212 if (typeof data === 'undefined' || data.success !== true) {
3213 PMA_ajaxShowMessage(data.error, false);
3217 var $pageContent = $('#page_content');
3218 $pageContent.prepend(data.message);
3219 PMA_highlightSQL($pageContent);
3220 $('#change_password_dialog').hide().remove();
3221 $('#edit_user_dialog').dialog('close').remove();
3222 PMA_ajaxRemoveMessage($msgbox);
3226 button_options[PMA_messages.strCancel] = function () {
3227 $(this).dialog('close');
3229 $.get($(this).attr('href'), { 'ajax_request': true }, function (data) {
3230 if (typeof data === 'undefined' || !data.success) {
3231 PMA_ajaxShowMessage(data.error, false);
3235 if (data._scripts) {
3236 AJAX.scriptHandler.load(data._scripts);
3239 $('<div id="change_password_dialog"></div>')
3241 title: PMA_messages.strChangePassword,
3243 close: function (ev, ui) {
3246 buttons: button_options,
3249 .append(data.message);
3250 // for this dialog, we remove the fieldset wrapping due to double headings
3251 $('fieldset#fieldset_change_password')
3252 .find('legend').remove().end()
3253 .find('table.noclick').unwrap().addClass('some-margin')
3254 .find('input#text_pma_pw').focus();
3255 $('#fieldset_change_password_footer').hide();
3256 PMA_ajaxRemoveMessage($msgbox);
3257 displayPasswordGenerateButton();
3258 $('#change_password_form').on('submit', function (e) {
3261 .closest('.ui-dialog')
3262 .find('.ui-dialog-buttonpane .ui-button')
3267 }); // end handler for change password anchor
3268 }); // end $() for Change Password
3271 * Unbind all event handlers before tearing down a page
3273 AJAX.registerTeardown('functions.js', function () {
3274 $(document).off('change', 'select.column_type');
3275 $(document).off('change', 'select.default_type');
3276 $(document).off('change', 'select.virtuality');
3277 $(document).off('change', 'input.allow_null');
3278 $(document).off('change', '.create_table_form select[name=tbl_storage_engine]');
3281 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
3282 * the page loads and when the selected data type changes
3284 AJAX.registerOnload('functions.js', function () {
3285 // is called here for normal page loads and also when opening
3286 // the Create table dialog
3287 PMA_verifyColumnsProperties();
3289 // needs on() to work also in the Create Table dialog
3290 $(document).on('change', 'select.column_type', function () {
3291 PMA_showNoticeForEnum($(this));
3293 $(document).on('change', 'select.default_type', function () {
3294 PMA_hideShowDefaultValue($(this));
3296 $(document).on('change', 'select.virtuality', function () {
3297 PMA_hideShowExpression($(this));
3299 $(document).on('change', 'input.allow_null', function () {
3300 PMA_validateDefaultValue($(this));
3302 $(document).on('change', '.create_table_form select[name=tbl_storage_engine]', function () {
3303 PMA_hideShowConnection($(this));
3308 * If the chosen storage engine is FEDERATED show connection field. Hide otherwise
3310 * @param $engine_selector storage engine selector
3312 function PMA_hideShowConnection ($engine_selector) {
3313 var $connection = $('.create_table_form input[name=connection]');
3314 var index = $connection.parent('td').index() + 1;
3315 var $labelTh = $connection.parents('tr').prev('tr').children('th:nth-child(' + index + ')');
3316 if ($engine_selector.val() !== 'FEDERATED') {
3318 .prop('disabled', true)
3319 .parent('td').hide();
3323 .prop('disabled', false)
3324 .parent('td').show();
3330 * If the column does not allow NULL values, makes sure that default is not NULL
3332 function PMA_validateDefaultValue ($null_checkbox) {
3333 if (! $null_checkbox.prop('checked')) {
3334 var $default = $null_checkbox.closest('tr').find('.default_type');
3335 if ($default.val() === 'NULL') {
3336 $default.val('NONE');
3342 * function to populate the input fields on picking a column from central list
3344 * @param string input_id input id of the name field for the column to be populated
3345 * @param integer offset of the selected column in central list of columns
3347 function autoPopulate (input_id, offset) {
3348 var db = PMA_commonParams.get('db');
3349 var table = PMA_commonParams.get('table');
3350 input_id = input_id.substring(0, input_id.length - 1);
3351 $('#' + input_id + '1').val(central_column_list[db + '_' + table][offset].col_name);
3352 var col_type = central_column_list[db + '_' + table][offset].col_type.toUpperCase();
3353 $('#' + input_id + '2').val(col_type);
3354 var $input3 = $('#' + input_id + '3');
3355 $input3.val(central_column_list[db + '_' + table][offset].col_length);
3356 if (col_type === 'ENUM' || col_type === 'SET') {
3357 $input3.next().show();
3359 $input3.next().hide();
3361 var col_default = central_column_list[db + '_' + table][offset].col_default.toUpperCase();
3362 var $input4 = $('#' + input_id + '4');
3363 if (col_default !== '' && col_default !== 'NULL' && col_default !== 'CURRENT_TIMESTAMP' && col_default !== 'CURRENT_TIMESTAMP()') {
3364 $input4.val('USER_DEFINED');
3365 $input4.next().next().show();
3366 $input4.next().next().val(central_column_list[db + '_' + table][offset].col_default);
3368 $input4.val(central_column_list[db + '_' + table][offset].col_default);
3369 $input4.next().next().hide();
3371 $('#' + input_id + '5').val(central_column_list[db + '_' + table][offset].col_collation);
3372 var $input6 = $('#' + input_id + '6');
3373 $input6.val(central_column_list[db + '_' + table][offset].col_attribute);
3374 if (central_column_list[db + '_' + table][offset].col_extra === 'on update CURRENT_TIMESTAMP') {
3375 $input6.val(central_column_list[db + '_' + table][offset].col_extra);
3377 if (central_column_list[db + '_' + table][offset].col_extra.toUpperCase() === 'AUTO_INCREMENT') {
3378 $('#' + input_id + '9').prop('checked',true).change();
3380 $('#' + input_id + '9').prop('checked',false);
3382 if (central_column_list[db + '_' + table][offset].col_isNull !== '0') {
3383 $('#' + input_id + '7').prop('checked',true);
3385 $('#' + input_id + '7').prop('checked',false);
3390 * Unbind all event handlers before tearing down a page
3392 AJAX.registerTeardown('functions.js', function () {
3393 $(document).off('click', 'a.open_enum_editor');
3394 $(document).off('click', 'input.add_value');
3395 $(document).off('click', '#enum_editor td.drop');
3396 $(document).off('click', 'a.central_columns_dialog');
3399 * @var $enum_editor_dialog An object that points to the jQuery
3400 * dialog of the ENUM/SET editor
3402 var $enum_editor_dialog = null;
3404 * Opens the ENUM/SET editor and controls its functions
3406 AJAX.registerOnload('functions.js', function () {
3407 $(document).on('click', 'a.open_enum_editor', function () {
3408 // Get the name of the column that is being edited
3409 var colname = $(this).closest('tr').find('input:first').val();
3412 // And use it to make up a title for the page
3413 if (colname.length < 1) {
3414 title = PMA_messages.enum_newColumnVals;
3416 title = PMA_messages.enum_columnVals.replace(
3418 '"' + escapeHtml(decodeURIComponent(colname)) + '"'
3421 // Get the values as a string
3422 var inputstring = $(this)
3426 // Escape html entities
3427 inputstring = $('<div/>')
3430 // Parse the values, escaping quotes and
3431 // slashes on the fly, into an array
3433 var in_string = false;
3437 for (i = 0; i < inputstring.length; i++) {
3438 curr = inputstring.charAt(i);
3439 next = i === inputstring.length ? '' : inputstring.charAt(i + 1);
3440 if (! in_string && curr === '\'') {
3442 } else if (in_string && curr === '\\' && next === '\\') {
3445 } else if (in_string && next === '\'' && (curr === '\'' || curr === '\\')) {
3448 } else if (in_string && curr === '\'') {
3450 values.push(buffer);
3452 } else if (in_string) {
3456 if (buffer.length > 0) {
3457 // The leftovers in the buffer are the last value (if any)
3458 values.push(buffer);
3461 // If there are no values, maybe the user is about to make a
3462 // new list so we add a few for him/her to get started with.
3463 if (values.length === 0) {
3464 values.push('', '', '', '');
3466 // Add the parsed values to the editor
3467 var drop_icon = PMA_getImage('b_drop');
3468 for (i = 0; i < values.length; i++) {
3469 fields += '<tr><td>' +
3470 '<input type=\'text\' value=\'' + values[i] + '\'/>' +
3471 '</td><td class=\'drop\'>' +
3476 * @var dialog HTML code for the ENUM/SET dialog
3478 var dialog = '<div id=\'enum_editor\'>' +
3480 '<legend>' + title + '</legend>' +
3481 '<p>' + PMA_getImage('s_notice') +
3482 PMA_messages.enum_hint + '</p>' +
3483 '<table class=\'values\'>' + fields + '</table>' +
3484 '</fieldset><fieldset class=\'tblFooters\'>' +
3485 '<table class=\'add\'><tr><td>' +
3486 '<div class=\'slider\'></div>' +
3488 '<form><div><input type=\'submit\' class=\'add_value\' value=\'' +
3489 PMA_sprintf(PMA_messages.enum_addValue, 1) +
3490 '\'/></div></form>' +
3491 '</td></tr></table>' +
3492 '<input type=\'hidden\' value=\'' + // So we know which column's data is being edited
3493 $(this).closest('td').find('input').attr('id') +
3498 * @var Defines functions to be called when the buttons in
3499 * the buttonOptions jQuery dialog bar are pressed
3501 var buttonOptions = {};
3502 buttonOptions[PMA_messages.strGo] = function () {
3503 // When the submit button is clicked,
3504 // put the data back into the original form
3505 var value_array = [];
3506 $(this).find('.values input').each(function (index, elm) {
3507 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, '\'\'');
3508 value_array.push('\'' + val + '\'');
3510 // get the Length/Values text field where this value belongs
3511 var values_id = $(this).find('input[type=\'hidden\']').val();
3512 $('input#' + values_id).val(value_array.join(','));
3513 $(this).dialog('close');
3515 buttonOptions[PMA_messages.strClose] = function () {
3516 $(this).dialog('close');
3519 var width = parseInt(
3520 (parseInt($('html').css('font-size'), 10) / 13) * 340,
3526 $enum_editor_dialog = $(dialog).dialog({
3530 title: PMA_messages.enum_editor,
3531 buttons: buttonOptions,
3533 // Focus the "Go" button after opening the dialog
3534 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3536 close: function () {
3540 // slider for choosing how many fields to add
3541 $enum_editor_dialog.find('.slider').slider({
3547 slide: function (event, ui) {
3548 $(this).closest('table').find('input[type=submit]').val(
3549 PMA_sprintf(PMA_messages.enum_addValue, ui.value)
3553 // Focus the slider, otherwise it looks nearly transparent
3554 $('a.ui-slider-handle').addClass('ui-state-focus');
3558 $(document).on('click', 'a.central_columns_dialog', function (e) {
3559 var href = 'db_central_columns.php';
3560 var db = PMA_commonParams.get('db');
3561 var table = PMA_commonParams.get('table');
3562 var maxRows = $(this).data('maxrows');
3563 var pick = $(this).data('pick');
3564 if (pick !== false) {
3568 'ajax_request' : true,
3569 'server' : PMA_commonParams.get('server'),
3570 'db' : PMA_commonParams.get('db'),
3571 'cur_table' : PMA_commonParams.get('table'),
3572 'getColumnList':true
3574 var colid = $(this).closest('td').find('input').attr('id');
3576 if (! (db + '_' + table in central_column_list)) {
3577 central_column_list.push(db + '_' + table);
3582 success: function (data) {
3583 central_column_list[db + '_' + table] = JSON.parse(data.message);
3589 var list_size = central_column_list[db + '_' + table].length;
3590 var min = (list_size <= maxRows) ? list_size : maxRows;
3591 for (i = 0; i < min; i++) {
3592 fields += '<tr><td><div><span class="font_weight_bold">' +
3593 escapeHtml(central_column_list[db + '_' + table][i].col_name) +
3594 '</span><br><span class="color_gray">' + central_column_list[db + '_' + table][i].col_type;
3596 if (central_column_list[db + '_' + table][i].col_attribute !== '') {
3597 fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_attribute) + ') ';
3599 if (central_column_list[db + '_' + table][i].col_length !== '') {
3600 fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_length) + ') ';
3602 fields += escapeHtml(central_column_list[db + '_' + table][i].col_extra) + '</span>' +
3605 fields += '<td><input class="pick all100" type="submit" value="' +
3606 PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3610 var result_pointer = i;
3611 var search_in = '<input type="text" class="filter_rows" placeholder="' + PMA_messages.searchList + '">';
3612 if (fields === '') {
3613 fields = PMA_sprintf(PMA_messages.strEmptyCentralList, '\'' + escapeHtml(db) + '\'');
3617 if (list_size > maxRows) {
3618 seeMore = '<fieldset class=\'tblFooters center\' style=\'font-weight:bold\'>' +
3619 '<a href=\'#\' id=\'seeMore\'>' + PMA_messages.seeMore + '</a></fieldset>';
3621 var central_columns_dialog = '<div style=\'max-height:400px\'>' +
3624 '<table id=\'col_list\' style=\'width:100%\' class=\'values\'>' + fields + '</table>' +
3629 var width = parseInt(
3630 (parseInt($('html').css('font-size'), 10) / 13) * 500,
3636 var buttonOptions = {};
3637 var $central_columns_dialog = $(central_columns_dialog).dialog({
3641 title: PMA_messages.pickColumnTitle,
3642 buttons: buttonOptions,
3644 $('#col_list').on('click', '.pick', function () {
3645 $central_columns_dialog.remove();
3647 $('.filter_rows').on('keyup', function () {
3648 $.uiTableFilter($('#col_list'), $(this).val());
3650 $('#seeMore').click(function () {
3652 min = (list_size <= maxRows + result_pointer) ? list_size : maxRows + result_pointer;
3653 for (i = result_pointer; i < min; i++) {
3654 fields += '<tr><td><div><span class="font_weight_bold">' +
3655 central_column_list[db + '_' + table][i].col_name +
3656 '</span><br><span class="color_gray">' +
3657 central_column_list[db + '_' + table][i].col_type;
3659 if (central_column_list[db + '_' + table][i].col_attribute !== '') {
3660 fields += '(' + central_column_list[db + '_' + table][i].col_attribute + ') ';
3662 if (central_column_list[db + '_' + table][i].col_length !== '') {
3663 fields += '(' + central_column_list[db + '_' + table][i].col_length + ') ';
3665 fields += central_column_list[db + '_' + table][i].col_extra + '</span>' +
3668 fields += '<td><input class="pick all100" type="submit" value="' +
3669 PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3673 $('#col_list').append(fields);
3675 if (result_pointer === list_size) {
3676 $('.tblFooters').hide();
3680 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3682 close: function () {
3683 $('#col_list').off('click', '.pick');
3684 $('.filter_rows').off('keyup');
3691 // $(document).on('click', 'a.show_central_list',function(e) {
3694 // When "add a new value" is clicked, append an empty text field
3695 $(document).on('click', 'input.add_value', function (e) {
3697 var num_new_rows = $enum_editor_dialog.find('div.slider').slider('value');
3698 while (num_new_rows--) {
3699 $enum_editor_dialog.find('.values')
3701 '<tr class=\'hide\'><td>' +
3702 '<input type=\'text\' />' +
3703 '</td><td class=\'drop\'>' +
3704 PMA_getImage('b_drop') +
3712 // Removes the specified row from the enum editor
3713 $(document).on('click', '#enum_editor td.drop', function () {
3714 $(this).closest('tr').hide('fast', function () {
3721 * Ensures indexes names are valid according to their type and, for a primary
3722 * key, lock index name to 'PRIMARY'
3723 * @param string form_id Variable which parses the form name as
3725 * @return boolean false if there is no index form, true else
3727 function checkIndexName (form_id) {
3728 if ($('#' + form_id).length === 0) {
3732 // Gets the elements pointers
3733 var $the_idx_name = $('#input_index_name');
3734 var $the_idx_choice = $('#select_index_choice');
3736 // Index is a primary key
3737 if ($the_idx_choice.find('option:selected').val() === 'PRIMARY') {
3738 $the_idx_name.val('PRIMARY');
3739 $the_idx_name.prop('disabled', true);
3741 if ($the_idx_name.val() === 'PRIMARY') {
3742 $the_idx_name.val('');
3744 $the_idx_name.prop('disabled', false);
3748 } // end of the 'checkIndexName()' function
3750 AJAX.registerTeardown('functions.js', function () {
3751 $(document).off('click', '#index_frm input[type=submit]');
3753 AJAX.registerOnload('functions.js', function () {
3755 * Handler for adding more columns to an index in the editor
3757 $(document).on('click', '#index_frm input[type=submit]', function (event) {
3758 event.preventDefault();
3759 var rows_to_add = $(this)
3760 .closest('fieldset')
3764 var tempEmptyVal = function () {
3768 var tempSetFocus = function () {
3769 if ($(this).find('option:selected').val() === '') {
3772 $(this).closest('tr').find('input').focus();
3775 while (rows_to_add--) {
3776 var $indexColumns = $('#index_columns');
3777 var $newrow = $indexColumns
3778 .find('tbody > tr:first')
3781 $indexColumns.find('tbody')
3783 $newrow.find(':input').each(tempEmptyVal);
3784 // focus index size input on column picked
3785 $newrow.find('select').change(tempSetFocus);
3790 function indexEditorDialog (url, title, callback_success, callback_failure) {
3791 /* Remove the hidden dialogs if there are*/
3792 var $editIndexDialog = $('#edit_index_dialog');
3793 if ($editIndexDialog.length !== 0) {
3794 $editIndexDialog.remove();
3796 var $div = $('<div id="edit_index_dialog"></div>');
3799 * @var button_options Object that stores the options
3800 * passed to jQueryUI dialog
3802 var button_options = {};
3803 button_options[PMA_messages.strGo] = function () {
3805 * @var the_form object referring to the export form
3807 var $form = $('#index_frm');
3808 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
3809 PMA_prepareForAjaxRequest($form);
3810 // User wants to submit the form
3811 $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'do_save_data=1', function (data) {
3812 var $sqlqueryresults = $('.sqlqueryresults');
3813 if ($sqlqueryresults.length !== 0) {
3814 $sqlqueryresults.remove();
3816 if (typeof data !== 'undefined' && data.success === true) {
3817 PMA_ajaxShowMessage(data.message);
3818 PMA_highlightSQL($('.result_query'));
3819 $('.result_query .notice').remove();
3820 /* Reload the field form*/
3821 $('#table_index').remove();
3822 $('<div id=\'temp_div\'><div>')
3823 .append(data.index_table)
3824 .find('#table_index')
3825 .insertAfter('#index_header');
3826 var $editIndexDialog = $('#edit_index_dialog');
3827 if ($editIndexDialog.length > 0) {
3828 $editIndexDialog.dialog('close');
3830 $('div.no_indexes_defined').hide();
3831 if (callback_success) {
3834 PMA_reloadNavigation();
3836 var $temp_div = $('<div id=\'temp_div\'><div>').append(data.error);
3838 if ($temp_div.find('.error code').length !== 0) {
3839 $error = $temp_div.find('.error code').addClass('error');
3843 if (callback_failure) {
3846 PMA_ajaxShowMessage($error, false);
3850 button_options[PMA_messages.strPreviewSQL] = function () {
3851 // Function for Previewing SQL
3852 var $form = $('#index_frm');
3853 PMA_previewSQL($form);
3855 button_options[PMA_messages.strCancel] = function () {
3856 $(this).dialog('close');
3858 var $msgbox = PMA_ajaxShowMessage();
3859 $.post('tbl_indexes.php', url, function (data) {
3860 if (typeof data !== 'undefined' && data.success === false) {
3861 // in the case of an error, show the error message returned.
3862 PMA_ajaxShowMessage(data.error, false);
3864 PMA_ajaxRemoveMessage($msgbox);
3865 // Show dialog if the request was successful
3867 .append(data.message)
3871 open: PMA_verifyColumnsProperties,
3873 buttons: button_options,
3874 close: function () {
3878 $div.find('.tblFooters').remove();
3879 showIndexEditDialog($div);
3884 function showIndexEditDialog ($outer) {
3886 checkIndexName('index_frm');
3887 var $indexColumns = $('#index_columns');
3888 $indexColumns.find('td').each(function () {
3889 $(this).css('width', $(this).width() + 'px');
3891 $indexColumns.find('tbody').sortable({
3893 containment: $indexColumns.find('tbody'),
3894 tolerance: 'pointer'
3896 PMA_showHints($outer);
3898 // Add a slider for selecting how many columns to add to the index
3899 $outer.find('.slider').slider({
3904 slide: function (event, ui) {
3905 $(this).closest('fieldset').find('input[type=submit]').val(
3906 PMA_sprintf(PMA_messages.strAddToIndex, ui.value)
3910 $('div.add_fields').removeClass('hide');
3911 // focus index size input on column picked
3912 $outer.find('table#index_columns select').change(function () {
3913 if ($(this).find('option:selected').val() === '') {
3916 $(this).closest('tr').find('input').focus();
3918 // Focus the slider, otherwise it looks nearly transparent
3919 $('a.ui-slider-handle').addClass('ui-state-focus');
3920 // set focus on index name input, if empty
3921 var input = $outer.find('input#input_index_name');
3922 if (! input.val()) {
3928 * Function to display tooltips that were
3929 * generated on the PHP side by PhpMyAdmin\Util::showHint()
3931 * @param object $div a div jquery object which specifies the
3932 * domain for searching for tooltips. If we
3933 * omit this parameter the function searches
3936 function PMA_showHints ($div) {
3937 if ($div === undefined || ! $div instanceof jQuery || $div.length === 0) {
3940 $div.find('.pma_hint').each(function () {
3942 $(this).children('img'),
3944 $(this).children('span').html()
3949 AJAX.registerOnload('functions.js', function () {
3953 function PMA_mainMenuResizerCallback () {
3954 // 5 px margin for jumping menu in Chrome
3955 return $(document.body).width() - 5;
3957 // This must be fired only once after the initial page load
3959 // Initialise the menu resize plugin
3960 $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
3961 // register resize event
3962 $(window).on('resize', function () {
3963 $('#topmenu').menuResizer('resize');
3968 * Get the row number from the classlist (for example, row_1)
3970 function PMA_getRowNumber (classlist) {
3971 return parseInt(classlist.split(/\s+row_/)[1], 10);
3975 * Changes status of slider
3977 function PMA_set_status_label ($element) {
3979 if ($element.css('display') === 'none') {
3984 $element.closest('.slide-wrapper').prev().find('span').text(text);
3988 * var toggleButton This is a function that creates a toggle
3989 * sliding button given a jQuery reference
3990 * to the correct DOM element
3992 var toggleButton = function ($obj) {
3993 // In rtl mode the toggle switch is flipped horizontally
3994 // so we need to take that into account
3996 if ($('span.text_direction', $obj).text() === 'ltr') {
4002 * var h Height of the button, used to scale the
4003 * background image and position the layers
4005 var h = $obj.height();
4006 $('img', $obj).height(h);
4007 $('table', $obj).css('bottom', h - 1);
4009 * var on Width of the "ON" part of the toggle switch
4010 * var off Width of the "OFF" part of the toggle switch
4012 var on = $('td.toggleOn', $obj).width();
4013 var off = $('td.toggleOff', $obj).width();
4014 // Make the "ON" and "OFF" parts of the switch the same size
4015 // + 2 pixels to avoid overflowed
4016 $('td.toggleOn > div', $obj).width(Math.max(on, off) + 2);
4017 $('td.toggleOff > div', $obj).width(Math.max(on, off) + 2);
4019 * var w Width of the central part of the switch
4021 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
4022 // Resize the central part of the switch on the top
4023 // layer to match the background
4024 $('table td:nth-child(2) > div', $obj).width(w);
4026 * var imgw Width of the background image
4027 * var tblw Width of the foreground layer
4028 * var offset By how many pixels to move the background
4029 * image, so that it matches the top layer
4031 var imgw = $('img', $obj).width();
4032 var tblw = $('table', $obj).width();
4033 var offset = parseInt(((imgw - tblw) / 2), 10);
4034 // Move the background to match the layout of the top layer
4035 $obj.find('img').css(right, offset);
4037 * var offw Outer width of the "ON" part of the toggle switch
4038 * var btnw Outer width of the central part of the switch
4040 var offw = $('td.toggleOff', $obj).outerWidth();
4041 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
4042 // Resize the main div so that exactly one side of
4043 // the switch plus the central part fit into it.
4044 $obj.width(offw + btnw + 2);
4046 * var move How many pixels to move the
4047 * switch by when toggling
4049 var move = $('td.toggleOff', $obj).outerWidth();
4050 // If the switch is initialized to the
4051 // OFF state we need to move it now.
4052 if ($('div.container', $obj).hasClass('off')) {
4053 if (right === 'right') {
4054 $('div.container', $obj).animate({ 'left': '-=' + move + 'px' }, 0);
4056 $('div.container', $obj).animate({ 'left': '+=' + move + 'px' }, 0);
4059 // Attach an 'onclick' event to the switch
4060 $('div.container', $obj).click(function () {
4061 if ($(this).hasClass('isActive')) {
4064 $(this).addClass('isActive');
4066 var $msg = PMA_ajaxShowMessage();
4067 var $container = $(this);
4068 var callback = $('span.callback', this).text();
4073 // Perform the actual toggle
4074 if ($(this).hasClass('on')) {
4075 if (right === 'right') {
4080 url = $(this).find('td.toggleOff > span').text();
4084 if (right === 'right') {
4089 url = $(this).find('td.toggleOn > span').text();
4090 removeClass = 'off';
4094 var parts = url.split('?');
4095 $.post(parts[0], parts[1] + '&ajax_request=true', function (data) {
4096 if (typeof data !== 'undefined' && data.success === true) {
4097 PMA_ajaxRemoveMessage($msg);
4099 .removeClass(removeClass)
4101 .animate({ 'left': operator + move + 'px' }, function () {
4102 $container.removeClass('isActive');
4106 PMA_ajaxShowMessage(data.error, false);
4107 $container.removeClass('isActive');
4114 * Unbind all event handlers before tearing down a page
4116 AJAX.registerTeardown('functions.js', function () {
4117 $('div.container').off('click');
4120 * Initialise all toggle buttons
4122 AJAX.registerOnload('functions.js', function () {
4123 $('div.toggleAjax').each(function () {
4124 var $button = $(this).show();
4125 $button.find('img').each(function () {
4126 if (this.complete) {
4127 toggleButton($button);
4129 $(this).load(function () {
4130 toggleButton($button);
4138 * Unbind all event handlers before tearing down a page
4140 AJAX.registerTeardown('functions.js', function () {
4141 $(document).off('change', 'select.pageselector');
4142 $('#update_recent_tables').off('ready');
4143 $('#sync_favorite_tables').off('ready');
4146 AJAX.registerOnload('functions.js', function () {
4148 * Autosubmit page selector
4150 $(document).on('change', 'select.pageselector', function (event) {
4151 event.stopPropagation();
4152 // Check where to load the new content
4153 if ($(this).closest('#pma_navigation').length === 0) {
4154 // For the main page we don't need to do anything,
4155 $(this).closest('form').submit();
4157 // but for the navigation we need to manually replace the content
4158 PMA_navigationTreePagination($(this));
4163 * Load version information asynchronously.
4165 if ($('li.jsversioncheck').length > 0) {
4168 url: 'version_check.php',
4171 'server': PMA_commonParams.get('server')
4173 success: PMA_current_version
4177 if ($('#is_git_revision').length > 0) {
4178 setTimeout(PMA_display_git_revision, 10);
4186 var $updateRecentTables = $('#update_recent_tables');
4187 if ($updateRecentTables.length) {
4189 $updateRecentTables.attr('href'),
4192 if (typeof data !== 'undefined' && data.success === true) {
4193 $('#pma_recent_list').html(data.list);
4199 // Sync favorite tables from localStorage to pmadb.
4200 if ($('#sync_favorite_tables').length) {
4202 url: $('#sync_favorite_tables').attr('href'),
4206 favorite_tables: (isStorageSupported('localStorage') && typeof window.localStorage.favorite_tables !== 'undefined')
4207 ? window.localStorage.favorite_tables
4209 server: PMA_commonParams.get('server'),
4212 success: function (data) {
4213 // Update localStorage.
4214 if (isStorageSupported('localStorage')) {
4215 window.localStorage.favorite_tables = data.favorite_tables;
4217 $('#pma_favorite_list').html(data.list);
4224 * Submits the form placed in place of a link due to the excessive url length
4226 * @param $link anchor
4227 * @returns {Boolean}
4229 function submitFormLink ($link) {
4230 if ($link.attr('href').indexOf('=') !== -1) {
4231 var data = $link.attr('href').substr($link.attr('href').indexOf('#') + 1).split('=', 2);
4232 $link.parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
4234 $link.parents('form').submit();
4238 * Initializes slider effect.
4240 function PMA_init_slider () {
4241 $('div.pma_auto_slider').each(function () {
4242 var $this = $(this);
4243 if ($this.data('slider_init_done')) {
4246 var $wrapper = $('<div>', { 'class': 'slide-wrapper' });
4247 $wrapper.toggle($this.is(':visible'));
4248 $('<a>', { href: '#' + this.id, 'class': 'ajax' })
4249 .text($this.attr('title'))
4250 .prepend($('<span>'))
4251 .insertBefore($this)
4252 .click(function () {
4253 var $wrapper = $this.closest('.slide-wrapper');
4254 var visible = $this.is(':visible');
4258 $this[visible ? 'hide' : 'show']('blind', function () {
4259 $wrapper.toggle(!visible);
4260 $wrapper.parent().toggleClass('print_ignore', visible);
4261 PMA_set_status_label($this);
4265 $this.wrap($wrapper);
4266 $this.removeAttr('title');
4267 PMA_set_status_label($this);
4268 $this.data('slider_init_done', 1);
4273 * Initializes slider effect.
4275 AJAX.registerOnload('functions.js', function () {
4280 * Restores sliders to the state they were in before initialisation.
4282 AJAX.registerTeardown('functions.js', function () {
4283 $('div.pma_auto_slider').each(function () {
4284 var $this = $(this);
4286 $this.parent().replaceWith($this);
4287 $this.parent().children('a').remove();
4292 * Creates a message inside an object with a sliding effect
4294 * @param msg A string containing the text to display
4295 * @param $obj a jQuery object containing the reference
4296 * to the element where to put the message
4297 * This is optional, if no element is
4298 * provided, one will be created below the
4299 * navigation links at the top of the page
4301 * @return bool True on success, false on failure
4303 function PMA_slidingMessage (msg, $obj) {
4304 if (msg === undefined || msg.length === 0) {
4305 // Don't show an empty message
4308 if ($obj === undefined || ! $obj instanceof jQuery || $obj.length === 0) {
4309 // If the second argument was not supplied,
4310 // we might have to create a new DOM node.
4311 if ($('#PMA_slidingMessage').length === 0) {
4312 $('#page_content').prepend(
4313 '<span id="PMA_slidingMessage" ' +
4314 'class="pma_sliding_message"></span>'
4317 $obj = $('#PMA_slidingMessage');
4319 if ($obj.has('div').length > 0) {
4320 // If there already is a message inside the
4321 // target object, we must get rid of it
4325 .fadeOut(function () {
4330 .append('<div>' + msg + '</div>');
4331 // highlight any sql before taking height;
4332 PMA_highlightSQL($obj);
4338 height: $obj.find('div').first().height()
4345 // Object does not already have a message
4346 // inside it, so we simply slide it down
4348 .html('<div>' + msg + '</div>');
4349 // highlight any sql before taking height;
4350 PMA_highlightSQL($obj);
4364 // Set the height of the parent
4365 // to the height of the child
4376 } // end PMA_slidingMessage()
4379 * Attach CodeMirror2 editor to SQL edit area.
4381 AJAX.registerOnload('functions.js', function () {
4382 var $elm = $('#sqlquery');
4383 if ($elm.length > 0) {
4384 if (typeof CodeMirror !== 'undefined') {
4385 codemirror_editor = PMA_getSQLEditor($elm);
4386 codemirror_editor.focus();
4387 codemirror_editor.on('blur', updateQueryParameters);
4389 // without codemirror
4390 $elm.focus().on('blur', updateQueryParameters);
4393 PMA_highlightSQL($('body'));
4395 AJAX.registerTeardown('functions.js', function () {
4396 if (codemirror_editor) {
4397 $('#sqlquery').text(codemirror_editor.getValue());
4398 codemirror_editor.toTextArea();
4399 codemirror_editor = false;
4402 AJAX.registerOnload('functions.js', function () {
4403 // initializes all lock-page elements lock-id and
4404 // val-hash data property
4405 $('#page_content form.lock-page textarea, ' +
4406 '#page_content form.lock-page input[type="text"], ' +
4407 '#page_content form.lock-page input[type="number"], ' +
4408 '#page_content form.lock-page select').each(function (i) {
4409 $(this).data('lock-id', i);
4410 // val-hash is the hash of default value of the field
4411 // so that it can be compared with new value hash
4412 // to check whether field was modified or not.
4413 $(this).data('val-hash', AJAX.hash($(this).val()));
4416 // initializes lock-page elements (input types checkbox and radio buttons)
4417 // lock-id and val-hash data property
4418 $('#page_content form.lock-page input[type="checkbox"], ' +
4419 '#page_content form.lock-page input[type="radio"]').each(function (i) {
4420 $(this).data('lock-id', i);
4421 $(this).data('val-hash', AJAX.hash($(this).is(':checked')));
4426 * jQuery plugin to correctly filter input fields by value, needed
4427 * because some nasty values may break selector syntax
4430 $.fn.filterByValue = function (value) {
4431 return this.filter(function () {
4432 return $(this).val() === value;
4438 * Return value of a cell in a table.
4440 function PMA_getCellValue (td) {
4442 if ($td.is('.null')) {
4444 } else if ((! $td.is('.to_be_saved')
4446 && $td.data('original_data')
4448 return $td.data('original_data');
4454 $(window).on('popstate', function (event, data) {
4455 $('#printcss').attr('media','print');
4460 * Unbind all event handlers before tearing down a page
4462 AJAX.registerTeardown('functions.js', function () {
4463 $(document).off('click', 'a.themeselect');
4464 $(document).off('change', '.autosubmit');
4465 $('a.take_theme').off('click');
4468 AJAX.registerOnload('functions.js', function () {
4472 $(document).on('click', 'a.themeselect', function (e) {
4476 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
4482 * Automatic form submission on change.
4484 $(document).on('change', '.autosubmit', function (e) {
4485 $(this).closest('form').submit();
4491 $('a.take_theme').click(function (e) {
4492 var what = this.name;
4493 if (window.opener && window.opener.document.forms.setTheme.elements.set_theme) {
4494 window.opener.document.forms.setTheme.elements.set_theme.value = what;
4495 window.opener.document.forms.setTheme.submit();
4504 * Produce print preview
4506 function printPreview () {
4507 $('#printcss').attr('media','all');
4508 createPrintAndBackButtons();
4512 * Create print and back buttons in preview page
4514 function createPrintAndBackButtons () {
4515 var back_button = $('<input/>',{
4517 value: PMA_messages.back,
4518 id: 'back_button_print_view'
4520 back_button.click(removePrintAndBackButton);
4521 back_button.appendTo('#page_content');
4522 var print_button = $('<input/>',{
4524 value: PMA_messages.print,
4525 id: 'print_button_print_view'
4527 print_button.click(printPage);
4528 print_button.appendTo('#page_content');
4532 * Remove print and back buttons and revert to normal view
4534 function removePrintAndBackButton () {
4535 $('#printcss').attr('media','print');
4536 $('#back_button_print_view').remove();
4537 $('#print_button_print_view').remove();
4543 function printPage () {
4544 if (typeof(window.print) !== 'undefined') {
4550 * Unbind all event handlers before tearing down a page
4552 AJAX.registerTeardown('functions.js', function () {
4553 $('input#print').off('click');
4554 $(document).off('click', 'a.create_view.ajax');
4555 $(document).off('keydown', '#createViewDialog input, #createViewDialog select');
4556 $(document).off('change', '#fkc_checkbox');
4559 AJAX.registerOnload('functions.js', function () {
4560 $('input#print').click(printPage);
4561 $('.logout').click(function () {
4563 '<form method="POST" action="' + $(this).attr('href') + '" class="disableAjax">' +
4564 '<input type="hidden" name="token" value="' + escapeHtml(PMA_commonParams.get('token')) + '"/>' +
4567 $('body').append(form);
4572 * Ajaxification for the "Create View" action
4574 $(document).on('click', 'a.create_view.ajax', function (e) {
4576 PMA_createViewDialog($(this));
4579 * Attach Ajax event handlers for input fields in the editor
4580 * and used to submit the Ajax request when the ENTER key is pressed.
4582 if ($('#createViewDialog').length !== 0) {
4583 $(document).on('keydown', '#createViewDialog input, #createViewDialog select', function (e) {
4584 if (e.which === 13) { // 13 is the ENTER key
4587 // with preventing default, selection by <select> tag
4588 // was also prevented in IE
4591 $(this).closest('.ui-dialog').find('.ui-button:first').click();
4593 }); // end $(document).on()
4596 if ($('textarea[name="view[as]"]').length !== 0) {
4597 codemirror_editor = PMA_getSQLEditor($('textarea[name="view[as]"]'));
4601 function PMA_createViewDialog ($this) {
4602 var $msg = PMA_ajaxShowMessage();
4603 var sep = PMA_commonParams.get('arg_separator');
4604 var params = getJSConfirmCommonParam(this, $this.getPostData());
4605 params += sep + 'ajax_dialog=1';
4606 $.post($this.attr('href'), params, function (data) {
4607 if (typeof data !== 'undefined' && data.success === true) {
4608 PMA_ajaxRemoveMessage($msg);
4609 var buttonOptions = {};
4610 buttonOptions[PMA_messages.strGo] = function () {
4611 if (typeof CodeMirror !== 'undefined') {
4612 codemirror_editor.save();
4614 $msg = PMA_ajaxShowMessage();
4615 $.post('view_create.php', $('#createViewDialog').find('form').serialize(), function (data) {
4616 PMA_ajaxRemoveMessage($msg);
4617 if (typeof data !== 'undefined' && data.success === true) {
4618 $('#createViewDialog').dialog('close');
4619 $('.result_query').html(data.message);
4620 PMA_reloadNavigation();
4622 PMA_ajaxShowMessage(data.error);
4626 buttonOptions[PMA_messages.strClose] = function () {
4627 $(this).dialog('close');
4629 var $dialog = $('<div/>').attr('id', 'createViewDialog').append(data.message).dialog({
4633 buttons: buttonOptions,
4634 title: PMA_messages.strCreateView,
4635 close: function () {
4639 // Attach syntax highlighted editor
4640 codemirror_editor = PMA_getSQLEditor($dialog.find('textarea'));
4641 $('input:visible[type=text]', $dialog).first().focus();
4643 PMA_ajaxShowMessage(data.error);
4649 * Makes the breadcrumbs and the menu bar float at the top of the viewport
4652 if ($('#floating_menubar').length && $('#PMA_disable_floating_menubar').length === 0) {
4653 var left = $('html').attr('dir') === 'ltr' ? 'left' : 'right';
4654 $('#floating_menubar')
4655 .css('margin-' + left, $('#pma_navigation').width() + $('#pma_navigation_resizer').width())
4658 'position': 'fixed',
4663 .append($('#serverinfo'))
4664 .append($('#topmenucontainer'));
4665 // Allow the DOM to render, then adjust the padding on the body
4666 setTimeout(function () {
4669 $('#floating_menubar').outerHeight(true)
4671 $('#topmenu').menuResizer('resize');
4677 * Scrolls the page to the top if clicking the serverinfo bar
4680 $(document).on('click', '#serverinfo, #goto_pagetop', function (event) {
4681 event.preventDefault();
4682 $('html, body').animate({ scrollTop: 0 }, 'fast');
4686 var checkboxes_sel = 'input.checkall:checkbox:enabled';
4688 * Watches checkboxes in a form to set the checkall box accordingly
4690 var checkboxes_changed = function () {
4691 var $form = $(this.form);
4692 // total number of checkboxes in current form
4693 var total_boxes = $form.find(checkboxes_sel).length;
4694 // number of checkboxes checked in current form
4695 var checked_boxes = $form.find(checkboxes_sel + ':checked').length;
4696 var $checkall = $form.find('input.checkall_box');
4697 if (total_boxes === checked_boxes) {
4698 $checkall.prop({ checked: true, indeterminate: false });
4699 } else if (checked_boxes > 0) {
4700 $checkall.prop({ checked: true, indeterminate: true });
4702 $checkall.prop({ checked: false, indeterminate: false });
4705 $(document).on('change', checkboxes_sel, checkboxes_changed);
4707 $(document).on('change', 'input.checkall_box', function () {
4708 var is_checked = $(this).is(':checked');
4709 $(this.form).find(checkboxes_sel).not('.row-hidden').prop('checked', is_checked)
4710 .parents('tr').toggleClass('marked', is_checked);
4713 $(document).on('click', '.checkall-filter', function () {
4714 var $this = $(this);
4715 var selector = $this.data('checkall-selector');
4716 $('input.checkall_box').prop('checked', false);
4717 $this.parents('form').find(checkboxes_sel).filter(selector).prop('checked', true).trigger('change')
4718 .parents('tr').toggleClass('marked', true);
4723 * Watches checkboxes in a sub form to set the sub checkall box accordingly
4725 var sub_checkboxes_changed = function () {
4726 var $form = $(this).parent().parent();
4727 // total number of checkboxes in current sub form
4728 var total_boxes = $form.find(checkboxes_sel).length;
4729 // number of checkboxes checked in current sub form
4730 var checked_boxes = $form.find(checkboxes_sel + ':checked').length;
4731 var $checkall = $form.find('input.sub_checkall_box');
4732 if (total_boxes === checked_boxes) {
4733 $checkall.prop({ checked: true, indeterminate: false });
4734 } else if (checked_boxes > 0) {
4735 $checkall.prop({ checked: true, indeterminate: true });
4737 $checkall.prop({ checked: false, indeterminate: false });
4740 $(document).on('change', checkboxes_sel + ', input.checkall_box:checkbox:enabled', sub_checkboxes_changed);
4742 $(document).on('change', 'input.sub_checkall_box', function () {
4743 var is_checked = $(this).is(':checked');
4744 var $form = $(this).parent().parent();
4745 $form.find(checkboxes_sel).prop('checked', is_checked)
4746 .parents('tr').toggleClass('marked', is_checked);
4752 * - rows to filter are identified by data-filter-row attribute
4753 * which contains uppercase string to filter
4754 * - it is simple substring case insensitive search
4755 * - optionally number of matching rows is written to element with
4756 * id filter-rows-count
4758 $(document).on('keyup', '#filterText', function () {
4759 var filterInput = $(this).val().toUpperCase();
4761 $('[data-filter-row]').each(function () {
4763 /* Can not use data() here as it does magic conversion to int for numeric values */
4764 if ($row.attr('data-filter-row').indexOf(filterInput) > -1) {
4767 $row.find('input.checkall').removeClass('row-hidden');
4770 $row.find('input.checkall').addClass('row-hidden').prop('checked', false);
4771 $row.removeClass('marked');
4774 setTimeout(function () {
4775 $(checkboxes_sel).trigger('change');
4777 $('#filter-rows-count').html(count);
4779 AJAX.registerOnload('functions.js', function () {
4780 /* Trigger filtering of the list based on incoming database name */
4781 var $filter = $('#filterText');
4782 if ($filter.val()) {
4783 $filter.trigger('keyup').select();
4788 * Formats a byte number to human-readable form
4790 * @param bytes the bytes to format
4791 * @param optional subdecimals the number of digits after the point
4792 * @param optional pointchar the char to use as decimal point
4794 function formatBytes (bytes, subdecimals, pointchar) {
4801 var units = ['B', 'KiB', 'MiB', 'GiB'];
4802 for (var i = 0; bytes > 1024 && i < units.length; i++) {
4805 var factor = Math.pow(10, subdecimals);
4806 bytes = Math.round(bytes * factor) / factor;
4807 bytes = bytes.toString().split('.').join(pointchar);
4808 return bytes + ' ' + units[i];
4811 AJAX.registerOnload('functions.js', function () {
4813 * Reveal the login form to users with JS enabled
4814 * and focus the appropriate input field
4816 var $loginform = $('#loginform');
4817 if ($loginform.length) {
4818 $loginform.find('.js-show').show();
4819 if ($('#input_username').val()) {
4820 $('#input_password').trigger('focus');
4822 $('#input_username').trigger('focus');
4825 var $https_warning = $('#js-https-mismatch');
4826 if ($https_warning.length) {
4827 if ((window.location.protocol === 'https:') !== PMA_commonParams.get('is_https')) {
4828 $https_warning.show();
4834 * Formats timestamp for display
4836 function PMA_formatDateTime (date, seconds) {
4837 var result = $.datepicker.formatDate('yy-mm-dd', date);
4838 var timefmt = 'HH:mm';
4840 timefmt = 'HH:mm:ss';
4842 return result + ' ' + $.datepicker.formatTime(
4844 hour: date.getHours(),
4845 minute: date.getMinutes(),
4846 second: date.getSeconds()
4852 * Check than forms have less fields than max allowed by PHP.
4854 function checkNumberOfFields () {
4855 if (typeof maxInputVars === 'undefined') {
4858 if (false === maxInputVars) {
4861 $('form').each(function () {
4862 var nbInputs = $(this).find(':input').length;
4863 if (nbInputs > maxInputVars) {
4864 var warning = PMA_sprintf(PMA_messages.strTooManyInputs, maxInputVars);
4865 PMA_ajaxShowMessage(warning);
4875 * Ignore the displayed php errors.
4876 * Simply removes the displayed errors.
4878 * @param clearPrevErrors whether to clear errors stored
4879 * in $_SESSION['prev_errors'] at server
4882 function PMA_ignorePhpErrors (clearPrevErrors) {
4883 if (typeof(clearPrevErrors) === 'undefined' ||
4884 clearPrevErrors === null
4888 // send AJAX request to error_report.php with send_error_report=0, exception_type=php & token.
4889 // It clears the prev_errors stored in session.
4890 if (clearPrevErrors) {
4891 var $pmaReportErrorsForm = $('#pma_report_errors_form');
4892 $pmaReportErrorsForm.find('input[name="send_error_report"]').val(0); // change send_error_report to '0'
4893 $pmaReportErrorsForm.submit();
4896 // remove displayed errors
4897 var $pmaErrors = $('#pma_errors');
4898 $pmaErrors.fadeOut('slow');
4899 $pmaErrors.remove();
4903 * Toggle the Datetimepicker UI if the date value entered
4904 * by the user in the 'text box' is not going to be accepted
4905 * by the Datetimepicker plugin (but is accepted by MySQL)
4907 function toggleDatepickerIfInvalid ($td, $input_field) {
4908 // Regex allowed by the Datetimepicker UI
4909 var dtexpDate = new RegExp(['^([0-9]{4})',
4910 '-(((01|03|05|07|08|10|12)-((0[1-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)',
4911 '-((0[1-9])|([1-2][0-9])|30)))$'].join(''));
4912 var dtexpTime = new RegExp(['^(([0-1][0-9])|(2[0-3]))',
4913 ':((0[0-9])|([1-5][0-9]))',
4914 ':((0[0-9])|([1-5][0-9]))(\.[0-9]{1,6}){0,1}$'].join(''));
4916 // If key-ed in Time or Date values are unsupported by the UI, close it
4917 if ($td.attr('data-type') === 'date' && ! dtexpDate.test($input_field.val())) {
4918 $input_field.datepicker('hide');
4919 } else if ($td.attr('data-type') === 'time' && ! dtexpTime.test($input_field.val())) {
4920 $input_field.datepicker('hide');
4922 $input_field.datepicker('show');
4927 * Function to submit the login form after validation is done.
4929 function recaptchaCallback () {
4930 $('#login_form').submit();
4934 * Unbind all event handlers before tearing down a page
4936 AJAX.registerTeardown('functions.js', function () {
4937 $(document).off('keydown', 'form input, form textarea, form select');
4940 AJAX.registerOnload('functions.js', function () {
4942 * Handle 'Ctrl/Alt + Enter' form submits
4944 $('form input, form textarea, form select').on('keydown', function (e) {
4945 if ((e.ctrlKey && e.which === 13) || (e.altKey && e.which === 13)) {
4946 $form = $(this).closest('form');
4948 // There could be multiple submit buttons on the same form,
4949 // we assume all of them behave identical and just click one.
4950 if (! $form.find('input[type="submit"]:first') ||
4951 ! $form.find('input[type="submit"]:first').trigger('click')
4960 * Unbind all event handlers before tearing down a page
4962 AJAX.registerTeardown('functions.js', function () {
4963 $(document).off('change', 'input[type=radio][name="pw_hash"]');
4964 $(document).off('mouseover', '.sortlink');
4965 $(document).off('mouseout', '.sortlink');
4968 AJAX.registerOnload('functions.js', function () {
4970 * Display warning regarding SSL when sha256_password
4971 * method is selected
4972 * Used in user_password.php (Change Password link on index.php)
4974 $(document).on('change', 'select#select_authentication_plugin_cp', function () {
4975 if (this.value === 'sha256_password') {
4976 $('#ssl_reqd_warning_cp').show();
4978 $('#ssl_reqd_warning_cp').hide();
4982 Cookies.defaults.path = PMA_commonParams.get('rootPath');
4984 // Bind event handlers for toggling sort icons
4985 $(document).on('mouseover', '.sortlink', function () {
4986 $(this).find('.soimg').toggle();
4988 $(document).on('mouseout', '.sortlink', function () {
4989 $(this).find('.soimg').toggle();
4994 * Returns an HTML IMG tag for a particular image from a theme,
4995 * which may be an actual file or an icon from a sprite
4997 * @param string image The name of the file to get
4998 * @param string alternate Used to set 'alt' and 'title' attributes of the image
4999 * @param object attributes An associative array of other attributes
5001 * @return Object The requested image, this object has two methods:
5002 * .toString() - Returns the IMG tag for the requested image
5003 * .attr(name) - Returns a particular attribute of the IMG
5004 * tag given it's name
5005 * .attr(name, value) - Sets a particular attribute of the IMG
5006 * tag to the given value
5008 function PMA_getImage (image, alternate, attributes) {
5009 // custom image object, it will eventually be returned by this functions
5015 src: 'themes/dot.gif',
5017 attr: function (name, value) {
5018 if (value == undefined) {
5019 if (this.data[name] == undefined) {
5022 return this.data[name];
5025 this.data[name] = value;
5028 toString: function () {
5029 var retval = '<' + 'img';
5030 for (var i in this.data) {
5031 retval += ' ' + i + '="' + this.data[i] + '"';
5033 retval += ' /' + '>';
5037 // initialise missing parameters
5038 if (attributes == undefined) {
5041 if (alternate == undefined) {
5045 if (attributes.alt != undefined) {
5046 retval.attr('alt', escapeHtml(attributes.alt));
5048 retval.attr('alt', escapeHtml(alternate));
5051 if (attributes.title != undefined) {
5052 retval.attr('title', escapeHtml(attributes.title));
5054 retval.attr('title', escapeHtml(alternate));
5057 retval.attr('class', 'icon ic_' + image);
5058 // set all other attrubutes
5059 for (var i in attributes) {
5061 // do not allow to override the 'src' attribute
5065 retval.attr(i, attributes[i]);
5072 * Sets a configuration value.
5074 * A configuration value may be set in both browser's local storage and
5075 * remotely in server's configuration table.
5077 * If the `only_local` argument is `true`, the value is store is stored only in
5078 * browser's local storage and may be lost if the user resets his browser's
5081 * NOTE: Depending on server's configuration, the configuration table may be or
5084 * @param {string} key Configuration key.
5085 * @param {object} value Configuration value.
5086 * @param {boolean} only_local Configuration type.
5088 function configSet (key, value, only_local) {
5089 only_local = (typeof only_local !== 'undefined') ? only_local : false;
5090 var serialized = JSON.stringify(value);
5091 localStorage.setItem(key, serialized);
5099 server: PMA_commonParams.get('server'),
5102 success: function (data) {
5103 // Updating value in local storage.
5104 if (! data.success) {
5106 PMA_ajaxShowMessage(data.error);
5108 PMA_ajaxShowMessage(data.message);
5111 // Eventually, call callback.
5117 * Gets a configuration value. A configuration value will be searched in
5118 * browser's local storage first and if not found, a call to the server will be
5121 * If value should not be cached and the up-to-date configuration value from
5122 * right from the server is required, the third parameter should be `false`.
5124 * @param {string} key Configuration key.
5125 * @param {boolean} cached Configuration type.
5127 * @return {object} Configuration value.
5129 function configGet (key, cached) {
5130 cached = (typeof cached !== 'undefined') ? cached : true;
5131 var value = localStorage.getItem(key);
5132 if (cached && value !== undefined && value !== null) {
5133 return JSON.parse(value);
5136 // Result not found in local storage or ignored.
5137 // Hitting the server.
5139 // TODO: This is ugly, but usually when a configuration is needed,
5140 // processing cannot continue until that value is found.
5141 // Another solution is to provide a callback as a parameter.
5148 server: PMA_commonParams.get('server'),
5151 success: function (data) {
5152 // Updating value in local storage.
5154 localStorage.setItem(key, JSON.stringify(data.value));
5156 PMA_ajaxShowMessage(data.message);
5158 // Eventually, call callback.
5161 return JSON.parse(localStorage.getItem(key));
5165 * Return POST data as stored by Util::linkOrButton
5167 jQuery.fn.getPostData = function () {
5168 var dataPost = this.attr('data-post');
5169 // Strip possible leading ?
5170 if (dataPost !== undefined && dataPost.substring(0,1) == '?') {
5171 dataPost = dataPost.substr(1);