Translated using Weblate (Interlingua)
[phpmyadmin.git] / js / functions.js
blobfc5c8abe35703d9b4e29beb602859618d9c6389c
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * general function, usually for data manipulation pages
4  *
5  */
7 /**
8  * @var sql_box_locked lock for the sqlbox textarea in the querybox
9  */
10 var sql_box_locked = false;
12 /**
13  * @var array holds elements which content should only selected once
14  */
15 var only_once_elements = [];
17 /**
18  * @var   int   ajax_message_count   Number of AJAX messages shown since page load
19  */
20 var ajax_message_count = 0;
22 /**
23  * @var codemirror_editor object containing CodeMirror editor of the query editor in SQL tab
24  */
25 var codemirror_editor = false;
27 /**
28  * @var codemirror_editor object containing CodeMirror editor of the inline query editor
29  */
30 var codemirror_inline_editor = false;
32 /**
33  * @var sql_autocomplete_in_progress bool shows if Table/Column name autocomplete AJAX is in progress
34  */
35 var sql_autocomplete_in_progress = false;
37 /**
38  * @var sql_autocomplete object containing list of columns in each table
39  */
40 var sql_autocomplete = false;
42 /**
43  * @var sql_autocomplete_default_table string containing default table to autocomplete columns
44  */
45 var sql_autocomplete_default_table = '';
47 /**
48  * @var central_column_list array to hold the columns in central list per db.
49  */
50 var central_column_list = [];
52 /**
53  * @var primary_indexes array to hold 'Primary' index columns.
54  */
55 var primary_indexes = [];
57 /**
58  * @var unique_indexes array to hold 'Unique' index columns.
59  */
60 var unique_indexes = [];
62 /**
63  * @var indexes array to hold 'Index' columns.
64  */
65 var indexes = [];
67 /**
68  * @var fulltext_indexes array to hold 'Fulltext' columns.
69  */
70 var fulltext_indexes = [];
72 /**
73  * @var spatial_indexes array to hold 'Spatial' columns.
74  */
75 var spatial_indexes = [];
77 /**
78  * Make sure that ajax requests will not be cached
79  * by appending a random variable to their parameters
80  */
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});
87     }
88 });
91  * Adds a date/time picker to an element
92  *
93  * @param object  $this_element   a jQuery object pointing to the element
94  */
95 function PMA_addDatepicker($this_element, type, options)
97     var showTimepicker = true;
98     if (type=="date") {
99         showTimepicker = false;
100     }
102     var defaultOptions = {
103         showOn: 'button',
104         buttonImage: themeCalendarImage, // defined in js/messages.php
105         buttonImageOnly: true,
106         stepMinutes: 1,
107         stepHours: 1,
108         showSecond: true,
109         showMillisec: true,
110         showMicrosec: 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,
117         showAnim: '',
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 () {
124                     inst.dpDiv.css({
125                         top: 0,
126                         left: 0,
127                         position: 'relative'
128                     });
129                 }, 0);
130             }
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'));
134             }, 0);
135         },
136         onSelect: function() {
137             $this_element.data('datepicker').inline = true;
138         },
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;
144             }
145         }
146     };
147     if (type == "datetime" || type == "timestamp") {
148         $this_element.datetimepicker($.extend(defaultOptions, options));
149     }
150     else if (type == "date") {
151         $this_element.datetimepicker($.extend(defaultOptions, options));
152     }
153     else if (type == "time") {
154         $this_element.timepicker($.extend(defaultOptions, options));
155     }
159  * Add a date/time picker to each element that needs it
160  * (only when jquery-ui-timepicker-addon.js is loaded)
161  */
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){
174                 if (decimals > 3) {
175                     showMillisec = true;
176                     showMicrosec = true;
177                     timeFormat = 'HH:mm:ss.lc';
178                 } else {
179                     showMillisec = true;
180                     timeFormat = 'HH:mm:ss.l';
181                 }
182             }
183             PMA_addDatepicker($(this), type, {
184                 showMillisec: showMillisec,
185                 showMicrosec: showMicrosec,
186                 timeFormat: timeFormat
187             });
188         });
189     }
193  * Handle redirect and reload flags sent as part of AJAX requests
195  * @param data ajax response data
196  */
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';
202         } else {
203             window.location.href += '&session_expired=1';
204         }
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();
210     }
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
220  */
221 function PMA_getSQLEditor($textarea, options, resize, lintOptions) {
222     if ($textarea.length > 0 && typeof CodeMirror !== 'undefined') {
224         // merge options for CodeMirror
225         var defaults = {
226             lineNumbers: true,
227             matchBrackets: true,
228             extraKeys: {"Ctrl-Space": "autocomplete"},
229             hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
230             indentUnit: 4,
231             mode: "text/x-mysql",
232             lineWrapping: true
233         };
235         if (CodeMirror.sqlLint) {
236             $.extend(defaults, {
237                 gutters: ["CodeMirror-lint-markers"],
238                 lint: {
239                     "getAnnotations": CodeMirror.sqlLint,
240                     "async": true,
241                     "lintOptions": lintOptions
242                 }
243             });
244         }
246         $.extend(true, defaults, options);
248         // create CodeMirror editor
249         var codemirrorEditor = CodeMirror.fromTextArea($textarea[0], defaults);
250         // allow resizing
251         if (! resize) {
252             resize = 'vertical';
253         }
254         var handles = '';
255         if (resize == 'vertical') {
256             handles = 'n, s';
257         }
258         if (resize == 'both') {
259             handles = 'all';
260         }
261         if (resize == 'horizontal') {
262             handles = 'e, w';
263         }
264         $(codemirrorEditor.getWrapperElement())
265             .css('resize', resize)
266             .resizable({
267                 handles: handles,
268                 resize: function() {
269                     codemirrorEditor.setSize($(this).width(), $(this).height());
270                 }
271             });
272         // enable autocomplete
273         codemirrorEditor.on("inputRead", codemirrorAutocompleteOnInputRead);
275         return codemirrorEditor;
276     }
277     return null;
281  * Clear text selection
282  */
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();
288         if (sel.empty) {
289             sel.empty();
290         }
291         if (sel.removeAllRanges) {
292             sel.removeAllRanges();
293         }
294     }
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
306  */
307 function PMA_tooltip($elements, item, myContent, additionalOptions)
309     if ($('#no_hint').length > 0) {
310         return;
311     }
313     var defaultOptions = {
314         content: myContent,
315         items:  item,
316         tooltipClass: "tooltip",
317         track: true,
318         show: false,
319         hide: false
320     };
322     $elements.tooltip($.extend(true, defaultOptions, additionalOptions));
326  * HTML escaping
327  */
329 function escapeHtml(unsafe) {
330     if (typeof(unsafe) != 'undefined') {
331         return unsafe
332             .toString()
333             .replace(/&/g, "&")
334             .replace(/</g, "&lt;")
335             .replace(/>/g, "&gt;")
336             .replace(/"/g, "&quot;")
337             .replace(/'/g, "&#039;");
338     } else {
339         return false;
340     }
343 function escapeJsString(unsafe) {
344     if (typeof(unsafe) != 'undefined') {
345         return unsafe
346             .toString()
347             .replace("\000", '')
348             .replace('\\', '\\\\')
349             .replace('\'', '\\\'')
350             .replace("&#039;", "\\\&#039;")
351             .replace('"', '\"')
352             .replace("&quot;", "\&quot;")
353             .replace("\n", '\n')
354             .replace("\r", '\r')
355             .replace(/<\/script/gi, '</\' + \'script')
356     } else {
357         return false;
358     }
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.
368  */
369 function PMA_hideShowDefaultValue($default_type)
371     if ($default_type.val() == 'USER_DEFINED') {
372         $default_type.siblings('.default_value').show().focus();
373     } else {
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);
378         }
379     }
383  * Hides/shows the input field for column expression based on whether
384  * VIRTUAL/PERSISTENT is selected
386  * @param $virtuality virtuality dropdown
387  */
388 function PMA_hideShowExpression($virtuality)
390     if ($virtuality.val() === '') {
391         $virtuality.siblings('.expression').hide();
392     } else {
393         $virtuality.siblings('.expression').show();
394     }
398  * Show notices for ENUM columns; add/hide the default value
400  */
401 function PMA_verifyColumnsProperties()
403     $("select.column_type").each(function () {
404         PMA_showNoticeForEnum($(this));
405     });
406     $("select.default_type").each(function () {
407         PMA_hideShowDefaultValue($(this));
408     });
409     $('select.virtuality').each(function () {
410         PMA_hideShowExpression($(this));
411     });
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
419  */
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" />');
424     }
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
433  */
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);
444     passwd.value = '';
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);
449     }
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);
453     } else {
454         // Fallback to Math.random
455         for (var i = 0; i < passwordlength; i++) {
456             randomWords[i] = Math.floor(Math.random() * pwchars.length);
457         }
458     }
460     for (var i = 0; i < passwordlength; i++) {
461         passwd.value += pwchars.charAt(Math.abs(randomWords[i]) % pwchars.length);
462     }
464     passwd_form.text_pma_pw.value = passwd.value;
465     passwd_form.text_pma_pw2.value = passwd.value;
466     return true;
470  * Version string to integer conversion.
471  */
472 function parseVersionString(str)
474     if (typeof(str) != 'string') { return false; }
475     var add = 0;
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 */
487             add = 0;
488         }
489     }
490     // Parse version
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.
502  */
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) +
511             '</span>';
512         if (latest > current) {
513             var message = PMA_sprintf(
514                 PMA_messages.strNewerVersion,
515                 escapeHtml(data.version),
516                 escapeHtml(data.date)
517             );
518             var htmlClass = 'notice';
519             if (Math.floor(latest / 10000) === Math.floor(current / 10000)) {
520                 /* Security update */
521                 htmlClass = 'error';
522             }
523             $('#newer_version_notice').remove();
524             $('#maincontainer').after('<div id="newer_version_notice" class="' + htmlClass + '">' + message + '</div>');
525         }
526         if (latest === current) {
527             version_information_message = ' (' + PMA_messages.strUpToDate + ')';
528         }
529         var $liPmaVersion = $('#li_pma_version');
530         $liPmaVersion.find('span.latest').remove();
531         $liPmaVersion.append(version_information_message);
532     }
536  * Loads Git revision data from ajax for index.php
537  */
538 function PMA_display_git_revision()
540     $('#is_git_revision').remove();
541     $('#li_pma_version_git').remove();
542     $.get(
543         "index.php",
544         {
545             "server": PMA_commonParams.get('server'),
546             "token": PMA_commonParams.get('token'),
547             "git_revision": true,
548             "ajax_request": true,
549             "no_debug": true
550         },
551         function (data) {
552             if (typeof data !== 'undefined' && data.success === true) {
553                 $(data.message).insertAfter('#li_pma_version');
554             }
555         }
556     );
560  * for libraries/display_change_password.lib.php
561  *     libraries/user_password.php
563  */
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
579  */
580 function selectContent(element, lock, only_once)
582     if (only_once && only_once_elements[element.name]) {
583         return;
584     }
586     only_once_elements[element.name] = true;
588     if (lock) {
589         return;
590     }
592     element.select();
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
603  */
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') {
609         return true;
610     }
612     var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, theSqlQuery));
613     if (is_confirmed) {
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]';
618             }
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';
625         }
626     }
628     return is_confirmed;
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()
643  */
644 function confirmQuery(theForm1, sqlQuery1)
646     // Confirmation is not required in the configuration file
647     if (PMA_messages.strDoYouReally === '') {
648         return true;
649     }
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);
656             theForm1.reset();
657             sqlQuery1.focus();
658             return false;
659         } // end if
660     } // end if
662     // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
663     //
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)) {
678         var message;
679         if (sqlQuery1.value.length > 100) {
680             message = sqlQuery1.value.substr(0, 100) + '\n    ...';
681         } else {
682             message = sqlQuery1.value;
683         }
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
688         if (is_confirmed) {
689             theForm1.elements.is_js_confirmed.value = 1;
690             return true;
691         }
692         // statement is rejected -> do not submit the form
693         else {
694             window.focus();
695             sqlQuery1.focus();
696             return false;
697         } // end if (handle confirm box result)
698     } // end if (display confirm box)
700     return true;
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()
712  */
713 function checkSqlQuery(theForm)
715     // get the textarea element containing the query
716     var sqlQuery;
717     if (codemirror_editor) {
718         codemirror_editor.save();
719         sqlQuery = codemirror_editor.getValue();
720     } else {
721         sqlQuery = theForm.elements.sql_query.value;
722     }
723     var isEmpty  = 1;
724     var space_re = new RegExp('\\s+');
725     if (typeof(theForm.elements.sql_file) != 'undefined' &&
726             theForm.elements.sql_file.value.replace(space_re, '') !== '') {
727         return true;
728     }
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) {
732         return true;
733     }
734     // Checks for "DROP/DELETE/ALTER" statements
735     if (sqlQuery.replace(space_re, '') !== '') {
736         return confirmQuery(theForm, sqlQuery);
737     }
738     theForm.reset();
739     isEmpty = 1;
741     if (isEmpty) {
742         alert(PMA_messages.strFormEmpty);
743         codemirror_editor.focus();
744         return false;
745     }
747     return true;
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
758  */
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
775  */
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') {
782         min = 0;
783     }
784     if (typeof(max) == 'undefined') {
785         max = Number.MAX_VALUE;
786     }
788     // It's not a number
789     if (isNaN(val)) {
790         theField.select();
791         alert(PMA_messages.strEnterValidNumber);
792         theField.focus();
793         return false;
794     }
795     // It's a number but it is not between min and max
796     else if (val < min || val > max) {
797         theField.select();
798         alert(PMA_sprintf(message, val));
799         theField.focus();
800         return false;
801     }
802     // It's a valid number
803     else {
804         theField.value = val;
805     }
806     return true;
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";
821         elm = $(id);
822         val = elm.val();
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() !== "") {
828                 elm2.select();
829                 alert(PMA_messages.strEnterValidLength);
830                 elm2.focus();
831                 return false;
832             }
833         }
835         if (atLeastOneField === 0) {
836             id = "field_" + i + "_1";
837             if (!emptyCheckTheField(theForm, id)) {
838                 atLeastOneField = 1;
839             }
840         }
841     }
842     if (atLeastOneField === 0) {
843         var theField = theForm.elements.field_0_1;
844         alert(PMA_messages.strFormEmpty);
845         theField.focus();
846         return false;
847     }
849     // at least this section is under jQuery
850     var $input = $("input.textfield[name='table']");
851     if ($input.val() === "") {
852         alert(PMA_messages.strFormEmpty);
853         $input.focus();
854         return false;
855     }
857     return true;
858 } // enf of the 'checkTableEditForm()' function
861  * True if last click is to check a row.
862  */
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.
868  */
869 var last_clicked_row = -1;
872  * Zero-based index of last shift clicked row.
873  */
874 var last_shift_clicked_row = -1;
876 var _idleSecondsCounter = 0;
877 var IncInterval;
878 var updateTimeout;
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;
888     };
889     $(document).on('mousemove',function() {
890         _idleSecondsCounter = 0;
891     });
892     document.onkeypress = function() {
893         _idleSecondsCounter = 0;
894     };
896     function SetIdleTime() {
897         _idleSecondsCounter++;
898     }
899     function UpdateIdleTime() {
900         var href = 'index.php';
901         var params = {
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
907             };
908         $.ajax({
909                 type: 'POST',
910                 url: href,
911                 data: params,
912                 success: function (data) {
913                     if (data.success) {
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;
918                             }
919                             updateTimeout = window.setTimeout(UpdateIdleTime, interval);
920                         } else {
921                             updateTimeout = window.setTimeout(UpdateIdleTime, 2000);
922                         }
923                     } else { //timeout occurred
924                         if(isStorageSupported('sessionStorage')){
925                             window.sessionStorage.clear();
926                         }
927                         window.location.reload(true);
928                         clearInterval(IncInterval);
929                     }
930                 }
931             });
932     }
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;
938         }
939         updateTimeout = window.setTimeout(UpdateIdleTime, interval);
940     }
943  * Unbind all event handlers before tearing down a page
944  */
945 AJAX.registerTeardown('functions.js', function () {
946     $(document).off('click', 'input:checkbox.checkall');
948 AJAX.registerOnload('functions.js', function () {
949     /**
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
952      * this behavior.
953      */
955     $(document).on('click', 'input:checkbox.checkall', function (e) {
956         $this = $(this);
957         var $tr = $this.closest('tr');
958         var $table = $this.closest('table');
960         if (!e.shiftKey || last_clicked_row == -1) {
961             // usual click
963             var $checkbox = $tr.find(':checkbox.checkall');
964             var checked = $this.prop('checked');
965             $checkbox.prop('checked', checked).trigger('change');
966             if (checked) {
967                 $tr.addClass('marked');
968             } else {
969                 $tr.removeClass('marked');
970             }
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;
976         } else {
977             // handle the shift click
978             PMA_clearSelection();
979             var start, end;
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;
986                 } else {
987                     start = last_shift_clicked_row;
988                     end = last_clicked_row;
989                 }
990                 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
991                     .slice(start, end + 1)
992                     .removeClass('marked')
993                     .find(':checkbox')
994                     .prop('checked', false)
995                     .trigger('change');
996             }
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;
1002                 end = curr_row;
1003             } else {
1004                 start = curr_row;
1005                 end = last_clicked_row;
1006             }
1007             $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
1008                 .slice(start, end + 1)
1009                 .addClass('marked')
1010                 .find(':checkbox')
1011                 .prop('checked', true)
1012                 .trigger('change');
1014             // remember the last shift clicked row
1015             last_shift_clicked_row = curr_row;
1016         }
1017     });
1019     addDateTimePicker();
1021     /**
1022      * Add attribute to text boxes for iOS devices (based on bugID: 3508912)
1023      */
1024     if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) {
1025         $('input[type=text]').attr('autocapitalize', 'off').attr('autocorrect', 'off');
1026     }
1030  * Row highlighting in horizontal mode (use "on"
1031  * so that it works also for pages reached via AJAX)
1032  */
1033 /*AJAX.registerOnload('functions.js', function () {
1034     $(document).on('hover', 'tr.odd, tr.even',function (event) {
1035         var $tr = $(this);
1036         $tr.toggleClass('hover',event.type=='mouseover');
1037         $tr.children().toggleClass('hover',event.type=='mouseover');
1038     });
1039 })*/
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
1046  */
1047 function markAllRows(container_id)
1050     $("#" + container_id).find("input:checkbox:enabled").prop('checked', true)
1051     .trigger("change")
1052     .parents("tr").addClass("marked");
1053     return true;
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
1061  */
1062 function unMarkAllRows(container_id)
1065     $("#" + container_id).find("input:checkbox:enabled").prop('checked', false)
1066     .trigger("change")
1067     .parents("tr").removeClass("marked");
1068     return true;
1072   * Checks/unchecks all options of a <select> element
1073   *
1074   * @param string   the form name
1075   * @param string   the element name
1076   * @param boolean  whether to check or to uncheck options
1077   *
1078   * @return boolean  always true
1079   */
1080 function setSelectOptions(the_form, the_select, do_check)
1082     $("form[name='" + the_form + "'] select[name='" + the_select + "']").find("option").prop('selected', do_check);
1083     return true;
1084 } // end of the 'setSelectOptions()' function
1087  * Sets current value for query box.
1088  */
1089 function setQuery(query)
1091     if (codemirror_editor) {
1092         codemirror_editor.setValue(query);
1093         codemirror_editor.focus();
1094     } else {
1095         document.sqlform.sql_query.value = query;
1096         document.sqlform.sql_query.focus();
1097     }
1101  * Handles 'Simulate query' button on SQL query box.
1103  * @return void
1104  */
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');
1109     var query = '';
1111     if (codemirror_editor) {
1112         query = codemirror_editor.getValue();
1113     } else {
1114         query = $('#sqlquery').val();
1115     }
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 +
1124                 '" />');
1125         }
1126     } else {
1127         if ($simulateDml.length) {
1128             $simulateDml.remove();
1129         }
1130     }
1134   * Create quick sql statements.
1135   *
1136   */
1137 function insertQuery(queryType)
1139     if (queryType == "clear") {
1140         setQuery('');
1141         return;
1142     } else if (queryType == "format") {
1143         if (codemirror_editor) {
1144             $('#querymessage').html(PMA_messages.strFormatting +
1145                 '&nbsp;<img class="ajaxIcon" src="' +
1146                 pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1147             var href = 'db_sql_format.php';
1148             var params = {
1149                 'ajax_request': true,
1150                 'token': PMA_commonParams.get('token'),
1151                 'sql': codemirror_editor.getValue()
1152             };
1153             $.ajax({
1154                 type: 'POST',
1155                 url: href,
1156                 data: params,
1157                 success: function (data) {
1158                     if (data.success) {
1159                         codemirror_editor.setValue(data.sql);
1160                     }
1161                     $('#querymessage').html('');
1162                 }
1163             });
1164         }
1165         return;
1166     } else if (queryType == "saved") {
1167         if ($.cookie('auto_saved_sql')) {
1168             setQuery($.cookie('auto_saved_sql'));
1169         } else {
1170             PMA_ajaxShowMessage(PMA_messages.strNoAutoSavedQuery);
1171         }
1172         return;
1173     }
1175     var query = "";
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 = "";
1182         var valDis = "";
1183         var editDis = "";
1184         var NbSelect = 0;
1185         for (var i = 0; i < myListBox.options.length; i++) {
1186             NbSelect++;
1187             if (NbSelect > 1) {
1188                 columnsList += ", ";
1189                 valDis += ",";
1190                 editDis += ",";
1191             }
1192             columnsList += myListBox.options[i].value;
1193             valDis += "[value-" + NbSelect + "]";
1194             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
1195         }
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";
1206         }
1207         setQuery(query);
1208         sql_box_locked = false;
1209     }
1214   * Inserts multiple fields.
1215   *
1216   */
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 = "";
1225         var NbSelect = 0;
1226         for (var i = 0; i < myListBox.options.length; i++) {
1227             if (myListBox.options[i].selected) {
1228                 NbSelect++;
1229                 if (NbSelect > 1) {
1230                     columnsList += ", ";
1231                 }
1232                 columnsList += myListBox.options[i].value;
1233             }
1234         }
1236         /* CodeMirror support */
1237         if (codemirror_editor) {
1238             codemirror_editor.replaceSelection(columnsList);
1239         //IE support
1240         } else if (document.selection) {
1241             myQuery.focus();
1242             var sel = document.selection.createRange();
1243             sel.text = columnsList;
1244             document.sqlform.insert.focus();
1245         }
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);
1253         } else {
1254             myQuery.value += columnsList;
1255         }
1256         sql_box_locked = false;
1257     }
1261  * Updates the input fields for the parameters based on the query
1262  */
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);
1275                 }
1276             });
1277         } else {
1278             $('#parametersDiv').text(PMA_messages.strNoParam);
1279             return;
1280         }
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);
1293             }
1294             $('#parametersDiv').append($param);
1295         });
1296     } else {
1297         $('#parametersDiv').empty();
1298     }
1302   * Refresh/resize the WYSIWYG scratchboard
1303   */
1304 function refreshLayout()
1306     var $elm = $('#pdflayout');
1307     var orientation = $('#orientation_opt').val();
1308     var paper = 'A4';
1309     var $paperOpt = $('#paper_opt');
1310     if ($paperOpt.length == 1) {
1311         paper = $paperOpt.val();
1312     }
1313     var posa = 'y';
1314     var posb = 'x';
1315     if (orientation == 'P') {
1316         posa = 'x';
1317         posb = 'y';
1318     }
1319     $elm.css('width', pdfPaperSize(paper, posa) + 'px');
1320     $elm.css('height', pdfPaperSize(paper, posb) + 'px');
1324  * Initializes positions of elements.
1325  */
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 */
1335         $this.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));
1341             }
1342         });
1343     });
1347  * Resets drag and drop positions.
1348  */
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');
1356     });
1360  * User schema handlers.
1361  */
1362 $(function () {
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');
1368     });
1369     /* Refresh on paper size/orientation change */
1370     $(document).on('change', '.paper-change', function () {
1371         var $elm = $('#pdflayout');
1372         if ($elm.css('visibility') == 'visible') {
1373             refreshLayout();
1374             TableDragInit();
1375         }
1376     });
1377     /* Show/hide the WYSIWYG scratchboard */
1378     $(document).on('click', '#toggle-dragdrop', function () {
1379         var $elm = $('#pdflayout');
1380         if ($elm.css('visibility') == 'hidden') {
1381             refreshLayout();
1382             TableDragInit();
1383             $elm.css('visibility', 'visible');
1384             $elm.css('display', 'block');
1385             $('#showwysiwyg').val('1');
1386         } else {
1387             $elm.css('visibility', 'hidden');
1388             $elm.css('display', 'none');
1389             $('#showwysiwyg').val('0');
1390         }
1391     });
1392     /* Reset scratchboard */
1393     $(document).on('click', '#reset-dragdrop', function () {
1394         resetDrag();
1395     });
1399  * Returns paper sizes for a given format
1400  */
1401 function pdfPaperSize(format, axis)
1403     switch (format.toUpperCase()) {
1404     case '4A0':
1405         if (axis == 'x') {
1406             return 4767.87;
1407         } else {
1408             return 6740.79;
1409         }
1410         break;
1411     case '2A0':
1412         if (axis == 'x') {
1413             return 3370.39;
1414         } else {
1415             return 4767.87;
1416         }
1417         break;
1418     case 'A0':
1419         if (axis == 'x') {
1420             return 2383.94;
1421         } else {
1422             return 3370.39;
1423         }
1424         break;
1425     case 'A1':
1426         if (axis == 'x') {
1427             return 1683.78;
1428         } else {
1429             return 2383.94;
1430         }
1431         break;
1432     case 'A2':
1433         if (axis == 'x') {
1434             return 1190.55;
1435         } else {
1436             return 1683.78;
1437         }
1438         break;
1439     case 'A3':
1440         if (axis == 'x') {
1441             return 841.89;
1442         } else {
1443             return 1190.55;
1444         }
1445         break;
1446     case 'A4':
1447         if (axis == 'x') {
1448             return 595.28;
1449         } else {
1450             return 841.89;
1451         }
1452         break;
1453     case 'A5':
1454         if (axis == 'x') {
1455             return 419.53;
1456         } else {
1457             return 595.28;
1458         }
1459         break;
1460     case 'A6':
1461         if (axis == 'x') {
1462             return 297.64;
1463         } else {
1464             return 419.53;
1465         }
1466         break;
1467     case 'A7':
1468         if (axis == 'x') {
1469             return 209.76;
1470         } else {
1471             return 297.64;
1472         }
1473         break;
1474     case 'A8':
1475         if (axis == 'x') {
1476             return 147.40;
1477         } else {
1478             return 209.76;
1479         }
1480         break;
1481     case 'A9':
1482         if (axis == 'x') {
1483             return 104.88;
1484         } else {
1485             return 147.40;
1486         }
1487         break;
1488     case 'A10':
1489         if (axis == 'x') {
1490             return 73.70;
1491         } else {
1492             return 104.88;
1493         }
1494         break;
1495     case 'B0':
1496         if (axis == 'x') {
1497             return 2834.65;
1498         } else {
1499             return 4008.19;
1500         }
1501         break;
1502     case 'B1':
1503         if (axis == 'x') {
1504             return 2004.09;
1505         } else {
1506             return 2834.65;
1507         }
1508         break;
1509     case 'B2':
1510         if (axis == 'x') {
1511             return 1417.32;
1512         } else {
1513             return 2004.09;
1514         }
1515         break;
1516     case 'B3':
1517         if (axis == 'x') {
1518             return 1000.63;
1519         } else {
1520             return 1417.32;
1521         }
1522         break;
1523     case 'B4':
1524         if (axis == 'x') {
1525             return 708.66;
1526         } else {
1527             return 1000.63;
1528         }
1529         break;
1530     case 'B5':
1531         if (axis == 'x') {
1532             return 498.90;
1533         } else {
1534             return 708.66;
1535         }
1536         break;
1537     case 'B6':
1538         if (axis == 'x') {
1539             return 354.33;
1540         } else {
1541             return 498.90;
1542         }
1543         break;
1544     case 'B7':
1545         if (axis == 'x') {
1546             return 249.45;
1547         } else {
1548             return 354.33;
1549         }
1550         break;
1551     case 'B8':
1552         if (axis == 'x') {
1553             return 175.75;
1554         } else {
1555             return 249.45;
1556         }
1557         break;
1558     case 'B9':
1559         if (axis == 'x') {
1560             return 124.72;
1561         } else {
1562             return 175.75;
1563         }
1564         break;
1565     case 'B10':
1566         if (axis == 'x') {
1567             return 87.87;
1568         } else {
1569             return 124.72;
1570         }
1571         break;
1572     case 'C0':
1573         if (axis == 'x') {
1574             return 2599.37;
1575         } else {
1576             return 3676.54;
1577         }
1578         break;
1579     case 'C1':
1580         if (axis == 'x') {
1581             return 1836.85;
1582         } else {
1583             return 2599.37;
1584         }
1585         break;
1586     case 'C2':
1587         if (axis == 'x') {
1588             return 1298.27;
1589         } else {
1590             return 1836.85;
1591         }
1592         break;
1593     case 'C3':
1594         if (axis == 'x') {
1595             return 918.43;
1596         } else {
1597             return 1298.27;
1598         }
1599         break;
1600     case 'C4':
1601         if (axis == 'x') {
1602             return 649.13;
1603         } else {
1604             return 918.43;
1605         }
1606         break;
1607     case 'C5':
1608         if (axis == 'x') {
1609             return 459.21;
1610         } else {
1611             return 649.13;
1612         }
1613         break;
1614     case 'C6':
1615         if (axis == 'x') {
1616             return 323.15;
1617         } else {
1618             return 459.21;
1619         }
1620         break;
1621     case 'C7':
1622         if (axis == 'x') {
1623             return 229.61;
1624         } else {
1625             return 323.15;
1626         }
1627         break;
1628     case 'C8':
1629         if (axis == 'x') {
1630             return 161.57;
1631         } else {
1632             return 229.61;
1633         }
1634         break;
1635     case 'C9':
1636         if (axis == 'x') {
1637             return 113.39;
1638         } else {
1639             return 161.57;
1640         }
1641         break;
1642     case 'C10':
1643         if (axis == 'x') {
1644             return 79.37;
1645         } else {
1646             return 113.39;
1647         }
1648         break;
1649     case 'RA0':
1650         if (axis == 'x') {
1651             return 2437.80;
1652         } else {
1653             return 3458.27;
1654         }
1655         break;
1656     case 'RA1':
1657         if (axis == 'x') {
1658             return 1729.13;
1659         } else {
1660             return 2437.80;
1661         }
1662         break;
1663     case 'RA2':
1664         if (axis == 'x') {
1665             return 1218.90;
1666         } else {
1667             return 1729.13;
1668         }
1669         break;
1670     case 'RA3':
1671         if (axis == 'x') {
1672             return 864.57;
1673         } else {
1674             return 1218.90;
1675         }
1676         break;
1677     case 'RA4':
1678         if (axis == 'x') {
1679             return 609.45;
1680         } else {
1681             return 864.57;
1682         }
1683         break;
1684     case 'SRA0':
1685         if (axis == 'x') {
1686             return 2551.18;
1687         } else {
1688             return 3628.35;
1689         }
1690         break;
1691     case 'SRA1':
1692         if (axis == 'x') {
1693             return 1814.17;
1694         } else {
1695             return 2551.18;
1696         }
1697         break;
1698     case 'SRA2':
1699         if (axis == 'x') {
1700             return 1275.59;
1701         } else {
1702             return 1814.17;
1703         }
1704         break;
1705     case 'SRA3':
1706         if (axis == 'x') {
1707             return 907.09;
1708         } else {
1709             return 1275.59;
1710         }
1711         break;
1712     case 'SRA4':
1713         if (axis == 'x') {
1714             return 637.80;
1715         } else {
1716             return 907.09;
1717         }
1718         break;
1719     case 'LETTER':
1720         if (axis == 'x') {
1721             return 612.00;
1722         } else {
1723             return 792.00;
1724         }
1725         break;
1726     case 'LEGAL':
1727         if (axis == 'x') {
1728             return 612.00;
1729         } else {
1730             return 1008.00;
1731         }
1732         break;
1733     case 'EXECUTIVE':
1734         if (axis == 'x') {
1735             return 521.86;
1736         } else {
1737             return 756.00;
1738         }
1739         break;
1740     case 'FOLIO':
1741         if (axis == 'x') {
1742             return 612.00;
1743         } else {
1744             return 936.00;
1745         }
1746         break;
1747     } // end switch
1749     return 0;
1753  * Get checkbox for foreign key checks
1755  * @return string
1756  */
1757 function getForeignKeyCheckboxLoader() {
1758     var html = '';
1759     html    += '<div>';
1760     html    += '<div class="load-default-fk-check-value">';
1761     html    += PMA_getImage('ajax_clock_small.gif');
1762     html    += '</div>';
1763     html    += '</div>';
1764     return html;
1767 function loadForeignKeyCheckbox() {
1768     // Load default foreign key check value
1769     var params = {
1770         'ajax_request': true,
1771         'token': PMA_commonParams.get('token'),
1772         'server': PMA_commonParams.get('server'),
1773         'get_default_fk_check_value': true
1774     };
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);
1781     });
1784 function getJSConfirmCommonParam(elem) {
1785     return {
1786         'is_js_confirmed' : 1,
1787         'ajax_request' : true,
1788         'fk_checks': $(elem).find('#fk_checks').is(':checked') ? 1 : 0
1789     };
1793  * Unbind all event handlers before tearing down a page
1794  */
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');
1802     } else {
1803         $(document).off('blur', '#sqlquery');
1804     }
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;
1815     }
1816     if (codemirror_editor) {
1817         $(codemirror_editor.getWrapperElement()).unbind('keydown');
1818     }
1822  * Jquery Coding for inline editing SQL_QUERY
1823  */
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
1832             return false;
1833         }
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);
1848         }
1849         $editor_area.html(new_content);
1850         loadForeignKeyCheckbox();
1851         $inner_sql.hide();
1853         bindCodeMirrorToInlineEditor();
1854         return false;
1855     });
1857     $(document).on('click', "input#sql_query_edit_save", function () {
1858         $(".success").hide();
1859         //hide already existing success message
1860         var sql_query;
1861         if (codemirror_inline_editor) {
1862             codemirror_inline_editor.save();
1863             sql_query = codemirror_inline_editor.getValue();
1864         } else {
1865             sql_query = $(this).parent().find('#sql_query_edit').val();
1866         }
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])) {
1877             return false;
1878         }
1879         $fake_form.appendTo($('body')).submit();
1880     });
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();
1886     });
1888     $('input.sqlbutton').click(function (evt) {
1889         insertQuery(evt.target.id);
1890         PMA_handleSimulateQueryButton();
1891         return false;
1892     });
1894     $(document).on('change', '#parameterized', updateQueryParameters);
1896     var $inputUsername = $('#input_username');
1897     if ($inputUsername) {
1898         if ($inputUsername.val() === '') {
1899             $inputUsername.focus();
1900         } else {
1901             $('#input_password').focus();
1902         }
1903     }
1907  * "inputRead" event handler for CodeMirror SQL query editors for autocompletion
1908  */
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';
1921             var params = {
1922                 'ajax_request': true,
1923                 'token': PMA_commonParams.get('token'),
1924                 'server': PMA_commonParams.get('server'),
1925                 'db': PMA_commonParams.get('db'),
1926                 'no_debug': true
1927             };
1929             var columnHintRender = function(elem, self, data) {
1930                 $('<div class="autocomplete-column-name">')
1931                     .text(data.columnName)
1932                     .appendTo(elem);
1933                 $('<div class="autocomplete-column-hint">')
1934                     .text(data.columnHint)
1935                     .appendTo(elem);
1936             };
1938             $.ajax({
1939                 type: 'POST',
1940                 url: href,
1941                 data: params,
1942                 success: function (data) {
1943                     if (data.success) {
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];
1950                                 table = {
1951                                     text: table,
1952                                     columns: []
1953                                 };
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';
1961                                         }
1962                                         table.columns.push({
1963                                             text: column,
1964                                             displayText: column + " | " +  displayText,
1965                                             columnName: column,
1966                                             columnHint: displayText,
1967                                             render: columnHintRender
1968                                         });
1969                                     }
1970                                 }
1971                             }
1972                             sql_autocomplete.push(table);
1973                         }
1974                         instance.options.hintOptions.tables = sql_autocomplete;
1975                         instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
1976                     }
1977                 },
1978                 complete: function () {
1979                     sql_autocomplete_in_progress = false;
1980                 }
1981             });
1982         }
1983         else {
1984             instance.options.hintOptions.tables = sql_autocomplete;
1985             instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
1986         }
1987     }
1988     if (instance.state.completionActive) {
1989         return;
1990     }
1991     var cur = instance.getCursor();
1992     var token = instance.getTokenAt(cur);
1993     var string = '';
1994     if (token.string.match(/^[.`\w@]\w*$/)) {
1995         string = token.string;
1996     }
1997     if (string.length > 0) {
1998         CodeMirror.commands.autocomplete(instance);
1999     }
2003  * Remove autocomplete information before tearing down a page
2004  */
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.
2012  */
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);
2024         } else {
2025             $inline_editor
2026                 .focus()
2027                 .bind('keydown', catchKeypressesFromSqlInlineEdit);
2028         }
2029     }
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');
2036     }
2040  * Adds doc link to single highlighted SQL element
2041  */
2042 function PMA_doc_add($elm, params)
2044     if (typeof mysql_doc_template == 'undefined') {
2045         return;
2046     }
2048     var url = PMA_sprintf(
2049         decodeURIComponent(mysql_doc_template),
2050         params[0]
2051     );
2052     if (params.length > 1) {
2053         url += '#' + params[1];
2054     }
2055     var content = $elm.text();
2056     $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
2062  */
2063 function PMA_doc_keyword(idx, elm)
2065     var $elm = $(elm);
2066     /* Skip already processed ones */
2067     if ($elm.find('a').length > 0) {
2068         return;
2069     }
2070     var keyword = $elm.text().toUpperCase();
2071     var $next = $elm.next('.cm-keyword');
2072     if ($next) {
2073         var next_keyword = $next.text().toUpperCase();
2074         var full = keyword + ' ' + next_keyword;
2076         var $next2 = $next.next('.cm-keyword');
2077         if ($next2) {
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]);
2084                 return;
2085             }
2086         }
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]);
2090             return;
2091         }
2092     }
2093     if (keyword in mysql_doc_keyword) {
2094         PMA_doc_add($elm, mysql_doc_keyword[keyword]);
2095     }
2099  * Generates doc links for builtins inside highlighted SQL
2100  */
2101 function PMA_doc_builtin(idx, elm)
2103     var $elm = $(elm);
2104     var builtin = $elm.text().toUpperCase();
2105     if (builtin in mysql_doc_builtin) {
2106         PMA_doc_add($elm, mysql_doc_builtin[builtin]);
2107     }
2111  * Higlights SQL using CodeMirror.
2112  */
2113 function PMA_highlightSQL($base)
2115     var $elm = $base.find('code.sql');
2116     $elm.each(function () {
2117         var $sql = $(this);
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]);
2125                 $pre.hide();
2126                 $highlight.find('.cm-keyword').each(PMA_doc_keyword);
2127                 $highlight.find('.cm-builtin').each(PMA_doc_builtin);
2128             }
2129         }
2130     });
2134  * Updates an element containing code.
2136  * @param jQuery Object $base base element which contains the raw and the
2137  *                            highlighted code.
2139  * @param string htmlValue    code in HTML format, displayed if code cannot be
2140  *                            highlighted
2142  * @param string rawValue     raw code, used as a parameter for highlighter
2144  * @return bool               whether content was updated or not
2145  */
2146 function PMA_updateCode($base, htmlValue, rawValue)
2148     var $code = $base.find('code');
2149     if ($code.length === 0) {
2150         return false;
2151     }
2153     // Determines the type of the content and appropriate CodeMirror mode.
2154     var type = '', mode = '';
2155     if  ($code.hasClass('json')) {
2156         type = 'json';
2157         mode = 'application/json';
2158     } else if ($code.hasClass('sql')) {
2159         type = 'sql';
2160         mode = 'text/x-mysql';
2161     } else if ($code.hasClass('xml')) {
2162         type = 'xml';
2163         mode = 'application/xml';
2164     } else {
2165         return false;
2166     }
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]);
2177     } else {
2178         $code.html('').append($notHighlighted);
2179     }
2181     return true;
2185  * Show a message on the top of the page for an Ajax request
2187  * Sample usage:
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
2215  */
2216 function PMA_ajaxShowMessage(message, timeout)
2218     /**
2219      * @var self_closing Whether the notification will automatically disappear
2220      */
2221     var self_closing = true;
2222     /**
2223      * @var dismissable Whether the user will be able to remove
2224      *                  the notification by clicking on it
2225      */
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 === '') {
2230         return true;
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;
2240     }
2241     // Figure out whether (or after how long) to remove the notification
2242     if (timeout === undefined) {
2243         timeout = 5000;
2244     } else if (timeout === false) {
2245         self_closing = false;
2246     }
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");
2251     }
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();
2256     /**
2257      * @var    $retval    a jQuery object containing the reference
2258      *                    to the created AJAX message
2259      */
2260     var $retval = $(
2261             '<span class="ajax_notification" id="ajax_message_num_' +
2262             ajax_message_count +
2263             '"></span>'
2264     )
2265     .hide()
2266     .appendTo("#loading_parent")
2267     .html(message)
2268     .show();
2269     // If the notification is self-closing we should create a callback to remove it
2270     if (self_closing) {
2271         $retval
2272         .delay(timeout)
2273         .fadeOut('medium', function () {
2274             if ($(this).is(':data(tooltip)')) {
2275                 $(this).tooltip('destroy');
2276             }
2277             // Remove the notification
2278             $(this).remove();
2279         });
2280     }
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
2283     if (dismissable) {
2284         $retval.addClass('dismissable').css('cursor', 'pointer');
2285         /**
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.
2288          */
2289         PMA_tooltip(
2290             $retval,
2291             'span',
2292             PMA_messages.strDismiss
2293         );
2294     }
2295     PMA_highlightSQL($retval);
2297     return $retval;
2301  * Removes the message shown for an Ajax operation when it's completed
2303  * @param jQuery object   jQuery Element that holds the notification
2305  * @return nothing
2306  */
2307 function PMA_ajaxRemoveMessage($this_msgbox)
2309     if ($this_msgbox !== undefined && $this_msgbox instanceof jQuery) {
2310         $this_msgbox
2311         .stop(true, true)
2312         .fadeOut('medium');
2313         if ($this_msgbox.is(':data(tooltip)')) {
2314             $this_msgbox.tooltip('destroy');
2315         } else {
2316             $this_msgbox.remove();
2317         }
2318     }
2322  * Requests SQL for previewing before executing.
2324  * @param jQuery Object $form Form containing query data
2326  * @return void
2327  */
2328 function PMA_previewSQL($form)
2330     var form_url = $form.attr('action');
2331     var form_data = $form.serialize() +
2332         '&do_save_data=1' +
2333         '&preview_sql=1' +
2334         '&ajax_request=1';
2335     var $msgbox = PMA_ajaxShowMessage();
2336     $.ajax({
2337         type: 'POST',
2338         url: form_url,
2339         data: form_data,
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');
2348                 };
2349                 var $response_dialog = $dialog_content.dialog({
2350                     minWidth: 550,
2351                     maxHeight: 400,
2352                     modal: true,
2353                     buttons: button_options,
2354                     title: PMA_messages.strPreviewSQL,
2355                     close: function () {
2356                         $(this).remove();
2357                     },
2358                     open: function () {
2359                         // Pretty SQL printing.
2360                         PMA_highlightSQL($(this));
2361                     }
2362                 });
2363             } else {
2364                 PMA_ajaxShowMessage(response.message);
2365             }
2366         },
2367         error: function () {
2368             PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
2369         }
2370     });
2374  * check for reserved keyword column name
2376  * @param jQuery Object $form Form
2378  * @returns true|false
2379  */
2381 function PMA_checkReservedWordColumns($form) {
2382     var is_confirmed = true;
2383     $.ajax({
2384         type: 'POST',
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);
2390             }
2391         },
2392         async:false
2393     });
2394     return is_confirmed;
2397 // This event only need to be fired once after the initial page load
2398 $(function () {
2399     /**
2400      * Allows the user to dismiss a notification
2401      * created with PMA_ajaxShowMessage()
2402      */
2403     $(document).on('click', 'span.ajax_notification.dismissable', function () {
2404         PMA_ajaxRemoveMessage($(this));
2405     });
2406     /**
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
2409      */
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');
2413         }
2414     });
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');
2418         }
2419     });
2423  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
2424  */
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();
2432     } else {
2433         $("p#enum_notice_" + enum_notice_id).hide();
2434     }
2438  * Creates a Profiling Chart. Used in sql.js
2439  * and in server_status_monitor.js
2440  */
2441 function PMA_createProfilingChart(target, data)
2443     // create the chart
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, {
2455         seriesDefaults: {
2456             rendererOptions: {
2457                 showDataLabels:  true
2458             }
2459         },
2460         highlighter: {
2461             tooltipLocation: 'se',
2462             sizeAdjust: 0,
2463             tooltipAxes: 'pieref',
2464             formatString: '%s, %.9Ps'
2465         },
2466         legend: {
2467             show: true,
2468             location: 'e',
2469             rendererOptions: {
2470                 numberColumns: 2
2471             }
2472         },
2473         // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
2474         seriesColors: [
2475             '#fce94f',
2476             '#fcaf3e',
2477             '#e9b96e',
2478             '#8ae234',
2479             '#729fcf',
2480             '#ad7fa8',
2481             '#ef2929',
2482             '#eeeeec',
2483             '#888a85',
2484             '#c4a000',
2485             '#ce5c00',
2486             '#8f5902',
2487             '#4e9a06',
2488             '#204a87',
2489             '#5c3566',
2490             '#a40000',
2491             '#babdb6',
2492             '#2e3436'
2493         ]
2494     });
2495     return chart;
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
2505  */
2506 function PMA_prettyProfilingNum(num, acc)
2508     if (!acc) {
2509         acc = 2;
2510     }
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';
2516     } else {
2517         num = Math.round(acc * num) / acc;
2518     }
2520     return num + 's';
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
2529  */
2530 function PMA_SQLPrettyPrint(string)
2532     if (typeof CodeMirror == 'undefined') {
2533         return string;
2534     }
2536     var mode = CodeMirror.getMode({}, "text/x-mysql");
2537     var stream = new CodeMirror.StringStream(string);
2538     var state = mode.startState();
2539     var token, tokens = [];
2540     var output = '';
2541     var tabs = function (cnt) {
2542         var ret = '';
2543         for (var i = 0; i < 4 * cnt; i++) {
2544             ret += " ";
2545         }
2546         return ret;
2547     };
2549     // "root-level" statements
2550     var statements = {
2551         'select': ['select', 'from', 'on', 'where', 'having', 'limit', 'order by', 'group by'],
2552         'update': ['update', 'set', 'where'],
2553         'insert into': ['insert into', 'values']
2554     };
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
2561     var str = '';
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()]);
2567         }
2568     }
2570     var currentStatement = tokens[0][1];
2572     if (! statements[currentStatement]) {
2573         return string;
2574     }
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])
2578     var previousBlock;
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');
2598             } else {
2599                 blockStack.unshift(newBlock = 'generic');
2600             }
2601         } else {
2602             newBlock = null;
2603         }
2605         // Block end => pop from stack
2606         if (tokens[i][1] == ')') {
2607             endBlock = blockStack[0];
2608             blockStack.shift();
2609         } else {
2610             endBlock = null;
2611         }
2613         // A subquery is starting
2614         if (i > 0 && newBlock == 'statement') {
2615             indentLevel++;
2616             output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i + 1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
2617             currentStatement = tokens[i + 1][1];
2618             i++;
2619             continue;
2620         }
2622         // A subquery is ending
2623         if (endBlock == 'statement' && indentLevel > 0) {
2624             output += "\n" + tabs(indentLevel);
2625             indentLevel--;
2626         }
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) {
2631             if (i > 0) {
2632                 output += "\n";
2633             }
2634             output += tabs(indentLevel) + tokens[i][1].toUpperCase();
2635             output += "\n" + tabs(indentLevel + 1);
2636             lastStatementPart = tokens[i][1];
2637         }
2638         // Normal indentation and spaces for everything else
2639         else {
2640             if (! spaceExceptionsBefore[tokens[i][1]] &&
2641                ! (i > 0 && spaceExceptionsAfter[tokens[i - 1][1]]) &&
2642                output.charAt(output.length - 1) != ' ') {
2643                 output += " ";
2644             }
2645             if (tokens[i][0] == 'keyword') {
2646                 output += tokens[i][1].toUpperCase();
2647             } else {
2648                 output += tokens[i][1];
2649             }
2650         }
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);
2657         }
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);
2665             }
2666             // Todo: Also split and or blocks in newlines & indentation++
2667             //if (blockStack[0] == 'generic')
2668              //   output += ...
2669         }
2670     }
2671     return output;
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
2680  *                                  an Ajax call to
2681  * @param function    callbackFn    callback to execute after user clicks on OK
2682  * @param function    openCallback  optional callback to run when dialog is shown
2683  */
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);
2691             return true;
2692         }
2693     }
2694     if (PMA_messages.strDoYouReally === '') {
2695         return true;
2696     }
2698     /**
2699      * @var    button_options  Object that stores the options passed to jQueryUI
2700      *                          dialog
2701      */
2702     var button_options = [
2703         {
2704             text: PMA_messages.strOK,
2705             'class': 'submitOK',
2706             click: function () {
2707                 $(this).dialog("close");
2708                 if ($.isFunction(callbackFn)) {
2709                     callbackFn.call(this, url);
2710                 }
2711             }
2712         },
2713         {
2714             text: PMA_messages.strCancel,
2715             'class': 'submitCancel',
2716             click: function () {
2717                 $(this).dialog("close");
2718             }
2719         }
2720     ];
2722     $('<div/>', {'id': 'confirm_dialog', 'title': PMA_messages.strConfirm})
2723     .prepend(question)
2724     .dialog({
2725         buttons: button_options,
2726         close: function () {
2727             $(this).remove();
2728         },
2729         open: openCallback,
2730         modal: true
2731     });
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
2741  */
2742 jQuery.fn.PMA_sort_table = function (text_selector) {
2743     return this.each(function () {
2745         /**
2746          * @var table_body  Object referring to the table's <tbody> element
2747          */
2748         var table_body = $(this);
2749         /**
2750          * @var rows    Object referring to the collection of rows in {@link table_body}
2751          */
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());
2757         });
2759         //get the sorted order
2760         rows.sort(function (a, b) {
2761             if (a.sortKey < b.sortKey) {
2762                 return -1;
2763             }
2764             if (a.sortKey > b.sortKey) {
2765                 return 1;
2766             }
2767             return 0;
2768         });
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);
2773             row.sortKey = null;
2774         });
2776         //Re-check the classes of each row
2777         $(this).find('tr:odd')
2778         .removeClass('even').addClass('odd')
2779         .end()
2780         .find('tr:even')
2781         .removeClass('odd').addClass('even');
2782     });
2786  * Unbind all event handlers before tearing down a page
2787  */
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
2802  */
2803 AJAX.registerOnload('functions.js', function () {
2804     /**
2805      * Attach event handler for submission of create table form (save)
2806      */
2807     $(document).on('submit', "form.create_table_form.ajax", function (event) {
2808         event.preventDefault();
2810         /**
2811          * @var    the_form    object referring to the create table form
2812          */
2813         var $form = $(this);
2815         /*
2816          * First validate the form; if there is a problem, avoid submitting it
2817          *
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)
2821          */
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')
2832                          .html('');
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();
2838                         }
2839                         $('#tableslistcontainer').before(data.formatted_sql);
2841                         /**
2842                          * @var tables_table    Object referring to the <tbody> element that holds the list of tables
2843                          */
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')
2849                             );
2850                         } else {
2851                             /**
2852                              * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
2853                              */
2854                             var curr_last_row = $(tables_table).find('tr:last');
2855                             /**
2856                              * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
2857                              */
2858                             var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2859                             /**
2860                              * @var curr_last_row_index Index of {@link curr_last_row}
2861                              */
2862                             var curr_last_row_index = parseFloat(curr_last_row_index_string);
2863                             /**
2864                              * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
2865                              */
2866                             var new_last_row_index = curr_last_row_index + 1;
2867                             /**
2868                              * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2869                              */
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);
2873                             //append to table
2874                             $(data.new_table_string)
2875                              .appendTo(tables_table);
2877                             //Sort the table
2878                             $(tables_table).PMA_sort_table('th');
2880                             // Adjust summary row
2881                             PMA_adjustTotals();
2882                         }
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();
2890                         }
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);
2895                     } else {
2896                         PMA_ajaxShowMessage(
2897                             '<div class="error">' + data.error + '</div>',
2898                             false
2899                         );
2900                     }
2901                 }); // end $.post()
2902             }
2903         } // end if (checkTableEditForm() )
2904     }); // end create table form (save)
2906     /**
2907      * Submits the intermediate changes in the table creation form
2908      * to refresh the UI accordingly
2909      */
2910     function submitChangesInCreateTableForm (actionParam) {
2912         /**
2913          * @var    the_form    object referring to the create table form
2914          */
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);
2929             } else {
2930                 PMA_ajaxShowMessage(data.error);
2931             }
2932         }); //end $.post()
2933     }
2935     /**
2936      * Attach event handler for create table form (add fields)
2937      */
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)) {
2942             return;
2943         }
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();
2952             $(this)
2953                 .closest('form')
2954                 .find('input[name=submit_num_fields]')
2955                 .click();
2956         }
2957     });
2959     /**
2960      * Attach event handler to manage changes in number of partitions and subpartitions
2961      */
2962     $(document).on('change', "input[name=partition_count],input[name=subpartition_count],select[name=partition_by]", function (event) {
2963         $this = $(this);
2964         $form = $this.parents('form');
2965         if ($form.is(".create_table_form.ajax")) {
2966             submitChangesInCreateTableForm('submit_partition_change=1');
2967         } else {
2968             $form.submit();
2969         }
2970     });
2972     $("input[value=AUTO_INCREMENT]").change(function(){
2973         if (this.checked) {
2974             var col = /\d/.exec($(this).attr('name'));
2975             col = col[0];
2976             var $selectFieldKey = $('select[name="field_key[' + col + ']"]');
2977             if ($selectFieldKey.val() === 'none_'+col) {
2978                 $selectFieldKey.val('primary_'+col).change();
2979             }
2980         }
2981     });
2982     $('body')
2983     .off('click', 'input.preview_sql')
2984     .on('click', 'input.preview_sql', function () {
2985         var $form = $(this).closest('form');
2986         PMA_previewSQL($form);
2987     });
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
2997  * @return bool
2998  */
2999 function PMA_checkPassword($the_form)
3001     // Did the user select 'no password'?
3002     if ($the_form.find('#nopass_1').is(':checked')) {
3003         return true;
3004     } else {
3005         var $pred = $the_form.find('#select_pred_password');
3006         if ($pred.length && ($pred.val() == 'none' || $pred.val() == 'keep')) {
3007             return true;
3008         }
3009     }
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;
3019     }
3021     if (alert_msg) {
3022         alert(alert_msg);
3023         $password.val('');
3024         $password_repeat.val('');
3025         $password.focus();
3026         return false;
3027     }
3028     return true;
3032  * Unbind all event handlers before tearing down a page
3033  */
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
3039  */
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') {
3046             hostname.val('%');
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);
3055         }
3056     });
3058     /* Handler for editing hostname */
3059     $(document).on('change', '#pma_hostname', function () {
3060         $('#select_pred_hostname').val('userdefined');
3061         $('#pma_hostname').prop('required', true);
3062     });
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);
3071         }
3072     });
3074     /* Handler for editing username */
3075     $(document).on('change', '#pma_username', function () {
3076         $('#select_pred_username').val('userdefined');
3077         $('#pma_username').prop('required', true);
3078     });
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();
3088         } else {
3089             $('#text_pma_pw2').prop('required', false);
3090             $('#text_pma_pw').prop('required', false);
3091         }
3092     });
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);
3099     });
3101     /**
3102      * Attach Ajax event handler on the change password anchor
3103      */
3104     $(document).on('click', '#change_password_anchor.ajax', function (event) {
3105         event.preventDefault();
3107         var $msgbox = PMA_ajaxShowMessage();
3109         /**
3110          * @var button_options  Object containing options to be passed to jQueryUI's dialog
3111          */
3112         var button_options = {};
3113         button_options[PMA_messages.strGo] = function () {
3115             event.preventDefault();
3117             /**
3118              * @var $the_form    Object referring to the change password form
3119              */
3120             var $the_form = $("#change_password_form");
3122             if (! PMA_checkPassword($the_form)) {
3123                 return false;
3124             }
3126             /**
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
3129              * page to work
3130              */
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);
3139                     return;
3140                 }
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);
3148             }); // end $.post()
3149         };
3151         button_options[PMA_messages.strCancel] = function () {
3152             $(this).dialog('close');
3153         };
3154         $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
3155             if (typeof data === 'undefined' || !data.success) {
3156                 PMA_ajaxShowMessage(data.error, false);
3157                 return;
3158             }
3160             $('<div id="change_password_dialog"></div>')
3161                 .dialog({
3162                     title: PMA_messages.strChangePassword,
3163                     width: 600,
3164                     close: function (ev, ui) {
3165                         $(this).remove();
3166                     },
3167                     buttons: button_options,
3168                     modal: true
3169                 })
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) {
3180                 e.preventDefault();
3181                 $(this)
3182                     .closest('.ui-dialog')
3183                     .find('.ui-dialog-buttonpane .ui-button')
3184                     .first()
3185                     .click();
3186             });
3187         }); // end $.get()
3188     }); // end handler for change password anchor
3189 }); // end $() for Change Password
3192  * Unbind all event handlers before tearing down a page
3193  */
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
3204  */
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();
3209     //
3210     // needs on() to work also in the Create Table dialog
3211     $(document).on('change', "select.column_type", function () {
3212         PMA_showNoticeForEnum($(this));
3213     });
3214     $(document).on('change', "select.default_type", function () {
3215         PMA_hideShowDefaultValue($(this));
3216     });
3217     $(document).on('change', "select.virtuality", function () {
3218         PMA_hideShowExpression($(this));
3219     });
3220     $(document).on('change', 'input.allow_null', function () {
3221         PMA_validateDefaultValue($(this));
3222     });
3223     $(document).on('change', '.create_table_form select[name=tbl_storage_engine]', function () {
3224         PMA_hideShowConnection($(this));
3225     });
3229  * If the chosen storage engine is FEDERATED show connection field. Hide otherwise
3231  * @param $engine_selector storage engine selector
3232  */
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') {
3239         $connection
3240             .prop('disabled', true)
3241             .parent('td').hide();
3242         $labelTh.hide();
3243     } else {
3244         $connection
3245             .prop('disabled', false)
3246             .parent('td').show();
3247         $labelTh.show();
3248     }
3252  * If the column does not allow NULL values, makes sure that default is not NULL
3253  */
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');
3260         }
3261     }
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
3269  */
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();
3282     } else {
3283         $input3.next().hide();
3284     }
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);
3291     } else {
3292         $input4.val(central_column_list[db + '_' + table][offset].col_default);
3293         $input4.next().next().hide();
3294     }
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);
3300     }
3301     if(central_column_list[db + '_' + table][offset].col_extra.toUpperCase() === 'AUTO_INCREMENT') {
3302         $('#' + input_id + '9').prop("checked",true).change();
3303     } else {
3304         $('#' + input_id + '9').prop("checked",false);
3305     }
3306     if(central_column_list[db + '_' + table][offset].col_isNull !== '0') {
3307         $('#' + input_id + '7').prop("checked",true);
3308     } else {
3309         $('#' + input_id + '7').prop("checked",false);
3310     }
3314  * Unbind all event handlers before tearing down a page
3315  */
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
3325  */
3326 var $enum_editor_dialog = null;
3328  * Opens the ENUM/SET editor and controls its functions
3329  */
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();
3334         var title;
3335         var i;
3336         // And use it to make up a title for the page
3337         if (colname.length < 1) {
3338             title = PMA_messages.enum_newColumnVals;
3339         } else {
3340             title = PMA_messages.enum_columnVals.replace(
3341                 /%s/,
3342                 '"' + escapeHtml(decodeURIComponent(colname)) + '"'
3343             );
3344         }
3345         // Get the values as a string
3346         var inputstring = $(this)
3347             .closest('td')
3348             .find("input")
3349             .val();
3350         // Escape html entities
3351         inputstring = $('<div/>')
3352             .text(inputstring)
3353             .html();
3354         // Parse the values, escaping quotes and
3355         // slashes on the fly, into an array
3356         var values = [];
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 == "'") {
3363                 in_string = true;
3364             } else if (in_string && curr == "\\" && next == "\\") {
3365                 buffer += "&#92;";
3366                 i++;
3367             } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
3368                 buffer += "&#39;";
3369                 i++;
3370             } else if (in_string && curr == "'") {
3371                 in_string = false;
3372                 values.push(buffer);
3373                 buffer = '';
3374             } else if (in_string) {
3375                 buffer += curr;
3376             }
3377         }
3378         if (buffer.length > 0) {
3379             // The leftovers in the buffer are the last value (if any)
3380             values.push(buffer);
3381         }
3382         var fields = '';
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('', '', '', '');
3387         }
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'>" +
3394                    drop_icon +
3395                    "</td></tr>";
3396         }
3397         /**
3398          * @var dialog HTML code for the ENUM/SET dialog
3399          */
3400         var dialog = "<div id='enum_editor'>" +
3401                    "<fieldset>" +
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>" +
3409                     "</td><td>" +
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") +
3416                     "' />" +
3417                     "</fieldset>" +
3418                     "</div>";
3419         /**
3420          * @var  Defines functions to be called when the buttons in
3421          * the buttonOptions jQuery dialog bar are pressed
3422          */
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 + "'");
3431             });
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");
3436         };
3437         buttonOptions[PMA_messages.strClose] = function () {
3438             $(this).dialog("close");
3439         };
3440         // Show the dialog
3441         var width = parseInt(
3442             (parseInt($('html').css('font-size'), 10) / 13) * 340,
3443             10
3444         );
3445         if (! width) {
3446             width = 340;
3447         }
3448         $enum_editor_dialog = $(dialog).dialog({
3449             minWidth: width,
3450             maxHeight: 450,
3451             modal: true,
3452             title: PMA_messages.enum_editor,
3453             buttons: buttonOptions,
3454             open: function () {
3455                 // Focus the "Go" button after opening the dialog
3456                 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3457             },
3458             close: function () {
3459                 $(this).remove();
3460             }
3461         });
3462         // slider for choosing how many fields to add
3463         $enum_editor_dialog.find(".slider").slider({
3464             animate: true,
3465             range: "min",
3466             value: 1,
3467             min: 1,
3468             max: 9,
3469             slide: function (event, ui) {
3470                 $(this).closest('table').find('input[type=submit]').val(
3471                     PMA_sprintf(PMA_messages.enum_addValue, ui.value)
3472                 );
3473             }
3474         });
3475         // Focus the slider, otherwise it looks nearly transparent
3476         $('a.ui-slider-handle').addClass('ui-state-focus');
3477         return false;
3478     });
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) {
3487             pick = true;
3488         }
3489         var params = {
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
3496         };
3497         var colid = $(this).closest('td').find("input").attr("id");
3498         var fields = '';
3499         if (! (db + '_' + table in central_column_list)) {
3500             central_column_list.push(db + '_' + table);
3501             $.ajax({
3502                 type: 'POST',
3503                 url: href,
3504                 data: params,
3505                 success: function (data) {
3506                     central_column_list[db + '_' + table] = $.parseJSON(data.message);
3507                 },
3508                 async:false
3509             });
3510         }
3511         var i = 0;
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) + ') ';
3522             }
3523             if (central_column_list[db + '_' + table][i].col_length !== '') {
3524                 fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_length) +') ';
3525             }
3526             fields += escapeHtml(central_column_list[db + '_' + table][i].col_extra) + '</span>' +
3527                 '</div></td>';
3528             if (pick) {
3529                 fields += '<td><input class="pick" style="width:100%" type="submit" value="' +
3530                     PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3531             }
3532             fields += '</tr>';
3533         }
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 + "'");
3538             search_in = '';
3539         }
3540         var seeMore = '';
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>";
3544         }
3545         var central_columns_dialog = "<div style='max-height:400px'>" +
3546             "<fieldset>" +
3547             search_in +
3548             "<table id='col_list' style='width:100%' class='values'>" + fields + "</table>" +
3549             "</fieldset>" +
3550             seeMore +
3551             "</div>";
3553         var width = parseInt(
3554             (parseInt($('html').css('font-size'), 10) / 13) * 500,
3555             10
3556         );
3557         if (! width) {
3558             width = 500;
3559         }
3560         var buttonOptions = {};
3561         var $central_columns_dialog = $(central_columns_dialog).dialog({
3562             minWidth: width,
3563             maxHeight: 450,
3564             modal: true,
3565             title: PMA_messages.pickColumnTitle,
3566             buttons: buttonOptions,
3567             open: function () {
3568                 $('#col_list').on("click", ".pick", function (){
3569                     $central_columns_dialog.remove();
3570                 });
3571                 $(".filter_rows").on("keyup", function () {
3572                     $.uiTableFilter($("#col_list"), $(this).val());
3573                 });
3574                 $("#seeMore").click(function() {
3575                     fields = '';
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 + ') ';
3586                         }
3587                         if (central_column_list[db + '_' + table][i].col_length !== '') {
3588                             fields += '(' + central_column_list[db + '_' + table][i].col_length + ') ';
3589                         }
3590                         fields += central_column_list[db + '_' + table][i].col_extra + '</span>' +
3591                             '</div></td>';
3592                         if (pick) {
3593                             fields += '<td><input class="pick" style="width:100%" type="submit" value="' +
3594                                 PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
3595                         }
3596                         fields += '</tr>';
3597                     }
3598                     $("#col_list").append(fields);
3599                     result_pointer = i;
3600                     if (result_pointer === list_size) {
3601                         $('.tblFooters').hide();
3602                     }
3603                     return false;
3604                 });
3605                 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
3606             },
3607             close: function () {
3608                 $('#col_list').off("click", ".pick");
3609                 $(".filter_rows").off("keyup");
3610                 $(this).remove();
3611             }
3612         });
3613         return false;
3614     });
3616    // $(document).on('click', 'a.show_central_list',function(e) {
3618    // });
3619     // When "add a new value" is clicked, append an empty text field
3620     $(document).on('click', "input.add_value", function (e) {
3621         e.preventDefault();
3622         var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
3623         while (num_new_rows--) {
3624             $enum_editor_dialog.find('.values')
3625                 .append(
3626                     "<tr style='display: none;'><td>" +
3627                     "<input type='text' />" +
3628                     "</td><td class='drop'>" +
3629                     PMA_getImage('b_drop.png') +
3630                     "</td></tr>"
3631                 )
3632                 .find('tr:last')
3633                 .show('fast');
3634         }
3635     });
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 () {
3640             $(this).remove();
3641         });
3642     });
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
3649  *                            the input
3650  * @return boolean  false    if there is no index form, true else
3651  */
3652 function checkIndexName(form_id)
3654     if ($("#" + form_id).length === 0) {
3655         return false;
3656     }
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);
3666     }
3668     // Other cases
3669     else {
3670         if ($the_idx_name.val() == 'PRIMARY') {
3671             $the_idx_name.val("");
3672         }
3673         $the_idx_name.prop("disabled", false);
3674     }
3676     return true;
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 () {
3683     /**
3684      * Handler for adding more columns to an index in the editor
3685      */
3686     $(document).on('click', '#index_frm input[type=submit]', function (event) {
3687         event.preventDefault();
3688         var rows_to_add = $(this)
3689             .closest('fieldset')
3690             .find('.slider')
3691             .slider('value');
3693         var tempEmptyVal = function () {
3694             $(this).val('');
3695         };
3697         var tempSetFocus = function () {
3698             if ($(this).find("option:selected").val() === '') {
3699                 return true;
3700             }
3701             $(this).closest("tr").find("input").focus();
3702         };
3704         while (rows_to_add--) {
3705             var $indexColumns = $('#index_columns');
3706             var $newrow = $indexColumns
3707                 .find('tbody > tr:first')
3708                 .clone()
3709                 .appendTo(
3710                     $indexColumns.find('tbody')
3711                 );
3712             $newrow.find(':input').each(tempEmptyVal);
3713             // focus index size input on column picked
3714             $newrow.find('select').change(tempSetFocus);
3715         }
3716     });
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();
3725     }
3726     var $div = $('<div id="edit_index_dialog"></div>');
3728     /**
3729      * @var button_options Object that stores the options
3730      *                     passed to jQueryUI dialog
3731      */
3732     var button_options = {};
3733     button_options[PMA_messages.strGo] = function () {
3734         /**
3735          * @var    the_form    object referring to the export form
3736          */
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();
3745             }
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();
3751                 }
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'));
3757                 }
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");
3769                 }
3770                 $('div.no_indexes_defined').hide();
3771                 if (callback_success) {
3772                     callback_success();
3773                 }
3774                 PMA_reloadNavigation();
3775             } else {
3776                 var $temp_div = $("<div id='temp_div'><div>").append(data.error);
3777                 var $error;
3778                 if ($temp_div.find(".error code").length !== 0) {
3779                     $error = $temp_div.find(".error code").addClass("error");
3780                 } else {
3781                     $error = $temp_div;
3782                 }
3783                 if (callback_failure) {
3784                     callback_failure();
3785                 }
3786                 PMA_ajaxShowMessage($error, false);
3787             }
3788         }); // end $.post()
3789     };
3790     button_options[PMA_messages.strPreviewSQL] = function () {
3791         // Function for Previewing SQL
3792         var $form = $('#index_frm');
3793         PMA_previewSQL($form);
3794     };
3795     button_options[PMA_messages.strCancel] = function () {
3796         $(this).dialog('close');
3797     };
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);
3803         } else {
3804             PMA_ajaxRemoveMessage($msgbox);
3805             // Show dialog if the request was successful
3806             $div
3807             .append(data.message)
3808             .dialog({
3809                 title: title,
3810                 width: 450,
3811                 height: 350,
3812                 open: PMA_verifyColumnsProperties,
3813                 modal: true,
3814                 buttons: button_options,
3815                 close: function () {
3816                     $(this).remove();
3817                 }
3818             });
3819             $div.find('.tblFooters').remove();
3820             showIndexEditDialog($div);
3821         }
3822     }); // end $.get()
3825 function showIndexEditDialog($outer)
3827     checkIndexType();
3828     checkIndexName("index_frm");
3829     var $indexColumns = $('#index_columns');
3830     $indexColumns.find('td').each(function () {
3831         $(this).css("width", $(this).width() + 'px');
3832     });
3833     $indexColumns.find('tbody').sortable({
3834         axis: 'y',
3835         containment: $indexColumns.find("tbody"),
3836         tolerance: 'pointer'
3837     });
3838     PMA_showHints($outer);
3839     PMA_init_slider();
3840     // Add a slider for selecting how many columns to add to the index
3841     $outer.find('.slider').slider({
3842         animate: true,
3843         value: 1,
3844         min: 1,
3845         max: 16,
3846         slide: function (event, ui) {
3847             $(this).closest('fieldset').find('input[type=submit]').val(
3848                 PMA_sprintf(PMA_messages.strAddToIndex, ui.value)
3849             );
3850         }
3851     });
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() === '') {
3856             return true;
3857         }
3858         $(this).closest("tr").find("input").focus();
3859     });
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()) {
3865         input.focus();
3866     }
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
3876  *                    in the whole body
3877  **/
3878 function PMA_showHints($div)
3880     if ($div === undefined || ! $div instanceof jQuery || $div.length === 0) {
3881         $div = $("body");
3882     }
3883     $div.find('.pma_hint').each(function () {
3884         PMA_tooltip(
3885             $(this).children('img'),
3886             'img',
3887             $(this).children('span').html()
3888         );
3889     });
3892 AJAX.registerOnload('functions.js', function () {
3893     PMA_showHints();
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
3901 $(function () {
3902     // Initialise the menu resize plugin
3903     $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
3904     // register resize event
3905     $(window).resize(function () {
3906         $('#topmenu').menuResizer('resize');
3907     });
3911  * Get the row number from the classlist (for example, row_1)
3912  */
3913 function PMA_getRowNumber(classlist)
3915     return parseInt(classlist.split(/\s+row_/)[1], 10);
3919  * Changes status of slider
3920  */
3921 function PMA_set_status_label($element)
3923     var text;
3924     if ($element.css('display') == 'none') {
3925         text = '+ ';
3926     } else {
3927         text = '- ';
3928     }
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
3936  */
3937 var toggleButton = function ($obj) {
3938     // In rtl mode the toggle switch is flipped horizontally
3939     // so we need to take that into account
3940     var right;
3941     if ($('span.text_direction', $obj).text() == 'ltr') {
3942         right = 'right';
3943     } else {
3944         right = 'left';
3945     }
3946     /**
3947      *  var  h  Height of the button, used to scale the
3948      *          background image and position the layers
3949      */
3950     var h = $obj.height();
3951     $('img', $obj).height(h);
3952     $('table', $obj).css('bottom', h - 1);
3953     /**
3954      *  var  on   Width of the "ON" part of the toggle switch
3955      *  var  off  Width of the "OFF" part of the toggle switch
3956      */
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);
3963     /**
3964      *  var  w  Width of the central part of the switch
3965      */
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);
3970     /**
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
3975      */
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);
3981     /**
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
3984      */
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);
3990     /**
3991      *  var  move  How many pixels to move the
3992      *             switch by when toggling
3993      */
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);
4000         } else {
4001             $('div.container', $obj).animate({'left': '+=' + move + 'px'}, 0);
4002         }
4003     }
4004     // Attach an 'onclick' event to the switch
4005     $('div.container', $obj).click(function () {
4006         if ($(this).hasClass('isActive')) {
4007             return false;
4008         } else {
4009             $(this).addClass('isActive');
4010         }
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') {
4018                 operator = '-=';
4019             } else {
4020                 operator = '+=';
4021             }
4022             url = $(this).find('td.toggleOff > span').text();
4023             removeClass = 'on';
4024             addClass = 'off';
4025         } else {
4026             if (right == 'right') {
4027                 operator = '+=';
4028             } else {
4029                 operator = '-=';
4030             }
4031             url = $(this).find('td.toggleOn > span').text();
4032             removeClass = 'off';
4033             addClass = 'on';
4034         }
4035         $.post(url, {'ajax_request': true}, function (data) {
4036             if (typeof data !== 'undefined' && data.success === true) {
4037                 PMA_ajaxRemoveMessage($msg);
4038                 $container
4039                 .removeClass(removeClass)
4040                 .addClass(addClass)
4041                 .animate({'left': operator + move + 'px'}, function () {
4042                     $container.removeClass('isActive');
4043                 });
4044                 eval(callback);
4045             } else {
4046                 PMA_ajaxShowMessage(data.error, false);
4047                 $container.removeClass('isActive');
4048             }
4049         });
4050     });
4054  * Unbind all event handlers before tearing down a page
4055  */
4056 AJAX.registerTeardown('functions.js', function () {
4057     $('div.container').unbind('click');
4060  * Initialise all toggle buttons
4061  */
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);
4068             } else {
4069                 $(this).load(function () {
4070                     toggleButton($button);
4071                 });
4072             }
4073         });
4074     });
4078  * Unbind all event handlers before tearing down a page
4079  */
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 () {
4089     /**
4090      * Autosubmit page selector
4091      */
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();
4098         } else {
4099             // but for the navigation we need to manually replace the content
4100             PMA_navigationTreePagination($(this));
4101         }
4102     });
4104     /**
4105      * Load version information asynchronously.
4106      */
4107     if ($('li.jsversioncheck').length > 0) {
4108         $.getJSON('version_check.php', {'server' : PMA_commonParams.get('server')}, PMA_current_version);
4109     }
4111     if ($('#is_git_revision').length > 0) {
4112         setTimeout(PMA_display_git_revision, 10);
4113     }
4115     /**
4116      * Slider effect.
4117      */
4118     PMA_init_slider();
4120     /**
4121      * Enables the text generated by PMA\libraries\Util::linkOrButton() to be clickable
4122      */
4123     $(document).on('click', 'a.formLinkSubmit', function (e) {
4124         if (! $(this).hasClass('requireConfirm')) {
4125             submitFormLink($(this));
4126             return false;
4127         }
4128     });
4130     var $updateRecentTables = $('#update_recent_tables');
4131     if ($updateRecentTables.length) {
4132         $.get(
4133             $updateRecentTables.attr('href'),
4134             {no_debug: true},
4135             function (data) {
4136                 if (typeof data !== 'undefined' && data.success === true) {
4137                     $('#pma_recent_list').html(data.list);
4138                 }
4139             }
4140         );
4141     }
4143     // Sync favorite tables from localStorage to pmadb.
4144     if ($('#sync_favorite_tables').length) {
4145         $.ajax({
4146             url: $('#sync_favorite_tables').attr("href"),
4147             cache: false,
4148             type: 'POST',
4149             data: {
4150                 favorite_tables: (isStorageSupported('localStorage') && typeof window.localStorage.favorite_tables !== 'undefined')
4151                     ? window.localStorage.favorite_tables
4152                     : '',
4153                 no_debug: true
4154             },
4155             success: function (data) {
4156                 // Update localStorage.
4157                 if (isStorageSupported('localStorage')) {
4158                     window.localStorage.favorite_tables = data.favorite_tables;
4159                 }
4160                 $('#pma_favorite_list').html(data.list);
4161             }
4162         });
4163     }
4164 }); // end of $()
4167  * Submits the form placed in place of a link due to the excessive url length
4169  * @param $link anchor
4170  * @returns {Boolean}
4171  */
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] + '"/>');
4177     }
4178     $link.parents('form').submit();
4182  * Initializes slider effect.
4183  */
4184 function PMA_init_slider()
4186     $('div.pma_auto_slider').each(function () {
4187         var $this = $(this);
4188         if ($this.data('slider_init_done')) {
4189             return;
4190         }
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');
4200                 if (!visible) {
4201                     $wrapper.show();
4202                 }
4203                 $this[visible ? 'hide' : 'show']('blind', function () {
4204                     $wrapper.toggle(!visible);
4205                     $wrapper.parent().toggleClass("print_ignore", visible);
4206                     PMA_set_status_label($this);
4207                 });
4208                 return false;
4209             });
4210         $this.wrap($wrapper);
4211         $this.removeAttr('title');
4212         PMA_set_status_label($this);
4213         $this.data('slider_init_done', 1);
4214     });
4218  * Initializes slider effect.
4219  */
4220 AJAX.registerOnload('functions.js', function () {
4221     PMA_init_slider();
4225  * Restores sliders to the state they were in before initialisation.
4226  */
4227 AJAX.registerTeardown('functions.js', function () {
4228     $('div.pma_auto_slider').each(function () {
4229         var $this = $(this);
4230         $this.removeData();
4231         $this.parent().replaceWith($this);
4232         $this.parent().children('a').remove();
4233     });
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
4247  */
4248 function PMA_slidingMessage(msg, $obj)
4250     if (msg === undefined || msg.length === 0) {
4251         // Don't show an empty message
4252         return false;
4253     }
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>'
4261             );
4262         }
4263         $obj = $('#PMA_slidingMessage');
4264     }
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
4268         $obj
4269         .find('div')
4270         .first()
4271         .fadeOut(function () {
4272             $obj
4273             .children()
4274             .remove();
4275             $obj
4276             .append('<div>' + msg + '</div>');
4277             // highlight any sql before taking height;
4278             PMA_highlightSQL($obj);
4279             $obj.find('div')
4280                 .first()
4281                 .hide();
4282             $obj
4283             .animate({
4284                 height: $obj.find('div').first().height()
4285             })
4286             .find('div')
4287             .first()
4288             .fadeIn();
4289         });
4290     } else {
4291         // Object does not already have a message
4292         // inside it, so we simply slide it down
4293         $obj.width('100%')
4294             .html('<div>' + msg + '</div>');
4295         // highlight any sql before taking height;
4296         PMA_highlightSQL($obj);
4297         var h = $obj
4298             .find('div')
4299             .first()
4300             .hide()
4301             .height();
4302         $obj
4303         .find('div')
4304         .first()
4305         .css('height', 0)
4306         .show()
4307         .animate({
4308                 height: h
4309             }, function () {
4310             // Set the height of the parent
4311             // to the height of the child
4312                 $obj
4313                 .height(
4314                     $obj
4315                     .find('div')
4316                     .first()
4317                     .height()
4318                 );
4319             });
4320     }
4321     return true;
4322 } // end PMA_slidingMessage()
4325  * Attach CodeMirror2 editor to SQL edit area.
4326  */
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);
4334         } else {
4335             // without codemirror
4336             $elm.focus()
4337                 .bind('blur', updateQueryParameters);
4338         }
4339     }
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;
4347     }
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()));
4361     });
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")));
4369     });
4373  * jQuery plugin to correctly filter input fields by value, needed
4374  * because some nasty values may break selector syntax
4375  */
4376 (function ($) {
4377     $.fn.filterByValue = function (value) {
4378         return this.filter(function () {
4379             return $(this).val() === value;
4380         });
4381     };
4382 })(jQuery);
4385  * Return value of a cell in a table.
4386  */
4387 function PMA_getCellValue(td) {
4388     var $td = $(td);
4389     if ($td.is('.null')) {
4390         return '';
4391     } else if ((! $td.is('.to_be_saved')
4392         || $td.is('.set'))
4393         && $td.data('original_data')
4394     ) {
4395         return $td.data('original_data');
4396     } else {
4397         return $td.text();
4398     }
4401 $(window).on('popstate', function (event, data) {
4402     $('#printcss').attr('media','print');
4403     return true;
4407  * Unbind all event handlers before tearing down a page
4408  */
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 () {
4416     /**
4417      * Theme selector.
4418      */
4419     $(document).on('click', 'a.themeselect', function (e) {
4420         window.open(
4421             e.target,
4422             'themes',
4423             'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
4424             );
4425         return false;
4426     });
4428     /**
4429      * Automatic form submission on change.
4430      */
4431     $(document).on('change', '.autosubmit', function (e) {
4432         $(this).closest('form').submit();
4433     });
4435     /**
4436      * Theme changer.
4437      */
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();
4443             window.close();
4444             return false;
4445         }
4446         return true;
4447     });
4451  * Produce print preview
4452  */
4453 function printPreview()
4455     $('#printcss').attr('media','all');
4456     createPrintAndBackButtons();
4460  * Create print and back buttons in preview page
4461  */
4462 function createPrintAndBackButtons() {
4464     var back_button = $("<input/>",{
4465         type: 'button',
4466         value: PMA_messages.back,
4467         id: 'back_button_print_view'
4468     });
4469     back_button.click(removePrintAndBackButton);
4470     back_button.appendTo('#page_content');
4471     var print_button = $("<input/>",{
4472         type: 'button',
4473         value: PMA_messages.print,
4474         id: 'print_button_print_view'
4475     });
4476     print_button.click(printPage);
4477     print_button.appendTo('#page_content');
4481  * Remove print and back buttons and revert to normal view
4482  */
4483 function removePrintAndBackButton(){
4484     $('#printcss').attr('media','print');
4485     $('#back_button_print_view').remove();
4486     $('#print_button_print_view').remove();
4490  * Print page
4491  */
4492 function printPage(){
4493     if (typeof(window.print) != 'undefined') {
4494         window.print();
4495     }
4499  * Print button
4500  */
4501 function copyToClipboard()
4503     var textArea = document.createElement("textarea");
4505     //
4506     // *** This styling is an extra step which is likely not required. ***
4507     //
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.
4513     //
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.
4518     //
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() + '/';
4547     });
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';
4555     });
4557     elementList = $('.sql pre');
4559     elementList.each(function() {
4560         textArea.value += $(this).text() + '\n\n';
4561     });
4563     elementList = $('.table_results .column_heading a');
4565     elementList.each(function() {
4566         textArea.value += $(this).clone().children().remove().end().text() + '\t';
4567     });
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';
4575         });
4576         textArea.value += '\n';
4577     });
4579     document.body.appendChild(textArea);
4581     textArea.select();
4583     try {
4584         document.execCommand('copy');
4585     } catch (err) {
4586         alert('Sorry! Unable to copy');
4587     }
4589     document.body.removeChild(textArea);
4593  * Unbind all event handlers before tearing down a page
4594  */
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);
4604     /**
4605      * Ajaxification for the "Create View" action
4606      */
4607     $(document).on('click', 'a.create_view.ajax', function (e) {
4608         e.preventDefault();
4609         PMA_createViewDialog($(this));
4610     });
4611     /**
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.
4614      */
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
4618                 e.preventDefault();
4620                 // with preventing default, selection by <select> tag
4621                 // was also prevented in IE
4622                 $(this).blur();
4624                 $(this).closest('.ui-dialog').find('.ui-button:first').click();
4625             }
4626         }); // end $(document).on()
4627     }
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();
4644                 }
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();
4652                     } else {
4653                         PMA_ajaxShowMessage(data.error, false);
4654                     }
4655                 });
4656             };
4657             buttonOptions[PMA_messages.strClose] = function () {
4658                 $(this).dialog("close");
4659             };
4660             var $dialog = $('<div/>').attr('id', 'createViewDialog').append(data.message).dialog({
4661                 width: 600,
4662                 minWidth: 400,
4663                 modal: true,
4664                 buttons: buttonOptions,
4665                 title: PMA_messages.strCreateView,
4666                 close: function () {
4667                     $(this).remove();
4668                 }
4669             });
4670             // Attach syntax highlighted editor
4671             syntaxHighlighter = PMA_getSQLEditor($dialog.find('textarea'));
4672             $('input:visible[type=text]', $dialog).first().focus();
4673         } else {
4674             PMA_ajaxShowMessage(data.error);
4675         }
4676     });
4680  * Makes the breadcrumbs and the menu bar float at the top of the viewport
4681  */
4682 $(function () {
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())
4687             .css(left, 0)
4688             .css({
4689                 'position': 'fixed',
4690                 'top': 0,
4691                 'width': '100%',
4692                 'z-index': 99
4693             })
4694             .append($('#serverinfo'))
4695             .append($('#topmenucontainer'));
4696         // Allow the DOM to render, then adjust the padding on the body
4697         setTimeout(function () {
4698             $('body').css(
4699                 'padding-top',
4700                 $('#floating_menubar').outerHeight(true)
4701             );
4702             $('#topmenu').menuResizer('resize');
4703         }, 4);
4704     }
4708  * Scrolls the page to the top if clicking the serverinfo bar
4709  */
4710 $(function () {
4711     $(document).delegate("#serverinfo, #goto_pagetop", "click", function (event) {
4712         event.preventDefault();
4713         $('html, body').animate({scrollTop: 0}, 'fast');
4714     });
4717 var checkboxes_sel = "input.checkall:checkbox:enabled";
4719  * Watches checkboxes in a form to set the checkall box accordingly
4720  */
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});
4730     }
4731     else if (checked_boxes > 0) {
4732         $checkall.prop({checked: true, indeterminate: true});
4733     }
4734     else {
4735         $checkall.prop({checked: false, indeterminate: false});
4736     }
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
4748  */
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});
4758     }
4759     else if (checked_boxes > 0) {
4760         $checkall.prop({checked: true, indeterminate: true});
4761     }
4762     else {
4763         $checkall.prop({checked: false, indeterminate: false});
4764     }
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
4779  */
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');
4787         }
4788     }
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
4797  */
4798 function formatBytes(bytes, subdecimals, pointchar) {
4799     if (!subdecimals) {
4800         subdecimals = 0;
4801     }
4802     if (!pointchar) {
4803         pointchar = '.';
4804     }
4805     var units = ['B', 'KiB', 'MiB', 'GiB'];
4806     for (var i = 0; bytes > 1024 && i < units.length; i++) {
4807         bytes /= 1024;
4808     }
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 () {
4816     /**
4817      * Opens pma more themes link in themes browser, in new window instead of popup
4818      * This way, we don't break HTML validity
4819      */
4820     $("a._blank").prop("target", "_blank");
4821     /**
4822      * Reveal the login form to users with JS enabled
4823      * and focus the appropriate input field
4824      */
4825     var $loginform = $('#loginform');
4826     if ($loginform.length) {
4827         $loginform.find('.js-show').show();
4828         if ($('#input_username').val()) {
4829             $('#input_password').focus();
4830         } else {
4831             $('#input_username').focus();
4832         }
4833     }
4837  * Dynamically adjust the width of the boxes
4838  * on the table and db operations pages
4839  */
4840 (function () {
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()
4848             .each(function () {
4849                 if (viewport < minWidth) {
4850                     $(this).width(minWidth);
4851                 } else {
4852                     $(this).css('width', ((1 /  slots) * 100) + "%");
4853                 }
4854             })
4855             .removeClass('clearfloat')
4856             .filter(':nth-child(' + slots + 'n+1)')
4857             .addClass('clearfloat');
4858         }
4859     }
4860     AJAX.registerOnload('functions.js', function () {
4861         DynamicBoxes();
4862     });
4863     $(function () {
4864         $(window).resize(DynamicBoxes);
4865     });
4866 })();
4869  * Formats timestamp for display
4870  */
4871 function PMA_formatDateTime(date, seconds) {
4872     var result = $.datepicker.formatDate('yy-mm-dd', date);
4873     var timefmt = 'HH:mm';
4874     if (seconds) {
4875         timefmt = 'HH:mm:ss';
4876     }
4877     return result + ' ' + $.datepicker.formatTime(
4878         timefmt, {
4879             hour: date.getHours(),
4880             minute: date.getMinutes(),
4881             second: date.getSeconds()
4882         }
4883     );
4887  * Check than forms have less fields than max allowed by PHP.
4888  */
4889 function checkNumberOfFields() {
4890     if (typeof maxInputVars === 'undefined') {
4891         return false;
4892     }
4893     if (false === maxInputVars) {
4894         return false;
4895     }
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);
4901             return false;
4902         }
4903         return true;
4904     });
4906     return true;
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
4916  */
4917 function PMA_ignorePhpErrors(clearPrevErrors){
4918     if (typeof(clearPrevErrors) === "undefined" ||
4919         clearPrevErrors === null
4920     ) {
4921         str = false;
4922     }
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();
4929     }
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
4939  */
4940 AJAX.registerTeardown('functions.js', function(){
4941     $(document).off('keydown', 'form input, form textarea, form select');
4944 AJAX.registerOnload('functions.js', function () {
4945     /**
4946      * Handle 'Ctrl/Alt + Enter' form submits
4947      */
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()
4953             ) {
4954                 $form.submit();
4955             }
4956         }
4957     });
4961  * Unbind all event handlers before tearing down a page
4962  */
4963 AJAX.registerTeardown('functions.js', function(){
4964     $(document).off('change', 'input[type=radio][name="pw_hash"]');
4967 AJAX.registerOnload('functions.js', function(){
4968     /*
4969      * Display warning regarding SSL when sha256_password
4970      * method is selected
4971      * Used in user_password.php (Change Password link on index.php)
4972      */
4973     $(document).on("change", 'select#select_authentication_plugin_cp', function() {
4974         if (this.value === 'sha256_password') {
4975             $('#ssl_reqd_warning_cp').show();
4976         } else {
4977             $('#ssl_reqd_warning_cp').hide();
4978         }
4979     });