1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * general function, usually for data manipulation pages
8 * @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
10 var sql_box_locked = false;
13 * @var array holds elements which content should only selected once
15 var only_once_elements = new Array();
18 * @var int ajax_message_count Number of AJAX messages shown since page load
20 var ajax_message_count = 0;
23 * @var codemirror_editor object containing CodeMirror editor
25 var codemirror_editor = false;
28 * @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
30 var chart_activeTimeouts = new Object();
33 * Returns browser's viewport size, without accounting for scrollbars
37 function getWindowSize(wnd) {
38 var vp = wnd || window;
40 // most browsers || IE6-8 strict || failsafe
41 width: vp.innerWidth || (vp.documentElement !== undefined ? vp.documentElement.clientWidth : false) || $(vp).width(),
42 height: vp.innerHeight || (vp.documentElement !== undefined ? vp.documentElement.clientHeight : false) || $(vp).height()
47 * Make sure that ajax requests will not be cached
48 * by appending a random variable to their parameters
50 $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
51 var nocache = new Date().getTime() + "" + Math.floor(Math.random() * 1000000);
52 if (typeof options.data == "string") {
53 options.data += "&_nocache=" + nocache;
54 } else if (typeof options.data == "object") {
55 options.data = $.extend(originalOptions.data, {'_nocache':nocache});
60 * Add a hidden field to the form to indicate that this will be an
61 * Ajax request (only if this hidden field does not exist)
63 * @param object the form
65 function PMA_prepareForAjaxRequest($form)
67 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
68 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
73 * Generate a new password and copy it to the password input areas
75 * @param object the form that holds the password fields
77 * @return boolean always true
79 function suggestPassword(passwd_form)
81 // restrict the password to just letters and numbers to avoid problems:
82 // "editors and viewers regard the password as multiple words and
83 // things like double click no longer work"
84 var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
85 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
86 var passwd = passwd_form.generated_pw;
89 for ( i = 0; i < passwordlength; i++ ) {
90 passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
92 passwd_form.text_pma_pw.value = passwd.value;
93 passwd_form.text_pma_pw2.value = passwd.value;
98 * Version string to integer conversion.
100 function parseVersionString (str)
102 if (typeof(str) != 'string') { return false; }
104 // Parse possible alpha/beta/rc/
105 var state = str.split('-');
106 if (state.length >= 2) {
107 if (state[1].substr(0, 2) == 'rc') {
108 add = - 20 - parseInt(state[1].substr(2));
109 } else if (state[1].substr(0, 4) == 'beta') {
110 add = - 40 - parseInt(state[1].substr(4));
111 } else if (state[1].substr(0, 5) == 'alpha') {
112 add = - 60 - parseInt(state[1].substr(5));
113 } else if (state[1].substr(0, 3) == 'dev') {
114 /* We don't handle dev, it's git snapshot */
119 var x = str.split('.');
120 // Use 0 for non existing parts
121 var maj = parseInt(x[0]) || 0;
122 var min = parseInt(x[1]) || 0;
123 var pat = parseInt(x[2]) || 0;
124 var hotfix = parseInt(x[3]) || 0;
125 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
129 * Indicates current available version on main page.
131 function PMA_current_version(data)
133 var current = parseVersionString(pmaversion);
134 var latest = parseVersionString(data['version']);
135 var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + escapeHtml(data['version']);
136 if (latest > current) {
137 var message = $.sprintf(PMA_messages['strNewerVersion'], escapeHtml(data['version']), escapeHtml(data['date']));
138 if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
139 /* Security update */
144 $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
146 if (latest == current) {
147 version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
149 $('#li_pma_version').append(version_information_message);
153 * for libraries/display_change_password.lib.php
154 * libraries/user_password.php
158 function displayPasswordGenerateButton()
160 $('#tr_element_before_generate_password').parent().append('<tr><td>' + PMA_messages['strGeneratePassword'] + '</td><td><input type="button" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /><input type="text" name="generated_pw" id="generated_pw" /></td></tr>');
161 $('#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" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /></span><input type="text" name="generated_pw" id="generated_pw" /></div>');
165 * Adds a date/time picker to an element
167 * @param object $this_element a jQuery object pointing to the element
169 function PMA_addDatepicker($this_element, options)
171 var showTimeOption = false;
172 if ($this_element.is('.datetimefield')) {
173 showTimeOption = true;
176 var defaultOptions = {
178 buttonImage: themeCalendarImage, // defined in js/messages.php
179 buttonImageOnly: true,
183 showTimepicker: showTimeOption,
184 showButtonPanel: false,
185 dateFormat: 'yy-mm-dd', // yy means year with four digits
186 timeFormat: 'hh:mm:ss',
187 altFieldTimeOnly: false,
189 beforeShow: function(input, inst) {
190 // Remember that we came from the datepicker; this is used
191 // in tbl_change.js by verificationsAfterFieldChange()
192 $this_element.data('comes_from', 'datepicker');
194 // Fix wrong timepicker z-index, doesn't work without timeout
195 setTimeout(function() {
196 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
199 onClose: function(dateText, dp_inst) {
200 // The value is no more from the date picker
201 $this_element.data('comes_from', '');
205 $this_element.datetimepicker($.extend(defaultOptions, options));
209 * selects the content of a given object, f.e. a textarea
211 * @param object element element of which the content will be selected
212 * @param var lock variable which holds the lock for this element
213 * or true, if no lock exists
214 * @param boolean only_once if true this is only done once
215 * f.e. only on first focus
217 function selectContent( element, lock, only_once )
219 if ( only_once && only_once_elements[element.name] ) {
223 only_once_elements[element.name] = true;
233 * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
234 * This function is called while clicking links
236 * @param object the link
237 * @param object the sql query to submit
239 * @return boolean whether to run the query or not
241 function confirmLink(theLink, theSqlQuery)
243 // Confirmation is not required in the configuration file
244 // or browser is Opera (crappy js implementation)
245 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
249 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
251 if ( $(theLink).hasClass('formLinkSubmit') ) {
252 var name = 'is_js_confirmed';
253 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
254 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
257 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
258 } else if ( typeof(theLink.href) != 'undefined' ) {
259 theLink.href += '&is_js_confirmed=1';
260 } else if ( typeof(theLink.form) != 'undefined' ) {
261 theLink.form.action += '?is_js_confirmed=1';
266 } // end of the 'confirmLink()' function
269 * Displays an error message if a "DROP DATABASE" statement is submitted
270 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
271 * sumitting it if required.
272 * This function is called by the 'checkSqlQuery()' js function.
274 * @param object the form
275 * @param object the sql query textarea
277 * @return boolean whether to run the query or not
279 * @see checkSqlQuery()
281 function confirmQuery(theForm1, sqlQuery1)
283 // Confirmation is not required in the configuration file
284 if (PMA_messages['strDoYouReally'] == '') {
288 // "DROP DATABASE" statement isn't allowed
289 if (PMA_messages['strNoDropDatabases'] != '') {
290 var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
291 if (drop_re.test(sqlQuery1.value)) {
292 alert(PMA_messages['strNoDropDatabases']);
299 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
301 // TODO: find a way (if possible) to use the parser-analyser
302 // for this kind of verification
303 // For now, I just added a ^ to check for the statement at
304 // beginning of expression
306 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
307 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
308 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
309 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
311 if (do_confirm_re_0.test(sqlQuery1.value)
312 || do_confirm_re_1.test(sqlQuery1.value)
313 || do_confirm_re_2.test(sqlQuery1.value)
314 || do_confirm_re_3.test(sqlQuery1.value)) {
315 var message = (sqlQuery1.value.length > 100)
316 ? sqlQuery1.value.substr(0, 100) + '\n ...'
318 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
319 // statement is confirmed -> update the
320 // "is_js_confirmed" form field so the confirm test won't be
321 // run on the server side and allows to submit the form
323 theForm1.elements['is_js_confirmed'].value = 1;
326 // statement is rejected -> do not submit the form
331 } // end if (handle confirm box result)
332 } // end if (display confirm box)
335 } // end of the 'confirmQuery()' function
339 * Displays a confirmation box before disabling the BLOB repository for a given database.
340 * This function is called while clicking links
342 * @param object the database
344 * @return boolean whether to disable the repository or not
346 function confirmDisableRepository(theDB)
348 // Confirmation is not required in the configuration file
349 // or browser is Opera (crappy js implementation)
350 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
354 var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
357 } // end of the 'confirmDisableBLOBRepository()' function
361 * Displays an error message if the user submitted the sql query form with no
362 * sql query, else checks for "DROP/DELETE/ALTER" statements
364 * @param object the form
366 * @return boolean always false
368 * @see confirmQuery()
370 function checkSqlQuery(theForm)
372 var sqlQuery = theForm.elements['sql_query'];
375 var space_re = new RegExp('\\s+');
376 if (typeof(theForm.elements['sql_file']) != 'undefined' &&
377 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
380 if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
381 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
384 if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
385 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
386 theForm.elements['id_bookmark'].selectedIndex != 0
390 // Checks for "DROP/DELETE/ALTER" statements
391 if (sqlQuery.value.replace(space_re, '') != '') {
392 if (confirmQuery(theForm, sqlQuery)) {
403 alert(PMA_messages['strFormEmpty']);
409 } // end of the 'checkSqlQuery()' function
412 * Check if a form's element is empty.
413 * An element containing only spaces is also considered empty
415 * @param object the form
416 * @param string the name of the form field to put the focus on
418 * @return boolean whether the form field is empty or not
420 function emptyCheckTheField(theForm, theFieldName)
422 var theField = theForm.elements[theFieldName];
423 var space_re = new RegExp('\\s+');
424 return (theField.value.replace(space_re, '') == '') ? 1 : 0;
425 } // end of the 'emptyCheckTheField()' function
429 * Check whether a form field is empty or not
431 * @param object the form
432 * @param string the name of the form field to put the focus on
434 * @return boolean whether the form field is empty or not
436 function emptyFormElements(theForm, theFieldName)
438 var theField = theForm.elements[theFieldName];
439 var isEmpty = emptyCheckTheField(theForm, theFieldName);
443 } // end of the 'emptyFormElements()' function
447 * Ensures a value submitted in a form is numeric and is in a range
449 * @param object the form
450 * @param string the name of the form field to check
451 * @param integer the minimum authorized value
452 * @param integer the maximum authorized value
454 * @return boolean whether a valid number has been submitted or not
456 function checkFormElementInRange(theForm, theFieldName, message, min, max)
458 var theField = theForm.elements[theFieldName];
459 var val = parseInt(theField.value);
461 if (typeof(min) == 'undefined') {
464 if (typeof(max) == 'undefined') {
465 max = Number.MAX_VALUE;
471 alert(PMA_messages['strNotNumber']);
475 // It's a number but it is not between min and max
476 else if (val < min || val > max) {
478 alert(message.replace('%d', val));
482 // It's a valid number
484 theField.value = val;
488 } // end of the 'checkFormElementInRange()' function
491 function checkTableEditForm(theForm, fieldsCnt)
493 // TODO: avoid sending a message if user just wants to add a line
494 // on the form but has not completed at least one field name
496 var atLeastOneField = 0;
497 var i, elm, elm2, elm3, val, id;
499 for (i=0; i<fieldsCnt; i++)
501 id = "#field_" + i + "_2";
504 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
505 elm2 = $("#field_" + i + "_3");
506 val = parseInt(elm2.val());
507 elm3 = $("#field_" + i + "_1");
508 if (isNaN(val) && elm3.val() != "") {
510 alert(PMA_messages['strNotNumber']);
516 if (atLeastOneField == 0) {
517 id = "field_" + i + "_1";
518 if (!emptyCheckTheField(theForm, id)) {
523 if (atLeastOneField == 0) {
524 var theField = theForm.elements["field_0_1"];
525 alert(PMA_messages['strFormEmpty']);
530 // at least this section is under jQuery
531 if ($("input.textfield[name='table']").val() == "") {
532 alert(PMA_messages['strFormEmpty']);
533 $("input.textfield[name='table']").focus();
539 } // enf of the 'checkTableEditForm()' function
541 $(document).ready(function() {
543 * Row marking in horizontal mode (use "live" so that it works also for
544 * next pages reached via AJAX); a tr may have the class noclick to remove
547 $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
548 // do not trigger when clicked on anchor
549 if ($(e.target).is('a, img, a *')) {
554 // make the table unselectable (to prevent default highlighting when shift+click)
555 //$tr.parents('table').noSelect();
557 if (!e.shiftKey || last_clicked_row == -1) {
560 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
561 var $checkbox = $tr.find(':checkbox');
562 if ($checkbox.length) {
563 // checkbox in a row, add or remove class depending on checkbox state
564 var checked = $checkbox.attr('checked');
565 if (!$(e.target).is(':checkbox, label')) {
567 $checkbox.attr('checked', checked);
570 $tr.addClass('marked');
572 $tr.removeClass('marked');
574 last_click_checked = checked;
576 // normaln data table, just toggle class
577 $tr.toggleClass('marked');
578 last_click_checked = false;
581 // remember the last clicked row
582 last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
583 last_shift_clicked_row = -1;
585 // handle the shift click
586 PMA_clearSelection();
589 // clear last shift click result
590 if (last_shift_clicked_row >= 0) {
591 if (last_shift_clicked_row >= last_clicked_row) {
592 start = last_clicked_row;
593 end = last_shift_clicked_row;
595 start = last_shift_clicked_row;
596 end = last_clicked_row;
598 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
599 .slice(start, end + 1)
600 .removeClass('marked')
602 .attr('checked', false);
605 // handle new shift click
606 var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
607 if (curr_row >= last_clicked_row) {
608 start = last_clicked_row;
612 end = last_clicked_row;
614 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
615 .slice(start, end + 1)
618 .attr('checked', true);
620 // remember the last shift clicked row
621 last_shift_clicked_row = curr_row;
626 * Add a date/time picker to each element that needs it
627 * (only when timepicker.js is loaded)
629 if ($.timepicker != undefined) {
630 $('.datefield, .datetimefield').each(function() {
631 PMA_addDatepicker($(this));
637 * True if last click is to check a row.
639 var last_click_checked = false;
642 * Zero-based index of last clicked row.
643 * Used to handle the shift + click event in the code above.
645 var last_clicked_row = -1;
648 * Zero-based index of last shift clicked row.
650 var last_shift_clicked_row = -1;
653 * Row highlighting in horizontal mode (use "live"
654 * so that it works also for pages reached via AJAX)
656 /*$(document).ready(function() {
657 $('tr.odd, tr.even').live('hover',function(event) {
659 $tr.toggleClass('hover',event.type=='mouseover');
660 $tr.children().toggleClass('hover',event.type=='mouseover');
665 * This array is used to remember mark status of rows in browse mode
667 var marked_row = new Array;
670 * marks all rows and selects its first checkbox inside the given element
671 * the given element is usaly a table or a div containing the table or tables
673 * @param container DOM element
675 function markAllRows( container_id )
678 $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
679 .parents("tr").addClass("marked");
684 * marks all rows and selects its first checkbox inside the given element
685 * the given element is usaly a table or a div containing the table or tables
687 * @param container DOM element
689 function unMarkAllRows( container_id )
692 $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
693 .parents("tr").removeClass("marked");
698 * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
700 * @param string container_id the container id
701 * @param boolean state new value for checkbox (true or false)
702 * @return boolean always true
704 function setCheckboxes( container_id, state )
708 $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
711 $("#"+container_id).find("input:checkbox").removeAttr('checked');
715 } // end of the 'setCheckboxes()' function
718 * Checks/unchecks all options of a <select> element
720 * @param string the form name
721 * @param string the element name
722 * @param boolean whether to check or to uncheck options
724 * @return boolean always true
726 function setSelectOptions(the_form, the_select, do_check)
728 $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
730 } // end of the 'setSelectOptions()' function
733 * Sets current value for query box.
735 function setQuery(query)
737 if (codemirror_editor) {
738 codemirror_editor.setValue(query);
740 document.sqlform.sql_query.value = query;
746 * Create quick sql statements.
749 function insertQuery(queryType)
751 if (queryType == "clear") {
756 var myQuery = document.sqlform.sql_query;
758 var myListBox = document.sqlform.dummy;
759 var table = document.sqlform.table.value;
761 if (myListBox.options.length > 0) {
762 sql_box_locked = true;
767 for (var i=0; i < myListBox.options.length; i++) {
774 chaineAj += myListBox.options[i].value;
775 valDis += "[value-" + NbSelect + "]";
776 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
778 if (queryType == "selectall") {
779 query = "SELECT * FROM `" + table + "` WHERE 1";
780 } else if (queryType == "select") {
781 query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
782 } else if (queryType == "insert") {
783 query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
784 } else if (queryType == "update") {
785 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
786 } else if(queryType == "delete") {
787 query = "DELETE FROM `" + table + "` WHERE 1";
790 sql_box_locked = false;
796 * Inserts multiple fields.
799 function insertValueQuery()
801 var myQuery = document.sqlform.sql_query;
802 var myListBox = document.sqlform.dummy;
804 if(myListBox.options.length > 0) {
805 sql_box_locked = true;
808 for(var i=0; i<myListBox.options.length; i++) {
809 if (myListBox.options[i].selected) {
814 chaineAj += myListBox.options[i].value;
818 /* CodeMirror support */
819 if (codemirror_editor) {
820 codemirror_editor.replaceSelection(chaineAj);
822 } else if (document.selection) {
824 sel = document.selection.createRange();
826 document.sqlform.insert.focus();
828 //MOZILLA/NETSCAPE support
829 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
830 var startPos = document.sqlform.sql_query.selectionStart;
831 var endPos = document.sqlform.sql_query.selectionEnd;
832 var chaineSql = document.sqlform.sql_query.value;
834 myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
836 myQuery.value += chaineAj;
838 sql_box_locked = false;
843 * listbox redirection
845 function goToUrl(selObj, goToLocation)
847 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
851 * Refresh the WYSIWYG scratchboard after changes have been made
853 function refreshDragOption(e)
855 var elm = $('#' + e);
856 if (elm.css('visibility') == 'visible') {
863 * Refresh/resize the WYSIWYG scratchboard
865 function refreshLayout()
867 var elm = $('#pdflayout')
868 var orientation = $('#orientation_opt').val();
869 if($('#paper_opt').length==1){
870 var paper = $('#paper_opt').val();
874 if (orientation == 'P') {
881 elm.css('width', pdfPaperSize(paper, posa) + 'px');
882 elm.css('height', pdfPaperSize(paper, posb) + 'px');
886 * Show/hide the WYSIWYG scratchboard
888 function ToggleDragDrop(e)
890 var elm = $('#' + e);
891 if (elm.css('visibility') == 'hidden') {
892 PDFinit(); /* Defined in pdf_pages.php */
893 elm.css('visibility', 'visible');
894 elm.css('display', 'block');
895 $('#showwysiwyg').val('1')
897 elm.css('visibility', 'hidden');
898 elm.css('display', 'none');
899 $('#showwysiwyg').val('0')
904 * PDF scratchboard: When a position is entered manually, update
905 * the fields inside the scratchboard.
907 function dragPlace(no, axis, value)
909 var elm = $('#table_' + no);
911 elm.css('left', value + 'px');
913 elm.css('top', value + 'px');
918 * Returns paper sizes for a given format
920 function pdfPaperSize(format, axis)
922 switch (format.toUpperCase()) {
924 if (axis == 'x') return 4767.87; else return 6740.79;
927 if (axis == 'x') return 3370.39; else return 4767.87;
930 if (axis == 'x') return 2383.94; else return 3370.39;
933 if (axis == 'x') return 1683.78; else return 2383.94;
936 if (axis == 'x') return 1190.55; else return 1683.78;
939 if (axis == 'x') return 841.89; else return 1190.55;
942 if (axis == 'x') return 595.28; else return 841.89;
945 if (axis == 'x') return 419.53; else return 595.28;
948 if (axis == 'x') return 297.64; else return 419.53;
951 if (axis == 'x') return 209.76; else return 297.64;
954 if (axis == 'x') return 147.40; else return 209.76;
957 if (axis == 'x') return 104.88; else return 147.40;
960 if (axis == 'x') return 73.70; else return 104.88;
963 if (axis == 'x') return 2834.65; else return 4008.19;
966 if (axis == 'x') return 2004.09; else return 2834.65;
969 if (axis == 'x') return 1417.32; else return 2004.09;
972 if (axis == 'x') return 1000.63; else return 1417.32;
975 if (axis == 'x') return 708.66; else return 1000.63;
978 if (axis == 'x') return 498.90; else return 708.66;
981 if (axis == 'x') return 354.33; else return 498.90;
984 if (axis == 'x') return 249.45; else return 354.33;
987 if (axis == 'x') return 175.75; else return 249.45;
990 if (axis == 'x') return 124.72; else return 175.75;
993 if (axis == 'x') return 87.87; else return 124.72;
996 if (axis == 'x') return 2599.37; else return 3676.54;
999 if (axis == 'x') return 1836.85; else return 2599.37;
1002 if (axis == 'x') return 1298.27; else return 1836.85;
1005 if (axis == 'x') return 918.43; else return 1298.27;
1008 if (axis == 'x') return 649.13; else return 918.43;
1011 if (axis == 'x') return 459.21; else return 649.13;
1014 if (axis == 'x') return 323.15; else return 459.21;
1017 if (axis == 'x') return 229.61; else return 323.15;
1020 if (axis == 'x') return 161.57; else return 229.61;
1023 if (axis == 'x') return 113.39; else return 161.57;
1026 if (axis == 'x') return 79.37; else return 113.39;
1029 if (axis == 'x') return 2437.80; else return 3458.27;
1032 if (axis == 'x') return 1729.13; else return 2437.80;
1035 if (axis == 'x') return 1218.90; else return 1729.13;
1038 if (axis == 'x') return 864.57; else return 1218.90;
1041 if (axis == 'x') return 609.45; else return 864.57;
1044 if (axis == 'x') return 2551.18; else return 3628.35;
1047 if (axis == 'x') return 1814.17; else return 2551.18;
1050 if (axis == 'x') return 1275.59; else return 1814.17;
1053 if (axis == 'x') return 907.09; else return 1275.59;
1056 if (axis == 'x') return 637.80; else return 907.09;
1059 if (axis == 'x') return 612.00; else return 792.00;
1062 if (axis == 'x') return 612.00; else return 1008.00;
1065 if (axis == 'x') return 521.86; else return 756.00;
1068 if (axis == 'x') return 612.00; else return 936.00;
1076 * for playing media from the BLOB repository
1079 * @param var url_params main purpose is to pass the token
1080 * @param var bs_ref BLOB repository reference
1081 * @param var m_type type of BLOB repository media
1082 * @param var w_width width of popup window
1083 * @param var w_height height of popup window
1085 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1087 // if width not specified, use default
1088 if (w_width == undefined) {
1092 // if height not specified, use default
1093 if (w_height == undefined) {
1097 // open popup window (for displaying video/playing audio)
1098 var mediaWin = window.open('bs_play_media.php?' + url_params + '&bs_reference=' + bs_ref + '&media_type=' + m_type + '&custom_type=' + is_cust_type, 'viewBSMedia', 'width=' + w_width + ', height=' + w_height + ', resizable=1, scrollbars=1, status=0');
1102 * popups a request for changing MIME types for files in the BLOB repository
1104 * @param var db database name
1105 * @param var table table name
1106 * @param var reference BLOB repository reference
1107 * @param var current_mime_type current MIME type associated with BLOB repository reference
1109 function requestMIMETypeChange(db, table, reference, current_mime_type)
1111 // no mime type specified, set to default (nothing)
1112 if (undefined == current_mime_type) {
1113 current_mime_type = "";
1116 // prompt user for new mime type
1117 var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1119 // if new mime_type is specified and is not the same as the previous type, request for mime type change
1120 if (new_mime_type && new_mime_type != current_mime_type) {
1121 changeMIMEType(db, table, reference, new_mime_type);
1126 * changes MIME types for files in the BLOB repository
1128 * @param var db database name
1129 * @param var table table name
1130 * @param var reference BLOB repository reference
1131 * @param var mime_type new MIME type to be associated with BLOB repository reference
1133 function changeMIMEType(db, table, reference, mime_type)
1135 // specify url and parameters for jQuery POST
1136 var mime_chg_url = 'bs_change_mime_type.php';
1137 var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1140 jQuery.post(mime_chg_url, params);
1144 * Jquery Coding for inline editing SQL_QUERY
1146 $(document).ready(function(){
1147 $(".inline_edit_sql").live('click', function(){
1148 if ($('#sql_query_edit').length) {
1149 // An inline query editor is already open,
1150 // we don't want another copy of it
1154 var $form = $(this).prev();
1155 var sql_query = $form.find("input[name='sql_query']").val();
1156 var $inner_sql = $(this).parent().prev().find('.inner_sql');
1157 var old_text = $inner_sql.html();
1159 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1160 new_content += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1161 new_content += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1162 $inner_sql.replaceWith(new_content);
1164 // These settings are duplicated from the .ready()function in functions.js
1165 var height = $('#sql_query_edit').css('height');
1166 codemirror_editor = CodeMirror.fromTextArea($('textarea[name="sql_query_edit"]')[0], {
1168 matchBrackets: true,
1170 mode: "text/x-mysql",
1173 codemirror_editor.getScrollerElement().style.height = height;
1174 codemirror_editor.refresh();
1176 $(".btnSave").click(function(){
1177 if (codemirror_editor !== undefined) {
1178 var sql_query = codemirror_editor.getValue();
1180 var sql_query = $(this).prev().val();
1182 var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1183 .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1184 .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1185 .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1186 $fake_form.appendTo($('body')).submit();
1188 $(".btnDiscard").click(function(){
1189 $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1194 $('.sqlbutton').click(function(evt){
1195 insertQuery(evt.target.id);
1199 $("#export_type").change(function(){
1200 if($("#export_type").val()=='svg'){
1201 $("#show_grid_opt").attr("disabled","disabled");
1202 $("#orientation_opt").attr("disabled","disabled");
1203 $("#with_doc").attr("disabled","disabled");
1204 $("#show_table_dim_opt").removeAttr("disabled");
1205 $("#all_table_same_wide").removeAttr("disabled");
1206 $("#paper_opt").removeAttr("disabled","disabled");
1207 $("#show_color_opt").removeAttr("disabled","disabled");
1208 //$(this).css("background-color","yellow");
1209 }else if($("#export_type").val()=='dia'){
1210 $("#show_grid_opt").attr("disabled","disabled");
1211 $("#with_doc").attr("disabled","disabled");
1212 $("#show_table_dim_opt").attr("disabled","disabled");
1213 $("#all_table_same_wide").attr("disabled","disabled");
1214 $("#paper_opt").removeAttr("disabled","disabled");
1215 $("#show_color_opt").removeAttr("disabled","disabled");
1216 $("#orientation_opt").removeAttr("disabled","disabled");
1217 }else if($("#export_type").val()=='eps'){
1218 $("#show_grid_opt").attr("disabled","disabled");
1219 $("#orientation_opt").removeAttr("disabled");
1220 $("#with_doc").attr("disabled","disabled");
1221 $("#show_table_dim_opt").attr("disabled","disabled");
1222 $("#all_table_same_wide").attr("disabled","disabled");
1223 $("#paper_opt").attr("disabled","disabled");
1224 $("#show_color_opt").attr("disabled","disabled");
1226 }else if($("#export_type").val()=='pdf'){
1227 $("#show_grid_opt").removeAttr("disabled");
1228 $("#orientation_opt").removeAttr("disabled");
1229 $("#with_doc").removeAttr("disabled","disabled");
1230 $("#show_table_dim_opt").removeAttr("disabled","disabled");
1231 $("#all_table_same_wide").removeAttr("disabled","disabled");
1232 $("#paper_opt").removeAttr("disabled","disabled");
1233 $("#show_color_opt").removeAttr("disabled","disabled");
1239 $('#sqlquery').focus().keydown(function (e) {
1240 if (e.ctrlKey && e.keyCode == 13) {
1241 $("#sqlqueryform").submit();
1245 if ($('#input_username')) {
1246 if ($('#input_username').val() == '') {
1247 $('#input_username').focus();
1249 $('#input_password').focus();
1255 * Show a message on the top of the page for an Ajax request
1259 * 1) var $msg = PMA_ajaxShowMessage();
1260 * This will show a message that reads "Loading...". Such a message will not
1261 * disappear automatically and cannot be dismissed by the user. To remove this
1262 * message either the PMA_ajaxRemoveMessage($msg) function must be called or
1263 * another message must be show with PMA_ajaxShowMessage() function.
1265 * 2) var $msg = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1266 * This is a special case. The behaviour is same as above,
1267 * just with a different message
1269 * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
1270 * This will show a message that will disappear automatically and it can also
1271 * be dismissed by the user.
1273 * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
1274 * This will show a message that will not disappear automatically, but it
1275 * can be dismissed by the user after he has finished reading it.
1277 * @param string message string containing the message to be shown.
1278 * optional, defaults to 'Loading...'
1279 * @param mixed timeout number of milliseconds for the message to be visible
1280 * optional, defaults to 5000. If set to 'false', the
1281 * notification will never disappear
1282 * @return jQuery object jQuery Element that holds the message div
1283 * this object can be passed to PMA_ajaxRemoveMessage()
1284 * to remove the notification
1286 function PMA_ajaxShowMessage(message, timeout)
1289 * @var self_closing Whether the notification will automatically disappear
1291 var self_closing = true;
1293 * @var dismissable Whether the user will be able to remove
1294 * the notification by clicking on it
1296 var dismissable = true;
1297 // Handle the case when a empty data.message is passed.
1298 // We don't want the empty message
1299 if (message == '') {
1301 } else if (! message) {
1302 // If the message is undefined, show the default
1303 message = PMA_messages['strLoading'];
1304 dismissable = false;
1305 self_closing = false;
1306 } else if (message == PMA_messages['strProcessingRequest']) {
1307 // This is another case where the message should not disappear
1308 dismissable = false;
1309 self_closing = false;
1311 // Figure out whether (or after how long) to remove the notification
1312 if (timeout == undefined) {
1314 } else if (timeout === false) {
1315 self_closing = false;
1317 // Create a parent element for the AJAX messages, if necessary
1318 if ($('#loading_parent').length == 0) {
1319 $('<div id="loading_parent"></div>')
1322 // Update message count to create distinct message elements every time
1323 ajax_message_count++;
1324 // Remove all old messages, if any
1325 $(".ajax_notification[id^=ajax_message_num]").remove();
1327 * @var $retval a jQuery object containing the reference
1328 * to the created AJAX message
1331 '<span class="ajax_notification" id="ajax_message_num_'
1332 + ajax_message_count +
1336 .appendTo("#loading_parent")
1339 // If the notification is self-closing we should create a callback to remove it
1343 .fadeOut('medium', function() {
1344 if ($(this).is('.dismissable')) {
1345 // Here we should destroy the qtip instance, but
1346 // due to a bug in qtip's implementation we can
1347 // only hide it without throwing JS errors.
1348 $(this).qtip('hide');
1350 // Remove the notification
1354 // If the notification is dismissable we need to add the relevant class to it
1355 // and add a tooltip so that the users know that it can be removed
1357 $retval.addClass('dismissable').css('cursor', 'pointer');
1359 * @var qOpts Options for "Dismiss notification" tooltip
1363 effect: { length: 0 },
1367 effect: { length: 0 },
1372 * Add a tooltip to the notification to let the user know that (s)he
1373 * can dismiss the ajax notification by clicking on it.
1375 PMA_createqTip($retval, PMA_messages['strDismiss'], qOpts);
1382 * Removes the message shown for an Ajax operation when it's completed
1384 * @param jQuery object jQuery Element that holds the notification
1388 function PMA_ajaxRemoveMessage($this_msgbox)
1390 if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1394 if ($this_msgbox.is('.dismissable')) {
1395 if ($('#no_hint').length < 0) {
1396 // Here we should destroy the qtip instance, but
1397 // due to a bug in qtip's implementation we can
1398 // only hide it without throwing JS errors.
1399 $this_msgbox.qtip('hide');
1402 $this_msgbox.remove();
1407 $(document).ready(function() {
1409 * Allows the user to dismiss a notification
1410 * created with PMA_ajaxShowMessage()
1412 $('.ajax_notification.dismissable').live('click', function () {
1413 PMA_ajaxRemoveMessage($(this));
1416 * The below two functions hide the "Dismiss notification" tooltip when a user
1417 * is hovering a link or button that is inside an ajax message
1419 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1420 .live('mouseover', function () {
1421 $(this).parents('.ajax_notification').qtip('hide');
1423 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1424 .live('mouseout', function () {
1425 $(this).parents('.ajax_notification').qtip('show');
1430 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1432 function PMA_showNoticeForEnum(selectElement)
1434 var enum_notice_id = selectElement.attr("id").split("_")[1];
1435 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1436 var selectedType = selectElement.val();
1437 if (selectedType == "ENUM" || selectedType == "SET") {
1438 $("p[id='enum_notice_" + enum_notice_id + "']").show();
1440 $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1445 * Generates a dialog box to pop up the create_table form
1447 function PMA_createTableDialog( $div, url , target)
1450 * @var button_options Object that stores the options passed to jQueryUI
1453 var button_options = {};
1454 // in the following function we need to use $(this)
1455 button_options[PMA_messages['strCancel']] = function() {
1456 $(this).closest('.ui-dialog-content').dialog('close').remove();
1459 var button_options_error = {};
1460 button_options_error[PMA_messages['strOK']] = function() {
1461 $(this).closest('.ui-dialog-content').dialog('close').remove();
1464 var $msgbox = PMA_ajaxShowMessage();
1466 $.get(target, url, function(data) {
1467 //in the case of an error, show the error message returned.
1468 if (data.success != undefined && data.success == false) {
1474 open: PMA_verifyColumnsProperties,
1475 buttons : button_options_error
1476 })// end dialog options
1477 //remove the redundant [Back] link in the error message.
1478 .find('fieldset').remove();
1481 var size = getWindowSize();
1486 dialogClass: 'create-table',
1491 position: ['left','top'],
1492 width: size.width-10,
1493 height: size.height-10,
1495 var dialog_id = $(this).attr('id');
1496 $(window).bind('resize.dialog-resizer', function() {
1497 clearTimeout(timeout);
1498 timeout = setTimeout(function() {
1499 var size = getWindowSize();
1500 $('#'+dialog_id).dialog('option', {
1501 width: size.width-10,
1502 height: size.height-10
1507 var $wrapper = $('<div>', {'id': 'content-hide'}).hide();
1508 $('body > *:not(.ui-dialog)').wrapAll($wrapper);
1511 .scrollTop(0) // for Chrome
1512 .closest('.ui-dialog').css({
1517 PMA_verifyColumnsProperties();
1519 // move the Cancel button next to the Save button
1520 var $button_pane = $('.ui-dialog-buttonpane');
1521 var $cancel_button = $button_pane.find('.ui-button');
1522 var $save_button = $('#create_table_form').find("input[name='do_save_data']");
1523 $cancel_button.insertAfter($save_button);
1524 $button_pane.hide();
1527 $(window).unbind('resize.dialog-resizer');
1528 $('#content-hide > *').unwrap();
1531 menuResize(); // somehow need to call it twice to work
1533 buttons: button_options
1534 }); // end dialog options
1536 PMA_convertFootnotesToTooltips($div);
1537 PMA_ajaxRemoveMessage($msgbox);
1543 * Creates a Profiling Chart with jqplot. Used in sql.js
1544 * and in server_status_monitor.js
1546 function PMA_createProfilingChartJqplot(target, data)
1548 return $.jqplot(target, [data],
1551 renderer: $.jqplot.PieRenderer,
1553 showDataLabels: true
1560 // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
1586 * Formats a profiling duration nicely (in us and ms time). Used in server_status.js
1588 * @param integer Number to be formatted, should be in the range of microsecond to second
1589 * @param integer Acuracy, how many numbers right to the comma should be
1590 * @return string The formatted number
1592 function PMA_prettyProfilingNum(num, acc)
1597 acc = Math.pow(10,acc);
1598 if (num * 1000 < 0.1) {
1599 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1600 } else if (num < 0.1) {
1601 num = Math.round(acc * (num * 1000)) / acc + 'm';
1603 num = Math.round(acc * num) / acc;
1611 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1613 * @param string Query to be formatted
1614 * @return string The formatted query
1616 function PMA_SQLPrettyPrint(string)
1618 var mode = CodeMirror.getMode({},"text/x-mysql");
1619 var stream = new CodeMirror.StringStream(string);
1620 var state = mode.startState();
1621 var token, tokens = [];
1623 var tabs = function(cnt) {
1625 for (var i=0; i<4*cnt; i++)
1630 // "root-level" statements
1632 'select': ['select', 'from','on','where','having','limit','order by','group by'],
1633 'update': ['update', 'set','where'],
1634 'insert into': ['insert into', 'values']
1636 // don't put spaces before these tokens
1637 var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1638 // don't put spaces after these tokens
1639 var spaceExceptionsAfter = { '.': true };
1641 // Populate tokens array
1643 while (! stream.eol()) {
1644 stream.start = stream.pos;
1645 token = mode.token(stream, state);
1647 tokens.push([token, stream.current().toLowerCase()]);
1651 var currentStatement = tokens[0][1];
1653 if(! statements[currentStatement]) {
1656 // Holds all currently opened code blocks (statement, function or generic)
1657 var blockStack = [];
1658 // Holds the type of block from last iteration (the current is in blockStack[0])
1660 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1661 var newBlock, endBlock;
1662 // How much to indent in the current line
1663 var indentLevel = 0;
1664 // Holds the "root-level" statements
1665 var statementPart, lastStatementPart = statements[currentStatement][0];
1667 blockStack.unshift('statement');
1669 // Iterate through every token and format accordingly
1670 for (var i = 0; i < tokens.length; i++) {
1671 previousBlock = blockStack[0];
1673 // New block => push to stack
1674 if (tokens[i][1] == '(') {
1675 if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1676 blockStack.unshift(newBlock = 'statement');
1677 } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1678 blockStack.unshift(newBlock = 'function');
1680 blockStack.unshift(newBlock = 'generic');
1686 // Block end => pop from stack
1687 if (tokens[i][1] == ')') {
1688 endBlock = blockStack[0];
1694 // A subquery is starting
1695 if (i > 0 && newBlock == 'statement') {
1697 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1698 currentStatement = tokens[i+1][1];
1703 // A subquery is ending
1704 if (endBlock == 'statement' && indentLevel > 0) {
1705 output += "\n" + tabs(indentLevel);
1709 // One less indentation for statement parts (from, where, order by, etc.) and a newline
1710 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1711 if (statementPart != -1) {
1712 if (i > 0) output += "\n";
1713 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1714 output += "\n" + tabs(indentLevel + 1);
1715 lastStatementPart = tokens[i][1];
1717 // Normal indentatin and spaces for everything else
1719 if (! spaceExceptionsBefore[tokens[i][1]]
1720 && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1721 && output.charAt(output.length -1) != ' ' ) {
1724 if (tokens[i][0] == 'keyword') {
1725 output += tokens[i][1].toUpperCase();
1727 output += tokens[i][1];
1731 // split columns in select and 'update set' clauses, but only inside statements blocks
1732 if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
1733 && tokens[i][1]==',' && blockStack[0] == 'statement') {
1735 output += "\n" + tabs(indentLevel + 1);
1738 // split conditions in where clauses, but only inside statements blocks
1739 if (lastStatementPart == 'where'
1740 && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1742 if (blockStack[0] == 'statement') {
1743 output += "\n" + tabs(indentLevel + 1);
1745 // Todo: Also split and or blocks in newlines & identation++
1746 //if(blockStack[0] == 'generic')
1754 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1755 * return a jQuery object yet and hence cannot be chained
1757 * @param string question
1758 * @param string url URL to be passed to the callbackFn to make
1760 * @param function callbackFn callback to execute after user clicks on OK
1763 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1764 if (PMA_messages['strDoYouReally'] == '') {
1769 * @var button_options Object that stores the options passed to jQueryUI
1772 var button_options = {};
1773 button_options[PMA_messages['strOK']] = function(){
1774 $(this).dialog("close").remove();
1776 if($.isFunction(callbackFn)) {
1777 callbackFn.call(this, url);
1780 button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1782 $('<div id="confirm_dialog"></div>')
1784 .dialog({buttons: button_options});
1788 * jQuery function to sort a table's body after a new row has been appended to it.
1789 * Also fixes the even/odd classes of the table rows at the end.
1791 * @param string text_selector string to select the sortKey's text
1793 * @return jQuery Object for chaining purposes
1795 jQuery.fn.PMA_sort_table = function(text_selector) {
1796 return this.each(function() {
1799 * @var table_body Object referring to the table's <tbody> element
1801 var table_body = $(this);
1803 * @var rows Object referring to the collection of rows in {@link table_body}
1805 var rows = $(this).find('tr').get();
1807 //get the text of the field that we will sort by
1808 $.each(rows, function(index, row) {
1809 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1812 //get the sorted order
1813 rows.sort(function(a,b) {
1814 if(a.sortKey < b.sortKey) {
1817 if(a.sortKey > b.sortKey) {
1823 //pull out each row from the table and then append it according to it's order
1824 $.each(rows, function(index, row) {
1825 $(table_body).append(row);
1829 //Re-check the classes of each row
1830 $(this).find('tr:odd')
1831 .removeClass('even').addClass('odd')
1834 .removeClass('odd').addClass('even');
1839 * jQuery coding for 'Create Table'. Used on db_operations.php,
1840 * db_structure.php and db_tracking.php (i.e., wherever
1841 * libraries/display_create_table.lib.php is used)
1843 * Attach Ajax Event handlers for Create Table
1845 $(document).ready(function() {
1848 * Attach event handler to the submit action of the create table minimal form
1849 * and retrieve the full table form and display it in a dialog
1851 $("#create_table_form_minimal.ajax").live('submit', function(event) {
1852 event.preventDefault();
1854 PMA_prepareForAjaxRequest($form);
1856 /*variables which stores the common attributes*/
1857 var url = $form.serialize();
1858 var action = $form.attr('action');
1859 var $div = $('<div id="create_table_dialog"></div>');
1861 /*Calling to the createTableDialog function*/
1862 PMA_createTableDialog($div, url, action);
1864 // empty table name and number of columns from the minimal form
1865 $form.find('input[name=table],input[name=num_fields]').val('');
1869 * Attach event handler for submission of create table form (save)
1871 * @uses PMA_ajaxShowMessage()
1872 * @uses $.PMA_sort_table()
1875 // .live() must be called after a selector, see http://api.jquery.com/live
1876 $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1877 event.preventDefault();
1880 * @var the_form object referring to the create table form
1882 var $form = $("#create_table_form");
1885 * First validate the form; if there is a problem, avoid submitting it
1887 * checkTableEditForm() needs a pure element and not a jQuery object,
1888 * this is why we pass $form[0] as a parameter (the jQuery object
1889 * is actually an array of DOM elements)
1892 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
1893 // OK, form passed validation step
1894 if ($form.hasClass('ajax')) {
1895 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1896 PMA_prepareForAjaxRequest($form);
1897 //User wants to submit the form
1898 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1899 if(data.success == true) {
1900 $('#properties_message')
1901 .removeClass('error')
1903 PMA_ajaxShowMessage(data.message);
1904 // Only if the create table dialog (distinct panel) exists
1905 if ($("#create_table_dialog").length > 0) {
1906 $("#create_table_dialog").dialog("close").remove();
1910 * @var tables_table Object referring to the <tbody> element that holds the list of tables
1912 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1913 // this is the first table created in this db
1914 if (tables_table.length == 0) {
1915 if (window.parent && window.parent.frame_content) {
1916 window.parent.frame_content.location.reload();
1920 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
1922 var curr_last_row = $(tables_table).find('tr:last');
1924 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
1926 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1928 * @var curr_last_row_index Index of {@link curr_last_row}
1930 var curr_last_row_index = parseFloat(curr_last_row_index_string);
1932 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
1934 var new_last_row_index = curr_last_row_index + 1;
1936 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1938 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1940 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
1942 $(data.new_table_string)
1943 .appendTo(tables_table);
1946 $(tables_table).PMA_sort_table('th');
1948 // Adjust summary row
1952 //Refresh navigation frame as a new table has been added
1953 if (window.parent && window.parent.frame_navigation) {
1954 window.parent.frame_navigation.location.reload();
1957 $('#properties_message')
1960 // scroll to the div containing the error message
1961 $('#properties_message')[0].scrollIntoView();
1964 } // end if ($form.hasClass('ajax')
1967 $form.append('<input type="hidden" name="do_save_data" value="save" />');
1970 } // end if (checkTableEditForm() )
1971 }) // end create table form (save)
1974 * Attach event handler for create table form (add fields)
1976 * @uses PMA_ajaxShowMessage()
1977 * @uses $.PMA_sort_table()
1978 * @uses window.parent.refreshNavigation()
1981 // .live() must be called after a selector, see http://api.jquery.com/live
1982 $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
1983 event.preventDefault();
1986 * @var the_form object referring to the create table form
1988 var $form = $("#create_table_form");
1990 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1991 PMA_prepareForAjaxRequest($form);
1993 //User wants to add more fields to the table
1994 $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
1995 // if 'create_table_dialog' exists
1996 if ($("#create_table_dialog").length > 0) {
1997 $("#create_table_dialog").html(data);
1999 // if 'create_table_div' exists
2000 if ($("#create_table_div").length > 0) {
2001 $("#create_table_div").html(data);
2003 PMA_verifyColumnsProperties();
2004 PMA_ajaxRemoveMessage($msgbox);
2007 }) // end create table form (add fields)
2009 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2012 * jQuery coding for 'Table operations'. Used on tbl_operations.php
2013 * Attach Ajax Event handlers for Table operations
2015 $(document).ready(function() {
2017 *Ajax action for submitting the "Alter table order by"
2019 $("#alterTableOrderby.ajax").live('submit', function(event) {
2020 event.preventDefault();
2021 var $form = $(this);
2023 PMA_prepareForAjaxRequest($form);
2024 /*variables which stores the common attributes*/
2025 $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2026 if ($("#sqlqueryresults").length != 0) {
2027 $("#sqlqueryresults").remove();
2029 if ($("#result_query").length != 0) {
2030 $("#result_query").remove();
2032 if (data.success == true) {
2033 PMA_ajaxShowMessage(data.message);
2034 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2035 $("#sqlqueryresults").html(data.sql_query);
2036 $("#result_query .notice").remove();
2037 $("#result_query").prepend((data.message));
2039 var $temp_div = $("<div id='temp_div'></div>")
2040 $temp_div.html(data.error);
2041 var $error = $temp_div.find("code").addClass("error");
2042 PMA_ajaxShowMessage($error, false);
2045 });//end of alterTableOrderby ajax submit
2048 *Ajax action for submitting the "Copy table"
2050 $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2051 event.preventDefault();
2052 var $form = $("#copyTable");
2053 if($form.find("input[name='switch_to_new']").attr('checked')) {
2054 $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2055 $form.removeClass('ajax');
2056 $form.find("#ajax_request_hidden").remove();
2059 PMA_prepareForAjaxRequest($form);
2060 /*variables which stores the common attributes*/
2061 $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2062 if ($("#sqlqueryresults").length != 0) {
2063 $("#sqlqueryresults").remove();
2065 if ($("#result_query").length != 0) {
2066 $("#result_query").remove();
2068 if (data.success == true) {
2069 PMA_ajaxShowMessage(data.message);
2070 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2071 $("#sqlqueryresults").html(data.sql_query);
2072 $("#result_query .notice").remove();
2073 $("#result_query").prepend((data.message));
2074 $("#copyTable").find("select[name='target_db'] option").filterByValue(data.db).attr('selected', 'selected');
2076 //Refresh navigation frame when the table is coppied
2077 if (window.parent && window.parent.frame_navigation) {
2078 window.parent.frame_navigation.location.reload();
2081 var $temp_div = $("<div id='temp_div'></div>");
2082 $temp_div.html(data.error);
2083 var $error = $temp_div.find("code").addClass("error");
2084 PMA_ajaxShowMessage($error, false);
2088 });//end of copyTable ajax submit
2091 *Ajax events for actions in the "Table maintenance"
2093 $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2094 event.preventDefault();
2095 var $link = $(this);
2096 var href = $link.attr("href");
2097 href = href.split('?');
2098 if ($("#sqlqueryresults").length != 0) {
2099 $("#sqlqueryresults").remove();
2101 if ($("#result_query").length != 0) {
2102 $("#result_query").remove();
2104 //variables which stores the common attributes
2105 $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2106 if (data.success == undefined) {
2107 var $temp_div = $("<div id='temp_div'></div>");
2108 $temp_div.html(data);
2109 var $success = $temp_div.find("#result_query .success");
2110 PMA_ajaxShowMessage($success);
2111 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2112 $("#sqlqueryresults").html(data);
2114 $("#sqlqueryresults").children("fieldset").remove();
2115 } else if (data.success == true ) {
2116 PMA_ajaxShowMessage(data.message);
2117 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2118 $("#sqlqueryresults").html(data.sql_query);
2120 var $temp_div = $("<div id='temp_div'></div>");
2121 $temp_div.html(data.error);
2122 var $error = $temp_div.find("code").addClass("error");
2123 PMA_ajaxShowMessage($error, false);
2126 });//end of table maintanance ajax click
2128 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2132 * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2133 * as it was also required on db_create.php
2135 * @uses $.PMA_confirm()
2136 * @uses PMA_ajaxShowMessage()
2137 * @uses window.parent.refreshNavigation()
2138 * @uses window.parent.refreshMain()
2139 * @see $cfg['AjaxEnable']
2141 $(document).ready(function() {
2142 $("#drop_db_anchor").live('click', function(event) {
2143 event.preventDefault();
2145 //context is top.frame_content, so we need to use window.parent.db to access the db var
2147 * @var question String containing the question to be asked for confirmation
2149 var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
2151 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2153 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2154 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2155 //Database deleted successfully, refresh both the frames
2156 window.parent.refreshNavigation();
2157 window.parent.refreshMain();
2159 }); // end $.PMA_confirm()
2160 }); //end of Drop Database Ajax action
2161 }) // end of $(document).ready() for Drop Database
2164 * Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
2165 * display_create_database.lib.php is used, ie main.php and server_databases.php
2167 * @uses PMA_ajaxShowMessage()
2168 * @see $cfg['AjaxEnable']
2170 $(document).ready(function() {
2172 $('#create_database_form.ajax').live('submit', function(event) {
2173 event.preventDefault();
2177 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2178 PMA_prepareForAjaxRequest($form);
2180 $.post($form.attr('action'), $form.serialize(), function(data) {
2181 if(data.success == true) {
2182 PMA_ajaxShowMessage(data.message);
2184 //Append database's row to table
2185 $("#tabledatabases")
2187 .append(data.new_db_string)
2188 .PMA_sort_table('.name')
2189 .find('#db_summary_row')
2190 .appendTo('#tabledatabases tbody')
2191 .removeClass('odd even');
2193 var $databases_count_object = $('#databases_count');
2194 var databases_count = parseInt($databases_count_object.text());
2195 $databases_count_object.text(++databases_count);
2196 //Refresh navigation frame as a new database has been added
2197 if (window.parent && window.parent.frame_navigation) {
2198 window.parent.frame_navigation.location.reload();
2202 PMA_ajaxShowMessage(data.error, false);
2205 }) // end $().live()
2206 }) // end $(document).ready() for Create Database
2209 * Validates the password field in a form
2211 * @see PMA_messages['strPasswordEmpty']
2212 * @see PMA_messages['strPasswordNotSame']
2213 * @param object the form
2214 * @return boolean whether the field value is valid or not
2216 function checkPassword(the_form)
2218 // Did the user select 'no password'?
2219 if (typeof(the_form.elements['nopass']) != 'undefined'
2220 && the_form.elements['nopass'][0].checked) {
2222 } else if (typeof(the_form.elements['pred_password']) != 'undefined'
2223 && (the_form.elements['pred_password'].value == 'none'
2224 || the_form.elements['pred_password'].value == 'keep')) {
2228 var password = the_form.elements['pma_pw'];
2229 var password_repeat = the_form.elements['pma_pw2'];
2230 var alert_msg = false;
2232 if (password.value == '') {
2233 alert_msg = PMA_messages['strPasswordEmpty'];
2234 } else if (password.value != password_repeat.value) {
2235 alert_msg = PMA_messages['strPasswordNotSame'];
2240 password.value = '';
2241 password_repeat.value = '';
2247 } // end of the 'checkPassword()' function
2250 * Attach Ajax event handlers for 'Change Password' on main.php
2252 $(document).ready(function() {
2255 * Attach Ajax event handler on the change password anchor
2256 * @see $cfg['AjaxEnable']
2258 $('#change_password_anchor.dialog_active').live('click',function(event) {
2259 event.preventDefault();
2262 $('#change_password_anchor.ajax').live('click', function(event) {
2263 event.preventDefault();
2264 $(this).removeClass('ajax').addClass('dialog_active');
2266 * @var button_options Object containing options to be passed to jQueryUI's dialog
2268 var button_options = {};
2269 button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2270 $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2271 $('<div id="change_password_dialog"></div>')
2273 title: PMA_messages['strChangePassword'],
2275 close: function(ev,ui) {$(this).remove();},
2276 buttons : button_options,
2277 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2280 displayPasswordGenerateButton();
2282 $('#change_password_form').bind('submit', function (e) {
2285 .closest('.ui-dialog')
2286 .find('.ui-dialog-buttonpane .ui-button')
2291 }) // end handler for change password anchor
2294 * Attach Ajax event handler for Change Password form submission
2296 * @uses PMA_ajaxShowMessage()
2297 * @see $cfg['AjaxEnable']
2299 $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2300 event.preventDefault();
2303 * @var the_form Object referring to the change password form
2305 var the_form = $("#change_password_form");
2307 if (! checkPassword(the_form[0])) {
2312 * @var this_value String containing the value of the submit button.
2313 * Need to append this for the change password form on Server Privileges
2316 var this_value = $(this).val();
2318 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2319 $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2321 $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2322 if(data.success == true) {
2323 $("#floating_menubar").after(data.sql_query);
2324 $("#change_password_dialog").hide().remove();
2325 $("#edit_user_dialog").dialog("close").remove();
2326 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2327 PMA_ajaxRemoveMessage($msgbox);
2330 PMA_ajaxShowMessage(data.error, false);
2333 }) // end handler for Change Password form submission
2334 }) // end $(document).ready() for Change Password
2337 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2338 * the page loads and when the selected data type changes
2340 $(document).ready(function() {
2341 // is called here for normal page loads and also when opening
2342 // the Create table dialog
2343 PMA_verifyColumnsProperties();
2345 // needs live() to work also in the Create Table dialog
2346 $("select[class='column_type']").live('change', function() {
2347 PMA_showNoticeForEnum($(this));
2349 $(".default_type").live('change', function() {
2350 PMA_hideShowDefaultValue($(this));
2354 function PMA_verifyColumnsProperties()
2356 $("select[class='column_type']").each(function() {
2357 PMA_showNoticeForEnum($(this));
2359 $(".default_type").each(function() {
2360 PMA_hideShowDefaultValue($(this));
2365 * Hides/shows the default value input field, depending on the default type
2367 function PMA_hideShowDefaultValue($default_type)
2369 if ($default_type.val() == 'USER_DEFINED') {
2370 $default_type.siblings('.default_value').show().focus();
2372 $default_type.siblings('.default_value').hide();
2377 * @var $enum_editor_dialog An object that points to the jQuery
2378 * dialog of the ENUM/SET editor
2380 var $enum_editor_dialog = null;
2382 * Opens the ENUM/SET editor and controls its functions
2384 $(document).ready(function() {
2385 $("a.open_enum_editor").live('click', function() {
2386 // Get the name of the column that is being edited
2387 var colname = $(this).closest('tr').find('input:first').val();
2388 // And use it to make up a title for the page
2389 if (colname.length < 1) {
2390 var title = PMA_messages['enum_newColumnVals'];
2392 var title = PMA_messages['enum_columnVals'].replace(
2394 '"' + decodeURIComponent(colname) + '"'
2397 // Get the values as a string
2398 var inputstring = $(this)
2402 // Escape html entities
2403 inputstring = $('<div/>')
2406 // Parse the values, escaping quotes and
2407 // slashes on the fly, into an array
2409 // There is a PHP port of the below parser in enum_editor.php
2410 // If you are fixing something here, you need to also update the PHP port.
2412 var in_string = false;
2413 var curr, next, buffer = '';
2414 for (var i=0; i<inputstring.length; i++) {
2415 curr = inputstring.charAt(i);
2416 next = i == inputstring.length ? '' : inputstring.charAt(i+1);
2417 if (! in_string && curr == "'") {
2419 } else if (in_string && curr == "\\" && next == "\\") {
2422 } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
2425 } else if (in_string && curr == "'") {
2427 values.push(buffer);
2429 } else if (in_string) {
2433 if (buffer.length > 0) {
2434 // The leftovers in the buffer are the last value (if any)
2435 values.push(buffer);
2438 // If there are no values, maybe the user is about to make a
2439 // new list so we add a few for him/her to get started with.
2440 if (values.length == 0) {
2441 values.push('','','','');
2443 // Add the parsed values to the editor
2444 var drop_icon = PMA_getImage('b_drop.png');
2445 for (var i=0; i<values.length; i++) {
2446 fields += "<tr><td>"
2447 + "<input type='text' value='" + values[i] + "'/>"
2448 + "</td><td class='drop'>"
2453 * @var dialog HTML code for the ENUM/SET dialog
2455 var dialog = "<div id='enum_editor'>"
2457 + "<legend>" + title + "</legend>"
2458 + "<p>" + PMA_getImage('s_notice.png')
2459 + PMA_messages['enum_hint'] + "</p>"
2460 + "<table class='values'>" + fields + "</table>"
2461 + "</fieldset><fieldset class='tblFooters'>"
2462 + "<table class='add'><tr><td>"
2463 + "<div class='slider'></div>"
2465 + "<form><div><input type='submit' class='add_value' value='"
2466 + PMA_messages['enum_addValue'].replace(/%d/, 1)
2467 + "'/></div></form>"
2468 + "</td></tr></table>"
2469 + "<input type='hidden' value='" // So we know which column's data is being edited
2470 + $(this).closest('td').find("input").attr("id")
2475 * @var Defines functions to be called when the buttons in
2476 * the buttonOptions jQuery dialog bar are pressed
2478 var buttonOptions = {};
2479 buttonOptions[PMA_messages['strGo']] = function () {
2480 // When the submit button is clicked,
2481 // put the data back into the original form
2482 var value_array = new Array();
2483 $(this).find(".values input").each(function(index, elm) {
2484 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
2485 value_array.push("'" + val + "'");
2487 // get the Length/Values text field where this value belongs
2488 var values_id = $(this).find("input[type='hidden']").attr("value");
2489 $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2490 $(this).dialog("close");
2492 buttonOptions[PMA_messages['strClose']] = function () {
2493 $(this).dialog("close");
2496 var width = parseInt(
2497 (parseInt($('html').css('font-size'), 10)/13)*340,
2503 $enum_editor_dialog = $(dialog).dialog({
2506 title: PMA_messages['enum_editor'],
2507 buttons: buttonOptions,
2509 // Focus the "Go" button after opening the dialog
2510 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
2516 // slider for choosing how many fields to add
2517 $enum_editor_dialog.find(".slider").slider({
2523 slide: function( event, ui ) {
2524 $(this).closest('table').find('input[type=submit]').val(
2525 PMA_messages['enum_addValue'].replace(/%d/, ui.value)
2529 // Focus the slider, otherwise it looks nearly transparent
2530 $('.ui-slider-handle').addClass('ui-state-focus');
2534 // When "add a new value" is clicked, append an empty text field
2535 $("input.add_value").live('click', function(e) {
2537 var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
2538 while (num_new_rows--) {
2539 $enum_editor_dialog.find('.values')
2541 "<tr style='display: none;'><td>"
2542 + "<input type='text' />"
2543 + "</td><td class='drop'>"
2544 + PMA_getImage('b_drop.png')
2552 // Removes the specified row from the enum editor
2553 $("#enum_editor td.drop").live('click', function() {
2554 $(this).closest('tr').hide('fast', function () {
2560 $(document).ready(function(){
2561 PMA_convertFootnotesToTooltips();
2565 * Ensures indexes names are valid according to their type and, for a primary
2566 * key, lock index name to 'PRIMARY'
2567 * @param string form_id Variable which parses the form name as
2569 * @return boolean false if there is no index form, true else
2571 function checkIndexName(form_id)
2573 if ($("#"+form_id).length == 0) {
2577 // Gets the elements pointers
2578 var $the_idx_name = $("#input_index_name");
2579 var $the_idx_type = $("#select_index_type");
2581 // Index is a primary key
2582 if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2583 $the_idx_name.attr("value", 'PRIMARY');
2584 $the_idx_name.attr("disabled", true);
2589 if ($the_idx_name.attr("value") == 'PRIMARY') {
2590 $the_idx_name.attr("value", '');
2592 $the_idx_name.attr("disabled", false);
2596 } // end of the 'checkIndexName()' function
2599 * function to convert the footnotes to tooltips
2601 * @param jquery-Object $div a div jquery object which specifies the
2602 * domain for searching footnootes. If we
2603 * ommit this parameter the function searches
2604 * the footnotes in the whole body
2606 function PMA_convertFootnotesToTooltips($div)
2608 // Hide the footnotes from the footer (which are displayed for
2609 // JavaScript-disabled browsers) since the tooltip is sufficient
2611 if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2615 $footnotes = $div.find(".footnotes");
2618 $footnotes.find('span').each(function() {
2619 $(this).children("sup").remove();
2621 // The border and padding must be removed otherwise a thin yellow box remains visible
2622 $footnotes.css("border", "none");
2623 $footnotes.css("padding", "0px");
2625 // Replace the superscripts with the help icon
2626 $div.find("sup.footnotemarker").hide();
2627 $div.find("img.footnotemarker").show();
2629 $div.find("img.footnotemarker").each(function() {
2630 var img_class = $(this).attr("class");
2631 /** img contains two classes, as example "footnotemarker footnote_1".
2632 * We split it by second class and take it for the id of span
2634 img_class = img_class.split(" ");
2635 for (i = 0; i < img_class.length; i++) {
2636 if (img_class[i].split("_")[0] == "footnote") {
2637 var span_id = img_class[i].split("_")[1];
2641 * Now we get the #id of the span with span_id variable. As an example if we
2642 * initially get the img class as "footnotemarker footnote_2", now we get
2643 * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2645 var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2647 content: tooltip_text,
2649 hide: { delay: 1000 },
2650 style: { background: '#ffffcc' }
2656 * This function handles the resizing of the content frame
2657 * and adjusts the top menu according to the new size of the frame
2659 function menuResize()
2661 var $cnt = $('#topmenu');
2662 var wmax = $cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2663 var $submenu = $cnt.find('.submenu');
2664 var submenu_w = $submenu.outerWidth(true);
2665 var $submenu_ul = $submenu.find('ul');
2666 var $li = $cnt.find('> li');
2667 var $li2 = $submenu_ul.find('li');
2668 var more_shown = $li2.length > 0;
2670 // Calculate the total width used by all the shown tabs
2671 var total_len = more_shown ? submenu_w : 0;
2672 for (var i = 0; i < $li.length-1; i++) {
2673 total_len += $($li[i]).outerWidth(true);
2676 // Now hide menu elements that don't fit into the menubar
2677 var i = $li.length-1;
2678 var hidden = false; // Whether we have hidden any tabs
2679 while (total_len >= wmax && --i >= 0) { // Process the tabs backwards
2682 var el_width = el.outerWidth(true);
2683 el.data('width', el_width);
2685 total_len -= el_width;
2686 el.prependTo($submenu_ul);
2687 total_len += submenu_w;
2690 total_len -= el_width;
2691 el.prependTo($submenu_ul);
2695 // If we didn't hide any tabs, then there might be some space to show some
2697 // Show menu elements that do fit into the menubar
2698 for (var i = 0; i < $li2.length; i++) {
2699 total_len += $($li2[i]).data('width');
2700 // item fits or (it is the last item
2701 // and it would fit if More got removed)
2702 if (total_len < wmax
2703 || (i == $li2.length - 1 && total_len - submenu_w < wmax)
2705 $($li2[i]).insertBefore($submenu);
2712 // Show/hide the "More" tab as needed
2713 if ($submenu_ul.find('li').length > 0) {
2714 $submenu.addClass('shown');
2716 $submenu.removeClass('shown');
2719 if ($cnt.find('> li').length == 1) {
2720 // If there is only the "More" tab left, then we need
2721 // to align the submenu to the left edge of the tab
2722 $submenu_ul.removeClass().addClass('only');
2724 // Otherwise we align the submenu to the right edge of the tab
2725 $submenu_ul.removeClass().addClass('notonly');
2728 if ($submenu.find('.tabactive').length) {
2729 $submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2731 $submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2736 var topmenu = $('#topmenu');
2737 if (topmenu.length == 0) {
2740 // create submenu container
2741 var link = $('<a />', {href: '#', 'class': 'tab'})
2742 .text(PMA_messages['strMore'])
2743 .click(function(e) {
2746 var img = topmenu.find('li:first-child img');
2748 $(PMA_getImage('b_more.png').toString()).prependTo(link);
2750 var submenu = $('<li />', {'class': 'submenu'})
2752 .append($('<ul />'))
2753 .mouseenter(function() {
2754 if ($(this).find('ul .tabactive').length == 0) {
2755 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2758 .mouseleave(function() {
2759 if ($(this).find('ul .tabactive').length == 0) {
2760 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2763 topmenu.append(submenu);
2765 // populate submenu and register resize event
2767 $(window).resize(menuResize);
2771 * Get the row number from the classlist (for example, row_1)
2773 function PMA_getRowNumber(classlist)
2775 return parseInt(classlist.split(/\s+row_/)[1]);
2779 * Changes status of slider
2781 function PMA_set_status_label($element)
2783 var text = $element.css('display') == 'none'
2786 $element.closest('.slide-wrapper').prev().find('span').text(text);
2790 * Initializes slider effect.
2792 function PMA_init_slider()
2794 $('.pma_auto_slider').each(function() {
2795 var $this = $(this);
2797 if ($this.hasClass('slider_init_done')) {
2800 $this.addClass('slider_init_done');
2802 var $wrapper = $('<div>', {'class': 'slide-wrapper'});
2803 $wrapper.toggle($this.is(':visible'));
2804 $('<a>', {href: '#'+this.id})
2806 .prepend($('<span>'))
2807 .insertBefore($this)
2809 var $wrapper = $this.closest('.slide-wrapper');
2810 var visible = $this.is(':visible');
2814 $this[visible ? 'hide' : 'show']('blind', function() {
2815 $wrapper.toggle(!visible);
2816 PMA_set_status_label($this);
2820 $this.wrap($wrapper);
2821 PMA_set_status_label($this);
2826 * var toggleButton This is a function that creates a toggle
2827 * sliding button given a jQuery reference
2828 * to the correct DOM element
2830 var toggleButton = function ($obj) {
2831 // In rtl mode the toggle switch is flipped horizontally
2832 // so we need to take that into account
2833 if ($('.text_direction', $obj).text() == 'ltr') {
2834 var right = 'right';
2839 * var h Height of the button, used to scale the
2840 * background image and position the layers
2842 var h = $obj.height();
2843 $('img', $obj).height(h);
2844 $('table', $obj).css('bottom', h-1);
2846 * var on Width of the "ON" part of the toggle switch
2847 * var off Width of the "OFF" part of the toggle switch
2849 var on = $('.toggleOn', $obj).width();
2850 var off = $('.toggleOff', $obj).width();
2851 // Make the "ON" and "OFF" parts of the switch the same size
2852 // + 2 pixels to avoid overflowed
2853 $('.toggleOn > div', $obj).width(Math.max(on, off) + 2);
2854 $('.toggleOff > div', $obj).width(Math.max(on, off) + 2);
2856 * var w Width of the central part of the switch
2858 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
2859 // Resize the central part of the switch on the top
2860 // layer to match the background
2861 $('table td:nth-child(2) > div', $obj).width(w);
2863 * var imgw Width of the background image
2864 * var tblw Width of the foreground layer
2865 * var offset By how many pixels to move the background
2866 * image, so that it matches the top layer
2868 var imgw = $('img', $obj).width();
2869 var tblw = $('table', $obj).width();
2870 var offset = parseInt(((imgw - tblw) / 2), 10);
2871 // Move the background to match the layout of the top layer
2872 $obj.find('img').css(right, offset);
2874 * var offw Outer width of the "ON" part of the toggle switch
2875 * var btnw Outer width of the central part of the switch
2877 var offw = $('.toggleOff', $obj).outerWidth();
2878 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
2879 // Resize the main div so that exactly one side of
2880 // the switch plus the central part fit into it.
2881 $obj.width(offw + btnw + 2);
2883 * var move How many pixels to move the
2884 * switch by when toggling
2886 var move = $('.toggleOff', $obj).outerWidth();
2887 // If the switch is initialized to the
2888 // OFF state we need to move it now.
2889 if ($('.container', $obj).hasClass('off')) {
2890 if (right == 'right') {
2891 $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
2893 $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
2896 // Attach an 'onclick' event to the switch
2897 $('.container', $obj).click(function () {
2898 if ($(this).hasClass('isActive')) {
2901 $(this).addClass('isActive');
2903 var $msg = PMA_ajaxShowMessage();
2904 var $container = $(this);
2905 var callback = $('.callback', this).text();
2906 // Perform the actual toggle
2907 if ($(this).hasClass('on')) {
2908 if (right == 'right') {
2909 var operator = '-=';
2911 var operator = '+=';
2913 var url = $(this).find('.toggleOff > span').text();
2914 var removeClass = 'on';
2915 var addClass = 'off';
2917 if (right == 'right') {
2918 var operator = '+=';
2920 var operator = '-=';
2922 var url = $(this).find('.toggleOn > span').text();
2923 var removeClass = 'off';
2924 var addClass = 'on';
2926 $.post(url, {'ajax_request': true}, function(data) {
2927 if(data.success == true) {
2928 PMA_ajaxRemoveMessage($msg);
2930 .removeClass(removeClass)
2932 .animate({'left': operator + move + 'px'}, function () {
2933 $container.removeClass('isActive');
2937 PMA_ajaxShowMessage(data.error, false);
2938 $container.removeClass('isActive');
2945 * Initialise all toggle buttons
2947 $(window).load(function () {
2948 $('.toggleAjax').each(function () {
2951 .find('.toggleButton')
2952 toggleButton($(this));
2959 $(document).ready(function() {
2960 $('.vpointer').live('hover',
2963 var $this_td = $(this);
2964 var row_num = PMA_getRowNumber($this_td.attr('class'));
2965 // for all td of the same vertical row, toggle hover
2966 $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2969 }) // end of $(document).ready() for vertical pointer
2971 $(document).ready(function() {
2975 $('.vmarker').live('click', function(e) {
2976 // do not trigger when clicked on anchor
2977 if ($(e.target).is('a, img, a *')) {
2981 var $this_td = $(this);
2982 var row_num = PMA_getRowNumber($this_td.attr('class'));
2984 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
2986 var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
2987 if ($checkbox.length) {
2988 // checkbox in a row, add or remove class depending on checkbox state
2989 var checked = $checkbox.attr('checked');
2990 if (!$(e.target).is(':checkbox, label')) {
2992 $checkbox.attr('checked', checked);
2994 // for all td of the same vertical row, toggle the marked class
2996 $('.vmarker').filter('.row_' + row_num).addClass('marked');
2998 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
3001 // normaln data table, just toggle class
3002 $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
3007 * Reveal visual builder anchor
3010 $('#visual_builder_anchor').show();
3013 * Page selector in db Structure (non-AJAX)
3015 $('#tableslistcontainer').find('#pageselector').live('change', function() {
3016 $(this).parent("form").submit();
3020 * Page selector in navi panel (non-AJAX)
3022 $('#navidbpageselector').find('#pageselector').live('change', function() {
3023 $(this).parent("form").submit();
3027 * Page selector in browse_foreigners windows (non-AJAX)
3029 $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3030 $(this).closest("form").submit();
3034 * Load version information asynchronously.
3036 if ($('.jsversioncheck').length > 0) {
3037 $.getJSON('http://www.phpmyadmin.net/home_page/version.json', {}, PMA_current_version);
3046 * Enables the text generated by PMA_linkOrButton() to be clickable
3048 $('a[class~="formLinkSubmit"]').live('click',function(e) {
3050 if($(this).attr('href').indexOf('=') != -1) {
3051 var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3052 $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3054 $(this).parents('form').submit();
3058 $('#update_recent_tables').ready(function() {
3059 if (window.parent.frame_navigation != undefined
3060 && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3062 window.parent.frame_navigation.PMA_reloadRecentTable();
3066 }) // end of $(document).ready()
3069 * Creates a message inside an object with a sliding effect
3071 * @param msg A string containing the text to display
3072 * @param $obj a jQuery object containing the reference
3073 * to the element where to put the message
3074 * This is optional, if no element is
3075 * provided, one will be created below the
3076 * navigation links at the top of the page
3078 * @return bool True on success, false on failure
3080 function PMA_slidingMessage(msg, $obj)
3082 if (msg == undefined || msg.length == 0) {
3083 // Don't show an empty message
3086 if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3087 // If the second argument was not supplied,
3088 // we might have to create a new DOM node.
3089 if ($('#PMA_slidingMessage').length == 0) {
3090 $('#floating_menubar')
3091 .after('<span id="PMA_slidingMessage" '
3092 + 'style="display: inline-block;"></span>');
3094 $obj = $('#PMA_slidingMessage');
3096 if ($obj.has('div').length > 0) {
3097 // If there already is a message inside the
3098 // target object, we must get rid of it
3102 .fadeOut(function () {
3107 .append('<div style="display: none;">' + msg + '</div>')
3109 height: $obj.find('div').first().height()
3116 // Object does not already have a message
3117 // inside it, so we simply slide it down
3120 .html('<div style="display: none;">' + msg + '</div>')
3132 // Set the height of the parent
3133 // to the height of the child
3144 } // end PMA_slidingMessage()
3147 * Attach Ajax event handlers for Drop Table.
3149 * @uses $.PMA_confirm()
3150 * @uses PMA_ajaxShowMessage()
3151 * @uses window.parent.refreshNavigation()
3152 * @uses window.parent.refreshMain()
3153 * @see $cfg['AjaxEnable']
3155 $(document).ready(function() {
3156 $("#drop_tbl_anchor").live('click', function(event) {
3157 event.preventDefault();
3159 //context is top.frame_content, so we need to use window.parent.table to access the table var
3161 * @var question String containing the question to be asked for confirmation
3163 var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + escapeHtml(window.parent.table);
3165 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3167 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3168 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3169 //Database deleted successfully, refresh both the frames
3170 window.parent.refreshNavigation();
3171 window.parent.refreshMain();
3173 }); // end $.PMA_confirm()
3174 }); //end of Drop Table Ajax action
3175 }) // end of $(document).ready() for Drop Table
3178 * Attach Ajax event handlers for Truncate Table.
3180 * @uses $.PMA_confirm()
3181 * @uses PMA_ajaxShowMessage()
3182 * @uses window.parent.refreshNavigation()
3183 * @uses window.parent.refreshMain()
3184 * @see $cfg['AjaxEnable']
3186 $(document).ready(function() {
3187 $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3188 event.preventDefault();
3190 //context is top.frame_content, so we need to use window.parent.table to access the table var
3192 * @var question String containing the question to be asked for confirmation
3194 var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + escapeHtml(window.parent.table);
3196 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3198 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3199 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3200 if ($("#sqlqueryresults").length != 0) {
3201 $("#sqlqueryresults").remove();
3203 if ($("#result_query").length != 0) {
3204 $("#result_query").remove();
3206 if (data.success == true) {
3207 PMA_ajaxShowMessage(data.message);
3208 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
3209 $("#sqlqueryresults").html(data.sql_query);
3211 var $temp_div = $("<div id='temp_div'></div>")
3212 $temp_div.html(data.error);
3213 var $error = $temp_div.find("code").addClass("error");
3214 PMA_ajaxShowMessage($error, false);
3217 }); // end $.PMA_confirm()
3218 }); //end of Truncate Table Ajax action
3219 }) // end of $(document).ready() for Truncate Table
3222 * Attach CodeMirror2 editor to SQL edit area.
3224 $(document).ready(function() {
3225 var elm = $('#sqlquery');
3226 if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3227 codemirror_editor = CodeMirror.fromTextArea(elm[0], {
3229 matchBrackets: true,
3231 mode: "text/x-mysql",
3238 * jQuery plugin to cancel selection in HTML code.
3241 $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3242 var prevent = (p == null) ? true : p;
3244 return this.each(function () {
3245 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3248 else if ($.browser.mozilla) {
3249 $(this).css('MozUserSelect', 'none');
3250 $('body').trigger('focus');
3251 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3254 else $(this).attr('unselectable', 'on');
3257 return this.each(function () {
3258 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3259 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3260 else if ($.browser.opera) $(this).unbind('mousedown');
3261 else $(this).removeAttr('unselectable', 'on');
3268 * jQuery plugin to correctly filter input fields by value, needed
3269 * because some nasty values may break selector syntax
3272 $.fn.filterByValue = function (value) {
3273 return this.filter(function () {
3274 return $(this).val() === value
3280 * Create default PMA tooltip for the element specified. The default appearance
3281 * can be overriden by specifying optional "options" parameter (see qTip options).
3283 function PMA_createqTip($elements, content, options)
3285 if ($('#no_hint').length > 0) {
3293 tooltip: 'normalqTip',
3294 content: 'normalqTipContent'
3300 corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3301 adjust: { x: 10, y: 20 }
3318 $elements.qtip($.extend(true, o, options));
3322 * Return value of a cell in a table.
3324 function PMA_getCellValue(td) {
3325 if ($(td).is('.null')) {
3327 } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3328 return $(td).data('original_data');
3330 return $(td).text();
3334 /* Loads a js file, an array may be passed as well */
3335 loadJavascript=function(file) {
3336 if($.isArray(file)) {
3337 for(var i=0; i<file.length; i++) {
3338 $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3341 $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3345 $(document).ready(function() {
3349 $('a.themeselect').live('click', function(e) {
3353 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3359 * Automatic form submission on change.
3361 $('.autosubmit').change(function(e) {
3362 e.target.form.submit();
3368 $('.take_theme').click(function(e) {
3369 var what = this.name;
3370 if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3371 window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3372 window.opener.document.forms['setTheme'].submit();
3381 * Clear text selection
3383 function PMA_clearSelection() {
3384 if(document.selection && document.selection.empty) {
3385 document.selection.empty();
3386 } else if(window.getSelection) {
3387 var sel = window.getSelection();
3388 if(sel.empty) sel.empty();
3389 if(sel.removeAllRanges) sel.removeAllRanges();
3396 function escapeHtml(unsafe) {
3398 .replace(/&/g, "&")
3399 .replace(/</g, "<")
3400 .replace(/>/g, ">")
3401 .replace(/"/g, """)
3402 .replace(/'/g, "'");
3408 function printPage()
3410 // Do print the page
3411 if (typeof(window.print) != 'undefined') {
3416 $(document).ready(function() {
3417 $('input#print').click(printPage);
3421 * Makes the breadcrumbs and the menu bar float at the top of the viewport
3423 $(document).ready(function () {
3424 if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length == 0) {
3425 $("#floating_menubar")
3427 'position': 'fixed',
3433 .append($('#serverinfo'))
3434 .append($('#topmenucontainer'));
3437 $('#floating_menubar').outerHeight(true)
3443 * Toggles row colors of a set of 'tr' elements starting from a given element
3445 * @param $start Starting element
3447 function toggleRowColors($start)
3449 for (var $curr_row = $start; $curr_row.length > 0; $curr_row = $curr_row.next()) {
3450 if ($curr_row.hasClass('odd')) {
3451 $curr_row.removeClass('odd').addClass('even');
3452 } else if ($curr_row.hasClass('even')) {
3453 $curr_row.removeClass('even').addClass('odd');