1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * general function, usally 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 * Add a hidden field to the form to indicate that this will be an
34 * Ajax request (only if this hidden field does not exist)
36 * @param object the form
38 function PMA_prepareForAjaxRequest($form)
40 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
41 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
46 * Generate a new password and copy it to the password input areas
48 * @param object the form that holds the password fields
50 * @return boolean always true
52 function suggestPassword(passwd_form)
54 // restrict the password to just letters and numbers to avoid problems:
55 // "editors and viewers regard the password as multiple words and
56 // things like double click no longer work"
57 var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
58 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
59 var passwd = passwd_form.generated_pw;
62 for ( i = 0; i < passwordlength; i++ ) {
63 passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
65 passwd_form.text_pma_pw.value = passwd.value;
66 passwd_form.text_pma_pw2.value = passwd.value;
71 * Version string to integer conversion.
73 function parseVersionString (str)
75 if (typeof(str) != 'string') { return false; }
77 // Parse possible alpha/beta/rc/
78 var state = str.split('-');
79 if (state.length >= 2) {
80 if (state[1].substr(0, 2) == 'rc') {
81 add = - 20 - parseInt(state[1].substr(2));
82 } else if (state[1].substr(0, 4) == 'beta') {
83 add = - 40 - parseInt(state[1].substr(4));
84 } else if (state[1].substr(0, 5) == 'alpha') {
85 add = - 60 - parseInt(state[1].substr(5));
86 } else if (state[1].substr(0, 3) == 'dev') {
87 /* We don't handle dev, it's git snapshot */
92 var x = str.split('.');
93 // Use 0 for non existing parts
94 var maj = parseInt(x[0]) || 0;
95 var min = parseInt(x[1]) || 0;
96 var pat = parseInt(x[2]) || 0;
97 var hotfix = parseInt(x[3]) || 0;
98 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
102 * Indicates current available version on main page.
104 function PMA_current_version()
106 var current = parseVersionString(pmaversion);
107 var latest = parseVersionString(PMA_latest_version);
108 var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
109 if (latest > current) {
110 var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
111 if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
112 /* Security update */
117 $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
119 if (latest == current) {
120 version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
122 $('#li_pma_version').append(version_information_message);
126 * for libraries/display_change_password.lib.php
127 * libraries/user_password.php
131 function displayPasswordGenerateButton()
133 $('#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>');
134 $('#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>');
138 * Adds a date/time picker to an element
140 * @param object $this_element a jQuery object pointing to the element
142 function PMA_addDatepicker($this_element, options)
144 var showTimeOption = false;
145 if ($this_element.is('.datetimefield')) {
146 showTimeOption = true;
149 var defaultOptions = {
151 buttonImage: themeCalendarImage, // defined in js/messages.php
152 buttonImageOnly: true,
156 showTimepicker: showTimeOption,
157 showButtonPanel: false,
158 dateFormat: 'yy-mm-dd', // yy means year with four digits
159 timeFormat: 'hh:mm:ss',
160 altFieldTimeOnly: false,
162 beforeShow: function(input, inst) {
163 // Remember that we came from the datepicker; this is used
164 // in tbl_change.js by verificationsAfterFieldChange()
165 $this_element.data('comes_from', 'datepicker');
167 // Fix wrong timepicker z-index, doesn't work without timeout
168 setTimeout(function() {
169 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
174 $this_element.datetimepicker($.extend(defaultOptions, options));
178 * selects the content of a given object, f.e. a textarea
180 * @param object element element of which the content will be selected
181 * @param var lock variable which holds the lock for this element
182 * or true, if no lock exists
183 * @param boolean only_once if true this is only done once
184 * f.e. only on first focus
186 function selectContent( element, lock, only_once )
188 if ( only_once && only_once_elements[element.name] ) {
192 only_once_elements[element.name] = true;
202 * Displays a confirmation box before to submit a "DROP/DELETE/ALTER" query.
203 * This function is called while clicking links
205 * @param object the link
206 * @param object the sql query to submit
208 * @return boolean whether to run the query or not
210 function confirmLink(theLink, theSqlQuery)
212 // Confirmation is not required in the configuration file
213 // or browser is Opera (crappy js implementation)
214 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
218 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
220 if ( $(theLink).hasClass('formLinkSubmit') ) {
221 var name = 'is_js_confirmed';
222 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
223 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
226 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
227 } else if ( typeof(theLink.href) != 'undefined' ) {
228 theLink.href += '&is_js_confirmed=1';
229 } else if ( typeof(theLink.form) != 'undefined' ) {
230 theLink.form.action += '?is_js_confirmed=1';
235 } // end of the 'confirmLink()' function
239 * Displays a confirmation box before doing some action
241 * @param object the message to display
243 * @return boolean whether to run the query or not
245 * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
246 * and replace with a jQuery equivalent
248 function confirmAction(theMessage)
250 // TODO: Confirmation is not required in the configuration file
251 // or browser is Opera (crappy js implementation)
252 if (typeof(window.opera) != 'undefined') {
256 var is_confirmed = confirm(theMessage);
259 } // end of the 'confirmAction()' function
263 * Displays an error message if a "DROP DATABASE" statement is submitted
264 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
265 * sumitting it if required.
266 * This function is called by the 'checkSqlQuery()' js function.
268 * @param object the form
269 * @param object the sql query textarea
271 * @return boolean whether to run the query or not
273 * @see checkSqlQuery()
275 function confirmQuery(theForm1, sqlQuery1)
277 // Confirmation is not required in the configuration file
278 if (PMA_messages['strDoYouReally'] == '') {
282 // "DROP DATABASE" statement isn't allowed
283 if (PMA_messages['strNoDropDatabases'] != '') {
284 var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
285 if (drop_re.test(sqlQuery1.value)) {
286 alert(PMA_messages['strNoDropDatabases']);
293 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
295 // TODO: find a way (if possible) to use the parser-analyser
296 // for this kind of verification
297 // For now, I just added a ^ to check for the statement at
298 // beginning of expression
300 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
301 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
302 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
303 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
305 if (do_confirm_re_0.test(sqlQuery1.value)
306 || do_confirm_re_1.test(sqlQuery1.value)
307 || do_confirm_re_2.test(sqlQuery1.value)
308 || do_confirm_re_3.test(sqlQuery1.value)) {
309 var message = (sqlQuery1.value.length > 100)
310 ? sqlQuery1.value.substr(0, 100) + '\n ...'
312 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
313 // statement is confirmed -> update the
314 // "is_js_confirmed" form field so the confirm test won't be
315 // run on the server side and allows to submit the form
317 theForm1.elements['is_js_confirmed'].value = 1;
320 // statement is rejected -> do not submit the form
325 } // end if (handle confirm box result)
326 } // end if (display confirm box)
329 } // end of the 'confirmQuery()' function
333 * Displays a confirmation box before disabling the BLOB repository for a given database.
334 * This function is called while clicking links
336 * @param object the database
338 * @return boolean whether to disable the repository or not
340 function confirmDisableRepository(theDB)
342 // Confirmation is not required in the configuration file
343 // or browser is Opera (crappy js implementation)
344 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
348 var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
351 } // end of the 'confirmDisableBLOBRepository()' function
355 * Displays an error message if the user submitted the sql query form with no
356 * sql query, else checks for "DROP/DELETE/ALTER" statements
358 * @param object the form
360 * @return boolean always false
362 * @see confirmQuery()
364 function checkSqlQuery(theForm)
366 var sqlQuery = theForm.elements['sql_query'];
369 var space_re = new RegExp('\\s+');
370 if (typeof(theForm.elements['sql_file']) != 'undefined' &&
371 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
374 if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
375 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
378 if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
379 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
380 theForm.elements['id_bookmark'].selectedIndex != 0
384 // Checks for "DROP/DELETE/ALTER" statements
385 if (sqlQuery.value.replace(space_re, '') != '') {
386 if (confirmQuery(theForm, sqlQuery)) {
397 alert(PMA_messages['strFormEmpty']);
403 } // end of the 'checkSqlQuery()' function
406 * Check if a form's element is empty.
407 * An element containing only spaces is also considered empty
409 * @param object the form
410 * @param string the name of the form field to put the focus on
412 * @return boolean whether the form field is empty or not
414 function emptyCheckTheField(theForm, theFieldName)
416 var theField = theForm.elements[theFieldName];
417 var space_re = new RegExp('\\s+');
418 return (theField.value.replace(space_re, '') == '') ? 1 : 0;
419 } // end of the 'emptyCheckTheField()' function
423 * Check whether a form field is empty or not
425 * @param object the form
426 * @param string the name of the form field to put the focus on
428 * @return boolean whether the form field is empty or not
430 function emptyFormElements(theForm, theFieldName)
432 var theField = theForm.elements[theFieldName];
433 var isEmpty = emptyCheckTheField(theForm, theFieldName);
437 } // end of the 'emptyFormElements()' function
441 * Ensures a value submitted in a form is numeric and is in a range
443 * @param object the form
444 * @param string the name of the form field to check
445 * @param integer the minimum authorized value
446 * @param integer the maximum authorized value
448 * @return boolean whether a valid number has been submitted or not
450 function checkFormElementInRange(theForm, theFieldName, message, min, max)
452 var theField = theForm.elements[theFieldName];
453 var val = parseInt(theField.value);
455 if (typeof(min) == 'undefined') {
458 if (typeof(max) == 'undefined') {
459 max = Number.MAX_VALUE;
465 alert(PMA_messages['strNotNumber']);
469 // It's a number but it is not between min and max
470 else if (val < min || val > max) {
472 alert(message.replace('%d', val));
476 // It's a valid number
478 theField.value = val;
482 } // end of the 'checkFormElementInRange()' function
485 function checkTableEditForm(theForm, fieldsCnt)
487 // TODO: avoid sending a message if user just wants to add a line
488 // on the form but has not completed at least one field name
490 var atLeastOneField = 0;
491 var i, elm, elm2, elm3, val, id;
493 for (i=0; i<fieldsCnt; i++)
495 id = "#field_" + i + "_2";
498 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
499 elm2 = $("#field_" + i + "_3");
500 val = parseInt(elm2.val());
501 elm3 = $("#field_" + i + "_1");
502 if (isNaN(val) && elm3.val() != "") {
504 alert(PMA_messages['strNotNumber']);
510 if (atLeastOneField == 0) {
511 id = "field_" + i + "_1";
512 if (!emptyCheckTheField(theForm, id)) {
517 if (atLeastOneField == 0) {
518 var theField = theForm.elements["field_0_1"];
519 alert(PMA_messages['strFormEmpty']);
524 // at least this section is under jQuery
525 if ($("input.textfield[name='table']").val() == "") {
526 alert(PMA_messages['strFormEmpty']);
527 $("input.textfield[name='table']").focus();
533 } // enf of the 'checkTableEditForm()' function
537 * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
538 * checkboxes is consistant
540 * @param object the form
541 * @param string a code for the action that causes this function to be run
543 * @return boolean always true
545 function checkTransmitDump(theForm, theAction)
547 var formElts = theForm.elements;
549 // 'zipped' option has been checked
550 if (theAction == 'zip' && formElts['zip'].checked) {
551 if (!formElts['asfile'].checked) {
552 theForm.elements['asfile'].checked = true;
554 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
555 theForm.elements['gzip'].checked = false;
557 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
558 theForm.elements['bzip'].checked = false;
561 // 'gzipped' option has been checked
562 else if (theAction == 'gzip' && formElts['gzip'].checked) {
563 if (!formElts['asfile'].checked) {
564 theForm.elements['asfile'].checked = true;
566 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
567 theForm.elements['zip'].checked = false;
569 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
570 theForm.elements['bzip'].checked = false;
573 // 'bzipped' option has been checked
574 else if (theAction == 'bzip' && formElts['bzip'].checked) {
575 if (!formElts['asfile'].checked) {
576 theForm.elements['asfile'].checked = true;
578 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
579 theForm.elements['zip'].checked = false;
581 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
582 theForm.elements['gzip'].checked = false;
585 // 'transmit' option has been unchecked
586 else if (theAction == 'transmit' && !formElts['asfile'].checked) {
587 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
588 theForm.elements['zip'].checked = false;
590 if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
591 theForm.elements['gzip'].checked = false;
593 if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
594 theForm.elements['bzip'].checked = false;
599 } // end of the 'checkTransmitDump()' function
601 $(document).ready(function() {
603 * Row marking in horizontal mode (use "live" so that it works also for
604 * next pages reached via AJAX); a tr may have the class noclick to remove
607 $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
608 // do not trigger when clicked on anchor
609 if ($(e.target).is('a, img, a *')) {
614 // make the table unselectable (to prevent default highlighting when shift+click)
615 //$tr.parents('table').noSelect();
617 if (!e.shiftKey || last_clicked_row == -1) {
620 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
621 var $checkbox = $tr.find(':checkbox');
622 if ($checkbox.length) {
623 // checkbox in a row, add or remove class depending on checkbox state
624 var checked = $checkbox.attr('checked');
625 if (!$(e.target).is(':checkbox, label')) {
627 $checkbox.attr('checked', checked);
630 $tr.addClass('marked');
632 $tr.removeClass('marked');
634 last_click_checked = checked;
636 // normaln data table, just toggle class
637 $tr.toggleClass('marked');
638 last_click_checked = false;
641 // remember the last clicked row
642 last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
643 last_shift_clicked_row = -1;
645 // handle the shift click
646 PMA_clearSelection();
649 // clear last shift click result
650 if (last_shift_clicked_row >= 0) {
651 if (last_shift_clicked_row >= last_clicked_row) {
652 start = last_clicked_row;
653 end = last_shift_clicked_row;
655 start = last_shift_clicked_row;
656 end = last_clicked_row;
658 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
659 .slice(start, end + 1)
660 .removeClass('marked')
662 .attr('checked', false);
665 // handle new shift click
666 var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
667 if (curr_row >= last_clicked_row) {
668 start = last_clicked_row;
672 end = last_clicked_row;
674 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
675 .slice(start, end + 1)
678 .attr('checked', true);
680 // remember the last shift clicked row
681 last_shift_clicked_row = curr_row;
686 * Add a date/time picker to each element that needs it
687 * (only when timepicker.js is loaded)
689 if ($.timepicker != undefined) {
690 $('.datefield, .datetimefield').each(function() {
691 PMA_addDatepicker($(this));
697 * True if last click is to check a row.
699 var last_click_checked = false;
702 * Zero-based index of last clicked row.
703 * Used to handle the shift + click event in the code above.
705 var last_clicked_row = -1;
708 * Zero-based index of last shift clicked row.
710 var last_shift_clicked_row = -1;
713 * Row highlighting in horizontal mode (use "live"
714 * so that it works also for pages reached via AJAX)
716 /*$(document).ready(function() {
717 $('tr.odd, tr.even').live('hover',function(event) {
719 $tr.toggleClass('hover',event.type=='mouseover');
720 $tr.children().toggleClass('hover',event.type=='mouseover');
725 * This array is used to remember mark status of rows in browse mode
727 var marked_row = new Array;
730 * marks all rows and selects its first checkbox inside the given element
731 * the given element is usaly a table or a div containing the table or tables
733 * @param container DOM element
735 function markAllRows( container_id )
738 $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
739 .parents("tr").addClass("marked");
744 * marks all rows and selects its first checkbox inside the given element
745 * the given element is usaly a table or a div containing the table or tables
747 * @param container DOM element
749 function unMarkAllRows( container_id )
752 $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
753 .parents("tr").removeClass("marked");
758 * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
760 * @param string container_id the container id
761 * @param boolean state new value for checkbox (true or false)
762 * @return boolean always true
764 function setCheckboxes( container_id, state )
768 $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
771 $("#"+container_id).find("input:checkbox").removeAttr('checked');
775 } // end of the 'setCheckboxes()' function
778 * Checks/unchecks all options of a <select> element
780 * @param string the form name
781 * @param string the element name
782 * @param boolean whether to check or to uncheck options
784 * @return boolean always true
786 function setSelectOptions(the_form, the_select, do_check)
788 $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
790 } // end of the 'setSelectOptions()' function
793 * Sets current value for query box.
795 function setQuery(query)
797 if (codemirror_editor) {
798 codemirror_editor.setValue(query);
800 document.sqlform.sql_query.value = query;
806 * Create quick sql statements.
809 function insertQuery(queryType)
811 if (queryType == "clear") {
816 var myQuery = document.sqlform.sql_query;
818 var myListBox = document.sqlform.dummy;
819 var table = document.sqlform.table.value;
821 if (myListBox.options.length > 0) {
822 sql_box_locked = true;
827 for (var i=0; i < myListBox.options.length; i++) {
834 chaineAj += myListBox.options[i].value;
835 valDis += "[value-" + NbSelect + "]";
836 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
838 if (queryType == "selectall") {
839 query = "SELECT * FROM `" + table + "` WHERE 1";
840 } else if (queryType == "select") {
841 query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
842 } else if (queryType == "insert") {
843 query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
844 } else if (queryType == "update") {
845 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
846 } else if(queryType == "delete") {
847 query = "DELETE FROM `" + table + "` WHERE 1";
850 sql_box_locked = false;
856 * Inserts multiple fields.
859 function insertValueQuery()
861 var myQuery = document.sqlform.sql_query;
862 var myListBox = document.sqlform.dummy;
864 if(myListBox.options.length > 0) {
865 sql_box_locked = true;
868 for(var i=0; i<myListBox.options.length; i++) {
869 if (myListBox.options[i].selected) {
874 chaineAj += myListBox.options[i].value;
878 /* CodeMirror support */
879 if (codemirror_editor) {
880 codemirror_editor.replaceSelection(chaineAj);
882 } else if (document.selection) {
884 sel = document.selection.createRange();
886 document.sqlform.insert.focus();
888 //MOZILLA/NETSCAPE support
889 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
890 var startPos = document.sqlform.sql_query.selectionStart;
891 var endPos = document.sqlform.sql_query.selectionEnd;
892 var chaineSql = document.sqlform.sql_query.value;
894 myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
896 myQuery.value += chaineAj;
898 sql_box_locked = false;
903 * listbox redirection
905 function goToUrl(selObj, goToLocation)
907 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
911 * Refresh the WYSIWYG scratchboard after changes have been made
913 function refreshDragOption(e)
915 var elm = $('#' + e);
916 if (elm.css('visibility') == 'visible') {
923 * Refresh/resize the WYSIWYG scratchboard
925 function refreshLayout()
927 var elm = $('#pdflayout')
928 var orientation = $('#orientation_opt').val();
929 if($('#paper_opt').length==1){
930 var paper = $('#paper_opt').val();
934 if (orientation == 'P') {
941 elm.css('width', pdfPaperSize(paper, posa) + 'px');
942 elm.css('height', pdfPaperSize(paper, posb) + 'px');
946 * Show/hide the WYSIWYG scratchboard
948 function ToggleDragDrop(e)
950 var elm = $('#' + e);
951 if (elm.css('visibility') == 'hidden') {
952 PDFinit(); /* Defined in pdf_pages.php */
953 elm.css('visibility', 'visible');
954 elm.css('display', 'block');
955 $('#showwysiwyg').val('1')
957 elm.css('visibility', 'hidden');
958 elm.css('display', 'none');
959 $('#showwysiwyg').val('0')
964 * PDF scratchboard: When a position is entered manually, update
965 * the fields inside the scratchboard.
967 function dragPlace(no, axis, value)
969 var elm = $('#table_' + no);
971 elm.css('left', value + 'px');
973 elm.css('top', value + 'px');
978 * Returns paper sizes for a given format
980 function pdfPaperSize(format, axis)
982 switch (format.toUpperCase()) {
984 if (axis == 'x') return 4767.87; else return 6740.79;
987 if (axis == 'x') return 3370.39; else return 4767.87;
990 if (axis == 'x') return 2383.94; else return 3370.39;
993 if (axis == 'x') return 1683.78; else return 2383.94;
996 if (axis == 'x') return 1190.55; else return 1683.78;
999 if (axis == 'x') return 841.89; else return 1190.55;
1002 if (axis == 'x') return 595.28; else return 841.89;
1005 if (axis == 'x') return 419.53; else return 595.28;
1008 if (axis == 'x') return 297.64; else return 419.53;
1011 if (axis == 'x') return 209.76; else return 297.64;
1014 if (axis == 'x') return 147.40; else return 209.76;
1017 if (axis == 'x') return 104.88; else return 147.40;
1020 if (axis == 'x') return 73.70; else return 104.88;
1023 if (axis == 'x') return 2834.65; else return 4008.19;
1026 if (axis == 'x') return 2004.09; else return 2834.65;
1029 if (axis == 'x') return 1417.32; else return 2004.09;
1032 if (axis == 'x') return 1000.63; else return 1417.32;
1035 if (axis == 'x') return 708.66; else return 1000.63;
1038 if (axis == 'x') return 498.90; else return 708.66;
1041 if (axis == 'x') return 354.33; else return 498.90;
1044 if (axis == 'x') return 249.45; else return 354.33;
1047 if (axis == 'x') return 175.75; else return 249.45;
1050 if (axis == 'x') return 124.72; else return 175.75;
1053 if (axis == 'x') return 87.87; else return 124.72;
1056 if (axis == 'x') return 2599.37; else return 3676.54;
1059 if (axis == 'x') return 1836.85; else return 2599.37;
1062 if (axis == 'x') return 1298.27; else return 1836.85;
1065 if (axis == 'x') return 918.43; else return 1298.27;
1068 if (axis == 'x') return 649.13; else return 918.43;
1071 if (axis == 'x') return 459.21; else return 649.13;
1074 if (axis == 'x') return 323.15; else return 459.21;
1077 if (axis == 'x') return 229.61; else return 323.15;
1080 if (axis == 'x') return 161.57; else return 229.61;
1083 if (axis == 'x') return 113.39; else return 161.57;
1086 if (axis == 'x') return 79.37; else return 113.39;
1089 if (axis == 'x') return 2437.80; else return 3458.27;
1092 if (axis == 'x') return 1729.13; else return 2437.80;
1095 if (axis == 'x') return 1218.90; else return 1729.13;
1098 if (axis == 'x') return 864.57; else return 1218.90;
1101 if (axis == 'x') return 609.45; else return 864.57;
1104 if (axis == 'x') return 2551.18; else return 3628.35;
1107 if (axis == 'x') return 1814.17; else return 2551.18;
1110 if (axis == 'x') return 1275.59; else return 1814.17;
1113 if (axis == 'x') return 907.09; else return 1275.59;
1116 if (axis == 'x') return 637.80; else return 907.09;
1119 if (axis == 'x') return 612.00; else return 792.00;
1122 if (axis == 'x') return 612.00; else return 1008.00;
1125 if (axis == 'x') return 521.86; else return 756.00;
1128 if (axis == 'x') return 612.00; else return 936.00;
1136 * for playing media from the BLOB repository
1139 * @param var url_params main purpose is to pass the token
1140 * @param var bs_ref BLOB repository reference
1141 * @param var m_type type of BLOB repository media
1142 * @param var w_width width of popup window
1143 * @param var w_height height of popup window
1145 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1147 // if width not specified, use default
1148 if (w_width == undefined) {
1152 // if height not specified, use default
1153 if (w_height == undefined) {
1157 // open popup window (for displaying video/playing audio)
1158 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');
1162 * popups a request for changing MIME types for files in the BLOB repository
1164 * @param var db database name
1165 * @param var table table name
1166 * @param var reference BLOB repository reference
1167 * @param var current_mime_type current MIME type associated with BLOB repository reference
1169 function requestMIMETypeChange(db, table, reference, current_mime_type)
1171 // no mime type specified, set to default (nothing)
1172 if (undefined == current_mime_type) {
1173 current_mime_type = "";
1176 // prompt user for new mime type
1177 var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1179 // if new mime_type is specified and is not the same as the previous type, request for mime type change
1180 if (new_mime_type && new_mime_type != current_mime_type) {
1181 changeMIMEType(db, table, reference, new_mime_type);
1186 * changes MIME types for files in the BLOB repository
1188 * @param var db database name
1189 * @param var table table name
1190 * @param var reference BLOB repository reference
1191 * @param var mime_type new MIME type to be associated with BLOB repository reference
1193 function changeMIMEType(db, table, reference, mime_type)
1195 // specify url and parameters for jQuery POST
1196 var mime_chg_url = 'bs_change_mime_type.php';
1197 var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1200 jQuery.post(mime_chg_url, params);
1204 * Jquery Coding for inline editing SQL_QUERY
1206 $(document).ready(function(){
1207 $(".inline_edit_sql").live('click', function(){
1208 var $form = $(this).prev();
1209 var sql_query = $form.find("input[name='sql_query']").val();
1210 var $inner_sql = $(this).parent().prev().find('.inner_sql');
1211 var old_text = $inner_sql.html();
1213 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1214 new_content += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1215 new_content += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1216 $inner_sql.replaceWith(new_content);
1217 $(".btnSave").click(function(){
1218 var sql_query = $(this).prev().val();
1219 var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1220 .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1221 .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1222 .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1223 $fake_form.appendTo($('body')).submit();
1225 $(".btnDiscard").click(function(){
1226 $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1231 $('.sqlbutton').click(function(evt){
1232 insertQuery(evt.target.id);
1236 $("#export_type").change(function(){
1237 if($("#export_type").val()=='svg'){
1238 $("#show_grid_opt").attr("disabled","disabled");
1239 $("#orientation_opt").attr("disabled","disabled");
1240 $("#with_doc").attr("disabled","disabled");
1241 $("#show_table_dim_opt").removeAttr("disabled");
1242 $("#all_table_same_wide").removeAttr("disabled");
1243 $("#paper_opt").removeAttr("disabled","disabled");
1244 $("#show_color_opt").removeAttr("disabled","disabled");
1245 //$(this).css("background-color","yellow");
1246 }else if($("#export_type").val()=='dia'){
1247 $("#show_grid_opt").attr("disabled","disabled");
1248 $("#with_doc").attr("disabled","disabled");
1249 $("#show_table_dim_opt").attr("disabled","disabled");
1250 $("#all_table_same_wide").attr("disabled","disabled");
1251 $("#paper_opt").removeAttr("disabled","disabled");
1252 $("#show_color_opt").removeAttr("disabled","disabled");
1253 $("#orientation_opt").removeAttr("disabled","disabled");
1254 }else if($("#export_type").val()=='eps'){
1255 $("#show_grid_opt").attr("disabled","disabled");
1256 $("#orientation_opt").removeAttr("disabled");
1257 $("#with_doc").attr("disabled","disabled");
1258 $("#show_table_dim_opt").attr("disabled","disabled");
1259 $("#all_table_same_wide").attr("disabled","disabled");
1260 $("#paper_opt").attr("disabled","disabled");
1261 $("#show_color_opt").attr("disabled","disabled");
1263 }else if($("#export_type").val()=='pdf'){
1264 $("#show_grid_opt").removeAttr("disabled");
1265 $("#orientation_opt").removeAttr("disabled");
1266 $("#with_doc").removeAttr("disabled","disabled");
1267 $("#show_table_dim_opt").removeAttr("disabled","disabled");
1268 $("#all_table_same_wide").removeAttr("disabled","disabled");
1269 $("#paper_opt").removeAttr("disabled","disabled");
1270 $("#show_color_opt").removeAttr("disabled","disabled");
1276 $('#sqlquery').focus().keydown(function (e) {
1277 if (e.ctrlKey && e.keyCode == 13) {
1278 $("#sqlqueryform").submit();
1282 if ($('#input_username')) {
1283 if ($('#input_username').val() == '') {
1284 $('#input_username').focus();
1286 $('#input_password').focus();
1292 * Show a message on the top of the page for an Ajax request
1294 * @param var message string containing the message to be shown.
1295 * optional, defaults to 'Loading...'
1296 * @param var timeout number of milliseconds for the message to be visible
1297 * optional, defaults to 5000
1298 * @return jQuery object jQuery Element that holds the message div
1300 function PMA_ajaxShowMessage(message, timeout)
1303 //Handle the case when a empty data.message is passed. We don't want the empty message
1304 if (message == '') {
1306 } else if (! message) {
1307 // If the message is undefined, show the default
1308 message = PMA_messages['strLoading'];
1312 * @var timeout Number of milliseconds for which the message will be visible
1319 // Create a parent element for the AJAX messages, if necessary
1320 if ($('#loading_parent').length == 0) {
1321 $('<div id="loading_parent"></div>')
1322 .insertBefore("#serverinfo");
1325 // Update message count to create distinct message elements every time
1326 ajax_message_count++;
1328 // Remove all old messages, if any
1329 $(".ajax_notification[id^=ajax_message_num]").remove();
1332 * @var $retval a jQuery object containing the reference
1333 * to the created AJAX message
1335 var $retval = $('<span class="ajax_notification" id="ajax_message_num_' + ajax_message_count + '"></span>')
1337 .appendTo("#loading_parent")
1341 .fadeOut('medium', function() {
1349 * Removes the message shown for an Ajax operation when it's completed
1351 function PMA_ajaxRemoveMessage($this_msgbox)
1353 if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1361 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1363 function PMA_showNoticeForEnum(selectElement)
1365 var enum_notice_id = selectElement.attr("id").split("_")[1];
1366 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1367 var selectedType = selectElement.attr("value");
1368 if (selectedType == "ENUM" || selectedType == "SET") {
1369 $("p[id='enum_notice_" + enum_notice_id + "']").show();
1371 $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1376 * Generates a dialog box to pop up the create_table form
1378 function PMA_createTableDialog( div, url , target)
1381 * @var button_options Object that stores the options passed to jQueryUI
1384 var button_options = {};
1385 // in the following function we need to use $(this)
1386 button_options[PMA_messages['strCancel']] = function() {$(this).parent().dialog('close').remove();}
1388 var button_options_error = {};
1389 button_options_error[PMA_messages['strOK']] = function() {$(this).parent().dialog('close').remove();}
1391 var $msgbox = PMA_ajaxShowMessage();
1393 $.get( target , url , function(data) {
1394 //in the case of an error, show the error message returned.
1395 if (data.success != undefined && data.success == false) {
1399 title: PMA_messages['strCreateTable'],
1402 open: PMA_verifyTypeOfAllColumns,
1403 buttons : button_options_error
1404 })// end dialog options
1405 //remove the redundant [Back] link in the error message.
1406 .find('fieldset').remove();
1411 title: PMA_messages['strCreateTable'],
1414 open: PMA_verifyTypeOfAllColumns,
1415 buttons : button_options
1416 }); // end dialog options
1418 PMA_ajaxRemoveMessage($msgbox);
1424 * Creates a highcharts chart in the given container
1426 * @param var settings object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1427 * requires at least settings.chart.renderTo and settings.series to be set.
1428 * In addition there may be an additional property object 'realtime' that allows for realtime charting:
1430 * url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1431 * type: the GET request will also add type=[value of the type property] to the request
1432 * callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1433 * - the chart object
1434 * - the current response value of the GET request, JSON parsed
1435 * - the previous response value of the GET request, JSON parsed
1436 * - the number of added points
1437 * error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1440 * @return object The created highcharts instance
1442 function PMA_createChart(passedSettings)
1444 var container = passedSettings.chart.renderTo;
1450 backgroundColor: 'none',
1452 /* Live charting support */
1454 var thisChart = this;
1455 var lastValue = null, curValue = null;
1456 var numLoadedPoints = 0, otherSum = 0;
1459 // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1460 // Also don't do live charting if we don't have the server time
1461 if(thisChart.options.chart.forExport == true ||
1462 ! thisChart.options.realtime ||
1463 ! thisChart.options.realtime.callback ||
1464 ! server_time_diff) return;
1466 thisChart.options.realtime.timeoutCallBack = function() {
1467 thisChart.options.realtime.postRequest = $.post(
1468 thisChart.options.realtime.url,
1469 thisChart.options.realtime.postData,
1472 curValue = jQuery.parseJSON(data);
1474 if(thisChart.options.realtime.error)
1475 thisChart.options.realtime.error(err);
1479 if (lastValue==null) {
1480 diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1482 diff = parseInt(curValue.x - lastValue.x);
1485 thisChart.xAxis[0].setExtremes(
1486 thisChart.xAxis[0].getExtremes().min+diff,
1487 thisChart.xAxis[0].getExtremes().max+diff,
1491 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1493 lastValue = curValue;
1496 // Timeout has been cleared => don't start a new timeout
1497 if (chart_activeTimeouts[container] == null) {
1501 chart_activeTimeouts[container] = setTimeout(
1502 thisChart.options.realtime.timeoutCallBack,
1503 thisChart.options.realtime.refreshRate
1508 chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1528 text: PMA_messages['strTotalCount']
1537 formatter: function() {
1538 return '<b>' + this.series.name +'</b><br/>' +
1539 Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1540 Highcharts.numberFormat(this.y, 2);
1549 /* Set/Get realtime chart default values */
1550 if(passedSettings.realtime) {
1551 if(!passedSettings.realtime.refreshRate) {
1552 passedSettings.realtime.refreshRate = 5000;
1555 if(!passedSettings.realtime.numMaxPoints) {
1556 passedSettings.realtime.numMaxPoints = 30;
1559 // Allow custom POST vars to be added
1560 passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1562 if(server_time_diff) {
1563 settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1564 settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1568 // Overwrite/Merge default settings with passedsettings
1569 $.extend(true,settings,passedSettings);
1571 return new Highcharts.Chart(settings);
1576 * Creates a Profiling Chart. Used in sql.php and server_status.js
1578 function PMA_createProfilingChart(data, options)
1580 return PMA_createChart($.extend(true, {
1582 renderTo: 'profilingchart',
1585 title: { text:'', margin:0 },
1588 name: PMA_messages['strQueryExecutionTime'],
1593 allowPointSelect: true,
1598 formatter: function() {
1599 return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1605 formatter: function() {
1606 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1613 * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1615 * @param integer Number to be formatted, should be in the range of microsecond to second
1616 * @param integer Acuracy, how many numbers right to the comma should be
1617 * @return string The formatted number
1619 function PMA_prettyProfilingNum(num, acc)
1624 acc = Math.pow(10,acc);
1625 if (num * 1000 < 0.1) {
1626 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1627 } else if (num < 0.1) {
1628 num = Math.round(acc * (num * 1000)) / acc + 'm';
1630 num = Math.round(acc * num) / acc;
1638 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1640 * @param string Query to be formatted
1641 * @return string The formatted query
1643 function PMA_SQLPrettyPrint(string)
1645 var mode = CodeMirror.getMode({},"text/x-mysql");
1646 var stream = new CodeMirror.StringStream(string);
1647 var state = mode.startState();
1648 var token, tokens = [];
1650 var tabs = function(cnt) {
1652 for (var i=0; i<4*cnt; i++)
1657 // "root-level" statements
1659 'select': ['select', 'from','on','where','having','limit','order by','group by'],
1660 'update': ['update', 'set','where'],
1661 'insert into': ['insert into', 'values']
1663 // don't put spaces before these tokens
1664 var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1665 // don't put spaces after these tokens
1666 var spaceExceptionsAfter = { '.': true };
1668 // Populate tokens array
1670 while (! stream.eol()) {
1671 stream.start = stream.pos;
1672 token = mode.token(stream, state);
1674 tokens.push([token, stream.current().toLowerCase()]);
1678 var currentStatement = tokens[0][1];
1680 if(! statements[currentStatement]) {
1683 // Holds all currently opened code blocks (statement, function or generic)
1684 var blockStack = [];
1685 // Holds the type of block from last iteration (the current is in blockStack[0])
1687 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1688 var newBlock, endBlock;
1689 // How much to indent in the current line
1690 var indentLevel = 0;
1691 // Holds the "root-level" statements
1692 var statementPart, lastStatementPart = statements[currentStatement][0];
1694 blockStack.unshift('statement');
1696 // Iterate through every token and format accordingly
1697 for (var i = 0; i < tokens.length; i++) {
1698 previousBlock = blockStack[0];
1700 // New block => push to stack
1701 if (tokens[i][1] == '(') {
1702 if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1703 blockStack.unshift(newBlock = 'statement');
1704 } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1705 blockStack.unshift(newBlock = 'function');
1707 blockStack.unshift(newBlock = 'generic');
1713 // Block end => pop from stack
1714 if (tokens[i][1] == ')') {
1715 endBlock = blockStack[0];
1721 // A subquery is starting
1722 if (i > 0 && newBlock == 'statement') {
1724 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1725 currentStatement = tokens[i+1][1];
1730 // A subquery is ending
1731 if (endBlock == 'statement' && indentLevel > 0) {
1732 output += "\n" + tabs(indentLevel);
1736 // One less indentation for statement parts (from, where, order by, etc.) and a newline
1737 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1738 if (statementPart != -1) {
1739 if (i > 0) output += "\n";
1740 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1741 output += "\n" + tabs(indentLevel + 1);
1742 lastStatementPart = tokens[i][1];
1744 // Normal indentatin and spaces for everything else
1746 if (! spaceExceptionsBefore[tokens[i][1]]
1747 && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1748 && output.charAt(output.length -1) != ' ' ) {
1751 if (tokens[i][0] == 'keyword') {
1752 output += tokens[i][1].toUpperCase();
1754 output += tokens[i][1];
1758 // split columns in select and 'update set' clauses, but only inside statements blocks
1759 if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
1760 && tokens[i][1]==',' && blockStack[0] == 'statement') {
1762 output += "\n" + tabs(indentLevel + 1);
1765 // split conditions in where clauses, but only inside statements blocks
1766 if (lastStatementPart == 'where'
1767 && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1769 if (blockStack[0] == 'statement') {
1770 output += "\n" + tabs(indentLevel + 1);
1772 // Todo: Also split and or blocks in newlines & identation++
1773 //if(blockStack[0] == 'generic')
1781 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1782 * return a jQuery object yet and hence cannot be chained
1784 * @param string question
1785 * @param string url URL to be passed to the callbackFn to make
1787 * @param function callbackFn callback to execute after user clicks on OK
1790 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1791 if (PMA_messages['strDoYouReally'] == '') {
1796 * @var button_options Object that stores the options passed to jQueryUI
1799 var button_options = {};
1800 button_options[PMA_messages['strOK']] = function(){
1801 $(this).dialog("close").remove();
1803 if($.isFunction(callbackFn)) {
1804 callbackFn.call(this, url);
1807 button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1809 $('<div id="confirm_dialog"></div>')
1811 .dialog({buttons: button_options});
1815 * jQuery function to sort a table's body after a new row has been appended to it.
1816 * Also fixes the even/odd classes of the table rows at the end.
1818 * @param string text_selector string to select the sortKey's text
1820 * @return jQuery Object for chaining purposes
1822 jQuery.fn.PMA_sort_table = function(text_selector) {
1823 return this.each(function() {
1826 * @var table_body Object referring to the table's <tbody> element
1828 var table_body = $(this);
1830 * @var rows Object referring to the collection of rows in {@link table_body}
1832 var rows = $(this).find('tr').get();
1834 //get the text of the field that we will sort by
1835 $.each(rows, function(index, row) {
1836 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1839 //get the sorted order
1840 rows.sort(function(a,b) {
1841 if(a.sortKey < b.sortKey) {
1844 if(a.sortKey > b.sortKey) {
1850 //pull out each row from the table and then append it according to it's order
1851 $.each(rows, function(index, row) {
1852 $(table_body).append(row);
1856 //Re-check the classes of each row
1857 $(this).find('tr:odd')
1858 .removeClass('even').addClass('odd')
1861 .removeClass('odd').addClass('even');
1866 * jQuery coding for 'Create Table'. Used on db_operations.php,
1867 * db_structure.php and db_tracking.php (i.e., wherever
1868 * libraries/display_create_table.lib.php is used)
1870 * Attach Ajax Event handlers for Create Table
1872 $(document).ready(function() {
1875 * Attach event handler to the submit action of the create table minimal form
1876 * and retrieve the full table form and display it in a dialog
1878 * @uses PMA_ajaxShowMessage()
1880 $("#create_table_form_minimal.ajax").live('submit', function(event) {
1881 event.preventDefault();
1883 PMA_prepareForAjaxRequest($form);
1885 /*variables which stores the common attributes*/
1886 var url = $form.serialize();
1887 var action = $form.attr('action');
1888 var div = $('<div id="create_table_dialog"></div>');
1890 /*Calling to the createTableDialog function*/
1891 PMA_createTableDialog(div, url, action);
1893 // empty table name and number of columns from the minimal form
1894 $form.find('input[name=table],input[name=num_fields]').val('');
1898 * Attach event handler for submission of create table form (save)
1900 * @uses PMA_ajaxShowMessage()
1901 * @uses $.PMA_sort_table()
1904 // .live() must be called after a selector, see http://api.jquery.com/live
1905 $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1906 event.preventDefault();
1909 * @var the_form object referring to the create table form
1911 var $form = $("#create_table_form");
1914 * First validate the form; if there is a problem, avoid submitting it
1916 * checkTableEditForm() needs a pure element and not a jQuery object,
1917 * this is why we pass $form[0] as a parameter (the jQuery object
1918 * is actually an array of DOM elements)
1921 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
1922 // OK, form passed validation step
1923 if ($form.hasClass('ajax')) {
1924 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1925 PMA_prepareForAjaxRequest($form);
1926 //User wants to submit the form
1927 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1928 if(data.success == true) {
1929 $('#properties_message')
1930 .removeClass('error')
1932 PMA_ajaxShowMessage(data.message);
1933 // Only if the create table dialog (distinct panel) exists
1934 if ($("#create_table_dialog").length > 0) {
1935 $("#create_table_dialog").dialog("close").remove();
1939 * @var tables_table Object referring to the <tbody> element that holds the list of tables
1941 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1942 // this is the first table created in this db
1943 if (tables_table.length == 0) {
1944 if (window.parent && window.parent.frame_content) {
1945 window.parent.frame_content.location.reload();
1949 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
1951 var curr_last_row = $(tables_table).find('tr:last');
1953 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
1955 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1957 * @var curr_last_row_index Index of {@link curr_last_row}
1959 var curr_last_row_index = parseFloat(curr_last_row_index_string);
1961 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
1963 var new_last_row_index = curr_last_row_index + 1;
1965 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1967 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1969 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
1971 $(data.new_table_string)
1972 .appendTo(tables_table);
1975 $(tables_table).PMA_sort_table('th');
1978 //Refresh navigation frame as a new table has been added
1979 if (window.parent && window.parent.frame_navigation) {
1980 window.parent.frame_navigation.location.reload();
1983 $('#properties_message')
1986 // scroll to the div containing the error message
1987 $('#properties_message')[0].scrollIntoView();
1990 } // end if ($form.hasClass('ajax')
1993 $form.append('<input type="hidden" name="do_save_data" value="save" />');
1996 } // end if (checkTableEditForm() )
1997 }) // end create table form (save)
2000 * Attach event handler for create table form (add fields)
2002 * @uses PMA_ajaxShowMessage()
2003 * @uses $.PMA_sort_table()
2004 * @uses window.parent.refreshNavigation()
2007 // .live() must be called after a selector, see http://api.jquery.com/live
2008 $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2009 event.preventDefault();
2012 * @var the_form object referring to the create table form
2014 var $form = $("#create_table_form");
2016 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2017 PMA_prepareForAjaxRequest($form);
2019 //User wants to add more fields to the table
2020 $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2021 // if 'create_table_dialog' exists
2022 if ($("#create_table_dialog").length > 0) {
2023 $("#create_table_dialog").html(data);
2025 // if 'create_table_div' exists
2026 if ($("#create_table_div").length > 0) {
2027 $("#create_table_div").html(data);
2029 PMA_verifyTypeOfAllColumns();
2030 PMA_ajaxRemoveMessage($msgbox);
2033 }) // end create table form (add fields)
2035 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2038 * jQuery coding for 'Change Table' and 'Add Column'. Used on tbl_structure.php *
2039 * Attach Ajax Event handlers for Change Table
2041 $(document).ready(function() {
2043 *Ajax action for submitting the "Column Change" and "Add Column" form
2045 $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2046 event.preventDefault();
2048 * @var the_form object referring to the export form
2050 var $form = $("#append_fields_form");
2053 * First validate the form; if there is a problem, avoid submitting it
2055 * checkTableEditForm() needs a pure element and not a jQuery object,
2056 * this is why we pass $form[0] as a parameter (the jQuery object
2057 * is actually an array of DOM elements)
2059 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2060 // OK, form passed validation step
2061 if ($form.hasClass('ajax')) {
2062 PMA_prepareForAjaxRequest($form);
2063 //User wants to submit the form
2064 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2065 if ($("#sqlqueryresults").length != 0) {
2066 $("#sqlqueryresults").remove();
2067 } else if ($(".error").length != 0) {
2068 $(".error").remove();
2070 if (data.success == true) {
2071 PMA_ajaxShowMessage(data.message);
2072 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2073 $("#sqlqueryresults").html(data.sql_query);
2074 $("#result_query .notice").remove();
2075 $("#result_query").prepend((data.message));
2076 if ($("#change_column_dialog").length > 0) {
2077 $("#change_column_dialog").dialog("close").remove();
2078 } else if ($("#add_columns").length > 0) {
2079 $("#add_columns").dialog("close").remove();
2081 /*Reload the field form*/
2082 $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2083 $("#fieldsForm").remove();
2084 $("#addColumns").remove();
2085 var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2086 if ($("#sqlqueryresults").length != 0) {
2087 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2089 $temp_div.find("#fieldsForm").insertAfter(".error");
2091 $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2092 /*Call the function to display the more options in table*/
2093 displayMoreTableOpts();
2096 var $temp_div = $("<div id='temp_div'><div>").append(data);
2097 var $error = $temp_div.find(".error code").addClass("error");
2098 PMA_ajaxShowMessage($error);
2103 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2107 }) // end change table button "do_save_data"
2109 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2112 * jQuery coding for 'Table operations'. Used on tbl_operations.php
2113 * Attach Ajax Event handlers for Table operations
2115 $(document).ready(function() {
2117 *Ajax action for submitting the "Alter table order by"
2119 $("#alterTableOrderby.ajax").live('submit', function(event) {
2120 event.preventDefault();
2121 var $form = $(this);
2123 PMA_prepareForAjaxRequest($form);
2124 /*variables which stores the common attributes*/
2125 $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2126 if ($("#sqlqueryresults").length != 0) {
2127 $("#sqlqueryresults").remove();
2129 if ($("#result_query").length != 0) {
2130 $("#result_query").remove();
2132 if (data.success == true) {
2133 PMA_ajaxShowMessage(data.message);
2134 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2135 $("#sqlqueryresults").html(data.sql_query);
2136 $("#result_query .notice").remove();
2137 $("#result_query").prepend((data.message));
2139 var $temp_div = $("<div id='temp_div'></div>")
2140 $temp_div.html(data.error);
2141 var $error = $temp_div.find("code").addClass("error");
2142 PMA_ajaxShowMessage($error);
2145 });//end of alterTableOrderby ajax submit
2148 *Ajax action for submitting the "Copy table"
2150 $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2151 event.preventDefault();
2152 var $form = $("#copyTable");
2153 if($form.find("input[name='switch_to_new']").attr('checked')) {
2154 $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2155 $form.removeClass('ajax');
2156 $form.find("#ajax_request_hidden").remove();
2159 PMA_prepareForAjaxRequest($form);
2160 /*variables which stores the common attributes*/
2161 $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2162 if ($("#sqlqueryresults").length != 0) {
2163 $("#sqlqueryresults").remove();
2165 if ($("#result_query").length != 0) {
2166 $("#result_query").remove();
2168 if (data.success == true) {
2169 PMA_ajaxShowMessage(data.message);
2170 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2171 $("#sqlqueryresults").html(data.sql_query);
2172 $("#result_query .notice").remove();
2173 $("#result_query").prepend((data.message));
2174 $("#copyTable").find("select[name='target_db'] option[value="+data.db+"]").attr('selected', 'selected');
2176 //Refresh navigation frame when the table is coppied
2177 if (window.parent && window.parent.frame_navigation) {
2178 window.parent.frame_navigation.location.reload();
2181 var $temp_div = $("<div id='temp_div'></div>");
2182 $temp_div.html(data.error);
2183 var $error = $temp_div.find("code").addClass("error");
2184 PMA_ajaxShowMessage($error);
2188 });//end of copyTable ajax submit
2191 *Ajax events for actions in the "Table maintenance"
2193 $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2194 event.preventDefault();
2195 var $link = $(this);
2196 var href = $link.attr("href");
2197 href = href.split('?');
2198 if ($("#sqlqueryresults").length != 0) {
2199 $("#sqlqueryresults").remove();
2201 if ($("#result_query").length != 0) {
2202 $("#result_query").remove();
2204 //variables which stores the common attributes
2205 $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2206 if (data.success == undefined) {
2207 var $temp_div = $("<div id='temp_div'></div>");
2208 $temp_div.html(data);
2209 var $success = $temp_div.find("#result_query .success");
2210 PMA_ajaxShowMessage($success);
2211 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2212 $("#sqlqueryresults").html(data);
2214 $("#sqlqueryresults").children("fieldset").remove();
2215 } else if (data.success == true ) {
2216 PMA_ajaxShowMessage(data.message);
2217 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2218 $("#sqlqueryresults").html(data.sql_query);
2220 var $temp_div = $("<div id='temp_div'></div>");
2221 $temp_div.html(data.error);
2222 var $error = $temp_div.find("code").addClass("error");
2223 PMA_ajaxShowMessage($error);
2226 });//end of table maintanance ajax click
2228 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2232 * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2233 * as it was also required on db_create.php
2235 * @uses $.PMA_confirm()
2236 * @uses PMA_ajaxShowMessage()
2237 * @uses window.parent.refreshNavigation()
2238 * @uses window.parent.refreshMain()
2239 * @see $cfg['AjaxEnable']
2241 $(document).ready(function() {
2242 $("#drop_db_anchor").live('click', function(event) {
2243 event.preventDefault();
2245 //context is top.frame_content, so we need to use window.parent.db to access the db var
2247 * @var question String containing the question to be asked for confirmation
2249 var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + window.parent.db;
2251 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2253 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2254 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2255 //Database deleted successfully, refresh both the frames
2256 window.parent.refreshNavigation();
2257 window.parent.refreshMain();
2259 }); // end $.PMA_confirm()
2260 }); //end of Drop Database Ajax action
2261 }) // end of $(document).ready() for Drop Database
2264 * Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
2265 * display_create_database.lib.php is used, ie main.php and server_databases.php
2267 * @uses PMA_ajaxShowMessage()
2268 * @see $cfg['AjaxEnable']
2270 $(document).ready(function() {
2272 $('#create_database_form.ajax').live('submit', function(event) {
2273 event.preventDefault();
2277 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2278 PMA_prepareForAjaxRequest($form);
2280 $.post($form.attr('action'), $form.serialize(), function(data) {
2281 if(data.success == true) {
2282 PMA_ajaxShowMessage(data.message);
2284 //Append database's row to table
2285 $("#tabledatabases")
2287 .append(data.new_db_string)
2288 .PMA_sort_table('.name')
2289 .find('#db_summary_row')
2290 .appendTo('#tabledatabases tbody')
2291 .removeClass('odd even');
2293 var $databases_count_object = $('#databases_count');
2294 var databases_count = parseInt($databases_count_object.text());
2295 $databases_count_object.text(++databases_count);
2296 //Refresh navigation frame as a new database has been added
2297 if (window.parent && window.parent.frame_navigation) {
2298 window.parent.frame_navigation.location.reload();
2302 PMA_ajaxShowMessage(data.error);
2305 }) // end $().live()
2306 }) // end $(document).ready() for Create Database
2309 * Attach Ajax event handlers for 'Change Password' on main.php
2311 $(document).ready(function() {
2314 * Attach Ajax event handler on the change password anchor
2315 * @see $cfg['AjaxEnable']
2317 $('#change_password_anchor.dialog_active').live('click',function(event) {
2318 event.preventDefault();
2321 $('#change_password_anchor.ajax').live('click', function(event) {
2322 event.preventDefault();
2323 $(this).removeClass('ajax').addClass('dialog_active');
2325 * @var button_options Object containing options to be passed to jQueryUI's dialog
2327 var button_options = {};
2328 button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2329 $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2330 $('<div id="change_password_dialog"></div>')
2332 title: PMA_messages['strChangePassword'],
2334 close: function(ev,ui) {$(this).remove();},
2335 buttons : button_options,
2336 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2339 displayPasswordGenerateButton();
2341 }) // end handler for change password anchor
2344 * Attach Ajax event handler for Change Password form submission
2346 * @uses PMA_ajaxShowMessage()
2347 * @see $cfg['AjaxEnable']
2349 $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2350 event.preventDefault();
2353 * @var the_form Object referring to the change password form
2355 var the_form = $("#change_password_form");
2358 * @var this_value String containing the value of the submit button.
2359 * Need to append this for the change password form on Server Privileges
2362 var this_value = $(this).val();
2364 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2365 $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2367 $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2368 if(data.success == true) {
2369 $("#topmenucontainer").after(data.sql_query);
2370 $("#change_password_dialog").hide().remove();
2371 $("#edit_user_dialog").dialog("close").remove();
2372 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2373 PMA_ajaxRemoveMessage($msgbox);
2376 PMA_ajaxShowMessage(data.error);
2379 }) // end handler for Change Password form submission
2380 }) // end $(document).ready() for Change Password
2383 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2384 * the page loads and when the selected data type changes
2386 $(document).ready(function() {
2387 // is called here for normal page loads and also when opening
2388 // the Create table dialog
2389 PMA_verifyTypeOfAllColumns();
2391 // needs live() to work also in the Create Table dialog
2392 $("select[class='column_type']").live('change', function() {
2393 PMA_showNoticeForEnum($(this));
2397 function PMA_verifyTypeOfAllColumns()
2399 $("select[class='column_type']").each(function() {
2400 PMA_showNoticeForEnum($(this));
2405 * Closes the ENUM/SET editor and removes the data in it
2407 function disable_popup()
2409 $("#popup_background").fadeOut("fast");
2410 $("#enum_editor").fadeOut("fast");
2411 // clear the data from the text boxes
2412 $("#enum_editor #values input").remove();
2413 $("#enum_editor input[type='hidden']").remove();
2417 * Opens the ENUM/SET editor and controls its functions
2419 $(document).ready(function() {
2420 // Needs live() to work also in the Create table dialog
2421 $("a[class='open_enum_editor']").live('click', function() {
2423 var windowWidth = document.documentElement.clientWidth;
2424 var windowHeight = document.documentElement.clientHeight;
2425 var popupWidth = windowWidth/2;
2426 var popupHeight = windowHeight*0.8;
2427 var popupOffsetTop = windowHeight/2 - popupHeight/2;
2428 var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2429 $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2432 $("#popup_background").css({"opacity":"0.7"});
2433 $("#popup_background").fadeIn("fast");
2434 $("#enum_editor").fadeIn("fast");
2435 /**Replacing the column name in the enum editor header*/
2436 var column_name = $("#append_fields_form").find("input[id=field_0_1]").attr("value");
2437 var h3_text = $("#enum_editor h3").html();
2438 $("#enum_editor h3").html(h3_text.split('"')[0]+'"'+column_name+'"');
2441 var values = $(this).parent().prev("input").attr("value").split(",");
2442 $.each(values, function(index, val) {
2443 if(jQuery.trim(val) != "") {
2444 // enclose the string in single quotes if it's not already
2445 if(val.substr(0, 1) != "'") {
2448 if(val.substr(val.length-1, val.length) != "'") {
2451 // escape the single quotes, except the mandatory ones enclosing the entire string
2452 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "'");
2453 // escape the greater-than symbol
2454 val = val.replace(/>/g, ">");
2455 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2458 // So we know which column's data is being edited
2459 $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2463 // If the "close" link is clicked, close the enum editor
2464 // Needs live() to work also in the Create table dialog
2465 $("a[class='close_enum_editor']").live('click', function() {
2469 // If the "cancel" link is clicked, close the enum editor
2470 // Needs live() to work also in the Create table dialog
2471 $("a[class='cancel_enum_editor']").live('click', function() {
2475 // When "add a new value" is clicked, append an empty text field
2476 // Needs live() to work also in the Create table dialog
2477 $("a[class='add_value']").live('click', function() {
2478 $("#enum_editor #values").append("<input type='text' />");
2481 // When the submit button is clicked, put the data back into the original form
2482 // Needs live() to work also in the Create table dialog
2483 $("#enum_editor input[type='submit']").live('click', function() {
2484 var value_array = new Array();
2485 $.each($("#enum_editor #values input"), function(index, input_element) {
2486 val = jQuery.trim(input_element.value);
2488 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2491 // get the Length/Values text field where this value belongs
2492 var values_id = $("#enum_editor input[type='hidden']").attr("value");
2493 $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2498 * Hides certain table structure actions, replacing them with the word "More". They are displayed
2499 * in a dropdown menu when the user hovers over the word "More."
2501 displayMoreTableOpts();
2504 function displayMoreTableOpts()
2506 // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2507 // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2508 if($("input[type='hidden'][name='table_type']").val() == "table") {
2509 var $table = $("table[id='tablestructure']");
2510 $table.find("td[class='browse']").remove();
2511 $table.find("td[class='primary']").remove();
2512 $table.find("td[class='unique']").remove();
2513 $table.find("td[class='index']").remove();
2514 $table.find("td[class='fulltext']").remove();
2515 $table.find("td[class='spatial']").remove();
2516 $table.find("th[class='action']").attr("colspan", 3);
2518 // Display the "more" text
2519 $table.find("td[class='more_opts']").show();
2521 // Position the dropdown
2522 $(".structure_actions_dropdown").each(function() {
2523 // Optimize DOM querying
2524 var $this_dropdown = $(this);
2525 // The top offset must be set for IE even if it didn't change
2526 var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2527 var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2528 var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2529 $this_dropdown.offset({ top: top_offset, left: left_offset });
2532 // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2533 // positioning an iframe directly on top of it
2534 var $after_field = $("select[name='after_field']");
2535 $("iframe[class='IE_hack']")
2536 .width($after_field.width())
2537 .height($after_field.height())
2539 top: $after_field.offset().top,
2540 left: $after_field.offset().left
2543 // When "more" is hovered over, show the hidden actions
2544 $table.find("td[class='more_opts']")
2545 .mouseenter(function() {
2546 if($.browser.msie && $.browser.version == "6.0") {
2547 $("iframe[class='IE_hack']")
2549 .width($after_field.width()+4)
2550 .height($after_field.height()+4)
2552 top: $after_field.offset().top,
2553 left: $after_field.offset().left
2556 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2557 $(this).children(".structure_actions_dropdown").show();
2558 // Need to do this again for IE otherwise the offset is wrong
2559 if($.browser.msie) {
2560 var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2561 var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2562 $(this).children(".structure_actions_dropdown").offset({
2564 left: left_offset_IE });
2567 .mouseleave(function() {
2568 $(this).children(".structure_actions_dropdown").hide();
2569 if($.browser.msie && $.browser.version == "6.0") {
2570 $("iframe[class='IE_hack']").hide();
2576 $(document).ready(function(){
2577 PMA_convertFootnotesToTooltips();
2581 * Ensures indexes names are valid according to their type and, for a primary
2582 * key, lock index name to 'PRIMARY'
2583 * @param string form_id Variable which parses the form name as
2585 * @return boolean false if there is no index form, true else
2587 function checkIndexName(form_id)
2589 if ($("#"+form_id).length == 0) {
2593 // Gets the elements pointers
2594 var $the_idx_name = $("#input_index_name");
2595 var $the_idx_type = $("#select_index_type");
2597 // Index is a primary key
2598 if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2599 $the_idx_name.attr("value", 'PRIMARY');
2600 $the_idx_name.attr("disabled", true);
2605 if ($the_idx_name.attr("value") == 'PRIMARY') {
2606 $the_idx_name.attr("value", '');
2608 $the_idx_name.attr("disabled", false);
2612 } // end of the 'checkIndexName()' function
2615 * function to convert the footnotes to tooltips
2617 * @param jquery-Object $div a div jquery object which specifies the
2618 * domain for searching footnootes. If we
2619 * ommit this parameter the function searches
2620 * the footnotes in the whole body
2622 function PMA_convertFootnotesToTooltips($div)
2624 // Hide the footnotes from the footer (which are displayed for
2625 // JavaScript-disabled browsers) since the tooltip is sufficient
2627 if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2628 $div = $("#serverinfo").parent();
2631 $footnotes = $div.find(".footnotes");
2634 $footnotes.find('span').each(function() {
2635 $(this).children("sup").remove();
2637 // The border and padding must be removed otherwise a thin yellow box remains visible
2638 $footnotes.css("border", "none");
2639 $footnotes.css("padding", "0px");
2641 // Replace the superscripts with the help icon
2642 $div.find("sup.footnotemarker").hide();
2643 $div.find("img.footnotemarker").show();
2645 $div.find("img.footnotemarker").each(function() {
2646 var img_class = $(this).attr("class");
2647 /** img contains two classes, as example "footnotemarker footnote_1".
2648 * We split it by second class and take it for the id of span
2650 img_class = img_class.split(" ");
2651 for (i = 0; i < img_class.length; i++) {
2652 if (img_class[i].split("_")[0] == "footnote") {
2653 var span_id = img_class[i].split("_")[1];
2657 * Now we get the #id of the span with span_id variable. As an example if we
2658 * initially get the img class as "footnotemarker footnote_2", now we get
2659 * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2661 var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2663 content: tooltip_text,
2665 hide: { delay: 1000 },
2666 style: { background: '#ffffcc' }
2671 function menuResize()
2673 var cnt = $('#topmenu');
2674 var wmax = cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2675 var submenu = cnt.find('.submenu');
2676 var submenu_w = submenu.outerWidth(true);
2677 var submenu_ul = submenu.find('ul');
2678 var li = cnt.find('> li');
2679 var li2 = submenu_ul.find('li');
2680 var more_shown = li2.length > 0;
2681 var w = more_shown ? submenu_w : 0;
2685 for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2687 var el_width = el.outerWidth(true);
2688 el.data('width', el_width);
2692 if (w + submenu_w < wmax) {
2696 w -= $(li[i-1]).data('width');
2702 if (hide_start > 0) {
2703 for (var i = hide_start; i < li.length-1; i++) {
2704 $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2706 submenu.addClass('shown');
2707 } else if (more_shown) {
2709 // nothing hidden, maybe something can be restored
2710 for (var i = 0; i < li2.length; i++) {
2711 //console.log(li2[i], submenu_w);
2712 w += $(li2[i]).data('width');
2713 // item fits or (it is the last item and it would fit if More got removed)
2714 if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2715 $(li2[i]).insertBefore(submenu);
2716 if (i == li2.length-1) {
2717 submenu.removeClass('shown');
2724 if (submenu.find('.tabactive').length) {
2725 submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2727 submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2732 var topmenu = $('#topmenu');
2733 if (topmenu.length == 0) {
2736 // create submenu container
2737 var link = $('<a />', {href: '#', 'class': 'tab'})
2738 .text(PMA_messages['strMore'])
2739 .click(function(e) {
2742 var img = topmenu.find('li:first-child img');
2744 img.clone().attr('class', 'icon ic_b_more').prependTo(link);
2746 var submenu = $('<li />', {'class': 'submenu'})
2748 .append($('<ul />'))
2749 .mouseenter(function() {
2750 if ($(this).find('ul .tabactive').length == 0) {
2751 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2754 .mouseleave(function() {
2755 if ($(this).find('ul .tabactive').length == 0) {
2756 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2759 topmenu.append(submenu);
2761 // populate submenu and register resize event
2762 $(window).resize(menuResize);
2767 * Get the row number from the classlist (for example, row_1)
2769 function PMA_getRowNumber(classlist)
2771 return parseInt(classlist.split(/\s+row_/)[1]);
2775 * Changes status of slider
2777 function PMA_set_status_label(id)
2779 if ($('#' + id).css('display') == 'none') {
2780 $('#anchor_status_' + id).text('+ ');
2782 $('#anchor_status_' + id).text('- ');
2787 * Initializes slider effect.
2789 function PMA_init_slider()
2791 $('.pma_auto_slider').each(function(idx, e) {
2792 if ($(e).hasClass('slider_init_done')) return;
2793 $(e).addClass('slider_init_done');
2794 $('<span id="anchor_status_' + e.id + '"></span>')
2796 PMA_set_status_label(e.id);
2798 $('<a href="#' + e.id + '" id="anchor_' + e.id + '">' + e.title + '</a>')
2801 $('#' + e.id).toggle('clip', function() {
2802 PMA_set_status_label(e.id);
2810 * var toggleButton This is a function that creates a toggle
2811 * sliding button given a jQuery reference
2812 * to the correct DOM element
2814 var toggleButton = function ($obj) {
2815 // In rtl mode the toggle switch is flipped horizontally
2816 // so we need to take that into account
2817 if ($('.text_direction', $obj).text() == 'ltr') {
2818 var right = 'right';
2823 * var h Height of the button, used to scale the
2824 * background image and position the layers
2826 var h = $obj.height();
2827 $('img', $obj).height(h);
2828 $('table', $obj).css('bottom', h-1);
2830 * var on Width of the "ON" part of the toggle switch
2831 * var off Width of the "OFF" part of the toggle switch
2833 var on = $('.toggleOn', $obj).width();
2834 var off = $('.toggleOff', $obj).width();
2835 // Make the "ON" and "OFF" parts of the switch the same size
2836 $('.toggleOn > div', $obj).width(Math.max(on, off));
2837 $('.toggleOff > div', $obj).width(Math.max(on, off));
2839 * var w Width of the central part of the switch
2841 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
2842 // Resize the central part of the switch on the top
2843 // layer to match the background
2844 $('table td:nth-child(2) > div', $obj).width(w);
2846 * var imgw Width of the background image
2847 * var tblw Width of the foreground layer
2848 * var offset By how many pixels to move the background
2849 * image, so that it matches the top layer
2851 var imgw = $('img', $obj).width();
2852 var tblw = $('table', $obj).width();
2853 var offset = parseInt(((imgw - tblw) / 2), 10);
2854 // Move the background to match the layout of the top layer
2855 $obj.find('img').css(right, offset);
2857 * var offw Outer width of the "ON" part of the toggle switch
2858 * var btnw Outer width of the central part of the switch
2860 var offw = $('.toggleOff', $obj).outerWidth();
2861 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
2862 // Resize the main div so that exactly one side of
2863 // the switch plus the central part fit into it.
2864 $obj.width(offw + btnw + 2);
2866 * var move How many pixels to move the
2867 * switch by when toggling
2869 var move = $('.toggleOff', $obj).outerWidth();
2870 // If the switch is initialized to the
2871 // OFF state we need to move it now.
2872 if ($('.container', $obj).hasClass('off')) {
2873 if (right == 'right') {
2874 $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
2876 $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
2879 // Attach an 'onclick' event to the switch
2880 $('.container', $obj).click(function () {
2881 if ($(this).hasClass('isActive')) {
2884 $(this).addClass('isActive');
2886 var $msg = PMA_ajaxShowMessage(PMA_messages['strLoading']);
2887 var $container = $(this);
2888 var callback = $('.callback', this).text();
2889 // Perform the actual toggle
2890 if ($(this).hasClass('on')) {
2891 if (right == 'right') {
2892 var operator = '-=';
2894 var operator = '+=';
2896 var url = $(this).find('.toggleOff > span').text();
2897 var removeClass = 'on';
2898 var addClass = 'off';
2900 if (right == 'right') {
2901 var operator = '+=';
2903 var operator = '-=';
2905 var url = $(this).find('.toggleOn > span').text();
2906 var removeClass = 'off';
2907 var addClass = 'on';
2909 $.post(url, {'ajax_request': true}, function(data) {
2910 if(data.success == true) {
2911 PMA_ajaxRemoveMessage($msg);
2913 .removeClass(removeClass)
2915 .animate({'left': operator + move + 'px'}, function () {
2916 $container.removeClass('isActive');
2920 PMA_ajaxShowMessage(data.error);
2921 $container.removeClass('isActive');
2928 * Initialise all toggle buttons
2930 $(window).load(function () {
2931 $('.toggleAjax').each(function () {
2934 .find('.toggleButton')
2935 toggleButton($(this));
2942 $(document).ready(function() {
2943 $('.vpointer').live('hover',
2946 var $this_td = $(this);
2947 var row_num = PMA_getRowNumber($this_td.attr('class'));
2948 // for all td of the same vertical row, toggle hover
2949 $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2952 }) // end of $(document).ready() for vertical pointer
2954 $(document).ready(function() {
2958 $('.vmarker').live('click', function(e) {
2959 // do not trigger when clicked on anchor
2960 if ($(e.target).is('a, img, a *')) {
2964 var $this_td = $(this);
2965 var row_num = PMA_getRowNumber($this_td.attr('class'));
2967 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
2969 var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
2970 if ($checkbox.length) {
2971 // checkbox in a row, add or remove class depending on checkbox state
2972 var checked = $checkbox.attr('checked');
2973 if (!$(e.target).is(':checkbox, label')) {
2975 $checkbox.attr('checked', checked);
2977 // for all td of the same vertical row, toggle the marked class
2979 $('.vmarker').filter('.row_' + row_num).addClass('marked');
2981 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
2984 // normaln data table, just toggle class
2985 $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
2990 * Reveal visual builder anchor
2993 $('#visual_builder_anchor').show();
2996 * Page selector in db Structure (non-AJAX)
2998 $('#tableslistcontainer').find('#pageselector').live('change', function() {
2999 $(this).parent("form").submit();
3003 * Page selector in navi panel (non-AJAX)
3005 $('#navidbpageselector').find('#pageselector').live('change', function() {
3006 $(this).parent("form").submit();
3010 * Page selector in browse_foreigners windows (non-AJAX)
3012 $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3013 $(this).closest("form").submit();
3017 * Load version information asynchronously.
3019 if ($('.jsversioncheck').length > 0) {
3021 var s = document.createElement('script');
3022 s.type = 'text/javascript';
3024 s.src = 'http://www.phpmyadmin.net/home_page/version.js';
3025 s.onload = PMA_current_version;
3026 var x = document.getElementsByTagName('script')[0];
3027 x.parentNode.insertBefore(s, x);
3037 * Enables the text generated by PMA_linkOrButton() to be clickable
3039 $('a[class~="formLinkSubmit"]').live('click',function(e) {
3041 if($(this).attr('href').indexOf('=') != -1) {
3042 var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3043 $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3045 $(this).parents('form').submit();
3049 $('#update_recent_tables').ready(function() {
3050 if (window.parent.frame_navigation != undefined
3051 && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3053 window.parent.frame_navigation.PMA_reloadRecentTable();
3057 }) // end of $(document).ready()
3060 * Creates a message inside an object with a sliding effect
3062 * @param msg A string containing the text to display
3063 * @param $obj a jQuery object containing the reference
3064 * to the element where to put the message
3065 * This is optional, if no element is
3066 * provided, one will be created below the
3067 * navigation links at the top of the page
3069 * @return bool True on success, false on failure
3071 function PMA_slidingMessage(msg, $obj)
3073 if (msg == undefined || msg.length == 0) {
3074 // Don't show an empty message
3077 if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3078 // If the second argument was not supplied,
3079 // we might have to create a new DOM node.
3080 if ($('#PMA_slidingMessage').length == 0) {
3081 $('#topmenucontainer')
3082 .after('<span id="PMA_slidingMessage" '
3083 + 'style="display: inline-block;"></span>');
3085 $obj = $('#PMA_slidingMessage');
3087 if ($obj.has('div').length > 0) {
3088 // If there already is a message inside the
3089 // target object, we must get rid of it
3093 .fadeOut(function () {
3098 .append('<div style="display: none;">' + msg + '</div>')
3100 height: $obj.find('div').first().height()
3107 // Object does not already have a message
3108 // inside it, so we simply slide it down
3111 .html('<div style="display: none;">' + msg + '</div>')
3123 // Set the height of the parent
3124 // to the height of the child
3135 } // end PMA_slidingMessage()
3138 * Attach Ajax event handlers for Drop Table.
3140 * @uses $.PMA_confirm()
3141 * @uses PMA_ajaxShowMessage()
3142 * @uses window.parent.refreshNavigation()
3143 * @uses window.parent.refreshMain()
3144 * @see $cfg['AjaxEnable']
3146 $(document).ready(function() {
3147 $("#drop_tbl_anchor").live('click', function(event) {
3148 event.preventDefault();
3150 //context is top.frame_content, so we need to use window.parent.table to access the table var
3152 * @var question String containing the question to be asked for confirmation
3154 var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + window.parent.table;
3156 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3158 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3159 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3160 //Database deleted successfully, refresh both the frames
3161 window.parent.refreshNavigation();
3162 window.parent.refreshMain();
3164 }); // end $.PMA_confirm()
3165 }); //end of Drop Table Ajax action
3166 }) // end of $(document).ready() for Drop Table
3169 * Attach Ajax event handlers for Truncate Table.
3171 * @uses $.PMA_confirm()
3172 * @uses PMA_ajaxShowMessage()
3173 * @uses window.parent.refreshNavigation()
3174 * @uses window.parent.refreshMain()
3175 * @see $cfg['AjaxEnable']
3177 $(document).ready(function() {
3178 $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3179 event.preventDefault();
3181 //context is top.frame_content, so we need to use window.parent.table to access the table var
3183 * @var question String containing the question to be asked for confirmation
3185 var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + window.parent.table;
3187 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3189 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3190 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3191 if ($("#sqlqueryresults").length != 0) {
3192 $("#sqlqueryresults").remove();
3194 if ($("#result_query").length != 0) {
3195 $("#result_query").remove();
3197 if (data.success == true) {
3198 PMA_ajaxShowMessage(data.message);
3199 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
3200 $("#sqlqueryresults").html(data.sql_query);
3202 var $temp_div = $("<div id='temp_div'></div>")
3203 $temp_div.html(data.error);
3204 var $error = $temp_div.find("code").addClass("error");
3205 PMA_ajaxShowMessage($error);
3208 }); // end $.PMA_confirm()
3209 }); //end of Truncate Table Ajax action
3210 }) // end of $(document).ready() for Truncate Table
3213 * Attach CodeMirror2 editor to SQL edit area.
3215 $(document).ready(function() {
3216 var elm = $('#sqlquery');
3217 if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3218 codemirror_editor = CodeMirror.fromTextArea(elm[0], {lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-mysql"});
3223 * jQuery plugin to cancel selection in HTML code.
3226 $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3227 var prevent = (p == null) ? true : p;
3229 return this.each(function () {
3230 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3233 else if ($.browser.mozilla) {
3234 $(this).css('MozUserSelect', 'none');
3235 $('body').trigger('focus');
3236 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3239 else $(this).attr('unselectable', 'on');
3242 return this.each(function () {
3243 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3244 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3245 else if ($.browser.opera) $(this).unbind('mousedown');
3246 else $(this).removeAttr('unselectable', 'on');
3253 * Create default PMA tooltip for the element specified. The default appearance
3254 * can be overriden by specifying optional "options" parameter (see qTip options).
3256 function PMA_createqTip($elements, content, options)
3258 if ($('#no_hint').length > 0) {
3266 tooltip: 'normalqTip',
3267 content: 'normalqTipContent'
3273 corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3274 adjust: { x: 10, y: 20 }
3291 $elements.qtip($.extend(true, o, options));
3295 * Return value of a cell in a table.
3297 function PMA_getCellValue(td) {
3298 if ($(td).is('.null')) {
3300 } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3301 return $(td).data('original_data');
3303 return $(td).text();
3307 /* Loads a js file, an array may be passed as well */
3308 loadJavascript=function(file) {
3309 if($.isArray(file)) {
3310 for(var i=0; i<file.length; i++) {
3311 $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3314 $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3318 $(document).ready(function() {
3322 $('a.themeselect').live('click', function(e) {
3326 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3332 * Automatic form submission on change.
3334 $('.autosubmit').change(function(e) {
3335 e.target.form.submit();
3341 $('.take_theme').click(function(e) {
3342 var what = this.name;
3343 if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3344 window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3345 window.opener.document.forms['setTheme'].submit();
3354 * Clear text selection
3356 function PMA_clearSelection() {
3357 if(document.selection && document.selection.empty) {
3358 document.selection.empty();
3359 } else if(window.getSelection) {
3360 var sel = window.getSelection();
3361 if(sel.empty) sel.empty();
3362 if(sel.removeAllRanges) sel.removeAllRanges();