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;
85 } else if (typeof options.data == "object") {
86 options.data = $.extend(originalOptions.data, {'_nocache' : nocache});
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)
97 var showTimepicker = true;
99 showTimepicker = false;
102 var defaultOptions = {
104 buttonImage: themeCalendarImage, // defined in js/messages.php
105 buttonImageOnly: true,
111 showTimepicker: showTimepicker,
112 showButtonPanel: false,
113 dateFormat: 'yy-mm-dd', // yy means year with four digits
114 timeFormat: 'HH:mm:ss.lc',
115 constrainInput: false,
116 altFieldTimeOnly: false,
118 beforeShow: function (input, inst) {
119 // Remember that we came from the datepicker; this is used
120 // in tbl_change.js by verificationsAfterFieldChange()
121 $this_element.data('comes_from', 'datepicker');
122 if ($(input).closest('.cEdit').length > 0) {
123 setTimeout(function () {
131 // Fix wrong timepicker z-index, doesn't work without timeout
132 setTimeout(function () {
133 $('#ui-timepicker-div').css('z-index', $('#ui-datepicker-div').css('z-index'));
136 onSelect: function() {
137 $this_element.data('datepicker').inline = true;
139 onClose: function (dateText, dp_inst) {
140 // The value is no more from the date picker
141 $this_element.data('comes_from', '');
142 if (typeof $this_element.data('datepicker') !== 'undefined') {
143 $this_element.data('datepicker').inline = false;
147 if (type == "datetime" || type == "timestamp") {
148 $this_element.datetimepicker($.extend(defaultOptions, options));
150 else if (type == "date") {
151 $this_element.datetimepicker($.extend(defaultOptions, options));
153 else if (type == "time") {
154 $this_element.timepicker($.extend(defaultOptions, options));
155 // Add a tip regarding entering MySQL allowed-values for TIME data-type
156 PMA_tooltip($this_element, 'input', PMA_messages.strMysqlAllowedValuesTipTime);
161 * Add a date/time picker to each element that needs it
162 * (only when jquery-ui-timepicker-addon.js is loaded)
164 function addDateTimePicker() {
165 if ($.timepicker !== undefined) {
166 $('input.timefield, input.datefield, input.datetimefield').each(function () {
168 var decimals = $(this).parent().attr('data-decimals');
169 var type = $(this).parent().attr('data-type');
171 var showMillisec = false;
172 var showMicrosec = false;
173 var timeFormat = 'HH:mm:ss';
174 // check for decimal places of seconds
175 if (decimals > 0 && type.indexOf('time') != -1){
179 timeFormat = 'HH:mm:ss.lc';
182 timeFormat = 'HH:mm:ss.l';
185 PMA_addDatepicker($(this), type, {
186 showMillisec: showMillisec,
187 showMicrosec: showMicrosec,
188 timeFormat: timeFormat
191 // Add a tip regarding entering MySQL allowed-values
192 // for TIME and DATE data-type
193 if ($(this).hasClass('timefield')) {
194 PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipTime);
195 } else if ($(this).hasClass('datefield')) {
196 PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipDate);
203 * Handle redirect and reload flags sent as part of AJAX requests
205 * @param data ajax response data
207 function PMA_handleRedirectAndReload(data) {
208 if (parseInt(data.redirect_flag) == 1) {
209 // add one more GET param to display session expiry msg
210 if (window.location.href.indexOf('?') === -1) {
211 window.location.href += '?session_expired=1';
213 window.location.href += '&session_expired=1';
215 window.location.reload();
216 } else if (parseInt(data.reload_flag) == 1) {
217 // remove the token param and reload
218 window.location.href = window.location.href.replace(/&?token=[^&#]*/g, "");
219 window.location.reload();
224 * Creates an SQL editor which supports auto completing etc.
226 * @param $textarea jQuery object wrapping the textarea to be made the editor
227 * @param options optional options for CodeMirror
228 * @param resize optional resizing ('vertical', 'horizontal', 'both')
229 * @param lintOptions additional options for lint
231 function PMA_getSQLEditor($textarea, options, resize, lintOptions) {
232 if ($textarea.length > 0 && typeof CodeMirror !== 'undefined') {
234 // merge options for CodeMirror
238 extraKeys: {"Ctrl-Space": "autocomplete"},
239 hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
241 mode: "text/x-mysql",
245 if (CodeMirror.sqlLint) {
247 gutters: ["CodeMirror-lint-markers"],
249 "getAnnotations": CodeMirror.sqlLint,
251 "lintOptions": lintOptions
256 $.extend(true, defaults, options);
258 // create CodeMirror editor
259 var codemirrorEditor = CodeMirror.fromTextArea($textarea[0], defaults);
265 if (resize == 'vertical') {
268 if (resize == 'both') {
271 if (resize == 'horizontal') {
274 $(codemirrorEditor.getWrapperElement())
275 .css('resize', resize)
279 codemirrorEditor.setSize($(this).width(), $(this).height());
282 // enable autocomplete
283 codemirrorEditor.on("inputRead", codemirrorAutocompleteOnInputRead);
285 return codemirrorEditor;
291 * Clear text selection
293 function PMA_clearSelection() {
294 if (document.selection && document.selection.empty) {
295 document.selection.empty();
296 } else if (window.getSelection) {
297 var sel = window.getSelection();
301 if (sel.removeAllRanges) {
302 sel.removeAllRanges();
308 * Create a jQuery UI tooltip
310 * @param $elements jQuery object representing the elements
311 * @param item the item
312 * (see https://api.jqueryui.com/tooltip/#option-items)
313 * @param myContent content of the tooltip
314 * @param additionalOptions to override the default options
317 function PMA_tooltip($elements, item, myContent, additionalOptions)
319 if ($('#no_hint').length > 0) {
323 var defaultOptions = {
326 tooltipClass: "tooltip",
332 $elements.tooltip($.extend(true, defaultOptions, additionalOptions));
339 function escapeHtml(unsafe) {
340 if (typeof(unsafe) != 'undefined') {
343 .replace(/&/g, "&")
344 .replace(/</g, "<")
345 .replace(/>/g, ">")
346 .replace(/"/g, """)
347 .replace(/'/g, "'");
353 function escapeJsString(unsafe) {
354 if (typeof(unsafe) != 'undefined') {
358 .replace('\\', '\\\\')
359 .replace('\'', '\\\'')
360 .replace("'", "\\\'")
362 .replace(""", "\"")
365 .replace(/<\/script/gi, '</\' + \'script')
371 function PMA_sprintf() {
372 return sprintf.apply(this, arguments);
376 * Hides/shows the default value input field, depending on the default type
377 * Ticks the NULL checkbox if NULL is chosen as default value.
379 function PMA_hideShowDefaultValue($default_type)
381 if ($default_type.val() == 'USER_DEFINED') {
382 $default_type.siblings('.default_value').show().focus();
384 $default_type.siblings('.default_value').hide();
385 if ($default_type.val() == 'NULL') {
386 var $null_checkbox = $default_type.closest('tr').find('.allow_null');
387 $null_checkbox.prop('checked', true);
393 * Hides/shows the input field for column expression based on whether
394 * VIRTUAL/PERSISTENT is selected
396 * @param $virtuality virtuality dropdown
398 function PMA_hideShowExpression($virtuality)
400 if ($virtuality.val() === '') {
401 $virtuality.siblings('.expression').hide();
403 $virtuality.siblings('.expression').show();
408 * Show notices for ENUM columns; add/hide the default value
411 function PMA_verifyColumnsProperties()
413 $("select.column_type").each(function () {
414 PMA_showNoticeForEnum($(this));
416 $("select.default_type").each(function () {
417 PMA_hideShowDefaultValue($(this));
419 $('select.virtuality').each(function () {
420 PMA_hideShowExpression($(this));
425 * Add a hidden field to the form to indicate that this will be an
426 * Ajax request (only if this hidden field does not exist)
428 * @param $form object the form
430 function PMA_prepareForAjaxRequest($form)
432 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
433 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
438 * Generate a new password and copy it to the password input areas
440 * @param passwd_form object the form that holds the password fields
442 * @return boolean always true
444 function suggestPassword(passwd_form)
446 // restrict the password to just letters and numbers to avoid problems:
447 // "editors and viewers regard the password as multiple words and
448 // things like double click no longer work"
449 var pwchars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ";
450 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
451 var passwd = passwd_form.generated_pw;
452 var randomWords = new Int32Array(passwordlength);
456 // First we're going to try to use a built-in CSPRNG
457 if (window.crypto && window.crypto.getRandomValues) {
458 window.crypto.getRandomValues(randomWords);
460 // Because of course IE calls it msCrypto instead of being standard
461 else if (window.msCrypto && window.msCrypto.getRandomValues) {
462 window.msCrypto.getRandomValues(randomWords);
464 // Fallback to Math.random
465 for (var i = 0; i < passwordlength; i++) {
466 randomWords[i] = Math.floor(Math.random() * pwchars.length);
470 for (var i = 0; i < passwordlength; i++) {
471 passwd.value += pwchars.charAt(Math.abs(randomWords[i]) % pwchars.length);
474 $jquery_passwd_form = $(passwd_form);
476 passwd_form.elements['pma_pw'].value = passwd.value;
477 passwd_form.elements['pma_pw2'].value = passwd.value;
478 meter_obj = $jquery_passwd_form.find('meter[name="pw_meter"]').first();
479 meter_obj_label = $jquery_passwd_form.find('span[name="pw_strength"]').first();
480 checkPasswordStrength(passwd.value, meter_obj, meter_obj_label);
485 * Version string to integer conversion.
487 function parseVersionString(str)
489 if (typeof(str) != 'string') { return false; }
491 // Parse possible alpha/beta/rc/
492 var state = str.split('-');
493 if (state.length >= 2) {
494 if (state[1].substr(0, 2) == 'rc') {
495 add = - 20 - parseInt(state[1].substr(2), 10);
496 } else if (state[1].substr(0, 4) == 'beta') {
497 add = - 40 - parseInt(state[1].substr(4), 10);
498 } else if (state[1].substr(0, 5) == 'alpha') {
499 add = - 60 - parseInt(state[1].substr(5), 10);
500 } else if (state[1].substr(0, 3) == 'dev') {
501 /* We don't handle dev, it's git snapshot */
506 var x = str.split('.');
507 // Use 0 for non existing parts
508 var maj = parseInt(x[0], 10) || 0;
509 var min = parseInt(x[1], 10) || 0;
510 var pat = parseInt(x[2], 10) || 0;
511 var hotfix = parseInt(x[3], 10) || 0;
512 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
516 * Indicates current available version on main page.
518 function PMA_current_version(data)
520 if (data && data.version && data.date) {
521 var current = parseVersionString($('span.version').text());
522 var latest = parseVersionString(data.version);
523 var url = 'https://web.phpmyadmin.net/files/' + escapeHtml(encodeURIComponent(data.version)) + '/';
524 var version_information_message = document.createElement('span');
525 version_information_message.className = 'latest';
526 var version_information_message_link = document.createElement('a');
527 version_information_message_link.href = url;
528 version_information_message_link.className = 'disableAjax';
529 version_information_message_link_text = document.createTextNode(data.version);
530 version_information_message_link.appendChild(version_information_message_link_text);
531 var prefix_message = document.createTextNode(PMA_messages.strLatestAvailable + ' ');
532 version_information_message.appendChild(prefix_message);
533 version_information_message.appendChild(version_information_message_link);
534 if (latest > current) {
535 var message = PMA_sprintf(
536 PMA_messages.strNewerVersion,
537 escapeHtml(data.version),
538 escapeHtml(data.date)
540 var htmlClass = 'notice';
541 if (Math.floor(latest / 10000) === Math.floor(current / 10000)) {
542 /* Security update */
545 $('#newer_version_notice').remove();
546 var maincontainer_div = document.createElement('div');
547 maincontainer_div.id = 'newer_version_notice';
548 maincontainer_div.className = htmlClass;
549 var maincontainer_div_link = document.createElement('a');
550 maincontainer_div_link.href = url;
551 maincontainer_div_link.className = 'disableAjax';
552 maincontainer_div_link_text = document.createTextNode(message);
553 maincontainer_div_link.appendChild(maincontainer_div_link_text);
554 maincontainer_div.appendChild(maincontainer_div_link);
555 $('#maincontainer').append($(maincontainer_div));
557 if (latest === current) {
558 version_information_message = document.createTextNode(' (' + PMA_messages.strUpToDate + ')');
560 /* Remove extra whitespace */
561 var version_info = $('#li_pma_version').contents().get(2);
562 version_info.textContent = $.trim(version_info.textContent);
563 var $liPmaVersion = $('#li_pma_version');
564 $liPmaVersion.find('span.latest').remove();
565 $liPmaVersion.append($(version_information_message));
570 * Loads Git revision data from ajax for index.php
572 function PMA_display_git_revision()
574 $('#is_git_revision').remove();
575 $('#li_pma_version_git').remove();
579 "server": PMA_commonParams.get('server'),
580 "token": PMA_commonParams.get('token'),
581 "git_revision": true,
582 "ajax_request": true,
586 if (typeof data !== 'undefined' && data.success === true) {
587 $(data.message).insertAfter('#li_pma_version');
594 * for libraries/display_change_password.lib.php
595 * libraries/user_password.php
599 function displayPasswordGenerateButton()
601 $('#tr_element_before_generate_password').parent().append('<tr class="vmiddle"><td>' + PMA_messages.strGeneratePassword + '</td><td><input type="button" class="button" id="button_generate_password" value="' + PMA_messages.strGenerate + '" onclick="suggestPassword(this.form)" /><input type="text" name="generated_pw" id="generated_pw" /></td></tr>');
602 $('#div_element_before_generate_password').parent().append('<div class="item"><label for="button_generate_password">' + PMA_messages.strGeneratePassword + ':</label><span class="options"><input type="button" class="button" id="button_generate_password" value="' + PMA_messages.strGenerate + '" onclick="suggestPassword(this.form)" /></span><input type="text" name="generated_pw" id="generated_pw" /></div>');
606 * selects the content of a given object, f.e. a textarea
608 * @param element object element of which the content will be selected
609 * @param lock var variable which holds the lock for this element
610 * or true, if no lock exists
611 * @param only_once boolean if true this is only done once
612 * f.e. only on first focus
614 function selectContent(element, lock, only_once)
616 if (only_once && only_once_elements[element.name]) {
620 only_once_elements[element.name] = true;
630 * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
631 * This function is called while clicking links
633 * @param theLink object the link
634 * @param theSqlQuery object the sql query to submit
636 * @return boolean whether to run the query or not
638 function confirmLink(theLink, theSqlQuery)
640 // Confirmation is not required in the configuration file
641 // or browser is Opera (crappy js implementation)
642 if (PMA_messages.strDoYouReally === '' || typeof(window.opera) != 'undefined') {
646 var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, theSqlQuery));
648 if ($(theLink).hasClass('formLinkSubmit')) {
649 var name = 'is_js_confirmed';
651 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
652 var matches = $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i);
653 if (matches != null) {
654 name = 'subform[' + matches[1] + '][is_js_confirmed]';
658 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
659 } else if (typeof(theLink.href) != 'undefined') {
660 theLink.href += '&is_js_confirmed=1';
661 } else if (typeof(theLink.form) != 'undefined') {
662 theLink.form.action += '?is_js_confirmed=1';
667 } // end of the 'confirmLink()' function
670 * Confirms a "DROP/DELETE/ALTER" query before
671 * submitting it if required.
672 * This function is called by the 'checkSqlQuery()' js function.
674 * @param theForm1 object the form
675 * @param sqlQuery1 string the sql query string
677 * @return boolean whether to run the query or not
679 * @see checkSqlQuery()
681 function confirmQuery(theForm1, sqlQuery1)
683 // Confirmation is not required in the configuration file
684 if (PMA_messages.strDoYouReally === '') {
688 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
690 // TODO: find a way (if possible) to use the parser-analyser
691 // for this kind of verification
692 // For now, I just added a ^ to check for the statement at
693 // beginning of expression
695 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|PROCEDURE)\\s', 'i');
696 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
697 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
698 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
700 if (do_confirm_re_0.test(sqlQuery1) ||
701 do_confirm_re_1.test(sqlQuery1) ||
702 do_confirm_re_2.test(sqlQuery1) ||
703 do_confirm_re_3.test(sqlQuery1)) {
705 if (sqlQuery1.length > 100) {
706 message = sqlQuery1.substr(0, 100) + '\n ...';
710 var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, message));
711 // statement is confirmed -> update the
712 // "is_js_confirmed" form field so the confirm test won't be
713 // run on the server side and allows to submit the form
715 theForm1.elements.is_js_confirmed.value = 1;
718 // statement is rejected -> do not submit the form
722 } // end if (handle confirm box result)
723 } // end if (display confirm box)
726 } // end of the 'confirmQuery()' function
729 * Displays an error message if the user submitted the sql query form with no
730 * sql query, else checks for "DROP/DELETE/ALTER" statements
732 * @param theForm object the form
734 * @return boolean always false
736 * @see confirmQuery()
738 function checkSqlQuery(theForm)
740 // get the textarea element containing the query
742 if (codemirror_editor) {
743 codemirror_editor.save();
744 sqlQuery = codemirror_editor.getValue();
746 sqlQuery = theForm.elements.sql_query.value;
748 var space_re = new RegExp('\\s+');
749 if (typeof(theForm.elements.sql_file) != 'undefined' &&
750 theForm.elements.sql_file.value.replace(space_re, '') !== '') {
753 if (typeof(theForm.elements.id_bookmark) != 'undefined' &&
754 (theForm.elements.id_bookmark.value !== null || theForm.elements.id_bookmark.value !== '') &&
755 theForm.elements.id_bookmark.selectedIndex !== 0) {
759 // Checks for "DROP/DELETE/ALTER" statements
760 if (sqlQuery.replace(space_re, '') !== '') {
761 result = confirmQuery(theForm, sqlQuery);
763 alert(PMA_messages.strFormEmpty);
766 if (codemirror_editor) {
767 codemirror_editor.focus();
768 } else if (codemirror_inline_editor) {
769 codemirror_inline_editor.focus();
772 } // end of the 'checkSqlQuery()' function
775 * Check if a form's element is empty.
776 * An element containing only spaces is also considered empty
778 * @param object the form
779 * @param string the name of the form field to put the focus on
781 * @return boolean whether the form field is empty or not
783 function emptyCheckTheField(theForm, theFieldName)
785 var theField = theForm.elements[theFieldName];
786 var space_re = new RegExp('\\s+');
787 return theField.value.replace(space_re, '') === '';
788 } // end of the 'emptyCheckTheField()' function
791 * Ensures a value submitted in a form is numeric and is in a range
793 * @param object the form
794 * @param string the name of the form field to check
795 * @param integer the minimum authorized value
796 * @param integer the maximum authorized value
798 * @return boolean whether a valid number has been submitted or not
800 function checkFormElementInRange(theForm, theFieldName, message, min, max)
802 var theField = theForm.elements[theFieldName];
803 var val = parseInt(theField.value, 10);
805 if (typeof(min) == 'undefined') {
808 if (typeof(max) == 'undefined') {
809 max = Number.MAX_VALUE;
815 alert(PMA_messages.strEnterValidNumber);
819 // It's a number but it is not between min and max
820 else if (val < min || val > max) {
822 alert(PMA_sprintf(message, val));
826 // It's a valid number
828 theField.value = val;
832 } // end of the 'checkFormElementInRange()' function
835 function checkTableEditForm(theForm, fieldsCnt)
837 // TODO: avoid sending a message if user just wants to add a line
838 // on the form but has not completed at least one field name
840 var atLeastOneField = 0;
841 var i, elm, elm2, elm3, val, id;
843 for (i = 0; i < fieldsCnt; i++) {
844 id = "#field_" + i + "_2";
847 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
848 elm2 = $("#field_" + i + "_3");
849 val = parseInt(elm2.val(), 10);
850 elm3 = $("#field_" + i + "_1");
851 if (isNaN(val) && elm3.val() !== "") {
853 alert(PMA_messages.strEnterValidLength);
859 if (atLeastOneField === 0) {
860 id = "field_" + i + "_1";
861 if (!emptyCheckTheField(theForm, id)) {
866 if (atLeastOneField === 0) {
867 var theField = theForm.elements.field_0_1;
868 alert(PMA_messages.strFormEmpty);
873 // at least this section is under jQuery
874 var $input = $("input.textfield[name='table']");
875 if ($input.val() === "") {
876 alert(PMA_messages.strFormEmpty);
882 } // enf of the 'checkTableEditForm()' function
885 * True if last click is to check a row.
887 var last_click_checked = false;
890 * Zero-based index of last clicked row.
891 * Used to handle the shift + click event in the code above.
893 var last_clicked_row = -1;
896 * Zero-based index of last shift clicked row.
898 var last_shift_clicked_row = -1;
900 var _idleSecondsCounter = 0;
903 AJAX.registerTeardown('functions.js', function () {
904 clearTimeout(updateTimeout);
905 clearInterval(IncInterval);
906 $(document).off('mousemove');
909 AJAX.registerOnload('functions.js', function () {
910 document.onclick = function() {
911 _idleSecondsCounter = 0;
913 $(document).on('mousemove',function() {
914 _idleSecondsCounter = 0;
916 document.onkeypress = function() {
917 _idleSecondsCounter = 0;
921 return Math.floor((1 + Math.random()) * 0x10000)
925 return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
926 s4() + '-' + s4() + s4() + s4();
929 function SetIdleTime() {
930 _idleSecondsCounter++;
932 function UpdateIdleTime() {
933 var href = 'index.php';
934 var guid = 'default';
935 if (isStorageSupported('sessionStorage')) {
936 guid = window.sessionStorage.guid;
939 'ajax_request' : true,
940 'token' : PMA_commonParams.get('token'),
941 'server' : PMA_commonParams.get('server'),
942 'db' : PMA_commonParams.get('db'),
944 'access_time':_idleSecondsCounter
950 success: function (data) {
952 if (PMA_commonParams.get('LoginCookieValidity') - _idleSecondsCounter < 0) {
953 /* There is other active window, let's reset counter */
954 _idleSecondsCounter = 0;
956 var remaining = Math.min(
957 /* Remaining login validity */
958 PMA_commonParams.get('LoginCookieValidity') - _idleSecondsCounter,
959 /* Remaining time till session GC */
960 PMA_commonParams.get('session_gc_maxlifetime')
964 // max value for setInterval() function
965 interval = Math.min((remaining - 1) * 1000, Math.pow(2, 31) - 1);
967 updateTimeout = window.setTimeout(UpdateIdleTime, interval);
968 } else { //timeout occurred
969 clearInterval(IncInterval);
970 if (isStorageSupported('sessionStorage')){
971 window.sessionStorage.clear();
973 window.location.reload(true);
978 if (PMA_commonParams.get('logged_in')) {
979 IncInterval = window.setInterval(SetIdleTime, 1000);
980 var session_timeout = Math.min(
981 PMA_commonParams.get('LoginCookieValidity'),
982 PMA_commonParams.get('session_gc_maxlifetime')
984 if (isStorageSupported('sessionStorage')) {
985 window.sessionStorage.setItem('guid', guid());
987 var interval = (session_timeout - 5) * 1000;
988 if (interval > Math.pow(2, 31) - 1) { // max value for setInterval() function
989 interval = Math.pow(2, 31) - 1;
991 updateTimeout = window.setTimeout(UpdateIdleTime, interval);
995 * Unbind all event handlers before tearing down a page
997 AJAX.registerTeardown('functions.js', function () {
998 $(document).off('click', 'input:checkbox.checkall');
1000 AJAX.registerOnload('functions.js', function () {
1002 * Row marking in horizontal mode (use "on" so that it works also for
1003 * next pages reached via AJAX); a tr may have the class noclick to remove
1007 $(document).on('click', 'input:checkbox.checkall', function (e) {
1009 var $tr = $this.closest('tr');
1010 var $table = $this.closest('table');
1012 if (!e.shiftKey || last_clicked_row == -1) {
1015 var $checkbox = $tr.find(':checkbox.checkall');
1016 var checked = $this.prop('checked');
1017 $checkbox.prop('checked', checked).trigger('change');
1019 $tr.addClass('marked');
1021 $tr.removeClass('marked');
1023 last_click_checked = checked;
1025 // remember the last clicked row
1026 last_clicked_row = last_click_checked ? $table.find('tr:not(.noclick)').index($tr) : -1;
1027 last_shift_clicked_row = -1;
1029 // handle the shift click
1030 PMA_clearSelection();
1033 // clear last shift click result
1034 if (last_shift_clicked_row >= 0) {
1035 if (last_shift_clicked_row >= last_clicked_row) {
1036 start = last_clicked_row;
1037 end = last_shift_clicked_row;
1039 start = last_shift_clicked_row;
1040 end = last_clicked_row;
1042 $tr.parent().find('tr:not(.noclick)')
1043 .slice(start, end + 1)
1044 .removeClass('marked')
1046 .prop('checked', false)
1050 // handle new shift click
1051 var curr_row = $table.find('tr:not(.noclick)').index($tr);
1052 if (curr_row >= last_clicked_row) {
1053 start = last_clicked_row;
1057 end = last_clicked_row;
1059 $tr.parent().find('tr:not(.noclick)')
1060 .slice(start, end + 1)
1063 .prop('checked', true)
1066 // remember the last shift clicked row
1067 last_shift_clicked_row = curr_row;
1071 addDateTimePicker();
1074 * Add attribute to text boxes for iOS devices (based on bugID: 3508912)
1076 if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) {
1077 $('input[type=text]').attr('autocapitalize', 'off').attr('autocorrect', 'off');
1082 * Row highlighting in horizontal mode (use "on"
1083 * so that it works also for pages reached via AJAX)
1085 /*AJAX.registerOnload('functions.js', function () {
1086 $(document).on('hover', 'tr',function (event) {
1088 $tr.toggleClass('hover',event.type=='mouseover');
1089 $tr.children().toggleClass('hover',event.type=='mouseover');
1094 * marks all rows and selects its first checkbox inside the given element
1095 * the given element is usually a table or a div containing the table or tables
1097 * @param container DOM element
1099 function markAllRows(container_id)
1102 $("#" + container_id).find("input:checkbox:enabled").prop('checked', true)
1104 .parents("tr").addClass("marked");
1109 * marks all rows and selects its first checkbox inside the given element
1110 * the given element is usually a table or a div containing the table or tables
1112 * @param container DOM element
1114 function unMarkAllRows(container_id)
1117 $("#" + container_id).find("input:checkbox:enabled").prop('checked', false)
1119 .parents("tr").removeClass("marked");
1124 * Checks/unchecks all options of a <select> element
1126 * @param string the form name
1127 * @param string the element name
1128 * @param boolean whether to check or to uncheck options
1130 * @return boolean always true
1132 function setSelectOptions(the_form, the_select, do_check)
1134 $("form[name='" + the_form + "'] select[name='" + the_select + "']").find("option").prop('selected', do_check);
1136 } // end of the 'setSelectOptions()' function
1139 * Sets current value for query box.
1141 function setQuery(query)
1143 if (codemirror_editor) {
1144 codemirror_editor.setValue(query);
1145 codemirror_editor.focus();
1147 document.sqlform.sql_query.value = query;
1148 document.sqlform.sql_query.focus();
1153 * Handles 'Simulate query' button on SQL query box.
1157 function PMA_handleSimulateQueryButton()
1159 var update_re = new RegExp('^\\s*UPDATE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+SET\\s', 'i');
1160 var delete_re = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
1163 if (codemirror_editor) {
1164 query = codemirror_editor.getValue();
1166 query = $('#sqlquery').val();
1169 var $simulateDml = $('#simulate_dml');
1170 if (update_re.test(query) || delete_re.test(query)) {
1171 if (! $simulateDml.length) {
1172 $('#button_submit_query')
1173 .before('<input type="button" id="simulate_dml"' +
1174 'tabindex="199" value="' +
1175 PMA_messages.strSimulateDML +
1179 if ($simulateDml.length) {
1180 $simulateDml.remove();
1186 * Create quick sql statements.
1189 function insertQuery(queryType)
1191 if (queryType == "clear") {
1194 } else if (queryType == "format") {
1195 if (codemirror_editor) {
1196 $('#querymessage').html(PMA_messages.strFormatting +
1197 ' <img class="ajaxIcon" src="' +
1198 pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1199 var href = 'db_sql_format.php';
1201 'ajax_request': true,
1202 'token': PMA_commonParams.get('token'),
1203 'sql': codemirror_editor.getValue()
1209 success: function (data) {
1211 codemirror_editor.setValue(data.sql);
1213 $('#querymessage').html('');
1218 } else if (queryType == "saved") {
1219 if (isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql != 'undefined') {
1220 setQuery(window.localStorage.auto_saved_sql);
1221 } else if ($.cookie('auto_saved_sql')) {
1222 setQuery($.cookie('auto_saved_sql'));
1224 PMA_ajaxShowMessage(PMA_messages.strNoAutoSavedQuery);
1230 var myListBox = document.sqlform.dummy;
1231 var table = document.sqlform.table.value;
1233 if (myListBox.options.length > 0) {
1234 sql_box_locked = true;
1235 var columnsList = "";
1239 for (var i = 0; i < myListBox.options.length; i++) {
1242 columnsList += ", ";
1246 columnsList += myListBox.options[i].value;
1247 valDis += "[value-" + NbSelect + "]";
1248 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
1250 if (queryType == "selectall") {
1251 query = "SELECT * FROM `" + table + "` WHERE 1";
1252 } else if (queryType == "select") {
1253 query = "SELECT " + columnsList + " FROM `" + table + "` WHERE 1";
1254 } else if (queryType == "insert") {
1255 query = "INSERT INTO `" + table + "`(" + columnsList + ") VALUES (" + valDis + ")";
1256 } else if (queryType == "update") {
1257 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
1258 } else if (queryType == "delete") {
1259 query = "DELETE FROM `" + table + "` WHERE 0";
1262 sql_box_locked = false;
1268 * Inserts multiple fields.
1271 function insertValueQuery()
1273 var myQuery = document.sqlform.sql_query;
1274 var myListBox = document.sqlform.dummy;
1276 if (myListBox.options.length > 0) {
1277 sql_box_locked = true;
1278 var columnsList = "";
1280 for (var i = 0; i < myListBox.options.length; i++) {
1281 if (myListBox.options[i].selected) {
1284 columnsList += ", ";
1286 columnsList += myListBox.options[i].value;
1290 /* CodeMirror support */
1291 if (codemirror_editor) {
1292 codemirror_editor.replaceSelection(columnsList);
1293 codemirror_editor.focus();
1295 } else if (document.selection) {
1297 var sel = document.selection.createRange();
1298 sel.text = columnsList;
1300 //MOZILLA/NETSCAPE support
1301 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
1302 var startPos = document.sqlform.sql_query.selectionStart;
1303 var endPos = document.sqlform.sql_query.selectionEnd;
1304 var SqlString = document.sqlform.sql_query.value;
1306 myQuery.value = SqlString.substring(0, startPos) + columnsList + SqlString.substring(endPos, SqlString.length);
1309 myQuery.value += columnsList;
1311 sql_box_locked = false;
1316 * Updates the input fields for the parameters based on the query
1318 function updateQueryParameters() {
1320 if ($('#parameterized').is(':checked')) {
1321 var query = codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val();
1323 var allParameters = query.match(/:[a-zA-Z0-9_]+/g);
1324 var parameters = [];
1325 // get unique parameters
1326 if (allParameters) {
1327 $.each(allParameters, function(i, parameter){
1328 if ($.inArray(parameter, parameters) === -1) {
1329 parameters.push(parameter);
1333 $('#parametersDiv').text(PMA_messages.strNoParam);
1337 var $temp = $('<div />');
1338 $temp.append($('#parametersDiv').children());
1339 $('#parametersDiv').empty();
1341 $.each(parameters, function (i, parameter) {
1342 var paramName = parameter.substring(1);
1343 var $param = $temp.find('#paramSpan_' + paramName );
1344 if (! $param.length) {
1345 $param = $('<span class="parameter" id="paramSpan_' + paramName + '" />');
1346 $('<label for="param_' + paramName + '" />').text(parameter).appendTo($param);
1347 $('<input type="text" name="parameters[' + parameter + ']" id="param_' + paramName + '" />').appendTo($param);
1349 $('#parametersDiv').append($param);
1352 $('#parametersDiv').empty();
1357 * Refresh/resize the WYSIWYG scratchboard
1359 function refreshLayout()
1361 var $elm = $('#pdflayout');
1362 var orientation = $('#orientation_opt').val();
1364 var $paperOpt = $('#paper_opt');
1365 if ($paperOpt.length == 1) {
1366 paper = $paperOpt.val();
1370 if (orientation == 'P') {
1374 $elm.css('width', pdfPaperSize(paper, posa) + 'px');
1375 $elm.css('height', pdfPaperSize(paper, posb) + 'px');
1379 * Initializes positions of elements.
1381 function TableDragInit() {
1382 $('.pdflayout_table').each(function () {
1383 var $this = $(this);
1384 var number = $this.data('number');
1385 var x = $('#c_table_' + number + '_x').val();
1386 var y = $('#c_table_' + number + '_y').val();
1387 $this.css('left', x + 'px');
1388 $this.css('top', y + 'px');
1389 /* Make elements draggable */
1391 containment: "parent",
1392 drag: function (evt, ui) {
1393 var number = $this.data('number');
1394 $('#c_table_' + number + '_x').val(parseInt(ui.position.left, 10));
1395 $('#c_table_' + number + '_y').val(parseInt(ui.position.top, 10));
1402 * Resets drag and drop positions.
1404 function resetDrag() {
1405 $('.pdflayout_table').each(function () {
1406 var $this = $(this);
1407 var x = $this.data('x');
1408 var y = $this.data('y');
1409 $this.css('left', x + 'px');
1410 $this.css('top', y + 'px');
1415 * User schema handlers.
1418 /* Move in scratchboard on manual change */
1419 $(document).on('change', '.position-change', function () {
1420 var $this = $(this);
1421 var $elm = $('#table_' + $this.data('number'));
1422 $elm.css($this.data('axis'), $this.val() + 'px');
1424 /* Refresh on paper size/orientation change */
1425 $(document).on('change', '.paper-change', function () {
1426 var $elm = $('#pdflayout');
1427 if ($elm.css('visibility') == 'visible') {
1432 /* Show/hide the WYSIWYG scratchboard */
1433 $(document).on('click', '#toggle-dragdrop', function () {
1434 var $elm = $('#pdflayout');
1435 if ($elm.css('visibility') == 'hidden') {
1438 $elm.css('visibility', 'visible');
1439 $elm.css('display', 'block');
1440 $('#showwysiwyg').val('1');
1442 $elm.css('visibility', 'hidden');
1443 $elm.css('display', 'none');
1444 $('#showwysiwyg').val('0');
1447 /* Reset scratchboard */
1448 $(document).on('click', '#reset-dragdrop', function () {
1454 * Returns paper sizes for a given format
1456 function pdfPaperSize(format, axis)
1458 switch (format.toUpperCase()) {
1808 * Get checkbox for foreign key checks
1812 function getForeignKeyCheckboxLoader() {
1815 html += '<div class="load-default-fk-check-value">';
1816 html += PMA_getImage('ajax_clock_small.gif');
1822 function loadForeignKeyCheckbox() {
1823 // Load default foreign key check value
1825 'ajax_request': true,
1826 'token': PMA_commonParams.get('token'),
1827 'server': PMA_commonParams.get('server'),
1828 'get_default_fk_check_value': true
1830 $.get('sql.php', params, function (data) {
1831 var html = '<input type="hidden" name="fk_checks" value="0" />' +
1832 '<input type="checkbox" name="fk_checks" id="fk_checks"' +
1833 (data.default_fk_check_value ? ' checked="checked"' : '') + ' />' +
1834 '<label for="fk_checks">' + PMA_messages.strForeignKeyCheck + '</label>';
1835 $('.load-default-fk-check-value').replaceWith(html);
1839 function getJSConfirmCommonParam(elem) {
1841 'is_js_confirmed' : 1,
1842 'ajax_request' : true,
1843 'fk_checks': $(elem).find('#fk_checks').is(':checked') ? 1 : 0
1848 * Unbind all event handlers before tearing down a page
1850 AJAX.registerTeardown('functions.js', function () {
1851 $(document).off('click', "a.inline_edit_sql");
1852 $(document).off('click', "input#sql_query_edit_save");
1853 $(document).off('click', "input#sql_query_edit_discard");
1854 $('input.sqlbutton').off('click');
1855 if (codemirror_editor) {
1856 codemirror_editor.off('blur');
1858 $(document).off('blur', '#sqlquery');
1860 $(document).off('change', '#parameterized');
1861 $('#sqlquery').off('keydown');
1862 $('#sql_query_edit').off('keydown');
1864 if (codemirror_inline_editor) {
1865 // Copy the sql query to the text area to preserve it.
1866 $('#sql_query_edit').text(codemirror_inline_editor.getValue());
1867 $(codemirror_inline_editor.getWrapperElement()).off('keydown');
1868 codemirror_inline_editor.toTextArea();
1869 codemirror_inline_editor = false;
1871 if (codemirror_editor) {
1872 $(codemirror_editor.getWrapperElement()).off('keydown');
1877 * Jquery Coding for inline editing SQL_QUERY
1879 AJAX.registerOnload('functions.js', function () {
1880 // If we are coming back to the page by clicking forward button
1881 // of the browser, bind the code mirror to inline query editor.
1882 bindCodeMirrorToInlineEditor();
1883 $(document).on('click', "a.inline_edit_sql", function () {
1884 if ($('#sql_query_edit').length) {
1885 // An inline query editor is already open,
1886 // we don't want another copy of it
1890 var $form = $(this).prev('form');
1891 var sql_query = $form.find("input[name='sql_query']").val().trim();
1892 var $inner_sql = $(this).parent().prev().find('code.sql');
1893 var old_text = $inner_sql.html();
1895 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + escapeHtml(sql_query) + "</textarea>\n";
1896 new_content += getForeignKeyCheckboxLoader();
1897 new_content += "<input type=\"submit\" id=\"sql_query_edit_save\" class=\"button btnSave\" value=\"" + PMA_messages.strGo + "\"/>\n";
1898 new_content += "<input type=\"button\" id=\"sql_query_edit_discard\" class=\"button btnDiscard\" value=\"" + PMA_messages.strCancel + "\"/>\n";
1899 var $editor_area = $('div#inline_editor');
1900 if ($editor_area.length === 0) {
1901 $editor_area = $('<div id="inline_editor_outer"></div>');
1902 $editor_area.insertBefore($inner_sql);
1904 $editor_area.html(new_content);
1905 loadForeignKeyCheckbox();
1908 bindCodeMirrorToInlineEditor();
1912 $(document).on('click', "input#sql_query_edit_save", function () {
1913 //hide already existing success message
1915 if (codemirror_inline_editor) {
1916 codemirror_inline_editor.save();
1917 sql_query = codemirror_inline_editor.getValue();
1919 sql_query = $(this).parent().find('#sql_query_edit').val();
1921 var fk_check = $(this).parent().find('#fk_checks').is(':checked');
1923 var $form = $("a.inline_edit_sql").prev('form');
1924 var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1925 .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1926 .append($('<input/>', {type: 'hidden', name: 'show_query', value: 1}))
1927 .append($('<input/>', {type: 'hidden', name: 'is_js_confirmed', value: 0}))
1928 .append($('<input/>', {type: 'hidden', name: 'sql_query', value: sql_query}))
1929 .append($('<input/>', {type: 'hidden', name: 'fk_checks', value: fk_check ? 1 : 0}));
1930 if (! checkSqlQuery($fake_form[0])) {
1933 $(".success").hide();
1934 $fake_form.appendTo($('body')).submit();
1937 $(document).on('click', "input#sql_query_edit_discard", function () {
1938 var $divEditor = $('div#inline_editor_outer');
1939 $divEditor.siblings('code.sql').show();
1940 $divEditor.remove();
1943 $('input.sqlbutton').click(function (evt) {
1944 insertQuery(evt.target.id);
1945 PMA_handleSimulateQueryButton();
1949 $(document).on('change', '#parameterized', updateQueryParameters);
1951 var $inputUsername = $('#input_username');
1952 if ($inputUsername) {
1953 if ($inputUsername.val() === '') {
1954 $inputUsername.focus();
1956 $('#input_password').focus();
1962 * "inputRead" event handler for CodeMirror SQL query editors for autocompletion
1964 function codemirrorAutocompleteOnInputRead(instance) {
1965 if (!sql_autocomplete_in_progress
1966 && (!instance.options.hintOptions.tables || !sql_autocomplete)) {
1968 if (!sql_autocomplete) {
1969 // Reset after teardown
1970 instance.options.hintOptions.tables = false;
1971 instance.options.hintOptions.defaultTable = '';
1973 sql_autocomplete_in_progress = true;
1975 var href = 'db_sql_autocomplete.php';
1977 'ajax_request': true,
1978 'token': PMA_commonParams.get('token'),
1979 'server': PMA_commonParams.get('server'),
1980 'db': PMA_commonParams.get('db'),
1984 var columnHintRender = function(elem, self, data) {
1985 $('<div class="autocomplete-column-name">')
1986 .text(data.columnName)
1988 $('<div class="autocomplete-column-hint">')
1989 .text(data.columnHint)
1997 success: function (data) {
1999 var tables = JSON.parse(data.tables);
2000 sql_autocomplete_default_table = PMA_commonParams.get('table');
2001 sql_autocomplete = [];
2002 for (var table in tables) {
2003 if (tables.hasOwnProperty(table)) {
2004 var columns = tables[table];
2009 for (var column in columns) {
2010 if (columns.hasOwnProperty(column)) {
2011 var displayText = columns[column].Type;
2012 if (columns[column].Key == 'PRI') {
2013 displayText += ' | Primary';
2014 } else if (columns[column].Key == 'UNI') {
2015 displayText += ' | Unique';
2017 table.columns.push({
2019 displayText: column + " | " + displayText,
2021 columnHint: displayText,
2022 render: columnHintRender
2027 sql_autocomplete.push(table);
2029 instance.options.hintOptions.tables = sql_autocomplete;
2030 instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
2033 complete: function () {
2034 sql_autocomplete_in_progress = false;
2039 instance.options.hintOptions.tables = sql_autocomplete;
2040 instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
2043 if (instance.state.completionActive) {
2046 var cur = instance.getCursor();
2047 var token = instance.getTokenAt(cur);
2049 if (token.string.match(/^[.`\w@]\w*$/)) {
2050 string = token.string;
2052 if (string.length > 0) {
2053 CodeMirror.commands.autocomplete(instance);
2058 * Remove autocomplete information before tearing down a page
2060 AJAX.registerTeardown('functions.js', function () {
2061 sql_autocomplete = false;
2062 sql_autocomplete_default_table = '';
2066 * Binds the CodeMirror to the text area used to inline edit a query.
2068 function bindCodeMirrorToInlineEditor() {
2069 var $inline_editor = $('#sql_query_edit');
2070 if ($inline_editor.length > 0) {
2071 if (typeof CodeMirror !== 'undefined') {
2072 var height = $inline_editor.css('height');
2073 codemirror_inline_editor = PMA_getSQLEditor($inline_editor);
2074 codemirror_inline_editor.getWrapperElement().style.height = height;
2075 codemirror_inline_editor.refresh();
2076 codemirror_inline_editor.focus();
2077 $(codemirror_inline_editor.getWrapperElement())
2078 .on('keydown', catchKeypressesFromSqlInlineEdit);
2082 .on('keydown', catchKeypressesFromSqlInlineEdit);
2087 function catchKeypressesFromSqlInlineEdit(event) {
2088 // ctrl-enter is 10 in chrome and ie, but 13 in ff
2089 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 13 || event.keyCode == 10)) {
2090 $("#sql_query_edit_save").trigger('click');
2095 * Adds doc link to single highlighted SQL element
2097 function PMA_doc_add($elm, params)
2099 if (typeof mysql_doc_template == 'undefined') {
2103 var url = PMA_sprintf(
2104 decodeURIComponent(mysql_doc_template),
2107 if (params.length > 1) {
2108 url += '#' + params[1];
2110 var content = $elm.text();
2112 $elm.append('<a target="mysql_doc" class="cm-sql-doc" href="' + url + '">' + content + '</a>');
2116 * Generates doc links for keywords inside highlighted SQL
2118 function PMA_doc_keyword(idx, elm)
2121 /* Skip already processed ones */
2122 if ($elm.find('a').length > 0) {
2125 var keyword = $elm.text().toUpperCase();
2126 var $next = $elm.next('.cm-keyword');
2128 var next_keyword = $next.text().toUpperCase();
2129 var full = keyword + ' ' + next_keyword;
2131 var $next2 = $next.next('.cm-keyword');
2133 var next2_keyword = $next2.text().toUpperCase();
2134 var full2 = full + ' ' + next2_keyword;
2135 if (full2 in mysql_doc_keyword) {
2136 PMA_doc_add($elm, mysql_doc_keyword[full2]);
2137 PMA_doc_add($next, mysql_doc_keyword[full2]);
2138 PMA_doc_add($next2, mysql_doc_keyword[full2]);
2142 if (full in mysql_doc_keyword) {
2143 PMA_doc_add($elm, mysql_doc_keyword[full]);
2144 PMA_doc_add($next, mysql_doc_keyword[full]);
2148 if (keyword in mysql_doc_keyword) {
2149 PMA_doc_add($elm, mysql_doc_keyword[keyword]);
2154 * Generates doc links for builtins inside highlighted SQL
2156 function PMA_doc_builtin(idx, elm)
2159 var builtin = $elm.text().toUpperCase();
2160 if (builtin in mysql_doc_builtin) {
2161 PMA_doc_add($elm, mysql_doc_builtin[builtin]);
2166 * Higlights SQL using CodeMirror.
2168 function PMA_highlightSQL($base)
2170 var $elm = $base.find('code.sql');
2171 $elm.each(function () {
2173 var $pre = $sql.find('pre');
2174 /* We only care about visible elements to avoid double processing */
2175 if ($pre.is(":visible")) {
2176 var $highlight = $('<div class="sql-highlight cm-s-default"></div>');
2177 $sql.append($highlight);
2178 if (typeof CodeMirror != 'undefined') {
2179 CodeMirror.runMode($sql.text(), 'text/x-mysql', $highlight[0]);
2181 $highlight.find('.cm-keyword').each(PMA_doc_keyword);
2182 $highlight.find('.cm-builtin').each(PMA_doc_builtin);
2189 * Updates an element containing code.
2191 * @param jQuery Object $base base element which contains the raw and the
2194 * @param string htmlValue code in HTML format, displayed if code cannot be
2197 * @param string rawValue raw code, used as a parameter for highlighter
2199 * @return bool whether content was updated or not
2201 function PMA_updateCode($base, htmlValue, rawValue)
2203 var $code = $base.find('code');
2204 if ($code.length === 0) {
2208 // Determines the type of the content and appropriate CodeMirror mode.
2209 var type = '', mode = '';
2210 if ($code.hasClass('json')) {
2212 mode = 'application/json';
2213 } else if ($code.hasClass('sql')) {
2215 mode = 'text/x-mysql';
2216 } else if ($code.hasClass('xml')) {
2218 mode = 'application/xml';
2223 // Element used to display unhighlighted code.
2224 var $notHighlighted = $('<pre>' + htmlValue + '</pre>');
2226 // Tries to highlight code using CodeMirror.
2227 if (typeof CodeMirror != 'undefined') {
2228 var $highlighted = $('<div class="' + type + '-highlight cm-s-default"></div>');
2229 CodeMirror.runMode(rawValue, mode, $highlighted[0]);
2230 $notHighlighted.hide();
2231 $code.html('').append($notHighlighted, $highlighted[0]);
2233 $code.html('').append($notHighlighted);
2240 * Show a message on the top of the page for an Ajax request
2244 * 1) var $msg = PMA_ajaxShowMessage();
2245 * This will show a message that reads "Loading...". Such a message will not
2246 * disappear automatically and cannot be dismissed by the user. To remove this
2247 * message either the PMA_ajaxRemoveMessage($msg) function must be called or
2248 * another message must be show with PMA_ajaxShowMessage() function.
2250 * 2) var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2251 * This is a special case. The behaviour is same as above,
2252 * just with a different message
2254 * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
2255 * This will show a message that will disappear automatically and it can also
2256 * be dismissed by the user.
2258 * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
2259 * This will show a message that will not disappear automatically, but it
2260 * can be dismissed by the user after he has finished reading it.
2262 * @param string message string containing the message to be shown.
2263 * optional, defaults to 'Loading...'
2264 * @param mixed timeout number of milliseconds for the message to be visible
2265 * optional, defaults to 5000. If set to 'false', the
2266 * notification will never disappear
2267 * @param string type string to dictate the type of message shown.
2268 * optional, defaults to normal notification.
2269 * If set to 'error', the notification will show message
2270 * with red background.
2271 * If set to 'success', the notification will show with
2272 * a green background.
2273 * @return jQuery object jQuery Element that holds the message div
2274 * this object can be passed to PMA_ajaxRemoveMessage()
2275 * to remove the notification
2277 function PMA_ajaxShowMessage(message, timeout, type)
2280 * @var self_closing Whether the notification will automatically disappear
2282 var self_closing = true;
2284 * @var dismissable Whether the user will be able to remove
2285 * the notification by clicking on it
2287 var dismissable = true;
2288 // Handle the case when a empty data.message is passed.
2289 // We don't want the empty message
2290 if (message === '') {
2292 } else if (! message) {
2293 // If the message is undefined, show the default
2294 message = PMA_messages.strLoading;
2295 dismissable = false;
2296 self_closing = false;
2297 } else if (message == PMA_messages.strProcessingRequest) {
2298 // This is another case where the message should not disappear
2299 dismissable = false;
2300 self_closing = false;
2302 // Figure out whether (or after how long) to remove the notification
2303 if (timeout === undefined) {
2305 } else if (timeout === false) {
2306 self_closing = false;
2308 // Determine type of message, add styling as required
2309 if (type === "error") {
2310 message = "<div class=\"error\">" + message + "</div>";
2311 } else if (type === "success") {
2312 message = "<div class=\"success\">" + message + "</div>";
2314 // Create a parent element for the AJAX messages, if necessary
2315 if ($('#loading_parent').length === 0) {
2316 $('<div id="loading_parent"></div>')
2317 .prependTo("#page_content");
2319 // Update message count to create distinct message elements every time
2320 ajax_message_count++;
2321 // Remove all old messages, if any
2322 $("span.ajax_notification[id^=ajax_message_num]").remove();
2324 * @var $retval a jQuery object containing the reference
2325 * to the created AJAX message
2328 '<span class="ajax_notification" id="ajax_message_num_' +
2329 ajax_message_count +
2333 .appendTo("#loading_parent")
2336 // If the notification is self-closing we should create a callback to remove it
2340 .fadeOut('medium', function () {
2341 if ($(this).is(':data(tooltip)')) {
2342 $(this).tooltip('destroy');
2344 // Remove the notification
2348 // If the notification is dismissable we need to add the relevant class to it
2349 // and add a tooltip so that the users know that it can be removed
2351 $retval.addClass('dismissable').css('cursor', 'pointer');
2353 * Add a tooltip to the notification to let the user know that (s)he
2354 * can dismiss the ajax notification by clicking on it.
2359 PMA_messages.strDismiss
2362 PMA_highlightSQL($retval);
2368 * Removes the message shown for an Ajax operation when it's completed
2370 * @param jQuery object jQuery Element that holds the notification
2374 function PMA_ajaxRemoveMessage($this_msgbox)
2376 if ($this_msgbox !== undefined && $this_msgbox instanceof jQuery) {
2380 if ($this_msgbox.is(':data(tooltip)')) {
2381 $this_msgbox.tooltip('destroy');
2383 $this_msgbox.remove();
2389 * Requests SQL for previewing before executing.
2391 * @param jQuery Object $form Form containing query data
2395 function PMA_previewSQL($form)
2397 var form_url = $form.attr('action');
2398 var form_data = $form.serialize() +
2402 var $msgbox = PMA_ajaxShowMessage();
2407 success: function (response) {
2408 PMA_ajaxRemoveMessage($msgbox);
2409 if (response.success) {
2410 var $dialog_content = $('<div/>')
2411 .append(response.sql_data);
2412 var button_options = {};
2413 button_options[PMA_messages.strClose] = function () {
2414 $(this).dialog('close');
2416 var $response_dialog = $dialog_content.dialog({
2420 buttons: button_options,
2421 title: PMA_messages.strPreviewSQL,
2422 close: function () {
2426 // Pretty SQL printing.
2427 PMA_highlightSQL($(this));
2431 PMA_ajaxShowMessage(response.message);
2434 error: function () {
2435 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
2441 * check for reserved keyword column name
2443 * @param jQuery Object $form Form
2445 * @returns true|false
2448 function PMA_checkReservedWordColumns($form) {
2449 var is_confirmed = true;
2452 url: "tbl_structure.php",
2453 data: $form.serialize() + '&reserved_word_check=1',
2454 success: function (data) {
2455 if (typeof data.success != 'undefined' && data.success === true) {
2456 is_confirmed = confirm(data.message);
2461 return is_confirmed;
2464 // This event only need to be fired once after the initial page load
2467 * Allows the user to dismiss a notification
2468 * created with PMA_ajaxShowMessage()
2470 $(document).on('click', 'span.ajax_notification.dismissable', function () {
2471 PMA_ajaxRemoveMessage($(this));
2474 * The below two functions hide the "Dismiss notification" tooltip when a user
2475 * is hovering a link or button that is inside an ajax message
2477 $(document).on('mouseover', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
2478 if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
2479 $(this).parents('span.ajax_notification').tooltip('disable');
2482 $(document).on('mouseout', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
2483 if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
2484 $(this).parents('span.ajax_notification').tooltip('enable');
2490 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
2492 function PMA_showNoticeForEnum(selectElement)
2494 var enum_notice_id = selectElement.attr("id").split("_")[1];
2495 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2], 10) + 1);
2496 var selectedType = selectElement.val();
2497 if (selectedType == "ENUM" || selectedType == "SET") {
2498 $("p#enum_notice_" + enum_notice_id).show();
2500 $("p#enum_notice_" + enum_notice_id).hide();
2505 * Creates a Profiling Chart. Used in sql.js
2506 * and in server_status_monitor.js
2508 function PMA_createProfilingChart(target, data)
2511 var factory = new JQPlotChartFactory();
2512 var chart = factory.createChart(ChartType.PIE, target);
2514 // create the data table and add columns
2515 var dataTable = new DataTable();
2516 dataTable.addColumn(ColumnType.STRING, '');
2517 dataTable.addColumn(ColumnType.NUMBER, '');
2518 dataTable.setData(data);
2520 // draw the chart and return the chart object
2521 chart.draw(dataTable, {
2524 showDataLabels: true
2528 tooltipLocation: 'se',
2530 tooltipAxes: 'pieref',
2531 formatString: '%s, %.9Ps'
2540 // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
2565 * Formats a profiling duration nicely (in us and ms time).
2566 * Used in server_status_monitor.js
2568 * @param integer Number to be formatted, should be in the range of microsecond to second
2569 * @param integer Accuracy, how many numbers right to the comma should be
2570 * @return string The formatted number
2572 function PMA_prettyProfilingNum(num, acc)
2577 acc = Math.pow(10, acc);
2578 if (num * 1000 < 0.1) {
2579 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
2580 } else if (num < 0.1) {
2581 num = Math.round(acc * (num * 1000)) / acc + 'm';
2583 num = Math.round(acc * num) / acc;
2591 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
2593 * @param string Query to be formatted
2594 * @return string The formatted query
2596 function PMA_SQLPrettyPrint(string)
2598 if (typeof CodeMirror == 'undefined') {
2602 var mode = CodeMirror.getMode({}, "text/x-mysql");
2603 var stream = new CodeMirror.StringStream(string);
2604 var state = mode.startState();
2605 var token, tokens = [];
2607 var tabs = function (cnt) {
2609 for (var i = 0; i < 4 * cnt; i++) {
2615 // "root-level" statements
2617 'select': ['select', 'from', 'on', 'where', 'having', 'limit', 'order by', 'group by'],
2618 'update': ['update', 'set', 'where'],
2619 'insert into': ['insert into', 'values']
2621 // don't put spaces before these tokens
2622 var spaceExceptionsBefore = {';': true, ',': true, '.': true, '(': true};
2623 // don't put spaces after these tokens
2624 var spaceExceptionsAfter = {'.': true};
2626 // Populate tokens array
2628 while (! stream.eol()) {
2629 stream.start = stream.pos;
2630 token = mode.token(stream, state);
2631 if (token !== null) {
2632 tokens.push([token, stream.current().toLowerCase()]);
2636 var currentStatement = tokens[0][1];
2638 if (! statements[currentStatement]) {
2641 // Holds all currently opened code blocks (statement, function or generic)
2642 var blockStack = [];
2643 // Holds the type of block from last iteration (the current is in blockStack[0])
2645 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
2646 var newBlock, endBlock;
2647 // How much to indent in the current line
2648 var indentLevel = 0;
2649 // Holds the "root-level" statements
2650 var statementPart, lastStatementPart = statements[currentStatement][0];
2652 blockStack.unshift('statement');
2654 // Iterate through every token and format accordingly
2655 for (var i = 0; i < tokens.length; i++) {
2656 previousBlock = blockStack[0];
2658 // New block => push to stack
2659 if (tokens[i][1] == '(') {
2660 if (i < tokens.length - 1 && tokens[i + 1][0] == 'statement-verb') {
2661 blockStack.unshift(newBlock = 'statement');
2662 } else if (i > 0 && tokens[i - 1][0] == 'builtin') {
2663 blockStack.unshift(newBlock = 'function');
2665 blockStack.unshift(newBlock = 'generic');
2671 // Block end => pop from stack
2672 if (tokens[i][1] == ')') {
2673 endBlock = blockStack[0];
2679 // A subquery is starting
2680 if (i > 0 && newBlock == 'statement') {
2682 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i + 1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
2683 currentStatement = tokens[i + 1][1];
2688 // A subquery is ending
2689 if (endBlock == 'statement' && indentLevel > 0) {
2690 output += "\n" + tabs(indentLevel);
2694 // One less indentation for statement parts (from, where, order by, etc.) and a newline
2695 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
2696 if (statementPart != -1) {
2700 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
2701 output += "\n" + tabs(indentLevel + 1);
2702 lastStatementPart = tokens[i][1];
2704 // Normal indentation and spaces for everything else
2706 if (! spaceExceptionsBefore[tokens[i][1]] &&
2707 ! (i > 0 && spaceExceptionsAfter[tokens[i - 1][1]]) &&
2708 output.charAt(output.length - 1) != ' ') {
2711 if (tokens[i][0] == 'keyword') {
2712 output += tokens[i][1].toUpperCase();
2714 output += tokens[i][1];
2718 // split columns in select and 'update set' clauses, but only inside statements blocks
2719 if ((lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set') &&
2720 tokens[i][1] == ',' && blockStack[0] == 'statement') {
2722 output += "\n" + tabs(indentLevel + 1);
2725 // split conditions in where clauses, but only inside statements blocks
2726 if (lastStatementPart == 'where' &&
2727 (tokens[i][1] == 'and' || tokens[i][1] == 'or' || tokens[i][1] == 'xor')) {
2729 if (blockStack[0] == 'statement') {
2730 output += "\n" + tabs(indentLevel + 1);
2732 // Todo: Also split and or blocks in newlines & indentation++
2733 //if (blockStack[0] == 'generic')
2741 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
2742 * return a jQuery object yet and hence cannot be chained
2744 * @param string question
2745 * @param string url URL to be passed to the callbackFn to make
2747 * @param function callbackFn callback to execute after user clicks on OK
2748 * @param function openCallback optional callback to run when dialog is shown
2751 jQuery.fn.PMA_confirm = function (question, url, callbackFn, openCallback) {
2752 var confirmState = PMA_commonParams.get('confirm');
2753 if (! confirmState) {
2754 // user does not want to confirm
2755 if ($.isFunction(callbackFn)) {
2756 callbackFn.call(this, url);
2760 if (PMA_messages.strDoYouReally === '') {
2765 * @var button_options Object that stores the options passed to jQueryUI
2768 var button_options = [
2770 text: PMA_messages.strOK,
2771 'class': 'submitOK',
2772 click: function () {
2773 $(this).dialog("close");
2774 if ($.isFunction(callbackFn)) {
2775 callbackFn.call(this, url);
2780 text: PMA_messages.strCancel,
2781 'class': 'submitCancel',
2782 click: function () {
2783 $(this).dialog("close");
2788 $('<div/>', {'id': 'confirm_dialog', 'title': PMA_messages.strConfirm})
2791 buttons: button_options,
2792 close: function () {
2801 * jQuery function to sort a table's body after a new row has been appended to it.
2803 * @param string text_selector string to select the sortKey's text
2805 * @return jQuery Object for chaining purposes
2807 jQuery.fn.PMA_sort_table = function (text_selector) {
2808 return this.each(function () {
2811 * @var table_body Object referring to the table's <tbody> element
2813 var table_body = $(this);
2815 * @var rows Object referring to the collection of rows in {@link table_body}
2817 var rows = $(this).find('tr').get();
2819 //get the text of the field that we will sort by
2820 $.each(rows, function (index, row) {
2821 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
2824 //get the sorted order
2825 rows.sort(function (a, b) {
2826 if (a.sortKey < b.sortKey) {
2829 if (a.sortKey > b.sortKey) {
2835 //pull out each row from the table and then append it according to it's order
2836 $.each(rows, function (index, row) {
2837 $(table_body).append(row);
2844 * Unbind all event handlers before tearing down a page
2846 AJAX.registerTeardown('functions.js', function () {
2847 $(document).off('submit', "#create_table_form_minimal.ajax");
2848 $(document).off('submit', "form.create_table_form.ajax");
2849 $(document).off('click', "form.create_table_form.ajax input[name=submit_num_fields]");
2850 $(document).off('keyup', "form.create_table_form.ajax input");
2851 $(document).off('change', "input[name=partition_count],input[name=subpartition_count],select[name=partition_by]");
2855 * jQuery coding for 'Create Table'. Used on db_operations.php,
2856 * db_structure.php and db_tracking.php (i.e., wherever
2857 * libraries/display_create_table.lib.php is used)
2859 * Attach Ajax Event handlers for Create Table
2861 AJAX.registerOnload('functions.js', function () {
2863 * Attach event handler for submission of create table form (save)
2865 $(document).on('submit', "form.create_table_form.ajax", function (event) {
2866 event.preventDefault();
2869 * @var the_form object referring to the create table form
2871 var $form = $(this);
2874 * First validate the form; if there is a problem, avoid submitting it
2876 * checkTableEditForm() needs a pure element and not a jQuery object,
2877 * this is why we pass $form[0] as a parameter (the jQuery object
2878 * is actually an array of DOM elements)
2881 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2882 PMA_prepareForAjaxRequest($form);
2883 if (PMA_checkReservedWordColumns($form)) {
2884 PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2885 //User wants to submit the form
2886 $.post($form.attr('action'), $form.serialize() + "&do_save_data=1", function (data) {
2887 if (typeof data !== 'undefined' && data.success === true) {
2888 $('#properties_message')
2889 .removeClass('error')
2891 PMA_ajaxShowMessage(data.message);
2892 // Only if the create table dialog (distinct panel) exists
2893 var $createTableDialog = $("#create_table_dialog");
2894 if ($createTableDialog.length > 0) {
2895 $createTableDialog.dialog("close").remove();
2897 $('#tableslistcontainer').before(data.formatted_sql);
2900 * @var tables_table Object referring to the <tbody> element that holds the list of tables
2902 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
2903 // this is the first table created in this db
2904 if (tables_table.length === 0) {
2905 PMA_commonActions.refreshMain(
2906 PMA_commonParams.get('opendb_url')
2910 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
2912 var curr_last_row = $(tables_table).find('tr:last');
2914 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
2916 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2918 * @var curr_last_row_index Index of {@link curr_last_row}
2920 var curr_last_row_index = parseFloat(curr_last_row_index_string);
2922 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
2924 var new_last_row_index = curr_last_row_index + 1;
2926 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2928 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2930 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2932 $(data.new_table_string)
2933 .appendTo(tables_table);
2936 $(tables_table).PMA_sort_table('th');
2938 // Adjust summary row
2942 //Refresh navigation as a new table has been added
2943 PMA_reloadNavigation();
2944 // Redirect to table structure page on creation of new table
2945 var params_12 = 'ajax_request=true&ajax_page_request=true';
2946 if (! (history && history.pushState)) {
2947 params_12 += PMA_MicroHistory.menus.getRequestParam();
2949 tblStruct_url = 'tbl_structure.php?server=' + data._params.server +
2950 '&db='+ data._params.db + '&token=' + data._params.token +
2951 '&goto=db_structure.php&table=' + data._params.table + '';
2952 $.get(tblStruct_url, params_12, AJAX.responseHandler);
2954 PMA_ajaxShowMessage(
2955 '<div class="error">' + data.error + '</div>',
2961 } // end if (checkTableEditForm() )
2962 }); // end create table form (save)
2965 * Submits the intermediate changes in the table creation form
2966 * to refresh the UI accordingly
2968 function submitChangesInCreateTableForm (actionParam) {
2971 * @var the_form object referring to the create table form
2973 var $form = $('form.create_table_form.ajax');
2975 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2976 PMA_prepareForAjaxRequest($form);
2978 //User wants to add more fields to the table
2979 $.post($form.attr('action'), $form.serialize() + "&" + actionParam, function (data) {
2980 if (typeof data !== 'undefined' && data.success) {
2981 var $pageContent = $("#page_content");
2982 $pageContent.html(data.message);
2983 PMA_highlightSQL($pageContent);
2984 PMA_verifyColumnsProperties();
2985 PMA_hideShowConnection($('.create_table_form select[name=tbl_storage_engine]'));
2986 PMA_ajaxRemoveMessage($msgbox);
2988 PMA_ajaxShowMessage(data.error);
2994 * Attach event handler for create table form (add fields)
2996 $(document).on('click', "form.create_table_form.ajax input[name=submit_num_fields]", function (event) {
2997 event.preventDefault();
2999 if (!checkFormElementInRange(this.form, 'added_fields', PMA_messages.strLeastColumnError, 1)) {
3003 submitChangesInCreateTableForm('submit_num_fields=1');
3004 }); // end create table form (add fields)
3006 $(document).on('keydown', "form.create_table_form.ajax input[name=added_fields]", function (event) {
3007 if (event.keyCode == 13) {
3008 event.preventDefault();
3009 event.stopImmediatePropagation();
3012 .find('input[name=submit_num_fields]')
3018 * Attach event handler to manage changes in number of partitions and subpartitions
3020 $(document).on('change', "input[name=partition_count],input[name=subpartition_count],select[name=partition_by]", function (event) {
3022 $form = $this.parents('form');
3023 if ($form.is(".create_table_form.ajax")) {
3024 submitChangesInCreateTableForm('submit_partition_change=1');
3030 $(document).on('change', "input[value=AUTO_INCREMENT]", function() {
3032 var col = /\d/.exec($(this).attr('name'));
3034 var $selectFieldKey = $('select[name="field_key[' + col + ']"]');
3035 if ($selectFieldKey.val() === 'none_'+col) {
3036 $selectFieldKey.val('primary_'+col).change();
3041 .off('click', 'input.preview_sql')
3042 .on('click', 'input.preview_sql', function () {
3043 var $form = $(this).closest('form');
3044 PMA_previewSQL($form);
3050 * Validates the password field in a form
3052 * @see PMA_messages.strPasswordEmpty
3053 * @see PMA_messages.strPasswordNotSame
3054 * @param object $the_form The form to be validated
3057 function PMA_checkPassword($the_form)
3059 // Did the user select 'no password'?
3060 if ($the_form.find('#nopass_1').is(':checked')) {
3063 var $pred = $the_form.find('#select_pred_password');
3064 if ($pred.length && ($pred.val() == 'none' || $pred.val() == 'keep')) {
3069 var $password = $the_form.find('input[name=pma_pw]');
3070 var $password_repeat = $the_form.find('input[name=pma_pw2]');
3071 var alert_msg = false;
3073 if ($password.val() === '') {
3074 alert_msg = PMA_messages.strPasswordEmpty;
3075 } else if ($password.val() != $password_repeat.val()) {
3076 alert_msg = PMA_messages.strPasswordNotSame;
3082 $password_repeat.val('');
3090 * Unbind all event handlers before tearing down a page
3092 AJAX.registerTeardown('functions.js', function () {
3093 $(document).off('click', '#change_password_anchor.ajax');
3096 * Attach Ajax event handlers for 'Change Password' on index.php
3098 AJAX.registerOnload('functions.js', function () {
3100 /* Handler for hostname type */
3101 $(document).on('change', '#select_pred_hostname', function () {
3102 var hostname = $('#pma_hostname');
3103 if (this.value == 'any') {
3105 } else if (this.value == 'localhost') {
3106 hostname.val('localhost');
3107 } else if (this.value == 'thishost' && $(this).data('thishost')) {
3108 hostname.val($(this).data('thishost'));
3109 } else if (this.value == 'hosttable') {
3110 hostname.val('').prop('required', false);
3111 } else if (this.value == 'userdefined') {
3112 hostname.focus().select().prop('required', true);
3116 /* Handler for editing hostname */
3117 $(document).on('change', '#pma_hostname', function () {
3118 $('#select_pred_hostname').val('userdefined');
3119 $('#pma_hostname').prop('required', true);
3122 /* Handler for username type */
3123 $(document).on('change', '#select_pred_username', function () {
3124 if (this.value == 'any') {
3125 $('#pma_username').val('').prop('required', false);
3126 $('#user_exists_warning').css('display', 'none');
3127 } else if (this.value == 'userdefined') {
3128 $('#pma_username').focus().select().prop('required', true);
3132 /* Handler for editing username */
3133 $(document).on('change', '#pma_username', function () {
3134 $('#select_pred_username').val('userdefined');
3135 $('#pma_username').prop('required', true);
3138 /* Handler for password type */
3139 $(document).on('change', '#select_pred_password', function () {
3140 if (this.value == 'none') {
3141 $('#text_pma_pw2').prop('required', false).val('');
3142 $('#text_pma_pw').prop('required', false).val('');
3143 } else if (this.value == 'userdefined') {
3144 $('#text_pma_pw2').prop('required', true);
3145 $('#text_pma_pw').prop('required', true).focus().select();
3147 $('#text_pma_pw2').prop('required', false);
3148 $('#text_pma_pw').prop('required', false);
3152 /* Handler for editing password */
3153 $(document).on('change', '#text_pma_pw,#text_pma_pw2', function () {
3154 $('#select_pred_password').val('userdefined');
3155 $('#text_pma_pw2').prop('required', true);
3156 $('#text_pma_pw').prop('required', true);
3160 * Attach Ajax event handler on the change password anchor
3162 $(document).on('click', '#change_password_anchor.ajax', function (event) {
3163 event.preventDefault();
3165 var $msgbox = PMA_ajaxShowMessage();
3168 * @var button_options Object containing options to be passed to jQueryUI's dialog
3170 var button_options = {};
3171 button_options[PMA_messages.strGo] = function () {
3173 event.preventDefault();
3176 * @var $the_form Object referring to the change password form
3178 var $the_form = $("#change_password_form");
3180 if (! PMA_checkPassword($the_form)) {
3185 * @var this_value String containing the value of the submit button.
3186 * Need to append this for the change password form on Server Privileges
3189 var this_value = $(this).val();
3191 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
3192 $the_form.append('<input type="hidden" name="ajax_request" value="true" />');
3194 $.post($the_form.attr('action'), $the_form.serialize() + '&change_pw=' + this_value, function (data) {
3195 if (typeof data === 'undefined' || data.success !== true) {
3196 PMA_ajaxShowMessage(data.error, false);
3200 var $pageContent = $("#page_content");
3201 $pageContent.prepend(data.message);
3202 PMA_highlightSQL($pageContent);
3203 $("#change_password_dialog").hide().remove();
3204 $("#edit_user_dialog").dialog("close").remove();
3205 PMA_ajaxRemoveMessage($msgbox);
3209 button_options[PMA_messages.strCancel] = function () {
3210 $(this).dialog('close');
3212 $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
3213 if (typeof data === 'undefined' || !data.success) {
3214 PMA_ajaxShowMessage(data.error, false);
3218 if (data._scripts) {
3219 AJAX.scriptHandler.load(data._scripts);
3222 $('<div id="change_password_dialog"></div>')
3224 title: PMA_messages.strChangePassword,
3226 close: function (ev, ui) {
3229 buttons: button_options,
3232 .append(data.message);
3233 // for this dialog, we remove the fieldset wrapping due to double headings
3234 $("fieldset#fieldset_change_password")
3235 .find("legend").remove().end()
3236 .find("table.noclick").unwrap().addClass("some-margin")
3237 .find("input#text_pma_pw").focus();
3238 $('#fieldset_change_password_footer').hide();
3239 PMA_ajaxRemoveMessage($msgbox);
3240 $('#change_password_form').on('submit', function (e) {
3243 .closest('.ui-dialog')
3244 .find('.ui-dialog-buttonpane .ui-button')
3249 }); // end handler for change password anchor
3250 }); // end $() for Change Password
3253 * Unbind all event handlers before tearing down a page
3255 AJAX.registerTeardown('functions.js', function () {
3256 $(document).off('change', "select.column_type");
3257 $(document).off('change', "select.default_type");
3258 $(document).off('change', "select.virtuality");
3259 $(document).off('change', 'input.allow_null');
3260 $(document).off('change', '.create_table_form select[name=tbl_storage_engine]');
3263 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
3264 * the page loads and when the selected data type changes
3266 AJAX.registerOnload('functions.js', function () {
3267 // is called here for normal page loads and also when opening
3268 // the Create table dialog
3269 PMA_verifyColumnsProperties();
3271 // needs on() to work also in the Create Table dialog
3272 $(document).on('change', "select.column_type", function () {
3273 PMA_showNoticeForEnum($(this));
3275 $(document).on('change', "select.default_type", function () {
3276 PMA_hideShowDefaultValue($(this));
3278 $(document).on('change', "select.virtuality", function () {
3279 PMA_hideShowExpression($(this));
3281 $(document).on('change', 'input.allow_null', function () {
3282 PMA_validateDefaultValue($(this));
3284 $(document).on('change', '.create_table_form select[name=tbl_storage_engine]', function () {
3285 PMA_hideShowConnection($(this));
3290 * If the chosen storage engine is FEDERATED show connection field. Hide otherwise
3292 * @param $engine_selector storage engine selector
3294 function PMA_hideShowConnection($engine_selector)
3296 var $connection = $('.create_table_form input[name=connection]');
3297 var index = $connection.parent('td').index() + 1;
3298 var $labelTh = $connection.parents('tr').prev('tr').children('th:nth-child(' + index + ')');
3299 if ($engine_selector.val() != 'FEDERATED') {
3301 .prop('disabled', true)
3302 .parent('td').hide();
3306 .prop('disabled', false)
3307 .parent('td').show();
3313 * If the column does not allow NULL values, makes sure that default is not NULL
3315 function PMA_validateDefaultValue($null_checkbox)
3317 if (! $null_checkbox.prop('checked')) {
3318 var $default = $null_checkbox.closest('tr').find('.default_type');
3319 if ($default.val() == 'NULL') {
3320 $default.val('NONE');
3326 * function to populate the input fields on picking a column from central list
3328 * @param string input_id input id of the name field for the column to be populated
3329 * @param integer offset of the selected column in central list of columns
3331 function autoPopulate(input_id, offset)
3333 var db = PMA_commonParams.get('db');
3334 var table = PMA_commonParams.get('table');
3335 input_id = input_id.substring(0, input_id.length - 1);
3336 $('#' + input_id + '1').val(central_column_list[db + '_' + table][offset].col_name);
3337 var col_type = central_column_list[db + '_' + table][offset].col_type.toUpperCase();
3338 $('#' + input_id + '2').val(col_type);
3339 var $input3 = $('#' + input_id + '3');
3340 $input3.val(central_column_list[db + '_' + table][offset].col_length);
3341 if(col_type === 'ENUM' || col_type === 'SET') {
3342 $input3.next().show();
3344 $input3.next().hide();
3346 var col_default = central_column_list[db + '_' + table][offset].col_default.toUpperCase();
3347 var $input4 = $('#' + input_id + '4');
3348 if (col_default !== '' && col_default !== 'NULL' && col_default !== 'CURRENT_TIMESTAMP') {
3349 $input4.val("USER_DEFINED");
3350 $input4.next().next().show();
3351 $input4.next().next().val(central_column_list[db + '_' + table][offset].col_default);
3353 $input4.val(central_column_list[db + '_' + table][offset].col_default);
3354 $input4.next().next().hide();
3356 $('#' + input_id + '5').val(central_column_list[db + '_' + table][offset].col_collation);
3357 var $input6 = $('#' + input_id + '6');
3358 $input6.val(central_column_list[db + '_' + table][offset].col_attribute);
3359 if(central_column_list[db + '_' + table][offset].col_extra === 'on update CURRENT_TIMESTAMP') {
3360 $input6.val(central_column_list[db + '_' + table][offset].col_extra);
3362 if(central_column_list[db + '_' + table][offset].col_extra.toUpperCase() === 'AUTO_INCREMENT') {
3363 $('#' + input_id + '9').prop("checked",true).change();
3365 $('#' + input_id + '9').prop("checked",false);
3367 if(central_column_list[db + '_' + table][offset].col_isNull !== '0') {
3368 $('#' + input_id + '7').prop("checked",true);
3370 $('#' + input_id + '7').prop("checked",false);
3375 * Unbind all event handlers before tearing down a page
3377 AJAX.registerTeardown('functions.js', function () {
3378 $(document).off('click', "a.open_enum_editor");
3379 $(document).off('click', "input.add_value");
3380 $(document).off('click', "#enum_editor td.drop");
3381 $(document).off('click', 'a.central_columns_dialog');
3384 * @var $enum_editor_dialog An object that points to the jQuery
3385 * dialog of the ENUM/SET editor
3387 var $enum_editor_dialog = null;
3389 * Opens the ENUM/SET editor and controls its functions
3391 AJAX.registerOnload('functions.js', function () {
3392 $(document).on('click', "a.open_enum_editor", function () {
3393 // Get the name of the column that is being edited
3394 var colname = $(this).closest('tr').find('input:first').val();
3397 // And use it to make up a title for the page
3398 if (colname.length < 1) {
3399 title = PMA_messages.enum_newColumnVals;
3401 title = PMA_messages.enum_columnVals.replace(
3403 '"' + escapeHtml(decodeURIComponent(colname)) + '"'
3406 // Get the values as a string
3407 var inputstring = $(this)
3411 // Escape html entities
3412 inputstring = $('<div/>')
3415 // Parse the values, escaping quotes and
3416 // slashes on the fly, into an array
3418 var in_string = false;
3419 var curr, next, buffer = '';
3420 for (i = 0; i < inputstring.length; i++) {
3421 curr = inputstring.charAt(i);
3422 next = i == inputstring.length ? '' : inputstring.charAt(i + 1);
3423 if (! in_string && curr == "'") {
3425 } else if (in_string && curr == "\\" && next == "\\") {
3428 } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
3431 } else if (in_string && curr == "'") {
3433 values.push(buffer);
3435 } else if (in_string) {
3439 if (buffer.length > 0) {
3440 // The leftovers in the buffer are the last value (if any)
3441 values.push(buffer);
3444 // If there are no values, maybe the user is about to make a
3445 // new list so we add a few for him/her to get started with.
3446 if (values.length === 0) {
3447 values.push('', '', '', '');
3449 // Add the parsed values to the editor
3450 var drop_icon = PMA_getImage('b_drop.png');
3451 for (i = 0; i < values.length; i++) {
3452 fields += "<tr><td>" +
3453 "<input type='text' value='" + values[i] + "'/>" +
3454 "</td><td class='drop'>" +
3459 * @var dialog HTML code for the ENUM/SET dialog
3461 var dialog = "<div id='enum_editor'>" +
3463 "<legend>" + title + "</legend>" +
3464 "<p>" + PMA_getImage('s_notice.png') +
3465 PMA_messages.enum_hint + "</p>" +
3466 "<table class='values'>" + fields + "</table>" +
3467 "</fieldset><fieldset class='tblFooters'>" +
3468 "<table class='add'><tr><td>" +
3469 "<div class='slider'></div>" +
3471 "<form><div><input type='submit' class='add_value' value='" +
3472 PMA_sprintf(PMA_messages.enum_addValue, 1) +
3473 "'/></div></form>" +
3474 "</td></tr></table>" +
3475 "<input type='hidden' value='" + // So we know which column's data is being edited
3476 $(this).closest('td').find("input").attr("id") +
3481 * @var Defines functions to be called when the buttons in
3482 * the buttonOptions jQuery dialog bar are pressed
3484 var buttonOptions = {};
3485 buttonOptions[PMA_messages.strGo] = function () {
3486 // When the submit button is clicked,
3487 // put the data back into the original form
3488 var value_array = [];
3489 $(this).find(".values input").each(function (index, elm) {
3490 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
3491 value_array.push("'" + val + "'");
3493 // get the Length/Values text field where this value belongs
3494 var values_id = $(this).find("input[type='hidden']").val();
3495 $("input#" + values_id).val(value_array.join(","));
3496 $(this).dialog("close");
3498 buttonOptions[PMA_messages.strClose] = function () {
3499 $(this).dialog("close");
3502 var width = parseInt(
3503 (parseInt($('html').css('font-size'), 10) / 13) * 340,
3509 $enum_editor_dialog = $(dialog).dialog({
3513 title: PMA_messages.enum_editor,
3514 buttons: buttonOptions,
3516 // Focus the "Go" button after opening the dialog
3517 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3519 close: function () {
3523 // slider for choosing how many fields to add
3524 $enum_editor_dialog.find(".slider").slider({
3530 slide: function (event, ui) {
3531 $(this).closest('table').find('input[type=submit]').val(
3532 PMA_sprintf(PMA_messages.enum_addValue, ui.value)
3536 // Focus the slider, otherwise it looks nearly transparent
3537 $('a.ui-slider-handle').addClass('ui-state-focus');
3541 $(document).on('click', 'a.central_columns_dialog', function (e) {
3542 var href = "db_central_columns.php";
3543 var db = PMA_commonParams.get('db');
3544 var table = PMA_commonParams.get('table');
3545 var maxRows = $(this).data('maxrows');
3546 var pick = $(this).data('pick');
3547 if (pick !== false) {
3551 'ajax_request' : true,
3552 'token' : PMA_commonParams.get('token'),
3553 'server' : PMA_commonParams.get('server'),
3554 'db' : PMA_commonParams.get('db'),
3555 'cur_table' : PMA_commonParams.get('table'),
3556 'getColumnList':true
3558 var colid = $(this).closest('td').find("input").attr("id");
3560 if (! (db + '_' + table in central_column_list)) {
3561 central_column_list.push(db + '_' + table);
3566 success: function (data) {
3567 central_column_list[db + '_' + table] = JSON.parse(data.message);
3573 var list_size = central_column_list[db + '_' + table].length;
3574 var min = (list_size <= maxRows) ? list_size : maxRows;
3575 for (i = 0; i < min; i++) {
3577 fields += '<tr><td><div><span style="font-weight:bold">' +
3578 escapeHtml(central_column_list[db + '_' + table][i].col_name) +
3579 '</span><br><span style="color:gray">' + central_column_list[db + '_' + table][i].col_type;
3581 if (central_column_list[db + '_' + table][i].col_attribute !== '') {
3582 fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_attribute) + ') ';
3584 if (central_column_list[db + '_' + table][i].col_length !== '') {
3585 fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_length) +') ';
3587 fields += escapeHtml(central_column_list[db + '_' + table][i].col_extra) + '</span>' +
3590 fields += '<td><input class="pick" style="width:100%" type="submit" value="' +
3591 PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3595 var result_pointer = i;
3596 var search_in = '<input type="text" class="filter_rows" placeholder="' + PMA_messages.searchList + '">';
3597 if (fields === '') {
3598 fields = PMA_sprintf(PMA_messages.strEmptyCentralList, "'" + escapeHtml(db) + "'");
3602 if (list_size > maxRows) {
3603 seeMore = "<fieldset class='tblFooters' style='text-align:center;font-weight:bold'>" +
3604 "<a href='#' id='seeMore'>" + PMA_messages.seeMore + "</a></fieldset>";
3606 var central_columns_dialog = "<div style='max-height:400px'>" +
3609 "<table id='col_list' style='width:100%' class='values'>" + fields + "</table>" +
3614 var width = parseInt(
3615 (parseInt($('html').css('font-size'), 10) / 13) * 500,
3621 var buttonOptions = {};
3622 var $central_columns_dialog = $(central_columns_dialog).dialog({
3626 title: PMA_messages.pickColumnTitle,
3627 buttons: buttonOptions,
3629 $('#col_list').on("click", ".pick", function (){
3630 $central_columns_dialog.remove();
3632 $(".filter_rows").on("keyup", function () {
3633 $.uiTableFilter($("#col_list"), $(this).val());
3635 $("#seeMore").click(function() {
3637 min = (list_size <= maxRows + result_pointer) ? list_size : maxRows + result_pointer;
3638 for (i = result_pointer; i < min; i++) {
3640 fields += '<tr><td><div><span style="font-weight:bold">' +
3641 central_column_list[db + '_' + table][i].col_name +
3642 '</span><br><span style="color:gray">' +
3643 central_column_list[db + '_' + table][i].col_type;
3645 if (central_column_list[db + '_' + table][i].col_attribute !== '') {
3646 fields += '(' + central_column_list[db + '_' + table][i].col_attribute + ') ';
3648 if (central_column_list[db + '_' + table][i].col_length !== '') {
3649 fields += '(' + central_column_list[db + '_' + table][i].col_length + ') ';
3651 fields += central_column_list[db + '_' + table][i].col_extra + '</span>' +
3654 fields += '<td><input class="pick" style="width:100%" type="submit" value="' +
3655 PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3659 $("#col_list").append(fields);
3661 if (result_pointer === list_size) {
3662 $('.tblFooters').hide();
3666 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3668 close: function () {
3669 $('#col_list').off("click", ".pick");
3670 $(".filter_rows").off("keyup");
3677 // $(document).on('click', 'a.show_central_list',function(e) {
3680 // When "add a new value" is clicked, append an empty text field
3681 $(document).on('click', "input.add_value", function (e) {
3683 var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
3684 while (num_new_rows--) {
3685 $enum_editor_dialog.find('.values')
3687 "<tr style='display: none;'><td>" +
3688 "<input type='text' />" +
3689 "</td><td class='drop'>" +
3690 PMA_getImage('b_drop.png') +
3698 // Removes the specified row from the enum editor
3699 $(document).on('click', "#enum_editor td.drop", function () {
3700 $(this).closest('tr').hide('fast', function () {
3707 * Ensures indexes names are valid according to their type and, for a primary
3708 * key, lock index name to 'PRIMARY'
3709 * @param string form_id Variable which parses the form name as
3711 * @return boolean false if there is no index form, true else
3713 function checkIndexName(form_id)
3715 if ($("#" + form_id).length === 0) {
3719 // Gets the elements pointers
3720 var $the_idx_name = $("#input_index_name");
3721 var $the_idx_choice = $("#select_index_choice");
3723 // Index is a primary key
3724 if ($the_idx_choice.find("option:selected").val() == 'PRIMARY') {
3725 $the_idx_name.val('PRIMARY');
3726 $the_idx_name.prop("disabled", true);
3731 if ($the_idx_name.val() == 'PRIMARY') {
3732 $the_idx_name.val("");
3734 $the_idx_name.prop("disabled", false);
3738 } // end of the 'checkIndexName()' function
3740 AJAX.registerTeardown('functions.js', function () {
3741 $(document).off('click', '#index_frm input[type=submit]');
3743 AJAX.registerOnload('functions.js', function () {
3745 * Handler for adding more columns to an index in the editor
3747 $(document).on('click', '#index_frm input[type=submit]', function (event) {
3748 event.preventDefault();
3749 var rows_to_add = $(this)
3750 .closest('fieldset')
3754 var tempEmptyVal = function () {
3758 var tempSetFocus = function () {
3759 if ($(this).find("option:selected").val() === '') {
3762 $(this).closest("tr").find("input").focus();
3765 while (rows_to_add--) {
3766 var $indexColumns = $('#index_columns');
3767 var $newrow = $indexColumns
3768 .find('tbody > tr:first')
3771 $indexColumns.find('tbody')
3773 $newrow.find(':input').each(tempEmptyVal);
3774 // focus index size input on column picked
3775 $newrow.find('select').change(tempSetFocus);
3780 function indexEditorDialog(url, title, callback_success, callback_failure)
3782 /*Remove the hidden dialogs if there are*/
3783 var $editIndexDialog = $('#edit_index_dialog');
3784 if ($editIndexDialog.length !== 0) {
3785 $editIndexDialog.remove();
3787 var $div = $('<div id="edit_index_dialog"></div>');
3790 * @var button_options Object that stores the options
3791 * passed to jQueryUI dialog
3793 var button_options = {};
3794 button_options[PMA_messages.strGo] = function () {
3796 * @var the_form object referring to the export form
3798 var $form = $("#index_frm");
3799 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
3800 PMA_prepareForAjaxRequest($form);
3801 //User wants to submit the form
3802 $.post($form.attr('action'), $form.serialize() + "&do_save_data=1", function (data) {
3803 var $sqlqueryresults = $(".sqlqueryresults");
3804 if ($sqlqueryresults.length !== 0) {
3805 $sqlqueryresults.remove();
3807 if (typeof data !== 'undefined' && data.success === true) {
3808 PMA_ajaxShowMessage(data.message);
3809 var $resultQuery = $('.result_query');
3810 if ($resultQuery.length) {
3811 $resultQuery.remove();
3813 if (data.sql_query) {
3814 $('<div class="result_query"></div>')
3815 .html(data.sql_query)
3816 .prependTo('#page_content');
3817 PMA_highlightSQL($('#page_content'));
3819 $(".result_query .notice").remove();
3820 $resultQuery.prepend(data.message);
3821 /*Reload the field form*/
3822 $("#table_index").remove();
3823 $("<div id='temp_div'><div>")
3824 .append(data.index_table)
3825 .find("#table_index")
3826 .insertAfter("#index_header");
3827 var $editIndexDialog = $("#edit_index_dialog");
3828 if ($editIndexDialog.length > 0) {
3829 $editIndexDialog.dialog("close");
3831 $('div.no_indexes_defined').hide();
3832 if (callback_success) {
3835 PMA_reloadNavigation();
3837 var $temp_div = $("<div id='temp_div'><div>").append(data.error);
3839 if ($temp_div.find(".error code").length !== 0) {
3840 $error = $temp_div.find(".error code").addClass("error");
3844 if (callback_failure) {
3847 PMA_ajaxShowMessage($error, false);
3851 button_options[PMA_messages.strPreviewSQL] = function () {
3852 // Function for Previewing SQL
3853 var $form = $('#index_frm');
3854 PMA_previewSQL($form);
3856 button_options[PMA_messages.strCancel] = function () {
3857 $(this).dialog('close');
3859 var $msgbox = PMA_ajaxShowMessage();
3860 $.get("tbl_indexes.php", url, function (data) {
3861 if (typeof data !== 'undefined' && data.success === false) {
3862 //in the case of an error, show the error message returned.
3863 PMA_ajaxShowMessage(data.error, false);
3865 PMA_ajaxRemoveMessage($msgbox);
3866 // Show dialog if the request was successful
3868 .append(data.message)
3873 open: PMA_verifyColumnsProperties,
3875 buttons: button_options,
3876 close: function () {
3880 $div.find('.tblFooters').remove();
3881 showIndexEditDialog($div);
3886 function showIndexEditDialog($outer)
3889 checkIndexName("index_frm");
3890 var $indexColumns = $('#index_columns');
3891 $indexColumns.find('td').each(function () {
3892 $(this).css("width", $(this).width() + 'px');
3894 $indexColumns.find('tbody').sortable({
3896 containment: $indexColumns.find("tbody"),
3897 tolerance: 'pointer'
3899 PMA_showHints($outer);
3901 // Add a slider for selecting how many columns to add to the index
3902 $outer.find('.slider').slider({
3907 slide: function (event, ui) {
3908 $(this).closest('fieldset').find('input[type=submit]').val(
3909 PMA_sprintf(PMA_messages.strAddToIndex, ui.value)
3913 $('div.add_fields').removeClass('hide');
3914 // focus index size input on column picked
3915 $outer.find('table#index_columns select').change(function () {
3916 if ($(this).find("option:selected").val() === '') {
3919 $(this).closest("tr").find("input").focus();
3921 // Focus the slider, otherwise it looks nearly transparent
3922 $('a.ui-slider-handle').addClass('ui-state-focus');
3923 // set focus on index name input, if empty
3924 var input = $outer.find('input#input_index_name');
3925 if (! input.val()) {
3931 * Function to display tooltips that were
3932 * generated on the PHP side by PMA\libraries\Util::showHint()
3934 * @param object $div a div jquery object which specifies the
3935 * domain for searching for tooltips. If we
3936 * omit this parameter the function searches
3939 function PMA_showHints($div)
3941 if ($div === undefined || ! $div instanceof jQuery || $div.length === 0) {
3944 $div.find('.pma_hint').each(function () {
3946 $(this).children('img'),
3948 $(this).children('span').html()
3953 AJAX.registerOnload('functions.js', function () {
3957 function PMA_mainMenuResizerCallback() {
3958 // 5 px margin for jumping menu in Chrome
3959 return $(document.body).width() - 5;
3961 // This must be fired only once after the initial page load
3963 // Initialise the menu resize plugin
3964 $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
3965 // register resize event
3966 $(window).resize(function () {
3967 $('#topmenu').menuResizer('resize');
3972 * Get the row number from the classlist (for example, row_1)
3974 function PMA_getRowNumber(classlist)
3976 return parseInt(classlist.split(/\s+row_/)[1], 10);
3980 * Changes status of slider
3982 function PMA_set_status_label($element)
3985 if ($element.css('display') == 'none') {
3990 $element.closest('.slide-wrapper').prev().find('span').text(text);
3994 * var toggleButton This is a function that creates a toggle
3995 * sliding button given a jQuery reference
3996 * to the correct DOM element
3998 var toggleButton = function ($obj) {
3999 // In rtl mode the toggle switch is flipped horizontally
4000 // so we need to take that into account
4002 if ($('span.text_direction', $obj).text() == 'ltr') {
4008 * var h Height of the button, used to scale the
4009 * background image and position the layers
4011 var h = $obj.height();
4012 $('img', $obj).height(h);
4013 $('table', $obj).css('bottom', h - 1);
4015 * var on Width of the "ON" part of the toggle switch
4016 * var off Width of the "OFF" part of the toggle switch
4018 var on = $('td.toggleOn', $obj).width();
4019 var off = $('td.toggleOff', $obj).width();
4020 // Make the "ON" and "OFF" parts of the switch the same size
4021 // + 2 pixels to avoid overflowed
4022 $('td.toggleOn > div', $obj).width(Math.max(on, off) + 2);
4023 $('td.toggleOff > div', $obj).width(Math.max(on, off) + 2);
4025 * var w Width of the central part of the switch
4027 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
4028 // Resize the central part of the switch on the top
4029 // layer to match the background
4030 $('table td:nth-child(2) > div', $obj).width(w);
4032 * var imgw Width of the background image
4033 * var tblw Width of the foreground layer
4034 * var offset By how many pixels to move the background
4035 * image, so that it matches the top layer
4037 var imgw = $('img', $obj).width();
4038 var tblw = $('table', $obj).width();
4039 var offset = parseInt(((imgw - tblw) / 2), 10);
4040 // Move the background to match the layout of the top layer
4041 $obj.find('img').css(right, offset);
4043 * var offw Outer width of the "ON" part of the toggle switch
4044 * var btnw Outer width of the central part of the switch
4046 var offw = $('td.toggleOff', $obj).outerWidth();
4047 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
4048 // Resize the main div so that exactly one side of
4049 // the switch plus the central part fit into it.
4050 $obj.width(offw + btnw + 2);
4052 * var move How many pixels to move the
4053 * switch by when toggling
4055 var move = $('td.toggleOff', $obj).outerWidth();
4056 // If the switch is initialized to the
4057 // OFF state we need to move it now.
4058 if ($('div.container', $obj).hasClass('off')) {
4059 if (right == 'right') {
4060 $('div.container', $obj).animate({'left': '-=' + move + 'px'}, 0);
4062 $('div.container', $obj).animate({'left': '+=' + move + 'px'}, 0);
4065 // Attach an 'onclick' event to the switch
4066 $('div.container', $obj).click(function () {
4067 if ($(this).hasClass('isActive')) {
4070 $(this).addClass('isActive');
4072 var $msg = PMA_ajaxShowMessage();
4073 var $container = $(this);
4074 var callback = $('span.callback', this).text();
4075 var operator, url, removeClass, addClass;
4076 // Perform the actual toggle
4077 if ($(this).hasClass('on')) {
4078 if (right == 'right') {
4083 url = $(this).find('td.toggleOff > span').text();
4087 if (right == 'right') {
4092 url = $(this).find('td.toggleOn > span').text();
4093 removeClass = 'off';
4097 var params = {'ajax_request': true, 'token': PMA_commonParams.get('token')};
4098 $.post(url, params, function (data) {
4099 if (typeof data !== 'undefined' && data.success === true) {
4100 PMA_ajaxRemoveMessage($msg);
4102 .removeClass(removeClass)
4104 .animate({'left': operator + move + 'px'}, function () {
4105 $container.removeClass('isActive');
4109 PMA_ajaxShowMessage(data.error, false);
4110 $container.removeClass('isActive');
4117 * Unbind all event handlers before tearing down a page
4119 AJAX.registerTeardown('functions.js', function () {
4120 $('div.container').off('click');
4123 * Initialise all toggle buttons
4125 AJAX.registerOnload('functions.js', function () {
4126 $('div.toggleAjax').each(function () {
4127 var $button = $(this).show();
4128 $button.find('img').each(function () {
4129 if (this.complete) {
4130 toggleButton($button);
4132 $(this).load(function () {
4133 toggleButton($button);
4141 * Unbind all event handlers before tearing down a page
4143 AJAX.registerTeardown('functions.js', function () {
4144 $(document).off('change', 'select.pageselector');
4145 $(document).off('click', 'a.formLinkSubmit');
4146 $('#update_recent_tables').off('ready');
4147 $('#sync_favorite_tables').off('ready');
4150 AJAX.registerOnload('functions.js', function () {
4153 * Autosubmit page selector
4155 $(document).on('change', 'select.pageselector', function (event) {
4156 event.stopPropagation();
4157 // Check where to load the new content
4158 if ($(this).closest("#pma_navigation").length === 0) {
4159 // For the main page we don't need to do anything,
4160 $(this).closest("form").submit();
4162 // but for the navigation we need to manually replace the content
4163 PMA_navigationTreePagination($(this));
4168 * Load version information asynchronously.
4170 if ($('li.jsversioncheck').length > 0) {
4173 url: 'version_check.php',
4176 "server": PMA_commonParams.get('server'),
4177 "token": PMA_commonParams.get('token'),
4179 success: PMA_current_version
4183 if ($('#is_git_revision').length > 0) {
4184 setTimeout(PMA_display_git_revision, 10);
4193 * Enables the text generated by PMA\libraries\Util::linkOrButton() to be clickable
4195 $(document).on('click', 'a.formLinkSubmit', function (e) {
4196 if (! $(this).hasClass('requireConfirm')) {
4197 submitFormLink($(this));
4202 var $updateRecentTables = $('#update_recent_tables');
4203 if ($updateRecentTables.length) {
4205 $updateRecentTables.attr('href'),
4208 if (typeof data !== 'undefined' && data.success === true) {
4209 $('#pma_recent_list').html(data.list);
4215 // Sync favorite tables from localStorage to pmadb.
4216 if ($('#sync_favorite_tables').length) {
4218 url: $('#sync_favorite_tables').attr("href"),
4222 favorite_tables: (isStorageSupported('localStorage') && typeof window.localStorage.favorite_tables !== 'undefined')
4223 ? window.localStorage.favorite_tables
4225 token: PMA_commonParams.get('token'),
4226 server: PMA_commonParams.get('server'),
4229 success: function (data) {
4230 // Update localStorage.
4231 if (isStorageSupported('localStorage')) {
4232 window.localStorage.favorite_tables = data.favorite_tables;
4234 $('#pma_favorite_list').html(data.list);
4241 * Submits the form placed in place of a link due to the excessive url length
4243 * @param $link anchor
4244 * @returns {Boolean}
4246 function submitFormLink($link)
4248 if ($link.attr('href').indexOf('=') != -1) {
4249 var data = $link.attr('href').substr($link.attr('href').indexOf('#') + 1).split('=', 2);
4250 $link.parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
4252 $link.parents('form').submit();
4256 * Initializes slider effect.
4258 function PMA_init_slider()
4260 $('div.pma_auto_slider').each(function () {
4261 var $this = $(this);
4262 if ($this.data('slider_init_done')) {
4265 var $wrapper = $('<div>', {'class': 'slide-wrapper'});
4266 $wrapper.toggle($this.is(':visible'));
4267 $('<a>', {href: '#' + this.id, "class": 'ajax'})
4268 .text($this.attr('title'))
4269 .prepend($('<span>'))
4270 .insertBefore($this)
4271 .click(function () {
4272 var $wrapper = $this.closest('.slide-wrapper');
4273 var visible = $this.is(':visible');
4277 $this[visible ? 'hide' : 'show']('blind', function () {
4278 $wrapper.toggle(!visible);
4279 $wrapper.parent().toggleClass("print_ignore", visible);
4280 PMA_set_status_label($this);
4284 $this.wrap($wrapper);
4285 $this.removeAttr('title');
4286 PMA_set_status_label($this);
4287 $this.data('slider_init_done', 1);
4292 * Initializes slider effect.
4294 AJAX.registerOnload('functions.js', function () {
4299 * Restores sliders to the state they were in before initialisation.
4301 AJAX.registerTeardown('functions.js', function () {
4302 $('div.pma_auto_slider').each(function () {
4303 var $this = $(this);
4305 $this.parent().replaceWith($this);
4306 $this.parent().children('a').remove();
4311 * Creates a message inside an object with a sliding effect
4313 * @param msg A string containing the text to display
4314 * @param $obj a jQuery object containing the reference
4315 * to the element where to put the message
4316 * This is optional, if no element is
4317 * provided, one will be created below the
4318 * navigation links at the top of the page
4320 * @return bool True on success, false on failure
4322 function PMA_slidingMessage(msg, $obj)
4324 if (msg === undefined || msg.length === 0) {
4325 // Don't show an empty message
4328 if ($obj === undefined || ! $obj instanceof jQuery || $obj.length === 0) {
4329 // If the second argument was not supplied,
4330 // we might have to create a new DOM node.
4331 if ($('#PMA_slidingMessage').length === 0) {
4332 $('#page_content').prepend(
4333 '<span id="PMA_slidingMessage" ' +
4334 'style="display: inline-block;"></span>'
4337 $obj = $('#PMA_slidingMessage');
4339 if ($obj.has('div').length > 0) {
4340 // If there already is a message inside the
4341 // target object, we must get rid of it
4345 .fadeOut(function () {
4350 .append('<div>' + msg + '</div>');
4351 // highlight any sql before taking height;
4352 PMA_highlightSQL($obj);
4358 height: $obj.find('div').first().height()
4365 // Object does not already have a message
4366 // inside it, so we simply slide it down
4368 .html('<div>' + msg + '</div>');
4369 // highlight any sql before taking height;
4370 PMA_highlightSQL($obj);
4384 // Set the height of the parent
4385 // to the height of the child
4396 } // end PMA_slidingMessage()
4399 * Attach CodeMirror2 editor to SQL edit area.
4401 AJAX.registerOnload('functions.js', function () {
4402 var $elm = $('#sqlquery');
4403 if ($elm.length > 0) {
4404 if (typeof CodeMirror != 'undefined') {
4405 codemirror_editor = PMA_getSQLEditor($elm);
4406 codemirror_editor.focus();
4407 codemirror_editor.on("blur", updateQueryParameters);
4409 // without codemirror
4410 $elm.focus().on('blur', updateQueryParameters);
4413 PMA_highlightSQL($('body'));
4415 AJAX.registerTeardown('functions.js', function () {
4416 if (codemirror_editor) {
4417 $('#sqlquery').text(codemirror_editor.getValue());
4418 codemirror_editor.toTextArea();
4419 codemirror_editor = false;
4422 AJAX.registerOnload('functions.js', function () {
4423 // initializes all lock-page elements lock-id and
4424 // val-hash data property
4425 $('#page_content form.lock-page textarea, ' +
4426 '#page_content form.lock-page input[type="text"], '+
4427 '#page_content form.lock-page input[type="number"], '+
4428 '#page_content form.lock-page select').each(function (i) {
4429 $(this).data('lock-id', i);
4430 // val-hash is the hash of default value of the field
4431 // so that it can be compared with new value hash
4432 // to check whether field was modified or not.
4433 $(this).data('val-hash', AJAX.hash($(this).val()));
4436 // initializes lock-page elements (input types checkbox and radio buttons)
4437 // lock-id and val-hash data property
4438 $('#page_content form.lock-page input[type="checkbox"], ' +
4439 '#page_content form.lock-page input[type="radio"]').each(function (i) {
4440 $(this).data('lock-id', i);
4441 $(this).data('val-hash', AJAX.hash($(this).is(":checked")));
4446 * jQuery plugin to correctly filter input fields by value, needed
4447 * because some nasty values may break selector syntax
4450 $.fn.filterByValue = function (value) {
4451 return this.filter(function () {
4452 return $(this).val() === value;
4458 * Return value of a cell in a table.
4460 function PMA_getCellValue(td) {
4462 if ($td.is('.null')) {
4464 } else if ((! $td.is('.to_be_saved')
4466 && $td.data('original_data')
4468 return $td.data('original_data');
4474 $(window).on('popstate', function (event, data) {
4475 $('#printcss').attr('media','print');
4480 * Unbind all event handlers before tearing down a page
4482 AJAX.registerTeardown('functions.js', function () {
4483 $(document).off('click', 'a.themeselect');
4484 $(document).off('change', '.autosubmit');
4485 $('a.take_theme').off('click');
4488 AJAX.registerOnload('functions.js', function () {
4492 $(document).on('click', 'a.themeselect', function (e) {
4496 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
4502 * Automatic form submission on change.
4504 $(document).on('change', '.autosubmit', function (e) {
4505 $(this).closest('form').submit();
4511 $('a.take_theme').click(function (e) {
4512 var what = this.name;
4513 if (window.opener && window.opener.document.forms.setTheme.elements.set_theme) {
4514 window.opener.document.forms.setTheme.elements.set_theme.value = what;
4515 window.opener.document.forms.setTheme.submit();
4524 * Produce print preview
4526 function printPreview()
4528 $('#printcss').attr('media','all');
4529 createPrintAndBackButtons();
4533 * Create print and back buttons in preview page
4535 function createPrintAndBackButtons() {
4537 var back_button = $("<input/>",{
4539 value: PMA_messages.back,
4540 id: 'back_button_print_view'
4542 back_button.click(removePrintAndBackButton);
4543 back_button.appendTo('#page_content');
4544 var print_button = $("<input/>",{
4546 value: PMA_messages.print,
4547 id: 'print_button_print_view'
4549 print_button.click(printPage);
4550 print_button.appendTo('#page_content');
4554 * Remove print and back buttons and revert to normal view
4556 function removePrintAndBackButton(){
4557 $('#printcss').attr('media','print');
4558 $('#back_button_print_view').remove();
4559 $('#print_button_print_view').remove();
4565 function printPage(){
4566 if (typeof(window.print) != 'undefined') {
4574 function copyToClipboard()
4576 var textArea = document.createElement("textarea");
4579 // *** This styling is an extra step which is likely not required. ***
4581 // Why is it here? To ensure:
4582 // 1. the element is able to have focus and selection.
4583 // 2. if element was to flash render it has minimal visual impact.
4584 // 3. less flakyness with selection and copying which **might** occur if
4585 // the textarea element is not visible.
4587 // The likelihood is the element won't even render, not even a flash,
4588 // so some of these are just precautions. However in IE the element
4589 // is visible whilst the popup box asking the user for permission for
4590 // the web page to copy to the clipboard.
4593 // Place in top-left corner of screen regardless of scroll position.
4594 textArea.style.position = 'fixed';
4595 textArea.style.top = 0;
4596 textArea.style.left = 0;
4598 // Ensure it has a small width and height. Setting to 1px / 1em
4599 // doesn't work as this gives a negative w/h on some browsers.
4600 textArea.style.width = '2em';
4601 textArea.style.height = '2em';
4603 // We don't need padding, reducing the size if it does flash render.
4604 textArea.style.padding = 0;
4606 // Clean up any borders.
4607 textArea.style.border = 'none';
4608 textArea.style.outline = 'none';
4609 textArea.style.boxShadow = 'none';
4611 // Avoid flash of white box if rendered for any reason.
4612 textArea.style.background = 'transparent';
4614 textArea.value = '';
4616 var elementList = $('#serverinfo a');
4618 elementList.each(function(){
4619 textArea.value += $(this).text().split(':')[1].trim() + '/';
4621 textArea.value += '\t\t' + window.location.href;
4622 textArea.value += '\n';
4624 elementList = $('.notice,.success');
4626 elementList.each(function(){
4627 textArea.value += $(this).clone().children().remove().end().text() + '\n\n';
4630 elementList = $('.sql pre');
4632 elementList.each(function() {
4633 textArea.value += $(this).text() + '\n\n';
4636 elementList = $('.table_results .column_heading a');
4638 elementList.each(function() {
4639 textArea.value += $(this).clone().children().remove().end().text() + '\t';
4642 textArea.value += '\n';
4643 elementList = $('tbody tr');
4644 elementList.each(function() {
4645 var childElementList = $(this).find('.data span');
4646 childElementList.each(function(){
4647 textArea.value += $(this).clone().children().remove().end().text() + '\t';
4649 textArea.value += '\n';
4652 document.body.appendChild(textArea);
4657 document.execCommand('copy');
4659 alert('Sorry! Unable to copy');
4662 document.body.removeChild(textArea);
4666 * Unbind all event handlers before tearing down a page
4668 AJAX.registerTeardown('functions.js', function () {
4669 $('input#print').off('click');
4670 $(document).off('click', 'a.create_view.ajax');
4671 $(document).off('keydown', '#createViewDialog input, #createViewDialog select');
4672 $(document).off('change', '#fkc_checkbox');
4675 AJAX.registerOnload('functions.js', function () {
4676 $('input#print').click(printPage);
4677 $('.logout').click(function() {
4679 '<form method="POST" action="' + $(this).attr('href') + '" class="disableAjax">' +
4680 '<input type="hidden" name="token" value="' + PMA_commonParams.get('token') + '"/>' +
4683 $('body').append(form);
4688 * Ajaxification for the "Create View" action
4690 $(document).on('click', 'a.create_view.ajax', function (e) {
4692 PMA_createViewDialog($(this));
4695 * Attach Ajax event handlers for input fields in the editor
4696 * and used to submit the Ajax request when the ENTER key is pressed.
4698 if ($('#createViewDialog').length !== 0) {
4699 $(document).on('keydown', '#createViewDialog input, #createViewDialog select', function (e) {
4700 if (e.which === 13) { // 13 is the ENTER key
4703 // with preventing default, selection by <select> tag
4704 // was also prevented in IE
4707 $(this).closest('.ui-dialog').find('.ui-button:first').click();
4709 }); // end $(document).on()
4712 syntaxHighlighter = PMA_getSQLEditor($('textarea[name="view[as]"]'));
4716 function PMA_createViewDialog($this)
4718 var $msg = PMA_ajaxShowMessage();
4719 var syntaxHighlighter = null;
4720 $.get($this.attr('href') + '&ajax_request=1&ajax_dialog=1', function (data) {
4721 if (typeof data !== 'undefined' && data.success === true) {
4722 PMA_ajaxRemoveMessage($msg);
4723 var buttonOptions = {};
4724 buttonOptions[PMA_messages.strGo] = function () {
4725 if (typeof CodeMirror !== 'undefined') {
4726 syntaxHighlighter.save();
4728 $msg = PMA_ajaxShowMessage();
4729 $.post('view_create.php', $('#createViewDialog').find('form').serialize(), function (data) {
4730 PMA_ajaxRemoveMessage($msg);
4731 if (typeof data !== 'undefined' && data.success === true) {
4732 $('#createViewDialog').dialog("close");
4733 $('.result_query').html(data.message);
4734 PMA_reloadNavigation();
4736 PMA_ajaxShowMessage(data.error, false);
4740 buttonOptions[PMA_messages.strClose] = function () {
4741 $(this).dialog("close");
4743 var $dialog = $('<div/>').attr('id', 'createViewDialog').append(data.message).dialog({
4747 buttons: buttonOptions,
4748 title: PMA_messages.strCreateView,
4749 close: function () {
4753 // Attach syntax highlighted editor
4754 syntaxHighlighter = PMA_getSQLEditor($dialog.find('textarea'));
4755 $('input:visible[type=text]', $dialog).first().focus();
4757 PMA_ajaxShowMessage(data.error);
4763 * Makes the breadcrumbs and the menu bar float at the top of the viewport
4766 if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length === 0) {
4767 var left = $('html').attr('dir') == 'ltr' ? 'left' : 'right';
4768 $("#floating_menubar")
4769 .css('margin-' + left, $('#pma_navigation').width() + $('#pma_navigation_resizer').width())
4772 'position': 'fixed',
4777 .append($('#serverinfo'))
4778 .append($('#topmenucontainer'));
4779 // Allow the DOM to render, then adjust the padding on the body
4780 setTimeout(function () {
4783 $('#floating_menubar').outerHeight(true)
4785 $('#topmenu').menuResizer('resize');
4791 * Scrolls the page to the top if clicking the serverinfo bar
4794 $(document).on("click", "#serverinfo, #goto_pagetop", function (event) {
4795 event.preventDefault();
4796 $('html, body').animate({scrollTop: 0}, 'fast');
4800 var checkboxes_sel = "input.checkall:checkbox:enabled";
4802 * Watches checkboxes in a form to set the checkall box accordingly
4804 var checkboxes_changed = function () {
4805 var $form = $(this.form);
4806 // total number of checkboxes in current form
4807 var total_boxes = $form.find(checkboxes_sel).length;
4808 // number of checkboxes checked in current form
4809 var checked_boxes = $form.find(checkboxes_sel + ":checked").length;
4810 var $checkall = $form.find("input.checkall_box");
4811 if (total_boxes == checked_boxes) {
4812 $checkall.prop({checked: true, indeterminate: false});
4814 else if (checked_boxes > 0) {
4815 $checkall.prop({checked: true, indeterminate: true});
4818 $checkall.prop({checked: false, indeterminate: false});
4821 $(document).on("change", checkboxes_sel, checkboxes_changed);
4823 $(document).on("change", "input.checkall_box", function () {
4824 var is_checked = $(this).is(":checked");
4825 $(this.form).find(checkboxes_sel).prop("checked", is_checked)
4826 .parents("tr").toggleClass("marked", is_checked);
4830 * Watches checkboxes in a sub form to set the sub checkall box accordingly
4832 var sub_checkboxes_changed = function () {
4833 var $form = $(this).parent().parent();
4834 // total number of checkboxes in current sub form
4835 var total_boxes = $form.find(checkboxes_sel).length;
4836 // number of checkboxes checked in current sub form
4837 var checked_boxes = $form.find(checkboxes_sel + ":checked").length;
4838 var $checkall = $form.find("input.sub_checkall_box");
4839 if (total_boxes == checked_boxes) {
4840 $checkall.prop({checked: true, indeterminate: false});
4842 else if (checked_boxes > 0) {
4843 $checkall.prop({checked: true, indeterminate: true});
4846 $checkall.prop({checked: false, indeterminate: false});
4849 $(document).on("change", checkboxes_sel + ", input.checkall_box:checkbox:enabled", sub_checkboxes_changed);
4851 $(document).on("change", "input.sub_checkall_box", function () {
4852 var is_checked = $(this).is(":checked");
4853 var $form = $(this).parent().parent();
4854 $form.find(checkboxes_sel).prop("checked", is_checked)
4855 .parents("tr").toggleClass("marked", is_checked);
4859 * Formats a byte number to human-readable form
4861 * @param bytes the bytes to format
4862 * @param optional subdecimals the number of digits after the point
4863 * @param optional pointchar the char to use as decimal point
4865 function formatBytes(bytes, subdecimals, pointchar) {
4872 var units = ['B', 'KiB', 'MiB', 'GiB'];
4873 for (var i = 0; bytes > 1024 && i < units.length; i++) {
4876 var factor = Math.pow(10, subdecimals);
4877 bytes = Math.round(bytes * factor) / factor;
4878 bytes = bytes.toString().split('.').join(pointchar);
4879 return bytes + ' ' + units[i];
4882 AJAX.registerOnload('functions.js', function () {
4884 * Reveal the login form to users with JS enabled
4885 * and focus the appropriate input field
4887 var $loginform = $('#loginform');
4888 if ($loginform.length) {
4889 $loginform.find('.js-show').show();
4890 if ($('#input_username').val()) {
4891 $('#input_password').focus();
4893 $('#input_username').focus();
4896 var $https_warning = $('#js-https-mismatch');
4897 if ($https_warning.length) {
4898 if ((window.location.protocol === 'https:') != PMA_commonParams.get('is_https')) {
4899 $https_warning.show();
4905 * Dynamically adjust the width of the boxes
4906 * on the table and db operations pages
4909 function DynamicBoxes() {
4910 var $boxContainer = $('#boxContainer');
4911 if ($boxContainer.length) {
4912 var minWidth = $boxContainer.data('box-width');
4913 var viewport = $(window).width() - $('#pma_navigation').width();
4914 var slots = Math.floor(viewport / minWidth);
4915 $boxContainer.children()
4917 if (viewport < minWidth) {
4918 $(this).width(minWidth);
4920 $(this).css('width', ((1 / slots) * 100) + "%");
4923 .removeClass('clearfloat')
4924 .filter(':nth-child(' + slots + 'n+1)')
4925 .addClass('clearfloat');
4928 AJAX.registerOnload('functions.js', function () {
4932 $(window).resize(DynamicBoxes);
4937 * Formats timestamp for display
4939 function PMA_formatDateTime(date, seconds) {
4940 var result = $.datepicker.formatDate('yy-mm-dd', date);
4941 var timefmt = 'HH:mm';
4943 timefmt = 'HH:mm:ss';
4945 return result + ' ' + $.datepicker.formatTime(
4947 hour: date.getHours(),
4948 minute: date.getMinutes(),
4949 second: date.getSeconds()
4955 * Check than forms have less fields than max allowed by PHP.
4957 function checkNumberOfFields() {
4958 if (typeof maxInputVars === 'undefined') {
4961 if (false === maxInputVars) {
4964 $('form').each(function() {
4965 var nbInputs = $(this).find(':input').length;
4966 if (nbInputs > maxInputVars) {
4967 var warning = PMA_sprintf(PMA_messages.strTooManyInputs, maxInputVars);
4968 PMA_ajaxShowMessage(warning);
4978 * Ignore the displayed php errors.
4979 * Simply removes the displayed errors.
4981 * @param clearPrevErrors whether to clear errors stored
4982 * in $_SESSION['prev_errors'] at server
4985 function PMA_ignorePhpErrors(clearPrevErrors){
4986 if (typeof(clearPrevErrors) === "undefined" ||
4987 clearPrevErrors === null
4991 // send AJAX request to error_report.php with send_error_report=0, exception_type=php & token.
4992 // It clears the prev_errors stored in session.
4993 if(clearPrevErrors){
4994 var $pmaReportErrorsForm = $('#pma_report_errors_form');
4995 $pmaReportErrorsForm.find('input[name="send_error_report"]').val(0); // change send_error_report to '0'
4996 $pmaReportErrorsForm.submit();
4999 // remove displayed errors
5000 var $pmaErrors = $('#pma_errors');
5001 $pmaErrors.fadeOut( "slow");
5002 $pmaErrors.remove();
5006 * Toggle the Datetimepicker UI if the date value entered
5007 * by the user in the 'text box' is not going to be accepted
5008 * by the Datetimepicker plugin (but is accepted by MySQL)
5010 function toggleDatepickerIfInvalid($td, $input_field) {
5011 // Regex allowed by the Datetimepicker UI
5012 var dtexpDate = new RegExp(['^([0-9]{4})',
5013 '-(((01|03|05|07|08|10|12)-((0[1-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)',
5014 '-((0[1-9])|([1-2][0-9])|30)))$'].join(''));
5015 var dtexpTime = new RegExp(['^(([0-1][0-9])|(2[0-3]))',
5016 ':((0[0-9])|([1-5][0-9]))',
5017 ':((0[0-9])|([1-5][0-9]))(\.[0-9]{1,6}){0,1}$'].join(''));
5019 // If key-ed in Time or Date values are unsupported by the UI, close it
5020 if ($td.attr('data-type') === 'date' && ! dtexpDate.test($input_field.val())) {
5021 $input_field.datepicker('hide');
5022 } else if ($td.attr('data-type') === 'time' && ! dtexpTime.test($input_field.val())) {
5023 $input_field.datepicker('hide');
5025 $input_field.datepicker('show');
5030 * Function to enable the 'Go' button on login.
5032 function loginButtonEnable() {
5033 $('#input_go').prop('disabled', false);
5037 * Function to disable the 'Go' button on login.
5039 function loginButtonDisable() {
5040 $('#input_go').prop('disabled', true);
5044 * Unbind all event handlers before tearing down a page
5046 AJAX.registerTeardown('functions.js', function(){
5047 $(document).off('keydown', 'form input, form textarea, form select');
5050 AJAX.registerOnload('functions.js', function () {
5052 * Handle 'Ctrl/Alt + Enter' form submits
5054 $('form input, form textarea, form select').on('keydown', function(e){
5055 if((e.ctrlKey && e.which == 13) || (e.altKey && e.which == 13)) {
5056 $form = $(this).closest('form');
5057 if (! $form.find('input[type="submit"]') ||
5058 ! $form.find('input[type="submit"]').click()
5066 * Setting the 'Go' login button to disable if captcha is enabled.
5068 if ($('.g-recaptcha').attr('captcha') == 'enabled'){
5069 loginButtonDisable();
5074 * Unbind all event handlers before tearing down a page
5076 AJAX.registerTeardown('functions.js', function(){
5077 $(document).off('change', 'input[type=radio][name="pw_hash"]');
5080 AJAX.registerOnload('functions.js', function(){
5082 * Display warning regarding SSL when sha256_password
5083 * method is selected
5084 * Used in user_password.php (Change Password link on index.php)
5086 $(document).on("change", 'select#select_authentication_plugin_cp', function() {
5087 if (this.value === 'sha256_password') {
5088 $('#ssl_reqd_warning_cp').show();
5090 $('#ssl_reqd_warning_cp').hide();