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));
159 * Add a date/time picker to each element that needs it
160 * (only when jquery-ui-timepicker-addon.js is loaded)
162 function addDateTimePicker() {
163 if ($.timepicker !== undefined) {
164 $('input.timefield, input.datefield, input.datetimefield').each(function () {
166 var decimals = $(this).parent().attr('data-decimals');
167 var type = $(this).parent().attr('data-type');
169 var showMillisec = false;
170 var showMicrosec = false;
171 var timeFormat = 'HH:mm:ss';
172 // check for decimal places of seconds
173 if (decimals > 0 && type.indexOf('time') != -1){
177 timeFormat = 'HH:mm:ss.lc';
180 timeFormat = 'HH:mm:ss.l';
183 PMA_addDatepicker($(this), type, {
184 showMillisec: showMillisec,
185 showMicrosec: showMicrosec,
186 timeFormat: timeFormat
193 * Handle redirect and reload flags sent as part of AJAX requests
195 * @param data ajax response data
197 function PMA_handleRedirectAndReload(data) {
198 if (parseInt(data.redirect_flag) == 1) {
199 // add one more GET param to display session expiry msg
200 if (window.location.href.indexOf('?') === -1) {
201 window.location.href += '?session_expired=1';
203 window.location.href += '&session_expired=1';
205 window.location.reload();
206 } else if (parseInt(data.reload_flag) == 1) {
207 // remove the token param and reload
208 window.location.href = window.location.href.replace(/&?token=[^&#]*/g, "");
209 window.location.reload();
214 * Creates an SQL editor which supports auto completing etc.
216 * @param $textarea jQuery object wrapping the textarea to be made the editor
217 * @param options optional options for CodeMirror
218 * @param resize optional resizing ('vertical', 'horizontal', 'both')
219 * @param lintOptions additional options for lint
221 function PMA_getSQLEditor($textarea, options, resize, lintOptions) {
222 if ($textarea.length > 0 && typeof CodeMirror !== 'undefined') {
224 // merge options for CodeMirror
228 extraKeys: {"Ctrl-Space": "autocomplete"},
229 hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
231 mode: "text/x-mysql",
235 if (CodeMirror.sqlLint) {
237 gutters: ["CodeMirror-lint-markers"],
239 "getAnnotations": CodeMirror.sqlLint,
241 "lintOptions": lintOptions
246 $.extend(true, defaults, options);
248 // create CodeMirror editor
249 var codemirrorEditor = CodeMirror.fromTextArea($textarea[0], defaults);
255 if (resize == 'vertical') {
258 if (resize == 'both') {
261 if (resize == 'horizontal') {
264 $(codemirrorEditor.getWrapperElement())
265 .css('resize', resize)
269 codemirrorEditor.setSize($(this).width(), $(this).height());
272 // enable autocomplete
273 codemirrorEditor.on("inputRead", codemirrorAutocompleteOnInputRead);
275 return codemirrorEditor;
281 * Clear text selection
283 function PMA_clearSelection() {
284 if (document.selection && document.selection.empty) {
285 document.selection.empty();
286 } else if (window.getSelection) {
287 var sel = window.getSelection();
291 if (sel.removeAllRanges) {
292 sel.removeAllRanges();
298 * Create a jQuery UI tooltip
300 * @param $elements jQuery object representing the elements
301 * @param item the item
302 * (see http://api.jqueryui.com/tooltip/#option-items)
303 * @param myContent content of the tooltip
304 * @param additionalOptions to override the default options
307 function PMA_tooltip($elements, item, myContent, additionalOptions)
309 if ($('#no_hint').length > 0) {
313 var defaultOptions = {
316 tooltipClass: "tooltip",
322 $elements.tooltip($.extend(true, defaultOptions, additionalOptions));
329 function escapeHtml(unsafe) {
330 if (typeof(unsafe) != 'undefined') {
333 .replace(/&/g, "&")
334 .replace(/</g, "<")
335 .replace(/>/g, ">")
336 .replace(/"/g, """)
337 .replace(/'/g, "'");
343 function escapeJsString(unsafe) {
344 if (typeof(unsafe) != 'undefined') {
348 .replace('\\', '\\\\')
349 .replace('\'', '\\\'')
350 .replace("'", "\\\'")
352 .replace(""", "\"")
355 .replace(/<\/script/gi, '</\' + \'script')
361 function PMA_sprintf() {
362 return sprintf.apply(this, arguments);
366 * Hides/shows the default value input field, depending on the default type
367 * Ticks the NULL checkbox if NULL is chosen as default value.
369 function PMA_hideShowDefaultValue($default_type)
371 if ($default_type.val() == 'USER_DEFINED') {
372 $default_type.siblings('.default_value').show().focus();
374 $default_type.siblings('.default_value').hide();
375 if ($default_type.val() == 'NULL') {
376 var $null_checkbox = $default_type.closest('tr').find('.allow_null');
377 $null_checkbox.prop('checked', true);
383 * Hides/shows the input field for column expression based on whether
384 * VIRTUAL/PERSISTENT is selected
386 * @param $virtuality virtuality dropdown
388 function PMA_hideShowExpression($virtuality)
390 if ($virtuality.val() === '') {
391 $virtuality.siblings('.expression').hide();
393 $virtuality.siblings('.expression').show();
398 * Show notices for ENUM columns; add/hide the default value
401 function PMA_verifyColumnsProperties()
403 $("select.column_type").each(function () {
404 PMA_showNoticeForEnum($(this));
406 $("select.default_type").each(function () {
407 PMA_hideShowDefaultValue($(this));
409 $('select.virtuality').each(function () {
410 PMA_hideShowExpression($(this));
415 * Add a hidden field to the form to indicate that this will be an
416 * Ajax request (only if this hidden field does not exist)
418 * @param $form object the form
420 function PMA_prepareForAjaxRequest($form)
422 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
423 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
428 * Generate a new password and copy it to the password input areas
430 * @param passwd_form object the form that holds the password fields
432 * @return boolean always true
434 function suggestPassword(passwd_form)
436 // restrict the password to just letters and numbers to avoid problems:
437 // "editors and viewers regard the password as multiple words and
438 // things like double click no longer work"
439 var pwchars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ";
440 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
441 var passwd = passwd_form.generated_pw;
442 var randomWords = new Int32Array(passwordlength);
446 // First we're going to try to use a built-in CSPRNG
447 if (window.crypto && window.crypto.getRandomValues) {
448 window.crypto.getRandomValues(randomWords);
450 // Because of course IE calls it msCrypto instead of being standard
451 else if (window.msCrypto && window.msCrypto.getRandomValues) {
452 window.msCrypto.getRandomValues(randomWords);
454 // Fallback to Math.random
455 for (var i = 0; i < passwordlength; i++) {
456 randomWords[i] = Math.floor(Math.random() * pwchars.length);
460 for (var i = 0; i < passwordlength; i++) {
461 passwd.value += pwchars.charAt(Math.abs(randomWords[i]) % pwchars.length);
464 passwd_form.text_pma_pw.value = passwd.value;
465 passwd_form.text_pma_pw2.value = passwd.value;
470 * Version string to integer conversion.
472 function parseVersionString(str)
474 if (typeof(str) != 'string') { return false; }
476 // Parse possible alpha/beta/rc/
477 var state = str.split('-');
478 if (state.length >= 2) {
479 if (state[1].substr(0, 2) == 'rc') {
480 add = - 20 - parseInt(state[1].substr(2), 10);
481 } else if (state[1].substr(0, 4) == 'beta') {
482 add = - 40 - parseInt(state[1].substr(4), 10);
483 } else if (state[1].substr(0, 5) == 'alpha') {
484 add = - 60 - parseInt(state[1].substr(5), 10);
485 } else if (state[1].substr(0, 3) == 'dev') {
486 /* We don't handle dev, it's git snapshot */
491 var x = str.split('.');
492 // Use 0 for non existing parts
493 var maj = parseInt(x[0], 10) || 0;
494 var min = parseInt(x[1], 10) || 0;
495 var pat = parseInt(x[2], 10) || 0;
496 var hotfix = parseInt(x[3], 10) || 0;
497 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
501 * Indicates current available version on main page.
503 function PMA_current_version(data)
505 if (data && data.version && data.date) {
506 var current = parseVersionString($('span.version').text());
507 var latest = parseVersionString(data.version);
508 var version_information_message = '<span class="latest">' +
509 PMA_messages.strLatestAvailable +
510 ' ' + escapeHtml(data.version) +
512 if (latest > current) {
513 var message = PMA_sprintf(
514 PMA_messages.strNewerVersion,
515 escapeHtml(data.version),
516 escapeHtml(data.date)
518 var htmlClass = 'notice';
519 if (Math.floor(latest / 10000) === Math.floor(current / 10000)) {
520 /* Security update */
523 $('#newer_version_notice').remove();
524 $('#maincontainer').after('<div id="newer_version_notice" class="' + htmlClass + '">' + message + '</div>');
526 if (latest === current) {
527 version_information_message = ' (' + PMA_messages.strUpToDate + ')';
529 var $liPmaVersion = $('#li_pma_version');
530 $liPmaVersion.find('span.latest').remove();
531 $liPmaVersion.append(version_information_message);
536 * Loads Git revision data from ajax for index.php
538 function PMA_display_git_revision()
540 $('#is_git_revision').remove();
541 $('#li_pma_version_git').remove();
545 "server": PMA_commonParams.get('server'),
546 "token": PMA_commonParams.get('token'),
547 "git_revision": true,
548 "ajax_request": true,
552 if (typeof data !== 'undefined' && data.success === true) {
553 $(data.message).insertAfter('#li_pma_version');
560 * for libraries/display_change_password.lib.php
561 * libraries/user_password.php
565 function displayPasswordGenerateButton()
567 $('#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>');
568 $('#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>');
572 * selects the content of a given object, f.e. a textarea
574 * @param element object element of which the content will be selected
575 * @param lock var variable which holds the lock for this element
576 * or true, if no lock exists
577 * @param only_once boolean if true this is only done once
578 * f.e. only on first focus
580 function selectContent(element, lock, only_once)
582 if (only_once && only_once_elements[element.name]) {
586 only_once_elements[element.name] = true;
596 * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
597 * This function is called while clicking links
599 * @param theLink object the link
600 * @param theSqlQuery object the sql query to submit
602 * @return boolean whether to run the query or not
604 function confirmLink(theLink, theSqlQuery)
606 // Confirmation is not required in the configuration file
607 // or browser is Opera (crappy js implementation)
608 if (PMA_messages.strDoYouReally === '' || typeof(window.opera) != 'undefined') {
612 var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, theSqlQuery));
614 if ($(theLink).hasClass('formLinkSubmit')) {
615 var name = 'is_js_confirmed';
616 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
617 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
620 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
621 } else if (typeof(theLink.href) != 'undefined') {
622 theLink.href += '&is_js_confirmed=1';
623 } else if (typeof(theLink.form) != 'undefined') {
624 theLink.form.action += '?is_js_confirmed=1';
629 } // end of the 'confirmLink()' function
632 * Displays an error message if a "DROP DATABASE" statement is submitted
633 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
634 * submitting it if required.
635 * This function is called by the 'checkSqlQuery()' js function.
637 * @param theForm1 object the form
638 * @param sqlQuery1 object the sql query textarea
640 * @return boolean whether to run the query or not
642 * @see checkSqlQuery()
644 function confirmQuery(theForm1, sqlQuery1)
646 // Confirmation is not required in the configuration file
647 if (PMA_messages.strDoYouReally === '') {
651 // "DROP DATABASE" statement isn't allowed
652 if (PMA_messages.strNoDropDatabases !== '') {
653 var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
654 if (drop_re.test(sqlQuery1.value)) {
655 alert(PMA_messages.strNoDropDatabases);
662 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
664 // TODO: find a way (if possible) to use the parser-analyser
665 // for this kind of verification
666 // For now, I just added a ^ to check for the statement at
667 // beginning of expression
669 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
670 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
671 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
672 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
674 if (do_confirm_re_0.test(sqlQuery1.value) ||
675 do_confirm_re_1.test(sqlQuery1.value) ||
676 do_confirm_re_2.test(sqlQuery1.value) ||
677 do_confirm_re_3.test(sqlQuery1.value)) {
679 if (sqlQuery1.value.length > 100) {
680 message = sqlQuery1.value.substr(0, 100) + '\n ...';
682 message = sqlQuery1.value;
684 var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, message));
685 // statement is confirmed -> update the
686 // "is_js_confirmed" form field so the confirm test won't be
687 // run on the server side and allows to submit the form
689 theForm1.elements.is_js_confirmed.value = 1;
692 // statement is rejected -> do not submit the form
697 } // end if (handle confirm box result)
698 } // end if (display confirm box)
701 } // end of the 'confirmQuery()' function
704 * Displays an error message if the user submitted the sql query form with no
705 * sql query, else checks for "DROP/DELETE/ALTER" statements
707 * @param theForm object the form
709 * @return boolean always false
711 * @see confirmQuery()
713 function checkSqlQuery(theForm)
715 // get the textarea element containing the query
717 if (codemirror_editor) {
718 codemirror_editor.save();
719 sqlQuery = codemirror_editor.getValue();
721 sqlQuery = theForm.elements.sql_query.value;
724 var space_re = new RegExp('\\s+');
725 if (typeof(theForm.elements.sql_file) != 'undefined' &&
726 theForm.elements.sql_file.value.replace(space_re, '') !== '') {
729 if (isEmpty && typeof(theForm.elements.id_bookmark) != 'undefined' &&
730 (theForm.elements.id_bookmark.value !== null || theForm.elements.id_bookmark.value !== '') &&
731 theForm.elements.id_bookmark.selectedIndex !== 0) {
734 // Checks for "DROP/DELETE/ALTER" statements
735 if (sqlQuery.replace(space_re, '') !== '') {
736 return confirmQuery(theForm, sqlQuery);
742 alert(PMA_messages.strFormEmpty);
743 codemirror_editor.focus();
748 } // end of the 'checkSqlQuery()' function
751 * Check if a form's element is empty.
752 * An element containing only spaces is also considered empty
754 * @param object the form
755 * @param string the name of the form field to put the focus on
757 * @return boolean whether the form field is empty or not
759 function emptyCheckTheField(theForm, theFieldName)
761 var theField = theForm.elements[theFieldName];
762 var space_re = new RegExp('\\s+');
763 return theField.value.replace(space_re, '') === '';
764 } // end of the 'emptyCheckTheField()' function
767 * Ensures a value submitted in a form is numeric and is in a range
769 * @param object the form
770 * @param string the name of the form field to check
771 * @param integer the minimum authorized value
772 * @param integer the maximum authorized value
774 * @return boolean whether a valid number has been submitted or not
776 function checkFormElementInRange(theForm, theFieldName, message, min, max)
778 var theField = theForm.elements[theFieldName];
779 var val = parseInt(theField.value, 10);
781 if (typeof(min) == 'undefined') {
784 if (typeof(max) == 'undefined') {
785 max = Number.MAX_VALUE;
791 alert(PMA_messages.strEnterValidNumber);
795 // It's a number but it is not between min and max
796 else if (val < min || val > max) {
798 alert(PMA_sprintf(message, val));
802 // It's a valid number
804 theField.value = val;
808 } // end of the 'checkFormElementInRange()' function
811 function checkTableEditForm(theForm, fieldsCnt)
813 // TODO: avoid sending a message if user just wants to add a line
814 // on the form but has not completed at least one field name
816 var atLeastOneField = 0;
817 var i, elm, elm2, elm3, val, id;
819 for (i = 0; i < fieldsCnt; i++) {
820 id = "#field_" + i + "_2";
823 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
824 elm2 = $("#field_" + i + "_3");
825 val = parseInt(elm2.val(), 10);
826 elm3 = $("#field_" + i + "_1");
827 if (isNaN(val) && elm3.val() !== "") {
829 alert(PMA_messages.strEnterValidLength);
835 if (atLeastOneField === 0) {
836 id = "field_" + i + "_1";
837 if (!emptyCheckTheField(theForm, id)) {
842 if (atLeastOneField === 0) {
843 var theField = theForm.elements.field_0_1;
844 alert(PMA_messages.strFormEmpty);
849 // at least this section is under jQuery
850 var $input = $("input.textfield[name='table']");
851 if ($input.val() === "") {
852 alert(PMA_messages.strFormEmpty);
858 } // enf of the 'checkTableEditForm()' function
861 * True if last click is to check a row.
863 var last_click_checked = false;
866 * Zero-based index of last clicked row.
867 * Used to handle the shift + click event in the code above.
869 var last_clicked_row = -1;
872 * Zero-based index of last shift clicked row.
874 var last_shift_clicked_row = -1;
876 var _idleSecondsCounter = 0;
879 AJAX.registerTeardown('functions.js', function () {
880 clearTimeout(updateTimeout);
881 clearInterval(IncInterval);
882 $(document).off('mousemove');
885 AJAX.registerOnload('functions.js', function () {
886 document.onclick = function() {
887 _idleSecondsCounter = 0;
889 $(document).on('mousemove',function() {
890 _idleSecondsCounter = 0;
892 document.onkeypress = function() {
893 _idleSecondsCounter = 0;
896 function SetIdleTime() {
897 _idleSecondsCounter++;
899 function UpdateIdleTime() {
900 var href = 'index.php';
902 'ajax_request' : true,
903 'token' : PMA_commonParams.get('token'),
904 'server' : PMA_commonParams.get('server'),
905 'db' : PMA_commonParams.get('db'),
906 'access_time':_idleSecondsCounter
912 success: function (data) {
914 if (PMA_commonParams.get('LoginCookieValidity')-_idleSecondsCounter > 5) {
915 var interval = (PMA_commonParams.get('LoginCookieValidity') - _idleSecondsCounter - 5) * 1000;
916 if (interval > Math.pow(2, 31) - 1) { // max value for setInterval() function
917 interval = Math.pow(2, 31) - 1;
919 updateTimeout = window.setTimeout(UpdateIdleTime, interval);
921 updateTimeout = window.setTimeout(UpdateIdleTime, 2000);
923 } else { //timeout occurred
924 if(isStorageSupported('sessionStorage')){
925 window.sessionStorage.clear();
927 window.location.reload(true);
928 clearInterval(IncInterval);
933 if (PMA_commonParams.get('logged_in') && PMA_commonParams.get('auth_type') == 'cookie') {
934 IncInterval = window.setInterval(SetIdleTime, 1000);
935 var interval = (PMA_commonParams.get('LoginCookieValidity') - 5) * 1000;
936 if (interval > Math.pow(2, 31) - 1) { // max value for setInterval() function
937 interval = Math.pow(2, 31) - 1;
939 updateTimeout = window.setTimeout(UpdateIdleTime, interval);
943 * Unbind all event handlers before tearing down a page
945 AJAX.registerTeardown('functions.js', function () {
946 $(document).off('click', 'input:checkbox.checkall');
948 AJAX.registerOnload('functions.js', function () {
950 * Row marking in horizontal mode (use "on" so that it works also for
951 * next pages reached via AJAX); a tr may have the class noclick to remove
955 $(document).on('click', 'input:checkbox.checkall', function (e) {
957 var $tr = $this.closest('tr');
958 var $table = $this.closest('table');
960 if (!e.shiftKey || last_clicked_row == -1) {
963 var $checkbox = $tr.find(':checkbox.checkall');
964 var checked = $this.prop('checked');
965 $checkbox.prop('checked', checked).trigger('change');
967 $tr.addClass('marked');
969 $tr.removeClass('marked');
971 last_click_checked = checked;
973 // remember the last clicked row
974 last_clicked_row = last_click_checked ? $table.find('tr.odd:not(.noclick), tr.even:not(.noclick)').index($tr) : -1;
975 last_shift_clicked_row = -1;
977 // handle the shift click
978 PMA_clearSelection();
981 // clear last shift click result
982 if (last_shift_clicked_row >= 0) {
983 if (last_shift_clicked_row >= last_clicked_row) {
984 start = last_clicked_row;
985 end = last_shift_clicked_row;
987 start = last_shift_clicked_row;
988 end = last_clicked_row;
990 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
991 .slice(start, end + 1)
992 .removeClass('marked')
994 .prop('checked', false)
998 // handle new shift click
999 var curr_row = $table.find('tr.odd:not(.noclick), tr.even:not(.noclick)').index($tr);
1000 if (curr_row >= last_clicked_row) {
1001 start = last_clicked_row;
1005 end = last_clicked_row;
1007 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
1008 .slice(start, end + 1)
1011 .prop('checked', true)
1014 // remember the last shift clicked row
1015 last_shift_clicked_row = curr_row;
1019 addDateTimePicker();
1022 * Add attribute to text boxes for iOS devices (based on bugID: 3508912)
1024 if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) {
1025 $('input[type=text]').attr('autocapitalize', 'off').attr('autocorrect', 'off');
1030 * Row highlighting in horizontal mode (use "on"
1031 * so that it works also for pages reached via AJAX)
1033 /*AJAX.registerOnload('functions.js', function () {
1034 $(document).on('hover', 'tr.odd, tr.even',function (event) {
1036 $tr.toggleClass('hover',event.type=='mouseover');
1037 $tr.children().toggleClass('hover',event.type=='mouseover');
1042 * marks all rows and selects its first checkbox inside the given element
1043 * the given element is usually a table or a div containing the table or tables
1045 * @param container DOM element
1047 function markAllRows(container_id)
1050 $("#" + container_id).find("input:checkbox:enabled").prop('checked', true)
1052 .parents("tr").addClass("marked");
1057 * marks all rows and selects its first checkbox inside the given element
1058 * the given element is usually a table or a div containing the table or tables
1060 * @param container DOM element
1062 function unMarkAllRows(container_id)
1065 $("#" + container_id).find("input:checkbox:enabled").prop('checked', false)
1067 .parents("tr").removeClass("marked");
1072 * Checks/unchecks all options of a <select> element
1074 * @param string the form name
1075 * @param string the element name
1076 * @param boolean whether to check or to uncheck options
1078 * @return boolean always true
1080 function setSelectOptions(the_form, the_select, do_check)
1082 $("form[name='" + the_form + "'] select[name='" + the_select + "']").find("option").prop('selected', do_check);
1084 } // end of the 'setSelectOptions()' function
1087 * Sets current value for query box.
1089 function setQuery(query)
1091 if (codemirror_editor) {
1092 codemirror_editor.setValue(query);
1093 codemirror_editor.focus();
1095 document.sqlform.sql_query.value = query;
1096 document.sqlform.sql_query.focus();
1101 * Handles 'Simulate query' button on SQL query box.
1105 function PMA_handleSimulateQueryButton()
1107 var update_re = new RegExp('^\\s*UPDATE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+SET\\s', 'i');
1108 var delete_re = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
1111 if (codemirror_editor) {
1112 query = codemirror_editor.getValue();
1114 query = $('#sqlquery').val();
1117 var $simulateDml = $('#simulate_dml');
1118 if (update_re.test(query) || delete_re.test(query)) {
1119 if (! $simulateDml.length) {
1120 $('#button_submit_query')
1121 .before('<input type="button" id="simulate_dml"' +
1122 'tabindex="199" value="' +
1123 PMA_messages.strSimulateDML +
1127 if ($simulateDml.length) {
1128 $simulateDml.remove();
1134 * Create quick sql statements.
1137 function insertQuery(queryType)
1139 if (queryType == "clear") {
1142 } else if (queryType == "format") {
1143 if (codemirror_editor) {
1144 $('#querymessage').html(PMA_messages.strFormatting +
1145 ' <img class="ajaxIcon" src="' +
1146 pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1147 var href = 'db_sql_format.php';
1149 'ajax_request': true,
1150 'token': PMA_commonParams.get('token'),
1151 'sql': codemirror_editor.getValue()
1157 success: function (data) {
1159 codemirror_editor.setValue(data.sql);
1161 $('#querymessage').html('');
1166 } else if (queryType == "saved") {
1167 if ($.cookie('auto_saved_sql')) {
1168 setQuery($.cookie('auto_saved_sql'));
1170 PMA_ajaxShowMessage(PMA_messages.strNoAutoSavedQuery);
1176 var myListBox = document.sqlform.dummy;
1177 var table = document.sqlform.table.value;
1179 if (myListBox.options.length > 0) {
1180 sql_box_locked = true;
1181 var columnsList = "";
1185 for (var i = 0; i < myListBox.options.length; i++) {
1188 columnsList += ", ";
1192 columnsList += myListBox.options[i].value;
1193 valDis += "[value-" + NbSelect + "]";
1194 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
1196 if (queryType == "selectall") {
1197 query = "SELECT * FROM `" + table + "` WHERE 1";
1198 } else if (queryType == "select") {
1199 query = "SELECT " + columnsList + " FROM `" + table + "` WHERE 1";
1200 } else if (queryType == "insert") {
1201 query = "INSERT INTO `" + table + "`(" + columnsList + ") VALUES (" + valDis + ")";
1202 } else if (queryType == "update") {
1203 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
1204 } else if (queryType == "delete") {
1205 query = "DELETE FROM `" + table + "` WHERE 1";
1208 sql_box_locked = false;
1214 * Inserts multiple fields.
1217 function insertValueQuery()
1219 var myQuery = document.sqlform.sql_query;
1220 var myListBox = document.sqlform.dummy;
1222 if (myListBox.options.length > 0) {
1223 sql_box_locked = true;
1224 var columnsList = "";
1226 for (var i = 0; i < myListBox.options.length; i++) {
1227 if (myListBox.options[i].selected) {
1230 columnsList += ", ";
1232 columnsList += myListBox.options[i].value;
1236 /* CodeMirror support */
1237 if (codemirror_editor) {
1238 codemirror_editor.replaceSelection(columnsList);
1240 } else if (document.selection) {
1242 var sel = document.selection.createRange();
1243 sel.text = columnsList;
1244 document.sqlform.insert.focus();
1246 //MOZILLA/NETSCAPE support
1247 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
1248 var startPos = document.sqlform.sql_query.selectionStart;
1249 var endPos = document.sqlform.sql_query.selectionEnd;
1250 var SqlString = document.sqlform.sql_query.value;
1252 myQuery.value = SqlString.substring(0, startPos) + columnsList + SqlString.substring(endPos, SqlString.length);
1254 myQuery.value += columnsList;
1256 sql_box_locked = false;
1261 * Updates the input fields for the parameters based on the query
1263 function updateQueryParameters() {
1265 if ($('#parameterized').is(':checked')) {
1266 var query = codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val();
1268 var allParameters = query.match(/:[a-zA-Z0-9_]+/g);
1269 var parameters = [];
1270 // get unique parameters
1271 if (allParameters) {
1272 $.each(allParameters, function(i, parameter){
1273 if ($.inArray(parameter, parameters) === -1) {
1274 parameters.push(parameter);
1278 $('#parametersDiv').text(PMA_messages.strNoParam);
1282 var $temp = $('<div />');
1283 $temp.append($('#parametersDiv').children());
1284 $('#parametersDiv').empty();
1286 $.each(parameters, function (i, parameter) {
1287 var paramName = parameter.substring(1);
1288 var $param = $temp.find('#paramSpan_' + paramName );
1289 if (! $param.length) {
1290 $param = $('<span class="parameter" id="paramSpan_' + paramName + '" />');
1291 $('<label for="param_' + paramName + '" />').text(parameter).appendTo($param);
1292 $('<input type="text" name="parameters[' + parameter + ']" id="param_' + paramName + '" />').appendTo($param);
1294 $('#parametersDiv').append($param);
1297 $('#parametersDiv').empty();
1302 * Refresh/resize the WYSIWYG scratchboard
1304 function refreshLayout()
1306 var $elm = $('#pdflayout');
1307 var orientation = $('#orientation_opt').val();
1309 var $paperOpt = $('#paper_opt');
1310 if ($paperOpt.length == 1) {
1311 paper = $paperOpt.val();
1315 if (orientation == 'P') {
1319 $elm.css('width', pdfPaperSize(paper, posa) + 'px');
1320 $elm.css('height', pdfPaperSize(paper, posb) + 'px');
1324 * Initializes positions of elements.
1326 function TableDragInit() {
1327 $('.pdflayout_table').each(function () {
1328 var $this = $(this);
1329 var number = $this.data('number');
1330 var x = $('#c_table_' + number + '_x').val();
1331 var y = $('#c_table_' + number + '_y').val();
1332 $this.css('left', x + 'px');
1333 $this.css('top', y + 'px');
1334 /* Make elements draggable */
1336 containment: "parent",
1337 drag: function (evt, ui) {
1338 var number = $this.data('number');
1339 $('#c_table_' + number + '_x').val(parseInt(ui.position.left, 10));
1340 $('#c_table_' + number + '_y').val(parseInt(ui.position.top, 10));
1347 * Resets drag and drop positions.
1349 function resetDrag() {
1350 $('.pdflayout_table').each(function () {
1351 var $this = $(this);
1352 var x = $this.data('x');
1353 var y = $this.data('y');
1354 $this.css('left', x + 'px');
1355 $this.css('top', y + 'px');
1360 * User schema handlers.
1363 /* Move in scratchboard on manual change */
1364 $(document).on('change', '.position-change', function () {
1365 var $this = $(this);
1366 var $elm = $('#table_' + $this.data('number'));
1367 $elm.css($this.data('axis'), $this.val() + 'px');
1369 /* Refresh on paper size/orientation change */
1370 $(document).on('change', '.paper-change', function () {
1371 var $elm = $('#pdflayout');
1372 if ($elm.css('visibility') == 'visible') {
1377 /* Show/hide the WYSIWYG scratchboard */
1378 $(document).on('click', '#toggle-dragdrop', function () {
1379 var $elm = $('#pdflayout');
1380 if ($elm.css('visibility') == 'hidden') {
1383 $elm.css('visibility', 'visible');
1384 $elm.css('display', 'block');
1385 $('#showwysiwyg').val('1');
1387 $elm.css('visibility', 'hidden');
1388 $elm.css('display', 'none');
1389 $('#showwysiwyg').val('0');
1392 /* Reset scratchboard */
1393 $(document).on('click', '#reset-dragdrop', function () {
1399 * Returns paper sizes for a given format
1401 function pdfPaperSize(format, axis)
1403 switch (format.toUpperCase()) {
1753 * Get checkbox for foreign key checks
1757 function getForeignKeyCheckboxLoader() {
1760 html += '<div class="load-default-fk-check-value">';
1761 html += PMA_getImage('ajax_clock_small.gif');
1767 function loadForeignKeyCheckbox() {
1768 // Load default foreign key check value
1770 'ajax_request': true,
1771 'token': PMA_commonParams.get('token'),
1772 'server': PMA_commonParams.get('server'),
1773 'get_default_fk_check_value': true
1775 $.get('sql.php', params, function (data) {
1776 var html = '<input type="hidden" name="fk_checks" value="0" />' +
1777 '<input type="checkbox" name="fk_checks" id="fk_checks"' +
1778 (data.default_fk_check_value ? ' checked="checked"' : '') + ' />' +
1779 '<label for="fk_checks">' + PMA_messages.strForeignKeyCheck + '</label>';
1780 $('.load-default-fk-check-value').replaceWith(html);
1784 function getJSConfirmCommonParam(elem) {
1786 'is_js_confirmed' : 1,
1787 'ajax_request' : true,
1788 'fk_checks': $(elem).find('#fk_checks').is(':checked') ? 1 : 0
1793 * Unbind all event handlers before tearing down a page
1795 AJAX.registerTeardown('functions.js', function () {
1796 $(document).off('click', "a.inline_edit_sql");
1797 $(document).off('click', "input#sql_query_edit_save");
1798 $(document).off('click', "input#sql_query_edit_discard");
1799 $('input.sqlbutton').unbind('click');
1800 if (codemirror_editor) {
1801 codemirror_editor.off('blur');
1803 $(document).off('blur', '#sqlquery');
1805 $(document).off('change', '#parameterized');
1806 $('#sqlquery').unbind('keydown');
1807 $('#sql_query_edit').unbind('keydown');
1809 if (codemirror_inline_editor) {
1810 // Copy the sql query to the text area to preserve it.
1811 $('#sql_query_edit').text(codemirror_inline_editor.getValue());
1812 $(codemirror_inline_editor.getWrapperElement()).unbind('keydown');
1813 codemirror_inline_editor.toTextArea();
1814 codemirror_inline_editor = false;
1816 if (codemirror_editor) {
1817 $(codemirror_editor.getWrapperElement()).unbind('keydown');
1822 * Jquery Coding for inline editing SQL_QUERY
1824 AJAX.registerOnload('functions.js', function () {
1825 // If we are coming back to the page by clicking forward button
1826 // of the browser, bind the code mirror to inline query editor.
1827 bindCodeMirrorToInlineEditor();
1828 $(document).on('click', "a.inline_edit_sql", function () {
1829 if ($('#sql_query_edit').length) {
1830 // An inline query editor is already open,
1831 // we don't want another copy of it
1835 var $form = $(this).prev('form');
1836 var sql_query = $form.find("input[name='sql_query']").val().trim();
1837 var $inner_sql = $(this).parent().prev().find('code.sql');
1838 var old_text = $inner_sql.html();
1840 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + escapeHtml(sql_query) + "</textarea>\n";
1841 new_content += getForeignKeyCheckboxLoader();
1842 new_content += "<input type=\"submit\" id=\"sql_query_edit_save\" class=\"button btnSave\" value=\"" + PMA_messages.strGo + "\"/>\n";
1843 new_content += "<input type=\"button\" id=\"sql_query_edit_discard\" class=\"button btnDiscard\" value=\"" + PMA_messages.strCancel + "\"/>\n";
1844 var $editor_area = $('div#inline_editor');
1845 if ($editor_area.length === 0) {
1846 $editor_area = $('<div id="inline_editor_outer"></div>');
1847 $editor_area.insertBefore($inner_sql);
1849 $editor_area.html(new_content);
1850 loadForeignKeyCheckbox();
1853 bindCodeMirrorToInlineEditor();
1857 $(document).on('click', "input#sql_query_edit_save", function () {
1858 $(".success").hide();
1859 //hide already existing success message
1861 if (codemirror_inline_editor) {
1862 codemirror_inline_editor.save();
1863 sql_query = codemirror_inline_editor.getValue();
1865 sql_query = $(this).parent().find('#sql_query_edit').val();
1867 var fk_check = $(this).parent().find('#fk_checks').is(':checked');
1869 var $form = $("a.inline_edit_sql").prev('form');
1870 var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1871 .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1872 .append($('<input/>', {type: 'hidden', name: 'show_query', value: 1}))
1873 .append($('<input/>', {type: 'hidden', name: 'is_js_confirmed', value: 0}))
1874 .append($('<input/>', {type: 'hidden', name: 'sql_query', value: sql_query}))
1875 .append($('<input/>', {type: 'hidden', name: 'fk_checks', value: fk_check ? 1 : 0}));
1876 if (! checkSqlQuery($fake_form[0])) {
1879 $fake_form.appendTo($('body')).submit();
1882 $(document).on('click', "input#sql_query_edit_discard", function () {
1883 var $divEditor = $('div#inline_editor_outer');
1884 $divEditor.siblings('code.sql').show();
1885 $divEditor.remove();
1888 $('input.sqlbutton').click(function (evt) {
1889 insertQuery(evt.target.id);
1890 PMA_handleSimulateQueryButton();
1894 $(document).on('change', '#parameterized', updateQueryParameters);
1896 var $inputUsername = $('#input_username');
1897 if ($inputUsername) {
1898 if ($inputUsername.val() === '') {
1899 $inputUsername.focus();
1901 $('#input_password').focus();
1907 * "inputRead" event handler for CodeMirror SQL query editors for autocompletion
1909 function codemirrorAutocompleteOnInputRead(instance) {
1910 if (!sql_autocomplete_in_progress
1911 && (!instance.options.hintOptions.tables || !sql_autocomplete)) {
1913 if (!sql_autocomplete) {
1914 // Reset after teardown
1915 instance.options.hintOptions.tables = false;
1916 instance.options.hintOptions.defaultTable = '';
1918 sql_autocomplete_in_progress = true;
1920 var href = 'db_sql_autocomplete.php';
1922 'ajax_request': true,
1923 'token': PMA_commonParams.get('token'),
1924 'server': PMA_commonParams.get('server'),
1925 'db': PMA_commonParams.get('db'),
1929 var columnHintRender = function(elem, self, data) {
1930 $('<div class="autocomplete-column-name">')
1931 .text(data.columnName)
1933 $('<div class="autocomplete-column-hint">')
1934 .text(data.columnHint)
1942 success: function (data) {
1944 var tables = $.parseJSON(data.tables);
1945 sql_autocomplete_default_table = PMA_commonParams.get('table');
1946 sql_autocomplete = [];
1947 for (var table in tables) {
1948 if (tables.hasOwnProperty(table)) {
1949 var columns = tables[table];
1954 for (var column in columns) {
1955 if (columns.hasOwnProperty(column)) {
1956 var displayText = columns[column].Type;
1957 if (columns[column].Key == 'PRI') {
1958 displayText += ' | Primary';
1959 } else if (columns[column].Key == 'UNI') {
1960 displayText += ' | Unique';
1962 table.columns.push({
1964 displayText: column + " | " + displayText,
1966 columnHint: displayText,
1967 render: columnHintRender
1972 sql_autocomplete.push(table);
1974 instance.options.hintOptions.tables = sql_autocomplete;
1975 instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
1978 complete: function () {
1979 sql_autocomplete_in_progress = false;
1984 instance.options.hintOptions.tables = sql_autocomplete;
1985 instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
1988 if (instance.state.completionActive) {
1991 var cur = instance.getCursor();
1992 var token = instance.getTokenAt(cur);
1994 if (token.string.match(/^[.`\w@]\w*$/)) {
1995 string = token.string;
1997 if (string.length > 0) {
1998 CodeMirror.commands.autocomplete(instance);
2003 * Remove autocomplete information before tearing down a page
2005 AJAX.registerTeardown('functions.js', function () {
2006 sql_autocomplete = false;
2007 sql_autocomplete_default_table = '';
2011 * Binds the CodeMirror to the text area used to inline edit a query.
2013 function bindCodeMirrorToInlineEditor() {
2014 var $inline_editor = $('#sql_query_edit');
2015 if ($inline_editor.length > 0) {
2016 if (typeof CodeMirror !== 'undefined') {
2017 var height = $inline_editor.css('height');
2018 codemirror_inline_editor = PMA_getSQLEditor($inline_editor);
2019 codemirror_inline_editor.getWrapperElement().style.height = height;
2020 codemirror_inline_editor.refresh();
2021 codemirror_inline_editor.focus();
2022 $(codemirror_inline_editor.getWrapperElement())
2023 .bind('keydown', catchKeypressesFromSqlInlineEdit);
2027 .bind('keydown', catchKeypressesFromSqlInlineEdit);
2032 function catchKeypressesFromSqlInlineEdit(event) {
2033 // ctrl-enter is 10 in chrome and ie, but 13 in ff
2034 if (event.ctrlKey && (event.keyCode == 13 || event.keyCode == 10)) {
2035 $("#sql_query_edit_save").trigger('click');
2040 * Adds doc link to single highlighted SQL element
2042 function PMA_doc_add($elm, params)
2044 if (typeof mysql_doc_template == 'undefined') {
2048 var url = PMA_sprintf(
2049 decodeURIComponent(mysql_doc_template),
2052 if (params.length > 1) {
2053 url += '#' + params[1];
2055 var content = $elm.text();
2057 $elm.append('<a target="mysql_doc" class="cm-sql-doc" href="' + url + '">' + content + '</a>');
2061 * Generates doc links for keywords inside highlighted SQL
2063 function PMA_doc_keyword(idx, elm)
2066 /* Skip already processed ones */
2067 if ($elm.find('a').length > 0) {
2070 var keyword = $elm.text().toUpperCase();
2071 var $next = $elm.next('.cm-keyword');
2073 var next_keyword = $next.text().toUpperCase();
2074 var full = keyword + ' ' + next_keyword;
2076 var $next2 = $next.next('.cm-keyword');
2078 var next2_keyword = $next2.text().toUpperCase();
2079 var full2 = full + ' ' + next2_keyword;
2080 if (full2 in mysql_doc_keyword) {
2081 PMA_doc_add($elm, mysql_doc_keyword[full2]);
2082 PMA_doc_add($next, mysql_doc_keyword[full2]);
2083 PMA_doc_add($next2, mysql_doc_keyword[full2]);
2087 if (full in mysql_doc_keyword) {
2088 PMA_doc_add($elm, mysql_doc_keyword[full]);
2089 PMA_doc_add($next, mysql_doc_keyword[full]);
2093 if (keyword in mysql_doc_keyword) {
2094 PMA_doc_add($elm, mysql_doc_keyword[keyword]);
2099 * Generates doc links for builtins inside highlighted SQL
2101 function PMA_doc_builtin(idx, elm)
2104 var builtin = $elm.text().toUpperCase();
2105 if (builtin in mysql_doc_builtin) {
2106 PMA_doc_add($elm, mysql_doc_builtin[builtin]);
2111 * Higlights SQL using CodeMirror.
2113 function PMA_highlightSQL($base)
2115 var $elm = $base.find('code.sql');
2116 $elm.each(function () {
2118 var $pre = $sql.find('pre');
2119 /* We only care about visible elements to avoid double processing */
2120 if ($pre.is(":visible")) {
2121 var $highlight = $('<div class="sql-highlight cm-s-default"></div>');
2122 $sql.append($highlight);
2123 if (typeof CodeMirror != 'undefined') {
2124 CodeMirror.runMode($sql.text(), 'text/x-mysql', $highlight[0]);
2126 $highlight.find('.cm-keyword').each(PMA_doc_keyword);
2127 $highlight.find('.cm-builtin').each(PMA_doc_builtin);
2134 * Updates an element containing code.
2136 * @param jQuery Object $base base element which contains the raw and the
2139 * @param string htmlValue code in HTML format, displayed if code cannot be
2142 * @param string rawValue raw code, used as a parameter for highlighter
2144 * @return bool whether content was updated or not
2146 function PMA_updateCode($base, htmlValue, rawValue)
2148 var $code = $base.find('code');
2149 if ($code.length === 0) {
2153 // Determines the type of the content and appropriate CodeMirror mode.
2154 var type = '', mode = '';
2155 if ($code.hasClass('json')) {
2157 mode = 'application/json';
2158 } else if ($code.hasClass('sql')) {
2160 mode = 'text/x-mysql';
2161 } else if ($code.hasClass('xml')) {
2163 mode = 'application/xml';
2168 // Element used to display unhighlighted code.
2169 var $notHighlighted = $('<pre>' + htmlValue + '</pre>');
2171 // Tries to highlight code using CodeMirror.
2172 if (typeof CodeMirror != 'undefined') {
2173 var $highlighted = $('<div class="' + type + '-highlight cm-s-default"></div>');
2174 CodeMirror.runMode(rawValue, mode, $highlighted[0]);
2175 $notHighlighted.hide();
2176 $code.html('').append($notHighlighted, $highlighted[0]);
2178 $code.html('').append($notHighlighted);
2185 * Show a message on the top of the page for an Ajax request
2189 * 1) var $msg = PMA_ajaxShowMessage();
2190 * This will show a message that reads "Loading...". Such a message will not
2191 * disappear automatically and cannot be dismissed by the user. To remove this
2192 * message either the PMA_ajaxRemoveMessage($msg) function must be called or
2193 * another message must be show with PMA_ajaxShowMessage() function.
2195 * 2) var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2196 * This is a special case. The behaviour is same as above,
2197 * just with a different message
2199 * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
2200 * This will show a message that will disappear automatically and it can also
2201 * be dismissed by the user.
2203 * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
2204 * This will show a message that will not disappear automatically, but it
2205 * can be dismissed by the user after he has finished reading it.
2207 * @param string message string containing the message to be shown.
2208 * optional, defaults to 'Loading...'
2209 * @param mixed timeout number of milliseconds for the message to be visible
2210 * optional, defaults to 5000. If set to 'false', the
2211 * notification will never disappear
2212 * @return jQuery object jQuery Element that holds the message div
2213 * this object can be passed to PMA_ajaxRemoveMessage()
2214 * to remove the notification
2216 function PMA_ajaxShowMessage(message, timeout)
2219 * @var self_closing Whether the notification will automatically disappear
2221 var self_closing = true;
2223 * @var dismissable Whether the user will be able to remove
2224 * the notification by clicking on it
2226 var dismissable = true;
2227 // Handle the case when a empty data.message is passed.
2228 // We don't want the empty message
2229 if (message === '') {
2231 } else if (! message) {
2232 // If the message is undefined, show the default
2233 message = PMA_messages.strLoading;
2234 dismissable = false;
2235 self_closing = false;
2236 } else if (message == PMA_messages.strProcessingRequest) {
2237 // This is another case where the message should not disappear
2238 dismissable = false;
2239 self_closing = false;
2241 // Figure out whether (or after how long) to remove the notification
2242 if (timeout === undefined) {
2244 } else if (timeout === false) {
2245 self_closing = false;
2247 // Create a parent element for the AJAX messages, if necessary
2248 if ($('#loading_parent').length === 0) {
2249 $('<div id="loading_parent"></div>')
2250 .prependTo("#page_content");
2252 // Update message count to create distinct message elements every time
2253 ajax_message_count++;
2254 // Remove all old messages, if any
2255 $("span.ajax_notification[id^=ajax_message_num]").remove();
2257 * @var $retval a jQuery object containing the reference
2258 * to the created AJAX message
2261 '<span class="ajax_notification" id="ajax_message_num_' +
2262 ajax_message_count +
2266 .appendTo("#loading_parent")
2269 // If the notification is self-closing we should create a callback to remove it
2273 .fadeOut('medium', function () {
2274 if ($(this).is(':data(tooltip)')) {
2275 $(this).tooltip('destroy');
2277 // Remove the notification
2281 // If the notification is dismissable we need to add the relevant class to it
2282 // and add a tooltip so that the users know that it can be removed
2284 $retval.addClass('dismissable').css('cursor', 'pointer');
2286 * Add a tooltip to the notification to let the user know that (s)he
2287 * can dismiss the ajax notification by clicking on it.
2292 PMA_messages.strDismiss
2295 PMA_highlightSQL($retval);
2301 * Removes the message shown for an Ajax operation when it's completed
2303 * @param jQuery object jQuery Element that holds the notification
2307 function PMA_ajaxRemoveMessage($this_msgbox)
2309 if ($this_msgbox !== undefined && $this_msgbox instanceof jQuery) {
2313 if ($this_msgbox.is(':data(tooltip)')) {
2314 $this_msgbox.tooltip('destroy');
2316 $this_msgbox.remove();
2322 * Requests SQL for previewing before executing.
2324 * @param jQuery Object $form Form containing query data
2328 function PMA_previewSQL($form)
2330 var form_url = $form.attr('action');
2331 var form_data = $form.serialize() +
2335 var $msgbox = PMA_ajaxShowMessage();
2340 success: function (response) {
2341 PMA_ajaxRemoveMessage($msgbox);
2342 if (response.success) {
2343 var $dialog_content = $('<div/>')
2344 .append(response.sql_data);
2345 var button_options = {};
2346 button_options[PMA_messages.strClose] = function () {
2347 $(this).dialog('close');
2349 var $response_dialog = $dialog_content.dialog({
2353 buttons: button_options,
2354 title: PMA_messages.strPreviewSQL,
2355 close: function () {
2359 // Pretty SQL printing.
2360 PMA_highlightSQL($(this));
2364 PMA_ajaxShowMessage(response.message);
2367 error: function () {
2368 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
2374 * check for reserved keyword column name
2376 * @param jQuery Object $form Form
2378 * @returns true|false
2381 function PMA_checkReservedWordColumns($form) {
2382 var is_confirmed = true;
2385 url: "tbl_structure.php",
2386 data: $form.serialize() + '&reserved_word_check=1',
2387 success: function (data) {
2388 if (typeof data.success != 'undefined' && data.success === true) {
2389 is_confirmed = confirm(data.message);
2394 return is_confirmed;
2397 // This event only need to be fired once after the initial page load
2400 * Allows the user to dismiss a notification
2401 * created with PMA_ajaxShowMessage()
2403 $(document).on('click', 'span.ajax_notification.dismissable', function () {
2404 PMA_ajaxRemoveMessage($(this));
2407 * The below two functions hide the "Dismiss notification" tooltip when a user
2408 * is hovering a link or button that is inside an ajax message
2410 $(document).on('mouseover', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
2411 if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
2412 $(this).parents('span.ajax_notification').tooltip('disable');
2415 $(document).on('mouseout', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
2416 if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
2417 $(this).parents('span.ajax_notification').tooltip('enable');
2423 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
2425 function PMA_showNoticeForEnum(selectElement)
2427 var enum_notice_id = selectElement.attr("id").split("_")[1];
2428 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2], 10) + 1);
2429 var selectedType = selectElement.val();
2430 if (selectedType == "ENUM" || selectedType == "SET") {
2431 $("p#enum_notice_" + enum_notice_id).show();
2433 $("p#enum_notice_" + enum_notice_id).hide();
2438 * Creates a Profiling Chart. Used in sql.js
2439 * and in server_status_monitor.js
2441 function PMA_createProfilingChart(target, data)
2444 var factory = new JQPlotChartFactory();
2445 var chart = factory.createChart(ChartType.PIE, target);
2447 // create the data table and add columns
2448 var dataTable = new DataTable();
2449 dataTable.addColumn(ColumnType.STRING, '');
2450 dataTable.addColumn(ColumnType.NUMBER, '');
2451 dataTable.setData(data);
2453 // draw the chart and return the chart object
2454 chart.draw(dataTable, {
2457 showDataLabels: true
2461 tooltipLocation: 'se',
2463 tooltipAxes: 'pieref',
2464 formatString: '%s, %.9Ps'
2473 // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
2499 * Formats a profiling duration nicely (in us and ms time).
2500 * Used in server_status_monitor.js
2502 * @param integer Number to be formatted, should be in the range of microsecond to second
2503 * @param integer Accuracy, how many numbers right to the comma should be
2504 * @return string The formatted number
2506 function PMA_prettyProfilingNum(num, acc)
2511 acc = Math.pow(10, acc);
2512 if (num * 1000 < 0.1) {
2513 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
2514 } else if (num < 0.1) {
2515 num = Math.round(acc * (num * 1000)) / acc + 'm';
2517 num = Math.round(acc * num) / acc;
2525 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
2527 * @param string Query to be formatted
2528 * @return string The formatted query
2530 function PMA_SQLPrettyPrint(string)
2532 if (typeof CodeMirror == 'undefined') {
2536 var mode = CodeMirror.getMode({}, "text/x-mysql");
2537 var stream = new CodeMirror.StringStream(string);
2538 var state = mode.startState();
2539 var token, tokens = [];
2541 var tabs = function (cnt) {
2543 for (var i = 0; i < 4 * cnt; i++) {
2549 // "root-level" statements
2551 'select': ['select', 'from', 'on', 'where', 'having', 'limit', 'order by', 'group by'],
2552 'update': ['update', 'set', 'where'],
2553 'insert into': ['insert into', 'values']
2555 // don't put spaces before these tokens
2556 var spaceExceptionsBefore = {';': true, ',': true, '.': true, '(': true};
2557 // don't put spaces after these tokens
2558 var spaceExceptionsAfter = {'.': true};
2560 // Populate tokens array
2562 while (! stream.eol()) {
2563 stream.start = stream.pos;
2564 token = mode.token(stream, state);
2565 if (token !== null) {
2566 tokens.push([token, stream.current().toLowerCase()]);
2570 var currentStatement = tokens[0][1];
2572 if (! statements[currentStatement]) {
2575 // Holds all currently opened code blocks (statement, function or generic)
2576 var blockStack = [];
2577 // Holds the type of block from last iteration (the current is in blockStack[0])
2579 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
2580 var newBlock, endBlock;
2581 // How much to indent in the current line
2582 var indentLevel = 0;
2583 // Holds the "root-level" statements
2584 var statementPart, lastStatementPart = statements[currentStatement][0];
2586 blockStack.unshift('statement');
2588 // Iterate through every token and format accordingly
2589 for (var i = 0; i < tokens.length; i++) {
2590 previousBlock = blockStack[0];
2592 // New block => push to stack
2593 if (tokens[i][1] == '(') {
2594 if (i < tokens.length - 1 && tokens[i + 1][0] == 'statement-verb') {
2595 blockStack.unshift(newBlock = 'statement');
2596 } else if (i > 0 && tokens[i - 1][0] == 'builtin') {
2597 blockStack.unshift(newBlock = 'function');
2599 blockStack.unshift(newBlock = 'generic');
2605 // Block end => pop from stack
2606 if (tokens[i][1] == ')') {
2607 endBlock = blockStack[0];
2613 // A subquery is starting
2614 if (i > 0 && newBlock == 'statement') {
2616 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i + 1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
2617 currentStatement = tokens[i + 1][1];
2622 // A subquery is ending
2623 if (endBlock == 'statement' && indentLevel > 0) {
2624 output += "\n" + tabs(indentLevel);
2628 // One less indentation for statement parts (from, where, order by, etc.) and a newline
2629 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
2630 if (statementPart != -1) {
2634 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
2635 output += "\n" + tabs(indentLevel + 1);
2636 lastStatementPart = tokens[i][1];
2638 // Normal indentation and spaces for everything else
2640 if (! spaceExceptionsBefore[tokens[i][1]] &&
2641 ! (i > 0 && spaceExceptionsAfter[tokens[i - 1][1]]) &&
2642 output.charAt(output.length - 1) != ' ') {
2645 if (tokens[i][0] == 'keyword') {
2646 output += tokens[i][1].toUpperCase();
2648 output += tokens[i][1];
2652 // split columns in select and 'update set' clauses, but only inside statements blocks
2653 if ((lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set') &&
2654 tokens[i][1] == ',' && blockStack[0] == 'statement') {
2656 output += "\n" + tabs(indentLevel + 1);
2659 // split conditions in where clauses, but only inside statements blocks
2660 if (lastStatementPart == 'where' &&
2661 (tokens[i][1] == 'and' || tokens[i][1] == 'or' || tokens[i][1] == 'xor')) {
2663 if (blockStack[0] == 'statement') {
2664 output += "\n" + tabs(indentLevel + 1);
2666 // Todo: Also split and or blocks in newlines & indentation++
2667 //if (blockStack[0] == 'generic')
2675 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
2676 * return a jQuery object yet and hence cannot be chained
2678 * @param string question
2679 * @param string url URL to be passed to the callbackFn to make
2681 * @param function callbackFn callback to execute after user clicks on OK
2682 * @param function openCallback optional callback to run when dialog is shown
2685 jQuery.fn.PMA_confirm = function (question, url, callbackFn, openCallback) {
2686 var confirmState = PMA_commonParams.get('confirm');
2687 if (! confirmState) {
2688 // user does not want to confirm
2689 if ($.isFunction(callbackFn)) {
2690 callbackFn.call(this, url);
2694 if (PMA_messages.strDoYouReally === '') {
2699 * @var button_options Object that stores the options passed to jQueryUI
2702 var button_options = [
2704 text: PMA_messages.strOK,
2705 'class': 'submitOK',
2706 click: function () {
2707 $(this).dialog("close");
2708 if ($.isFunction(callbackFn)) {
2709 callbackFn.call(this, url);
2714 text: PMA_messages.strCancel,
2715 'class': 'submitCancel',
2716 click: function () {
2717 $(this).dialog("close");
2722 $('<div/>', {'id': 'confirm_dialog', 'title': PMA_messages.strConfirm})
2725 buttons: button_options,
2726 close: function () {
2735 * jQuery function to sort a table's body after a new row has been appended to it.
2736 * Also fixes the even/odd classes of the table rows at the end.
2738 * @param string text_selector string to select the sortKey's text
2740 * @return jQuery Object for chaining purposes
2742 jQuery.fn.PMA_sort_table = function (text_selector) {
2743 return this.each(function () {
2746 * @var table_body Object referring to the table's <tbody> element
2748 var table_body = $(this);
2750 * @var rows Object referring to the collection of rows in {@link table_body}
2752 var rows = $(this).find('tr').get();
2754 //get the text of the field that we will sort by
2755 $.each(rows, function (index, row) {
2756 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
2759 //get the sorted order
2760 rows.sort(function (a, b) {
2761 if (a.sortKey < b.sortKey) {
2764 if (a.sortKey > b.sortKey) {
2770 //pull out each row from the table and then append it according to it's order
2771 $.each(rows, function (index, row) {
2772 $(table_body).append(row);
2776 //Re-check the classes of each row
2777 $(this).find('tr:odd')
2778 .removeClass('even').addClass('odd')
2781 .removeClass('odd').addClass('even');
2786 * Unbind all event handlers before tearing down a page
2788 AJAX.registerTeardown('functions.js', function () {
2789 $(document).off('submit', "#create_table_form_minimal.ajax");
2790 $(document).off('submit', "form.create_table_form.ajax");
2791 $(document).off('click', "form.create_table_form.ajax input[name=submit_num_fields]");
2792 $(document).off('keyup', "form.create_table_form.ajax input");
2793 $(document).off('change', "input[name=partition_count],input[name=subpartition_count],select[name=partition_by]");
2797 * jQuery coding for 'Create Table'. Used on db_operations.php,
2798 * db_structure.php and db_tracking.php (i.e., wherever
2799 * libraries/display_create_table.lib.php is used)
2801 * Attach Ajax Event handlers for Create Table
2803 AJAX.registerOnload('functions.js', function () {
2805 * Attach event handler for submission of create table form (save)
2807 $(document).on('submit', "form.create_table_form.ajax", function (event) {
2808 event.preventDefault();
2811 * @var the_form object referring to the create table form
2813 var $form = $(this);
2816 * First validate the form; if there is a problem, avoid submitting it
2818 * checkTableEditForm() needs a pure element and not a jQuery object,
2819 * this is why we pass $form[0] as a parameter (the jQuery object
2820 * is actually an array of DOM elements)
2823 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2824 PMA_prepareForAjaxRequest($form);
2825 if (PMA_checkReservedWordColumns($form)) {
2826 PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2827 //User wants to submit the form
2828 $.post($form.attr('action'), $form.serialize() + "&do_save_data=1", function (data) {
2829 if (typeof data !== 'undefined' && data.success === true) {
2830 $('#properties_message')
2831 .removeClass('error')
2833 PMA_ajaxShowMessage(data.message);
2834 // Only if the create table dialog (distinct panel) exists
2835 var $createTableDialog = $("#create_table_dialog");
2836 if ($createTableDialog.length > 0) {
2837 $createTableDialog.dialog("close").remove();
2839 $('#tableslistcontainer').before(data.formatted_sql);
2842 * @var tables_table Object referring to the <tbody> element that holds the list of tables
2844 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
2845 // this is the first table created in this db
2846 if (tables_table.length === 0) {
2847 PMA_commonActions.refreshMain(
2848 PMA_commonParams.get('opendb_url')
2852 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
2854 var curr_last_row = $(tables_table).find('tr:last');
2856 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
2858 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2860 * @var curr_last_row_index Index of {@link curr_last_row}
2862 var curr_last_row_index = parseFloat(curr_last_row_index_string);
2864 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
2866 var new_last_row_index = curr_last_row_index + 1;
2868 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2870 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2872 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2874 $(data.new_table_string)
2875 .appendTo(tables_table);
2878 $(tables_table).PMA_sort_table('th');
2880 // Adjust summary row
2884 //Refresh navigation as a new table has been added
2885 PMA_reloadNavigation();
2886 // Redirect to table structure page on creation of new table
2887 var params_12 = 'ajax_request=true&ajax_page_request=true';
2888 if (! (history && history.pushState)) {
2889 params_12 += PMA_MicroHistory.menus.getRequestParam();
2891 tblStruct_url = 'tbl_structure.php?server=' + data._params.server +
2892 '&db='+ data._params.db + '&token=' + data._params.token +
2893 '&goto=db_structure.php&table=' + data._params.table + '';
2894 $.get(tblStruct_url, params_12, AJAX.responseHandler);
2896 PMA_ajaxShowMessage(
2897 '<div class="error">' + data.error + '</div>',
2903 } // end if (checkTableEditForm() )
2904 }); // end create table form (save)
2907 * Submits the intermediate changes in the table creation form
2908 * to refresh the UI accordingly
2910 function submitChangesInCreateTableForm (actionParam) {
2913 * @var the_form object referring to the create table form
2915 var $form = $('form.create_table_form.ajax');
2917 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
2918 PMA_prepareForAjaxRequest($form);
2920 //User wants to add more fields to the table
2921 $.post($form.attr('action'), $form.serialize() + "&" + actionParam, function (data) {
2922 if (typeof data !== 'undefined' && data.success) {
2923 var $pageContent = $("#page_content");
2924 $pageContent.html(data.message);
2925 PMA_highlightSQL($pageContent);
2926 PMA_verifyColumnsProperties();
2927 PMA_hideShowConnection($('.create_table_form select[name=tbl_storage_engine]'));
2928 PMA_ajaxRemoveMessage($msgbox);
2930 PMA_ajaxShowMessage(data.error);
2936 * Attach event handler for create table form (add fields)
2938 $(document).on('click', "form.create_table_form.ajax input[name=submit_num_fields]", function (event) {
2939 event.preventDefault();
2941 if (!checkFormElementInRange(this.form, 'added_fields', PMA_messages.strLeastColumnError, 1)) {
2945 submitChangesInCreateTableForm('submit_num_fields=1');
2946 }); // end create table form (add fields)
2948 $(document).on('keydown', "form.create_table_form.ajax input[name=added_fields]", function (event) {
2949 if (event.keyCode == 13) {
2950 event.preventDefault();
2951 event.stopImmediatePropagation();
2954 .find('input[name=submit_num_fields]')
2960 * Attach event handler to manage changes in number of partitions and subpartitions
2962 $(document).on('change', "input[name=partition_count],input[name=subpartition_count],select[name=partition_by]", function (event) {
2964 $form = $this.parents('form');
2965 if ($form.is(".create_table_form.ajax")) {
2966 submitChangesInCreateTableForm('submit_partition_change=1');
2972 $("input[value=AUTO_INCREMENT]").change(function(){
2974 var col = /\d/.exec($(this).attr('name'));
2976 var $selectFieldKey = $('select[name="field_key[' + col + ']"]');
2977 if ($selectFieldKey.val() === 'none_'+col) {
2978 $selectFieldKey.val('primary_'+col).change();
2983 .off('click', 'input.preview_sql')
2984 .on('click', 'input.preview_sql', function () {
2985 var $form = $(this).closest('form');
2986 PMA_previewSQL($form);
2992 * Validates the password field in a form
2994 * @see PMA_messages.strPasswordEmpty
2995 * @see PMA_messages.strPasswordNotSame
2996 * @param object $the_form The form to be validated
2999 function PMA_checkPassword($the_form)
3001 // Did the user select 'no password'?
3002 if ($the_form.find('#nopass_1').is(':checked')) {
3005 var $pred = $the_form.find('#select_pred_password');
3006 if ($pred.length && ($pred.val() == 'none' || $pred.val() == 'keep')) {
3011 var $password = $the_form.find('input[name=pma_pw]');
3012 var $password_repeat = $the_form.find('input[name=pma_pw2]');
3013 var alert_msg = false;
3015 if ($password.val() === '') {
3016 alert_msg = PMA_messages.strPasswordEmpty;
3017 } else if ($password.val() != $password_repeat.val()) {
3018 alert_msg = PMA_messages.strPasswordNotSame;
3024 $password_repeat.val('');
3032 * Unbind all event handlers before tearing down a page
3034 AJAX.registerTeardown('functions.js', function () {
3035 $(document).off('click', '#change_password_anchor.ajax');
3038 * Attach Ajax event handlers for 'Change Password' on index.php
3040 AJAX.registerOnload('functions.js', function () {
3042 /* Handler for hostname type */
3043 $(document).on('change', '#select_pred_hostname', function () {
3044 var hostname = $('#pma_hostname');
3045 if (this.value == 'any') {
3047 } else if (this.value == 'localhost') {
3048 hostname.val('localhost');
3049 } else if (this.value == 'thishost' && $(this).data('thishost')) {
3050 hostname.val($(this).data('thishost'));
3051 } else if (this.value == 'hosttable') {
3052 hostname.val('').prop('required', false);
3053 } else if (this.value == 'userdefined') {
3054 hostname.focus().select().prop('required', true);
3058 /* Handler for editing hostname */
3059 $(document).on('change', '#pma_hostname', function () {
3060 $('#select_pred_hostname').val('userdefined');
3061 $('#pma_hostname').prop('required', true);
3064 /* Handler for username type */
3065 $(document).on('change', '#select_pred_username', function () {
3066 if (this.value == 'any') {
3067 $('#pma_username').val('').prop('required', false);
3068 $('#user_exists_warning').css('display', 'none');
3069 } else if (this.value == 'userdefined') {
3070 $('#pma_username').focus().select().prop('required', true);
3074 /* Handler for editing username */
3075 $(document).on('change', '#pma_username', function () {
3076 $('#select_pred_username').val('userdefined');
3077 $('#pma_username').prop('required', true);
3080 /* Handler for password type */
3081 $(document).on('change', '#select_pred_password', function () {
3082 if (this.value == 'none') {
3083 $('#text_pma_pw2').prop('required', false).val('');
3084 $('#text_pma_pw').prop('required', false).val('');
3085 } else if (this.value == 'userdefined') {
3086 $('#text_pma_pw2').prop('required', true);
3087 $('#text_pma_pw').prop('required', true).focus().select();
3089 $('#text_pma_pw2').prop('required', false);
3090 $('#text_pma_pw').prop('required', false);
3094 /* Handler for editing password */
3095 $(document).on('change', '#text_pma_pw,#text_pma_pw2', function () {
3096 $('#select_pred_password').val('userdefined');
3097 $('#text_pma_pw2').prop('required', true);
3098 $('#text_pma_pw').prop('required', true);
3102 * Attach Ajax event handler on the change password anchor
3104 $(document).on('click', '#change_password_anchor.ajax', function (event) {
3105 event.preventDefault();
3107 var $msgbox = PMA_ajaxShowMessage();
3110 * @var button_options Object containing options to be passed to jQueryUI's dialog
3112 var button_options = {};
3113 button_options[PMA_messages.strGo] = function () {
3115 event.preventDefault();
3118 * @var $the_form Object referring to the change password form
3120 var $the_form = $("#change_password_form");
3122 if (! PMA_checkPassword($the_form)) {
3127 * @var this_value String containing the value of the submit button.
3128 * Need to append this for the change password form on Server Privileges
3131 var this_value = $(this).val();
3133 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
3134 $the_form.append('<input type="hidden" name="ajax_request" value="true" />');
3136 $.post($the_form.attr('action'), $the_form.serialize() + '&change_pw=' + this_value, function (data) {
3137 if (typeof data === 'undefined' || data.success !== true) {
3138 PMA_ajaxShowMessage(data.error, false);
3142 var $pageContent = $("#page_content");
3143 $pageContent.prepend(data.message);
3144 PMA_highlightSQL($pageContent);
3145 $("#change_password_dialog").hide().remove();
3146 $("#edit_user_dialog").dialog("close").remove();
3147 PMA_ajaxRemoveMessage($msgbox);
3151 button_options[PMA_messages.strCancel] = function () {
3152 $(this).dialog('close');
3154 $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
3155 if (typeof data === 'undefined' || !data.success) {
3156 PMA_ajaxShowMessage(data.error, false);
3160 $('<div id="change_password_dialog"></div>')
3162 title: PMA_messages.strChangePassword,
3164 close: function (ev, ui) {
3167 buttons: button_options,
3170 .append(data.message);
3171 // for this dialog, we remove the fieldset wrapping due to double headings
3172 $("fieldset#fieldset_change_password")
3173 .find("legend").remove().end()
3174 .find("table.noclick").unwrap().addClass("some-margin")
3175 .find("input#text_pma_pw").focus();
3176 displayPasswordGenerateButton();
3177 $('#fieldset_change_password_footer').hide();
3178 PMA_ajaxRemoveMessage($msgbox);
3179 $('#change_password_form').bind('submit', function (e) {
3182 .closest('.ui-dialog')
3183 .find('.ui-dialog-buttonpane .ui-button')
3188 }); // end handler for change password anchor
3189 }); // end $() for Change Password
3192 * Unbind all event handlers before tearing down a page
3194 AJAX.registerTeardown('functions.js', function () {
3195 $(document).off('change', "select.column_type");
3196 $(document).off('change', "select.default_type");
3197 $(document).off('change', "select.virtuality");
3198 $(document).off('change', 'input.allow_null');
3199 $(document).off('change', '.create_table_form select[name=tbl_storage_engine]');
3202 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
3203 * the page loads and when the selected data type changes
3205 AJAX.registerOnload('functions.js', function () {
3206 // is called here for normal page loads and also when opening
3207 // the Create table dialog
3208 PMA_verifyColumnsProperties();
3210 // needs on() to work also in the Create Table dialog
3211 $(document).on('change', "select.column_type", function () {
3212 PMA_showNoticeForEnum($(this));
3214 $(document).on('change', "select.default_type", function () {
3215 PMA_hideShowDefaultValue($(this));
3217 $(document).on('change', "select.virtuality", function () {
3218 PMA_hideShowExpression($(this));
3220 $(document).on('change', 'input.allow_null', function () {
3221 PMA_validateDefaultValue($(this));
3223 $(document).on('change', '.create_table_form select[name=tbl_storage_engine]', function () {
3224 PMA_hideShowConnection($(this));
3229 * If the chosen storage engine is FEDERATED show connection field. Hide otherwise
3231 * @param $engine_selector storage engine selector
3233 function PMA_hideShowConnection($engine_selector)
3235 var $connection = $('.create_table_form input[name=connection]');
3236 var index = $connection.parent('td').index() + 1;
3237 var $labelTh = $connection.parents('tr').prev('tr').children('th:nth-child(' + index + ')');
3238 if ($engine_selector.val() != 'FEDERATED') {
3240 .prop('disabled', true)
3241 .parent('td').hide();
3245 .prop('disabled', false)
3246 .parent('td').show();
3252 * If the column does not allow NULL values, makes sure that default is not NULL
3254 function PMA_validateDefaultValue($null_checkbox)
3256 if (! $null_checkbox.prop('checked')) {
3257 var $default = $null_checkbox.closest('tr').find('.default_type');
3258 if ($default.val() == 'NULL') {
3259 $default.val('NONE');
3265 * function to populate the input fields on picking a column from central list
3267 * @param string input_id input id of the name field for the column to be populated
3268 * @param integer offset of the selected column in central list of columns
3270 function autoPopulate(input_id, offset)
3272 var db = PMA_commonParams.get('db');
3273 var table = PMA_commonParams.get('table');
3274 input_id = input_id.substring(0, input_id.length - 1);
3275 $('#' + input_id + '1').val(central_column_list[db + '_' + table][offset].col_name);
3276 var col_type = central_column_list[db + '_' + table][offset].col_type.toUpperCase();
3277 $('#' + input_id + '2').val(col_type);
3278 var $input3 = $('#' + input_id + '3');
3279 $input3.val(central_column_list[db + '_' + table][offset].col_length);
3280 if(col_type === 'ENUM' || col_type === 'SET') {
3281 $input3.next().show();
3283 $input3.next().hide();
3285 var col_default = central_column_list[db + '_' + table][offset].col_default.toUpperCase();
3286 var $input4 = $('#' + input_id + '4');
3287 if (col_default !== '' && col_default !== 'NULL' && col_default !== 'CURRENT_TIMESTAMP') {
3288 $input4.val("USER_DEFINED");
3289 $input4.next().next().show();
3290 $input4.next().next().val(central_column_list[db + '_' + table][offset].col_default);
3292 $input4.val(central_column_list[db + '_' + table][offset].col_default);
3293 $input4.next().next().hide();
3295 $('#' + input_id + '5').val(central_column_list[db + '_' + table][offset].col_collation);
3296 var $input6 = $('#' + input_id + '6');
3297 $input6.val(central_column_list[db + '_' + table][offset].col_attribute);
3298 if(central_column_list[db + '_' + table][offset].col_extra === 'on update CURRENT_TIMESTAMP') {
3299 $input6.val(central_column_list[db + '_' + table][offset].col_extra);
3301 if(central_column_list[db + '_' + table][offset].col_extra.toUpperCase() === 'AUTO_INCREMENT') {
3302 $('#' + input_id + '9').prop("checked",true).change();
3304 $('#' + input_id + '9').prop("checked",false);
3306 if(central_column_list[db + '_' + table][offset].col_isNull !== '0') {
3307 $('#' + input_id + '7').prop("checked",true);
3309 $('#' + input_id + '7').prop("checked",false);
3314 * Unbind all event handlers before tearing down a page
3316 AJAX.registerTeardown('functions.js', function () {
3317 $(document).off('click', "a.open_enum_editor");
3318 $(document).off('click', "input.add_value");
3319 $(document).off('click', "#enum_editor td.drop");
3320 $(document).off('click', 'a.central_columns_dialog');
3323 * @var $enum_editor_dialog An object that points to the jQuery
3324 * dialog of the ENUM/SET editor
3326 var $enum_editor_dialog = null;
3328 * Opens the ENUM/SET editor and controls its functions
3330 AJAX.registerOnload('functions.js', function () {
3331 $(document).on('click', "a.open_enum_editor", function () {
3332 // Get the name of the column that is being edited
3333 var colname = $(this).closest('tr').find('input:first').val();
3336 // And use it to make up a title for the page
3337 if (colname.length < 1) {
3338 title = PMA_messages.enum_newColumnVals;
3340 title = PMA_messages.enum_columnVals.replace(
3342 '"' + escapeHtml(decodeURIComponent(colname)) + '"'
3345 // Get the values as a string
3346 var inputstring = $(this)
3350 // Escape html entities
3351 inputstring = $('<div/>')
3354 // Parse the values, escaping quotes and
3355 // slashes on the fly, into an array
3357 var in_string = false;
3358 var curr, next, buffer = '';
3359 for (i = 0; i < inputstring.length; i++) {
3360 curr = inputstring.charAt(i);
3361 next = i == inputstring.length ? '' : inputstring.charAt(i + 1);
3362 if (! in_string && curr == "'") {
3364 } else if (in_string && curr == "\\" && next == "\\") {
3367 } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
3370 } else if (in_string && curr == "'") {
3372 values.push(buffer);
3374 } else if (in_string) {
3378 if (buffer.length > 0) {
3379 // The leftovers in the buffer are the last value (if any)
3380 values.push(buffer);
3383 // If there are no values, maybe the user is about to make a
3384 // new list so we add a few for him/her to get started with.
3385 if (values.length === 0) {
3386 values.push('', '', '', '');
3388 // Add the parsed values to the editor
3389 var drop_icon = PMA_getImage('b_drop.png');
3390 for (i = 0; i < values.length; i++) {
3391 fields += "<tr><td>" +
3392 "<input type='text' value='" + values[i] + "'/>" +
3393 "</td><td class='drop'>" +
3398 * @var dialog HTML code for the ENUM/SET dialog
3400 var dialog = "<div id='enum_editor'>" +
3402 "<legend>" + title + "</legend>" +
3403 "<p>" + PMA_getImage('s_notice.png') +
3404 PMA_messages.enum_hint + "</p>" +
3405 "<table class='values'>" + fields + "</table>" +
3406 "</fieldset><fieldset class='tblFooters'>" +
3407 "<table class='add'><tr><td>" +
3408 "<div class='slider'></div>" +
3410 "<form><div><input type='submit' class='add_value' value='" +
3411 PMA_sprintf(PMA_messages.enum_addValue, 1) +
3412 "'/></div></form>" +
3413 "</td></tr></table>" +
3414 "<input type='hidden' value='" + // So we know which column's data is being edited
3415 $(this).closest('td').find("input").attr("id") +
3420 * @var Defines functions to be called when the buttons in
3421 * the buttonOptions jQuery dialog bar are pressed
3423 var buttonOptions = {};
3424 buttonOptions[PMA_messages.strGo] = function () {
3425 // When the submit button is clicked,
3426 // put the data back into the original form
3427 var value_array = [];
3428 $(this).find(".values input").each(function (index, elm) {
3429 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
3430 value_array.push("'" + val + "'");
3432 // get the Length/Values text field where this value belongs
3433 var values_id = $(this).find("input[type='hidden']").val();
3434 $("input#" + values_id).val(value_array.join(","));
3435 $(this).dialog("close");
3437 buttonOptions[PMA_messages.strClose] = function () {
3438 $(this).dialog("close");
3441 var width = parseInt(
3442 (parseInt($('html').css('font-size'), 10) / 13) * 340,
3448 $enum_editor_dialog = $(dialog).dialog({
3452 title: PMA_messages.enum_editor,
3453 buttons: buttonOptions,
3455 // Focus the "Go" button after opening the dialog
3456 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3458 close: function () {
3462 // slider for choosing how many fields to add
3463 $enum_editor_dialog.find(".slider").slider({
3469 slide: function (event, ui) {
3470 $(this).closest('table').find('input[type=submit]').val(
3471 PMA_sprintf(PMA_messages.enum_addValue, ui.value)
3475 // Focus the slider, otherwise it looks nearly transparent
3476 $('a.ui-slider-handle').addClass('ui-state-focus');
3480 $(document).on('click', 'a.central_columns_dialog', function (e) {
3481 var href = "db_central_columns.php";
3482 var db = PMA_commonParams.get('db');
3483 var table = PMA_commonParams.get('table');
3484 var maxRows = $(this).data('maxrows');
3485 var pick = $(this).data('pick');
3486 if (pick !== false) {
3490 'ajax_request' : true,
3491 'token' : PMA_commonParams.get('token'),
3492 'server' : PMA_commonParams.get('server'),
3493 'db' : PMA_commonParams.get('db'),
3494 'cur_table' : PMA_commonParams.get('table'),
3495 'getColumnList':true
3497 var colid = $(this).closest('td').find("input").attr("id");
3499 if (! (db + '_' + table in central_column_list)) {
3500 central_column_list.push(db + '_' + table);
3505 success: function (data) {
3506 central_column_list[db + '_' + table] = $.parseJSON(data.message);
3512 var list_size = central_column_list[db + '_' + table].length;
3513 var min = (list_size <= maxRows) ? list_size : maxRows;
3514 for (i = 0; i < min; i++) {
3516 fields += '<tr><td><div><span style="font-weight:bold">' +
3517 escapeHtml(central_column_list[db + '_' + table][i].col_name) +
3518 '</span><br><span style="color:gray">' + central_column_list[db + '_' + table][i].col_type;
3520 if (central_column_list[db + '_' + table][i].col_attribute !== '') {
3521 fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_attribute) + ') ';
3523 if (central_column_list[db + '_' + table][i].col_length !== '') {
3524 fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_length) +') ';
3526 fields += escapeHtml(central_column_list[db + '_' + table][i].col_extra) + '</span>' +
3529 fields += '<td><input class="pick" style="width:100%" type="submit" value="' +
3530 PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3534 var result_pointer = i;
3535 var search_in = '<input type="text" class="filter_rows" placeholder="' + PMA_messages.searchList + '">';
3536 if (fields === '') {
3537 fields = PMA_sprintf(PMA_messages.strEmptyCentralList, "'" + db + "'");
3541 if (list_size > maxRows) {
3542 seeMore = "<fieldset class='tblFooters' style='text-align:center;font-weight:bold'>" +
3543 "<a href='#' id='seeMore'>" + PMA_messages.seeMore + "</a></fieldset>";
3545 var central_columns_dialog = "<div style='max-height:400px'>" +
3548 "<table id='col_list' style='width:100%' class='values'>" + fields + "</table>" +
3553 var width = parseInt(
3554 (parseInt($('html').css('font-size'), 10) / 13) * 500,
3560 var buttonOptions = {};
3561 var $central_columns_dialog = $(central_columns_dialog).dialog({
3565 title: PMA_messages.pickColumnTitle,
3566 buttons: buttonOptions,
3568 $('#col_list').on("click", ".pick", function (){
3569 $central_columns_dialog.remove();
3571 $(".filter_rows").on("keyup", function () {
3572 $.uiTableFilter($("#col_list"), $(this).val());
3574 $("#seeMore").click(function() {
3576 min = (list_size <= maxRows + result_pointer) ? list_size : maxRows + result_pointer;
3577 for (i = result_pointer; i < min; i++) {
3579 fields += '<tr><td><div><span style="font-weight:bold">' +
3580 central_column_list[db + '_' + table][i].col_name +
3581 '</span><br><span style="color:gray">' +
3582 central_column_list[db + '_' + table][i].col_type;
3584 if (central_column_list[db + '_' + table][i].col_attribute !== '') {
3585 fields += '(' + central_column_list[db + '_' + table][i].col_attribute + ') ';
3587 if (central_column_list[db + '_' + table][i].col_length !== '') {
3588 fields += '(' + central_column_list[db + '_' + table][i].col_length + ') ';
3590 fields += central_column_list[db + '_' + table][i].col_extra + '</span>' +
3593 fields += '<td><input class="pick" style="width:100%" type="submit" value="' +
3594 PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3598 $("#col_list").append(fields);
3600 if (result_pointer === list_size) {
3601 $('.tblFooters').hide();
3605 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3607 close: function () {
3608 $('#col_list').off("click", ".pick");
3609 $(".filter_rows").off("keyup");
3616 // $(document).on('click', 'a.show_central_list',function(e) {
3619 // When "add a new value" is clicked, append an empty text field
3620 $(document).on('click', "input.add_value", function (e) {
3622 var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
3623 while (num_new_rows--) {
3624 $enum_editor_dialog.find('.values')
3626 "<tr style='display: none;'><td>" +
3627 "<input type='text' />" +
3628 "</td><td class='drop'>" +
3629 PMA_getImage('b_drop.png') +
3637 // Removes the specified row from the enum editor
3638 $(document).on('click', "#enum_editor td.drop", function () {
3639 $(this).closest('tr').hide('fast', function () {
3646 * Ensures indexes names are valid according to their type and, for a primary
3647 * key, lock index name to 'PRIMARY'
3648 * @param string form_id Variable which parses the form name as
3650 * @return boolean false if there is no index form, true else
3652 function checkIndexName(form_id)
3654 if ($("#" + form_id).length === 0) {
3658 // Gets the elements pointers
3659 var $the_idx_name = $("#input_index_name");
3660 var $the_idx_choice = $("#select_index_choice");
3662 // Index is a primary key
3663 if ($the_idx_choice.find("option:selected").val() == 'PRIMARY') {
3664 $the_idx_name.val('PRIMARY');
3665 $the_idx_name.prop("disabled", true);
3670 if ($the_idx_name.val() == 'PRIMARY') {
3671 $the_idx_name.val("");
3673 $the_idx_name.prop("disabled", false);
3677 } // end of the 'checkIndexName()' function
3679 AJAX.registerTeardown('functions.js', function () {
3680 $(document).off('click', '#index_frm input[type=submit]');
3682 AJAX.registerOnload('functions.js', function () {
3684 * Handler for adding more columns to an index in the editor
3686 $(document).on('click', '#index_frm input[type=submit]', function (event) {
3687 event.preventDefault();
3688 var rows_to_add = $(this)
3689 .closest('fieldset')
3693 var tempEmptyVal = function () {
3697 var tempSetFocus = function () {
3698 if ($(this).find("option:selected").val() === '') {
3701 $(this).closest("tr").find("input").focus();
3704 while (rows_to_add--) {
3705 var $indexColumns = $('#index_columns');
3706 var $newrow = $indexColumns
3707 .find('tbody > tr:first')
3710 $indexColumns.find('tbody')
3712 $newrow.find(':input').each(tempEmptyVal);
3713 // focus index size input on column picked
3714 $newrow.find('select').change(tempSetFocus);
3719 function indexEditorDialog(url, title, callback_success, callback_failure)
3721 /*Remove the hidden dialogs if there are*/
3722 var $editIndexDialog = $('#edit_index_dialog');
3723 if ($editIndexDialog.length !== 0) {
3724 $editIndexDialog.remove();
3726 var $div = $('<div id="edit_index_dialog"></div>');
3729 * @var button_options Object that stores the options
3730 * passed to jQueryUI dialog
3732 var button_options = {};
3733 button_options[PMA_messages.strGo] = function () {
3735 * @var the_form object referring to the export form
3737 var $form = $("#index_frm");
3738 var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
3739 PMA_prepareForAjaxRequest($form);
3740 //User wants to submit the form
3741 $.post($form.attr('action'), $form.serialize() + "&do_save_data=1", function (data) {
3742 var $sqlqueryresults = $(".sqlqueryresults");
3743 if ($sqlqueryresults.length !== 0) {
3744 $sqlqueryresults.remove();
3746 if (typeof data !== 'undefined' && data.success === true) {
3747 PMA_ajaxShowMessage(data.message);
3748 var $resultQuery = $('.result_query');
3749 if ($resultQuery.length) {
3750 $resultQuery.remove();
3752 if (data.sql_query) {
3753 $('<div class="result_query"></div>')
3754 .html(data.sql_query)
3755 .prependTo('#page_content');
3756 PMA_highlightSQL($('#page_content'));
3758 $(".result_query .notice").remove();
3759 $resultQuery.prepend(data.message);
3760 /*Reload the field form*/
3761 $("#table_index").remove();
3762 $("<div id='temp_div'><div>")
3763 .append(data.index_table)
3764 .find("#table_index")
3765 .insertAfter("#index_header");
3766 var $editIndexDialog = $("#edit_index_dialog");
3767 if ($editIndexDialog.length > 0) {
3768 $editIndexDialog.dialog("close");
3770 $('div.no_indexes_defined').hide();
3771 if (callback_success) {
3774 PMA_reloadNavigation();
3776 var $temp_div = $("<div id='temp_div'><div>").append(data.error);
3778 if ($temp_div.find(".error code").length !== 0) {
3779 $error = $temp_div.find(".error code").addClass("error");
3783 if (callback_failure) {
3786 PMA_ajaxShowMessage($error, false);
3790 button_options[PMA_messages.strPreviewSQL] = function () {
3791 // Function for Previewing SQL
3792 var $form = $('#index_frm');
3793 PMA_previewSQL($form);
3795 button_options[PMA_messages.strCancel] = function () {
3796 $(this).dialog('close');
3798 var $msgbox = PMA_ajaxShowMessage();
3799 $.get("tbl_indexes.php", url, function (data) {
3800 if (typeof data !== 'undefined' && data.success === false) {
3801 //in the case of an error, show the error message returned.
3802 PMA_ajaxShowMessage(data.error, false);
3804 PMA_ajaxRemoveMessage($msgbox);
3805 // Show dialog if the request was successful
3807 .append(data.message)
3812 open: PMA_verifyColumnsProperties,
3814 buttons: button_options,
3815 close: function () {
3819 $div.find('.tblFooters').remove();
3820 showIndexEditDialog($div);
3825 function showIndexEditDialog($outer)
3828 checkIndexName("index_frm");
3829 var $indexColumns = $('#index_columns');
3830 $indexColumns.find('td').each(function () {
3831 $(this).css("width", $(this).width() + 'px');
3833 $indexColumns.find('tbody').sortable({
3835 containment: $indexColumns.find("tbody"),
3836 tolerance: 'pointer'
3838 PMA_showHints($outer);
3840 // Add a slider for selecting how many columns to add to the index
3841 $outer.find('.slider').slider({
3846 slide: function (event, ui) {
3847 $(this).closest('fieldset').find('input[type=submit]').val(
3848 PMA_sprintf(PMA_messages.strAddToIndex, ui.value)
3852 $('div.add_fields').removeClass('hide');
3853 // focus index size input on column picked
3854 $outer.find('table#index_columns select').change(function () {
3855 if ($(this).find("option:selected").val() === '') {
3858 $(this).closest("tr").find("input").focus();
3860 // Focus the slider, otherwise it looks nearly transparent
3861 $('a.ui-slider-handle').addClass('ui-state-focus');
3862 // set focus on index name input, if empty
3863 var input = $outer.find('input#input_index_name');
3864 if (! input.val()) {
3870 * Function to display tooltips that were
3871 * generated on the PHP side by PMA\libraries\Util::showHint()
3873 * @param object $div a div jquery object which specifies the
3874 * domain for searching for tooltips. If we
3875 * omit this parameter the function searches
3878 function PMA_showHints($div)
3880 if ($div === undefined || ! $div instanceof jQuery || $div.length === 0) {
3883 $div.find('.pma_hint').each(function () {
3885 $(this).children('img'),
3887 $(this).children('span').html()
3892 AJAX.registerOnload('functions.js', function () {
3896 function PMA_mainMenuResizerCallback() {
3897 // 5 px margin for jumping menu in Chrome
3898 return $(document.body).width() - 5;
3900 // This must be fired only once after the initial page load
3902 // Initialise the menu resize plugin
3903 $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
3904 // register resize event
3905 $(window).resize(function () {
3906 $('#topmenu').menuResizer('resize');
3911 * Get the row number from the classlist (for example, row_1)
3913 function PMA_getRowNumber(classlist)
3915 return parseInt(classlist.split(/\s+row_/)[1], 10);
3919 * Changes status of slider
3921 function PMA_set_status_label($element)
3924 if ($element.css('display') == 'none') {
3929 $element.closest('.slide-wrapper').prev().find('span').text(text);
3933 * var toggleButton This is a function that creates a toggle
3934 * sliding button given a jQuery reference
3935 * to the correct DOM element
3937 var toggleButton = function ($obj) {
3938 // In rtl mode the toggle switch is flipped horizontally
3939 // so we need to take that into account
3941 if ($('span.text_direction', $obj).text() == 'ltr') {
3947 * var h Height of the button, used to scale the
3948 * background image and position the layers
3950 var h = $obj.height();
3951 $('img', $obj).height(h);
3952 $('table', $obj).css('bottom', h - 1);
3954 * var on Width of the "ON" part of the toggle switch
3955 * var off Width of the "OFF" part of the toggle switch
3957 var on = $('td.toggleOn', $obj).width();
3958 var off = $('td.toggleOff', $obj).width();
3959 // Make the "ON" and "OFF" parts of the switch the same size
3960 // + 2 pixels to avoid overflowed
3961 $('td.toggleOn > div', $obj).width(Math.max(on, off) + 2);
3962 $('td.toggleOff > div', $obj).width(Math.max(on, off) + 2);
3964 * var w Width of the central part of the switch
3966 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
3967 // Resize the central part of the switch on the top
3968 // layer to match the background
3969 $('table td:nth-child(2) > div', $obj).width(w);
3971 * var imgw Width of the background image
3972 * var tblw Width of the foreground layer
3973 * var offset By how many pixels to move the background
3974 * image, so that it matches the top layer
3976 var imgw = $('img', $obj).width();
3977 var tblw = $('table', $obj).width();
3978 var offset = parseInt(((imgw - tblw) / 2), 10);
3979 // Move the background to match the layout of the top layer
3980 $obj.find('img').css(right, offset);
3982 * var offw Outer width of the "ON" part of the toggle switch
3983 * var btnw Outer width of the central part of the switch
3985 var offw = $('td.toggleOff', $obj).outerWidth();
3986 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
3987 // Resize the main div so that exactly one side of
3988 // the switch plus the central part fit into it.
3989 $obj.width(offw + btnw + 2);
3991 * var move How many pixels to move the
3992 * switch by when toggling
3994 var move = $('td.toggleOff', $obj).outerWidth();
3995 // If the switch is initialized to the
3996 // OFF state we need to move it now.
3997 if ($('div.container', $obj).hasClass('off')) {
3998 if (right == 'right') {
3999 $('div.container', $obj).animate({'left': '-=' + move + 'px'}, 0);
4001 $('div.container', $obj).animate({'left': '+=' + move + 'px'}, 0);
4004 // Attach an 'onclick' event to the switch
4005 $('div.container', $obj).click(function () {
4006 if ($(this).hasClass('isActive')) {
4009 $(this).addClass('isActive');
4011 var $msg = PMA_ajaxShowMessage();
4012 var $container = $(this);
4013 var callback = $('span.callback', this).text();
4014 var operator, url, removeClass, addClass;
4015 // Perform the actual toggle
4016 if ($(this).hasClass('on')) {
4017 if (right == 'right') {
4022 url = $(this).find('td.toggleOff > span').text();
4026 if (right == 'right') {
4031 url = $(this).find('td.toggleOn > span').text();
4032 removeClass = 'off';
4035 $.post(url, {'ajax_request': true}, function (data) {
4036 if (typeof data !== 'undefined' && data.success === true) {
4037 PMA_ajaxRemoveMessage($msg);
4039 .removeClass(removeClass)
4041 .animate({'left': operator + move + 'px'}, function () {
4042 $container.removeClass('isActive');
4046 PMA_ajaxShowMessage(data.error, false);
4047 $container.removeClass('isActive');
4054 * Unbind all event handlers before tearing down a page
4056 AJAX.registerTeardown('functions.js', function () {
4057 $('div.container').unbind('click');
4060 * Initialise all toggle buttons
4062 AJAX.registerOnload('functions.js', function () {
4063 $('div.toggleAjax').each(function () {
4064 var $button = $(this).show();
4065 $button.find('img').each(function () {
4066 if (this.complete) {
4067 toggleButton($button);
4069 $(this).load(function () {
4070 toggleButton($button);
4078 * Unbind all event handlers before tearing down a page
4080 AJAX.registerTeardown('functions.js', function () {
4081 $(document).off('change', 'select.pageselector');
4082 $(document).off('click', 'a.formLinkSubmit');
4083 $('#update_recent_tables').unbind('ready');
4084 $('#sync_favorite_tables').unbind('ready');
4087 AJAX.registerOnload('functions.js', function () {
4090 * Autosubmit page selector
4092 $(document).on('change', 'select.pageselector', function (event) {
4093 event.stopPropagation();
4094 // Check where to load the new content
4095 if ($(this).closest("#pma_navigation").length === 0) {
4096 // For the main page we don't need to do anything,
4097 $(this).closest("form").submit();
4099 // but for the navigation we need to manually replace the content
4100 PMA_navigationTreePagination($(this));
4105 * Load version information asynchronously.
4107 if ($('li.jsversioncheck').length > 0) {
4108 $.getJSON('version_check.php', {'server' : PMA_commonParams.get('server')}, PMA_current_version);
4111 if ($('#is_git_revision').length > 0) {
4112 setTimeout(PMA_display_git_revision, 10);
4121 * Enables the text generated by PMA\libraries\Util::linkOrButton() to be clickable
4123 $(document).on('click', 'a.formLinkSubmit', function (e) {
4124 if (! $(this).hasClass('requireConfirm')) {
4125 submitFormLink($(this));
4130 var $updateRecentTables = $('#update_recent_tables');
4131 if ($updateRecentTables.length) {
4133 $updateRecentTables.attr('href'),
4136 if (typeof data !== 'undefined' && data.success === true) {
4137 $('#pma_recent_list').html(data.list);
4143 // Sync favorite tables from localStorage to pmadb.
4144 if ($('#sync_favorite_tables').length) {
4146 url: $('#sync_favorite_tables').attr("href"),
4150 favorite_tables: (isStorageSupported('localStorage') && typeof window.localStorage.favorite_tables !== 'undefined')
4151 ? window.localStorage.favorite_tables
4155 success: function (data) {
4156 // Update localStorage.
4157 if (isStorageSupported('localStorage')) {
4158 window.localStorage.favorite_tables = data.favorite_tables;
4160 $('#pma_favorite_list').html(data.list);
4167 * Submits the form placed in place of a link due to the excessive url length
4169 * @param $link anchor
4170 * @returns {Boolean}
4172 function submitFormLink($link)
4174 if ($link.attr('href').indexOf('=') != -1) {
4175 var data = $link.attr('href').substr($link.attr('href').indexOf('#') + 1).split('=', 2);
4176 $link.parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
4178 $link.parents('form').submit();
4182 * Initializes slider effect.
4184 function PMA_init_slider()
4186 $('div.pma_auto_slider').each(function () {
4187 var $this = $(this);
4188 if ($this.data('slider_init_done')) {
4191 var $wrapper = $('<div>', {'class': 'slide-wrapper'});
4192 $wrapper.toggle($this.is(':visible'));
4193 $('<a>', {href: '#' + this.id, "class": 'ajax'})
4194 .text($this.attr('title'))
4195 .prepend($('<span>'))
4196 .insertBefore($this)
4197 .click(function () {
4198 var $wrapper = $this.closest('.slide-wrapper');
4199 var visible = $this.is(':visible');
4203 $this[visible ? 'hide' : 'show']('blind', function () {
4204 $wrapper.toggle(!visible);
4205 $wrapper.parent().toggleClass("print_ignore", visible);
4206 PMA_set_status_label($this);
4210 $this.wrap($wrapper);
4211 $this.removeAttr('title');
4212 PMA_set_status_label($this);
4213 $this.data('slider_init_done', 1);
4218 * Initializes slider effect.
4220 AJAX.registerOnload('functions.js', function () {
4225 * Restores sliders to the state they were in before initialisation.
4227 AJAX.registerTeardown('functions.js', function () {
4228 $('div.pma_auto_slider').each(function () {
4229 var $this = $(this);
4231 $this.parent().replaceWith($this);
4232 $this.parent().children('a').remove();
4237 * Creates a message inside an object with a sliding effect
4239 * @param msg A string containing the text to display
4240 * @param $obj a jQuery object containing the reference
4241 * to the element where to put the message
4242 * This is optional, if no element is
4243 * provided, one will be created below the
4244 * navigation links at the top of the page
4246 * @return bool True on success, false on failure
4248 function PMA_slidingMessage(msg, $obj)
4250 if (msg === undefined || msg.length === 0) {
4251 // Don't show an empty message
4254 if ($obj === undefined || ! $obj instanceof jQuery || $obj.length === 0) {
4255 // If the second argument was not supplied,
4256 // we might have to create a new DOM node.
4257 if ($('#PMA_slidingMessage').length === 0) {
4258 $('#page_content').prepend(
4259 '<span id="PMA_slidingMessage" ' +
4260 'style="display: inline-block;"></span>'
4263 $obj = $('#PMA_slidingMessage');
4265 if ($obj.has('div').length > 0) {
4266 // If there already is a message inside the
4267 // target object, we must get rid of it
4271 .fadeOut(function () {
4276 .append('<div>' + msg + '</div>');
4277 // highlight any sql before taking height;
4278 PMA_highlightSQL($obj);
4284 height: $obj.find('div').first().height()
4291 // Object does not already have a message
4292 // inside it, so we simply slide it down
4294 .html('<div>' + msg + '</div>');
4295 // highlight any sql before taking height;
4296 PMA_highlightSQL($obj);
4310 // Set the height of the parent
4311 // to the height of the child
4322 } // end PMA_slidingMessage()
4325 * Attach CodeMirror2 editor to SQL edit area.
4327 AJAX.registerOnload('functions.js', function () {
4328 var $elm = $('#sqlquery');
4329 if ($elm.length > 0) {
4330 if (typeof CodeMirror != 'undefined') {
4331 codemirror_editor = PMA_getSQLEditor($elm);
4332 codemirror_editor.focus();
4333 codemirror_editor.on("blur", updateQueryParameters);
4335 // without codemirror
4337 .bind('blur', updateQueryParameters);
4340 PMA_highlightSQL($('body'));
4342 AJAX.registerTeardown('functions.js', function () {
4343 if (codemirror_editor) {
4344 $('#sqlquery').text(codemirror_editor.getValue());
4345 codemirror_editor.toTextArea();
4346 codemirror_editor = false;
4349 AJAX.registerOnload('functions.js', function () {
4350 // initializes all lock-page elements lock-id and
4351 // val-hash data property
4352 $('#page_content form.lock-page textarea, ' +
4353 '#page_content form.lock-page input[type="text"], '+
4354 '#page_content form.lock-page input[type="number"], '+
4355 '#page_content form.lock-page select').each(function (i) {
4356 $(this).data('lock-id', i);
4357 // val-hash is the hash of default value of the field
4358 // so that it can be compared with new value hash
4359 // to check whether field was modified or not.
4360 $(this).data('val-hash', AJAX.hash($(this).val()));
4363 // initializes lock-page elements (input types checkbox and radio buttons)
4364 // lock-id and val-hash data property
4365 $('#page_content form.lock-page input[type="checkbox"], ' +
4366 '#page_content form.lock-page input[type="radio"]').each(function (i) {
4367 $(this).data('lock-id', i);
4368 $(this).data('val-hash', AJAX.hash($(this).is(":checked")));
4373 * jQuery plugin to correctly filter input fields by value, needed
4374 * because some nasty values may break selector syntax
4377 $.fn.filterByValue = function (value) {
4378 return this.filter(function () {
4379 return $(this).val() === value;
4385 * Return value of a cell in a table.
4387 function PMA_getCellValue(td) {
4389 if ($td.is('.null')) {
4391 } else if ((! $td.is('.to_be_saved')
4393 && $td.data('original_data')
4395 return $td.data('original_data');
4401 $(window).on('popstate', function (event, data) {
4402 $('#printcss').attr('media','print');
4407 * Unbind all event handlers before tearing down a page
4409 AJAX.registerTeardown('functions.js', function () {
4410 $(document).off('click', 'a.themeselect');
4411 $(document).off('change', '.autosubmit');
4412 $('a.take_theme').unbind('click');
4415 AJAX.registerOnload('functions.js', function () {
4419 $(document).on('click', 'a.themeselect', function (e) {
4423 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
4429 * Automatic form submission on change.
4431 $(document).on('change', '.autosubmit', function (e) {
4432 $(this).closest('form').submit();
4438 $('a.take_theme').click(function (e) {
4439 var what = this.name;
4440 if (window.opener && window.opener.document.forms.setTheme.elements.set_theme) {
4441 window.opener.document.forms.setTheme.elements.set_theme.value = what;
4442 window.opener.document.forms.setTheme.submit();
4451 * Produce print preview
4453 function printPreview()
4455 $('#printcss').attr('media','all');
4456 createPrintAndBackButtons();
4460 * Create print and back buttons in preview page
4462 function createPrintAndBackButtons() {
4464 var back_button = $("<input/>",{
4466 value: PMA_messages.back,
4467 id: 'back_button_print_view'
4469 back_button.click(removePrintAndBackButton);
4470 back_button.appendTo('#page_content');
4471 var print_button = $("<input/>",{
4473 value: PMA_messages.print,
4474 id: 'print_button_print_view'
4476 print_button.click(printPage);
4477 print_button.appendTo('#page_content');
4481 * Remove print and back buttons and revert to normal view
4483 function removePrintAndBackButton(){
4484 $('#printcss').attr('media','print');
4485 $('#back_button_print_view').remove();
4486 $('#print_button_print_view').remove();
4492 function printPage(){
4493 if (typeof(window.print) != 'undefined') {
4501 function copyToClipboard()
4503 var textArea = document.createElement("textarea");
4506 // *** This styling is an extra step which is likely not required. ***
4508 // Why is it here? To ensure:
4509 // 1. the element is able to have focus and selection.
4510 // 2. if element was to flash render it has minimal visual impact.
4511 // 3. less flakyness with selection and copying which **might** occur if
4512 // the textarea element is not visible.
4514 // The likelihood is the element won't even render, not even a flash,
4515 // so some of these are just precautions. However in IE the element
4516 // is visible whilst the popup box asking the user for permission for
4517 // the web page to copy to the clipboard.
4520 // Place in top-left corner of screen regardless of scroll position.
4521 textArea.style.position = 'fixed';
4522 textArea.style.top = 0;
4523 textArea.style.left = 0;
4525 // Ensure it has a small width and height. Setting to 1px / 1em
4526 // doesn't work as this gives a negative w/h on some browsers.
4527 textArea.style.width = '2em';
4528 textArea.style.height = '2em';
4530 // We don't need padding, reducing the size if it does flash render.
4531 textArea.style.padding = 0;
4533 // Clean up any borders.
4534 textArea.style.border = 'none';
4535 textArea.style.outline = 'none';
4536 textArea.style.boxShadow = 'none';
4538 // Avoid flash of white box if rendered for any reason.
4539 textArea.style.background = 'transparent';
4541 textArea.value = '';
4543 var elementList = $('#serverinfo a');
4545 elementList.each(function(){
4546 textArea.value += $(this).text().split(':')[1].trim() + '/';
4548 textArea.value += '\t\t' + window.location.href;
4549 textArea.value += '\n';
4551 elementList = $('.notice,.success');
4553 elementList.each(function(){
4554 textArea.value += $(this).clone().children().remove().end().text() + '\n\n';
4557 elementList = $('.sql pre');
4559 elementList.each(function() {
4560 textArea.value += $(this).text() + '\n\n';
4563 elementList = $('.table_results .column_heading a');
4565 elementList.each(function() {
4566 textArea.value += $(this).clone().children().remove().end().text() + '\t';
4569 textArea.value += '\n';
4570 elementList = $('tbody .odd,tbody .even');
4571 elementList.each(function() {
4572 var childElementList = $(this).find('.data span');
4573 childElementList.each(function(){
4574 textArea.value += $(this).clone().children().remove().end().text() + '\t';
4576 textArea.value += '\n';
4579 document.body.appendChild(textArea);
4584 document.execCommand('copy');
4586 alert('Sorry! Unable to copy');
4589 document.body.removeChild(textArea);
4593 * Unbind all event handlers before tearing down a page
4595 AJAX.registerTeardown('functions.js', function () {
4596 $('input#print').unbind('click');
4597 $(document).off('click', 'a.create_view.ajax');
4598 $(document).off('keydown', '#createViewDialog input, #createViewDialog select');
4599 $(document).off('change', '#fkc_checkbox');
4602 AJAX.registerOnload('functions.js', function () {
4603 $('input#print').click(printPage);
4605 * Ajaxification for the "Create View" action
4607 $(document).on('click', 'a.create_view.ajax', function (e) {
4609 PMA_createViewDialog($(this));
4612 * Attach Ajax event handlers for input fields in the editor
4613 * and used to submit the Ajax request when the ENTER key is pressed.
4615 if ($('#createViewDialog').length !== 0) {
4616 $(document).on('keydown', '#createViewDialog input, #createViewDialog select', function (e) {
4617 if (e.which === 13) { // 13 is the ENTER key
4620 // with preventing default, selection by <select> tag
4621 // was also prevented in IE
4624 $(this).closest('.ui-dialog').find('.ui-button:first').click();
4626 }); // end $(document).on()
4629 syntaxHighlighter = PMA_getSQLEditor($('textarea[name="view[as]"]'));
4633 function PMA_createViewDialog($this)
4635 var $msg = PMA_ajaxShowMessage();
4636 var syntaxHighlighter = null;
4637 $.get($this.attr('href') + '&ajax_request=1&ajax_dialog=1', function (data) {
4638 if (typeof data !== 'undefined' && data.success === true) {
4639 PMA_ajaxRemoveMessage($msg);
4640 var buttonOptions = {};
4641 buttonOptions[PMA_messages.strGo] = function () {
4642 if (typeof CodeMirror !== 'undefined') {
4643 syntaxHighlighter.save();
4645 $msg = PMA_ajaxShowMessage();
4646 $.post('view_create.php', $('#createViewDialog').find('form').serialize(), function (data) {
4647 PMA_ajaxRemoveMessage($msg);
4648 if (typeof data !== 'undefined' && data.success === true) {
4649 $('#createViewDialog').dialog("close");
4650 $('.result_query').html(data.message);
4651 PMA_reloadNavigation();
4653 PMA_ajaxShowMessage(data.error, false);
4657 buttonOptions[PMA_messages.strClose] = function () {
4658 $(this).dialog("close");
4660 var $dialog = $('<div/>').attr('id', 'createViewDialog').append(data.message).dialog({
4664 buttons: buttonOptions,
4665 title: PMA_messages.strCreateView,
4666 close: function () {
4670 // Attach syntax highlighted editor
4671 syntaxHighlighter = PMA_getSQLEditor($dialog.find('textarea'));
4672 $('input:visible[type=text]', $dialog).first().focus();
4674 PMA_ajaxShowMessage(data.error);
4680 * Makes the breadcrumbs and the menu bar float at the top of the viewport
4683 if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length === 0) {
4684 var left = $('html').attr('dir') == 'ltr' ? 'left' : 'right';
4685 $("#floating_menubar")
4686 .css('margin-' + left, $('#pma_navigation').width() + $('#pma_navigation_resizer').width())
4689 'position': 'fixed',
4694 .append($('#serverinfo'))
4695 .append($('#topmenucontainer'));
4696 // Allow the DOM to render, then adjust the padding on the body
4697 setTimeout(function () {
4700 $('#floating_menubar').outerHeight(true)
4702 $('#topmenu').menuResizer('resize');
4708 * Scrolls the page to the top if clicking the serverinfo bar
4711 $(document).delegate("#serverinfo, #goto_pagetop", "click", function (event) {
4712 event.preventDefault();
4713 $('html, body').animate({scrollTop: 0}, 'fast');
4717 var checkboxes_sel = "input.checkall:checkbox:enabled";
4719 * Watches checkboxes in a form to set the checkall box accordingly
4721 var checkboxes_changed = function () {
4722 var $form = $(this.form);
4723 // total number of checkboxes in current form
4724 var total_boxes = $form.find(checkboxes_sel).length;
4725 // number of checkboxes checked in current form
4726 var checked_boxes = $form.find(checkboxes_sel + ":checked").length;
4727 var $checkall = $form.find("input.checkall_box");
4728 if (total_boxes == checked_boxes) {
4729 $checkall.prop({checked: true, indeterminate: false});
4731 else if (checked_boxes > 0) {
4732 $checkall.prop({checked: true, indeterminate: true});
4735 $checkall.prop({checked: false, indeterminate: false});
4738 $(document).on("change", checkboxes_sel, checkboxes_changed);
4740 $(document).on("change", "input.checkall_box", function () {
4741 var is_checked = $(this).is(":checked");
4742 $(this.form).find(checkboxes_sel).prop("checked", is_checked)
4743 .parents("tr").toggleClass("marked", is_checked);
4747 * Watches checkboxes in a sub form to set the sub checkall box accordingly
4749 var sub_checkboxes_changed = function () {
4750 var $form = $(this).parent().parent();
4751 // total number of checkboxes in current sub form
4752 var total_boxes = $form.find(checkboxes_sel).length;
4753 // number of checkboxes checked in current sub form
4754 var checked_boxes = $form.find(checkboxes_sel + ":checked").length;
4755 var $checkall = $form.find("input.sub_checkall_box");
4756 if (total_boxes == checked_boxes) {
4757 $checkall.prop({checked: true, indeterminate: false});
4759 else if (checked_boxes > 0) {
4760 $checkall.prop({checked: true, indeterminate: true});
4763 $checkall.prop({checked: false, indeterminate: false});
4766 $(document).on("change", checkboxes_sel + ", input.checkall_box:checkbox:enabled", sub_checkboxes_changed);
4768 $(document).on("change", "input.sub_checkall_box", function () {
4769 var is_checked = $(this).is(":checked");
4770 var $form = $(this).parent().parent();
4771 $form.find(checkboxes_sel).prop("checked", is_checked)
4772 .parents("tr").toggleClass("marked", is_checked);
4776 * Toggles row colors of a set of 'tr' elements starting from a given element
4778 * @param $start Starting element
4780 function toggleRowColors($start)
4782 for (var $curr_row = $start; $curr_row.length > 0; $curr_row = $curr_row.next()) {
4783 if ($curr_row.hasClass('odd')) {
4784 $curr_row.removeClass('odd').addClass('even');
4785 } else if ($curr_row.hasClass('even')) {
4786 $curr_row.removeClass('even').addClass('odd');
4792 * Formats a byte number to human-readable form
4794 * @param bytes the bytes to format
4795 * @param optional subdecimals the number of digits after the point
4796 * @param optional pointchar the char to use as decimal point
4798 function formatBytes(bytes, subdecimals, pointchar) {
4805 var units = ['B', 'KiB', 'MiB', 'GiB'];
4806 for (var i = 0; bytes > 1024 && i < units.length; i++) {
4809 var factor = Math.pow(10, subdecimals);
4810 bytes = Math.round(bytes * factor) / factor;
4811 bytes = bytes.toString().split('.').join(pointchar);
4812 return bytes + ' ' + units[i];
4815 AJAX.registerOnload('functions.js', function () {
4817 * Opens pma more themes link in themes browser, in new window instead of popup
4818 * This way, we don't break HTML validity
4820 $("a._blank").prop("target", "_blank");
4822 * Reveal the login form to users with JS enabled
4823 * and focus the appropriate input field
4825 var $loginform = $('#loginform');
4826 if ($loginform.length) {
4827 $loginform.find('.js-show').show();
4828 if ($('#input_username').val()) {
4829 $('#input_password').focus();
4831 $('#input_username').focus();
4837 * Dynamically adjust the width of the boxes
4838 * on the table and db operations pages
4841 function DynamicBoxes() {
4842 var $boxContainer = $('#boxContainer');
4843 if ($boxContainer.length) {
4844 var minWidth = $boxContainer.data('box-width');
4845 var viewport = $(window).width() - $('#pma_navigation').width();
4846 var slots = Math.floor(viewport / minWidth);
4847 $boxContainer.children()
4849 if (viewport < minWidth) {
4850 $(this).width(minWidth);
4852 $(this).css('width', ((1 / slots) * 100) + "%");
4855 .removeClass('clearfloat')
4856 .filter(':nth-child(' + slots + 'n+1)')
4857 .addClass('clearfloat');
4860 AJAX.registerOnload('functions.js', function () {
4864 $(window).resize(DynamicBoxes);
4869 * Formats timestamp for display
4871 function PMA_formatDateTime(date, seconds) {
4872 var result = $.datepicker.formatDate('yy-mm-dd', date);
4873 var timefmt = 'HH:mm';
4875 timefmt = 'HH:mm:ss';
4877 return result + ' ' + $.datepicker.formatTime(
4879 hour: date.getHours(),
4880 minute: date.getMinutes(),
4881 second: date.getSeconds()
4887 * Check than forms have less fields than max allowed by PHP.
4889 function checkNumberOfFields() {
4890 if (typeof maxInputVars === 'undefined') {
4893 if (false === maxInputVars) {
4896 $('form').each(function() {
4897 var nbInputs = $(this).find(':input').length;
4898 if (nbInputs > maxInputVars) {
4899 var warning = PMA_sprintf(PMA_messages.strTooManyInputs, maxInputVars);
4900 PMA_ajaxShowMessage(warning);
4910 * Ignore the displayed php errors.
4911 * Simply removes the displayed errors.
4913 * @param clearPrevErrors whether to clear errors stored
4914 * in $_SESSION['prev_errors'] at server
4917 function PMA_ignorePhpErrors(clearPrevErrors){
4918 if (typeof(clearPrevErrors) === "undefined" ||
4919 clearPrevErrors === null
4923 // send AJAX request to error_report.php with send_error_report=0, exception_type=php & token.
4924 // It clears the prev_errors stored in session.
4925 if(clearPrevErrors){
4926 var $pmaReportErrorsForm = $('#pma_report_errors_form');
4927 $pmaReportErrorsForm.find('input[name="send_error_report"]').val(0); // change send_error_report to '0'
4928 $pmaReportErrorsForm.submit();
4931 // remove displayed errors
4932 var $pmaErrors = $('#pma_errors');
4933 $pmaErrors.fadeOut( "slow");
4934 $pmaErrors.remove();
4938 * Unbind all event handlers before tearing down a page
4940 AJAX.registerTeardown('functions.js', function(){
4941 $(document).off('keydown', 'form input, form textarea, form select');
4944 AJAX.registerOnload('functions.js', function () {
4946 * Handle 'Ctrl/Alt + Enter' form submits
4948 $('form input, form textarea, form select').on('keydown', function(e){
4949 if((e.ctrlKey && e.which == 13) || (e.altKey && e.which == 13)) {
4950 $form = $(this).closest('form');
4951 if (! $form.find('input[type="submit"]') ||
4952 ! $form.find('input[type="submit"]').click()
4961 * Unbind all event handlers before tearing down a page
4963 AJAX.registerTeardown('functions.js', function(){
4964 $(document).off('change', 'input[type=radio][name="pw_hash"]');
4967 AJAX.registerOnload('functions.js', function(){
4969 * Display warning regarding SSL when sha256_password
4970 * method is selected
4971 * Used in user_password.php (Change Password link on index.php)
4973 $(document).on("change", 'select#select_authentication_plugin_cp', function() {
4974 if (this.value === 'sha256_password') {
4975 $('#ssl_reqd_warning_cp').show();
4977 $('#ssl_reqd_warning_cp').hide();