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 * Returns browser's viewport size, without accounting for scrollbars
37 function getWindowSize(wnd) {
38 var vp = wnd || window;
40 // most browsers || IE6-8 strict || failsafe
41 width: vp.innerWidth || (vp.documentElement !== undefined ? vp.documentElement.clientWidth : false) || $(vp).width(),
42 height: vp.innerHeight || (vp.documentElement !== undefined ? vp.documentElement.clientHeight : false) || $(vp).height()
47 * Add a hidden field to the form to indicate that this will be an
48 * Ajax request (only if this hidden field does not exist)
50 * @param object the form
52 function PMA_prepareForAjaxRequest($form)
54 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
55 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
60 * Generate a new password and copy it to the password input areas
62 * @param object the form that holds the password fields
64 * @return boolean always true
66 function suggestPassword(passwd_form)
68 // restrict the password to just letters and numbers to avoid problems:
69 // "editors and viewers regard the password as multiple words and
70 // things like double click no longer work"
71 var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
72 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
73 var passwd = passwd_form.generated_pw;
76 for ( i = 0; i < passwordlength; i++ ) {
77 passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
79 passwd_form.text_pma_pw.value = passwd.value;
80 passwd_form.text_pma_pw2.value = passwd.value;
85 * Version string to integer conversion.
87 function parseVersionString (str)
89 if (typeof(str) != 'string') { return false; }
91 // Parse possible alpha/beta/rc/
92 var state = str.split('-');
93 if (state.length >= 2) {
94 if (state[1].substr(0, 2) == 'rc') {
95 add = - 20 - parseInt(state[1].substr(2));
96 } else if (state[1].substr(0, 4) == 'beta') {
97 add = - 40 - parseInt(state[1].substr(4));
98 } else if (state[1].substr(0, 5) == 'alpha') {
99 add = - 60 - parseInt(state[1].substr(5));
100 } else if (state[1].substr(0, 3) == 'dev') {
101 /* We don't handle dev, it's git snapshot */
106 var x = str.split('.');
107 // Use 0 for non existing parts
108 var maj = parseInt(x[0]) || 0;
109 var min = parseInt(x[1]) || 0;
110 var pat = parseInt(x[2]) || 0;
111 var hotfix = parseInt(x[3]) || 0;
112 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
116 * Indicates current available version on main page.
118 function PMA_current_version()
120 var current = parseVersionString(pmaversion);
121 var latest = parseVersionString(PMA_latest_version);
122 var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
123 if (latest > current) {
124 var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
125 if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
126 /* Security update */
131 $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
133 if (latest == current) {
134 version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
136 $('#li_pma_version').append(version_information_message);
140 * for libraries/display_change_password.lib.php
141 * libraries/user_password.php
145 function displayPasswordGenerateButton()
147 $('#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>');
148 $('#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>');
152 * Adds a date/time picker to an element
154 * @param object $this_element a jQuery object pointing to the element
156 function PMA_addDatepicker($this_element, options)
158 var showTimeOption = false;
159 if ($this_element.is('.datetimefield')) {
160 showTimeOption = true;
163 var defaultOptions = {
165 buttonImage: themeCalendarImage, // defined in js/messages.php
166 buttonImageOnly: true,
170 showTimepicker: showTimeOption,
171 showButtonPanel: false,
172 dateFormat: 'yy-mm-dd', // yy means year with four digits
173 timeFormat: 'hh:mm:ss',
174 altFieldTimeOnly: false,
176 beforeShow: function(input, inst) {
177 // Remember that we came from the datepicker; this is used
178 // in tbl_change.js by verificationsAfterFieldChange()
179 $this_element.data('comes_from', 'datepicker');
181 // Fix wrong timepicker z-index, doesn't work without timeout
182 setTimeout(function() {
183 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
188 $this_element.datetimepicker($.extend(defaultOptions, options));
192 * selects the content of a given object, f.e. a textarea
194 * @param object element element of which the content will be selected
195 * @param var lock variable which holds the lock for this element
196 * or true, if no lock exists
197 * @param boolean only_once if true this is only done once
198 * f.e. only on first focus
200 function selectContent( element, lock, only_once )
202 if ( only_once && only_once_elements[element.name] ) {
206 only_once_elements[element.name] = true;
216 * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
217 * This function is called while clicking links
219 * @param object the link
220 * @param object the sql query to submit
222 * @return boolean whether to run the query or not
224 function confirmLink(theLink, theSqlQuery)
226 // Confirmation is not required in the configuration file
227 // or browser is Opera (crappy js implementation)
228 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
232 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
234 if ( $(theLink).hasClass('formLinkSubmit') ) {
235 var name = 'is_js_confirmed';
236 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
237 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
240 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
241 } else if ( typeof(theLink.href) != 'undefined' ) {
242 theLink.href += '&is_js_confirmed=1';
243 } else if ( typeof(theLink.form) != 'undefined' ) {
244 theLink.form.action += '?is_js_confirmed=1';
249 } // end of the 'confirmLink()' function
253 * Displays a confirmation box before doing some action
255 * @param object the message to display
257 * @return boolean whether to run the query or not
259 * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
260 * and replace with a jQuery equivalent
262 function confirmAction(theMessage)
264 // TODO: Confirmation is not required in the configuration file
265 // or browser is Opera (crappy js implementation)
266 if (typeof(window.opera) != 'undefined') {
270 var is_confirmed = confirm(theMessage);
273 } // end of the 'confirmAction()' function
277 * Displays an error message if a "DROP DATABASE" statement is submitted
278 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
279 * sumitting it if required.
280 * This function is called by the 'checkSqlQuery()' js function.
282 * @param object the form
283 * @param object the sql query textarea
285 * @return boolean whether to run the query or not
287 * @see checkSqlQuery()
289 function confirmQuery(theForm1, sqlQuery1)
291 // Confirmation is not required in the configuration file
292 if (PMA_messages['strDoYouReally'] == '') {
296 // "DROP DATABASE" statement isn't allowed
297 if (PMA_messages['strNoDropDatabases'] != '') {
298 var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
299 if (drop_re.test(sqlQuery1.value)) {
300 alert(PMA_messages['strNoDropDatabases']);
307 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
309 // TODO: find a way (if possible) to use the parser-analyser
310 // for this kind of verification
311 // For now, I just added a ^ to check for the statement at
312 // beginning of expression
314 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
315 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
316 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
317 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
319 if (do_confirm_re_0.test(sqlQuery1.value)
320 || do_confirm_re_1.test(sqlQuery1.value)
321 || do_confirm_re_2.test(sqlQuery1.value)
322 || do_confirm_re_3.test(sqlQuery1.value)) {
323 var message = (sqlQuery1.value.length > 100)
324 ? sqlQuery1.value.substr(0, 100) + '\n ...'
326 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
327 // statement is confirmed -> update the
328 // "is_js_confirmed" form field so the confirm test won't be
329 // run on the server side and allows to submit the form
331 theForm1.elements['is_js_confirmed'].value = 1;
334 // statement is rejected -> do not submit the form
339 } // end if (handle confirm box result)
340 } // end if (display confirm box)
343 } // end of the 'confirmQuery()' function
347 * Displays a confirmation box before disabling the BLOB repository for a given database.
348 * This function is called while clicking links
350 * @param object the database
352 * @return boolean whether to disable the repository or not
354 function confirmDisableRepository(theDB)
356 // Confirmation is not required in the configuration file
357 // or browser is Opera (crappy js implementation)
358 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
362 var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
365 } // end of the 'confirmDisableBLOBRepository()' function
369 * Displays an error message if the user submitted the sql query form with no
370 * sql query, else checks for "DROP/DELETE/ALTER" statements
372 * @param object the form
374 * @return boolean always false
376 * @see confirmQuery()
378 function checkSqlQuery(theForm)
380 var sqlQuery = theForm.elements['sql_query'];
383 var space_re = new RegExp('\\s+');
384 if (typeof(theForm.elements['sql_file']) != 'undefined' &&
385 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
388 if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
389 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
392 if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
393 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
394 theForm.elements['id_bookmark'].selectedIndex != 0
398 // Checks for "DROP/DELETE/ALTER" statements
399 if (sqlQuery.value.replace(space_re, '') != '') {
400 if (confirmQuery(theForm, sqlQuery)) {
411 alert(PMA_messages['strFormEmpty']);
417 } // end of the 'checkSqlQuery()' function
420 * Check if a form's element is empty.
421 * An element containing only spaces is also considered empty
423 * @param object the form
424 * @param string the name of the form field to put the focus on
426 * @return boolean whether the form field is empty or not
428 function emptyCheckTheField(theForm, theFieldName)
430 var theField = theForm.elements[theFieldName];
431 var space_re = new RegExp('\\s+');
432 return (theField.value.replace(space_re, '') == '') ? 1 : 0;
433 } // end of the 'emptyCheckTheField()' function
437 * Check whether a form field is empty or not
439 * @param object the form
440 * @param string the name of the form field to put the focus on
442 * @return boolean whether the form field is empty or not
444 function emptyFormElements(theForm, theFieldName)
446 var theField = theForm.elements[theFieldName];
447 var isEmpty = emptyCheckTheField(theForm, theFieldName);
451 } // end of the 'emptyFormElements()' function
455 * Ensures a value submitted in a form is numeric and is in a range
457 * @param object the form
458 * @param string the name of the form field to check
459 * @param integer the minimum authorized value
460 * @param integer the maximum authorized value
462 * @return boolean whether a valid number has been submitted or not
464 function checkFormElementInRange(theForm, theFieldName, message, min, max)
466 var theField = theForm.elements[theFieldName];
467 var val = parseInt(theField.value);
469 if (typeof(min) == 'undefined') {
472 if (typeof(max) == 'undefined') {
473 max = Number.MAX_VALUE;
479 alert(PMA_messages['strNotNumber']);
483 // It's a number but it is not between min and max
484 else if (val < min || val > max) {
486 alert(message.replace('%d', val));
490 // It's a valid number
492 theField.value = val;
496 } // end of the 'checkFormElementInRange()' function
499 function checkTableEditForm(theForm, fieldsCnt)
501 // TODO: avoid sending a message if user just wants to add a line
502 // on the form but has not completed at least one field name
504 var atLeastOneField = 0;
505 var i, elm, elm2, elm3, val, id;
507 for (i=0; i<fieldsCnt; i++)
509 id = "#field_" + i + "_2";
512 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
513 elm2 = $("#field_" + i + "_3");
514 val = parseInt(elm2.val());
515 elm3 = $("#field_" + i + "_1");
516 if (isNaN(val) && elm3.val() != "") {
518 alert(PMA_messages['strNotNumber']);
524 if (atLeastOneField == 0) {
525 id = "field_" + i + "_1";
526 if (!emptyCheckTheField(theForm, id)) {
531 if (atLeastOneField == 0) {
532 var theField = theForm.elements["field_0_1"];
533 alert(PMA_messages['strFormEmpty']);
538 // at least this section is under jQuery
539 if ($("input.textfield[name='table']").val() == "") {
540 alert(PMA_messages['strFormEmpty']);
541 $("input.textfield[name='table']").focus();
547 } // enf of the 'checkTableEditForm()' function
551 * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
552 * checkboxes is consistant
554 * @param object the form
555 * @param string a code for the action that causes this function to be run
557 * @return boolean always true
559 function checkTransmitDump(theForm, theAction)
561 var formElts = theForm.elements;
563 // 'zipped' option has been checked
564 if (theAction == 'zip' && formElts['zip'].checked) {
565 if (!formElts['asfile'].checked) {
566 theForm.elements['asfile'].checked = true;
568 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
569 theForm.elements['gzip'].checked = false;
571 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
572 theForm.elements['bzip'].checked = false;
575 // 'gzipped' option has been checked
576 else if (theAction == 'gzip' && formElts['gzip'].checked) {
577 if (!formElts['asfile'].checked) {
578 theForm.elements['asfile'].checked = true;
580 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
581 theForm.elements['zip'].checked = false;
583 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
584 theForm.elements['bzip'].checked = false;
587 // 'bzipped' option has been checked
588 else if (theAction == 'bzip' && formElts['bzip'].checked) {
589 if (!formElts['asfile'].checked) {
590 theForm.elements['asfile'].checked = true;
592 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
593 theForm.elements['zip'].checked = false;
595 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
596 theForm.elements['gzip'].checked = false;
599 // 'transmit' option has been unchecked
600 else if (theAction == 'transmit' && !formElts['asfile'].checked) {
601 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
602 theForm.elements['zip'].checked = false;
604 if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
605 theForm.elements['gzip'].checked = false;
607 if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
608 theForm.elements['bzip'].checked = false;
613 } // end of the 'checkTransmitDump()' function
615 $(document).ready(function() {
617 * Row marking in horizontal mode (use "live" so that it works also for
618 * next pages reached via AJAX); a tr may have the class noclick to remove
621 $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
622 // do not trigger when clicked on anchor
623 if ($(e.target).is('a, img, a *')) {
628 // make the table unselectable (to prevent default highlighting when shift+click)
629 //$tr.parents('table').noSelect();
631 if (!e.shiftKey || last_clicked_row == -1) {
634 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
635 var $checkbox = $tr.find(':checkbox');
636 if ($checkbox.length) {
637 // checkbox in a row, add or remove class depending on checkbox state
638 var checked = $checkbox.attr('checked');
639 if (!$(e.target).is(':checkbox, label')) {
641 $checkbox.attr('checked', checked);
644 $tr.addClass('marked');
646 $tr.removeClass('marked');
648 last_click_checked = checked;
650 // normaln data table, just toggle class
651 $tr.toggleClass('marked');
652 last_click_checked = false;
655 // remember the last clicked row
656 last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
657 last_shift_clicked_row = -1;
659 // handle the shift click
660 PMA_clearSelection();
663 // clear last shift click result
664 if (last_shift_clicked_row >= 0) {
665 if (last_shift_clicked_row >= last_clicked_row) {
666 start = last_clicked_row;
667 end = last_shift_clicked_row;
669 start = last_shift_clicked_row;
670 end = last_clicked_row;
672 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
673 .slice(start, end + 1)
674 .removeClass('marked')
676 .attr('checked', false);
679 // handle new shift click
680 var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
681 if (curr_row >= last_clicked_row) {
682 start = last_clicked_row;
686 end = last_clicked_row;
688 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
689 .slice(start, end + 1)
692 .attr('checked', true);
694 // remember the last shift clicked row
695 last_shift_clicked_row = curr_row;
700 * Add a date/time picker to each element that needs it
701 * (only when timepicker.js is loaded)
703 if ($.timepicker != undefined) {
704 $('.datefield, .datetimefield').each(function() {
705 PMA_addDatepicker($(this));
711 * True if last click is to check a row.
713 var last_click_checked = false;
716 * Zero-based index of last clicked row.
717 * Used to handle the shift + click event in the code above.
719 var last_clicked_row = -1;
722 * Zero-based index of last shift clicked row.
724 var last_shift_clicked_row = -1;
727 * Row highlighting in horizontal mode (use "live"
728 * so that it works also for pages reached via AJAX)
730 /*$(document).ready(function() {
731 $('tr.odd, tr.even').live('hover',function(event) {
733 $tr.toggleClass('hover',event.type=='mouseover');
734 $tr.children().toggleClass('hover',event.type=='mouseover');
739 * This array is used to remember mark status of rows in browse mode
741 var marked_row = new Array;
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 markAllRows( container_id )
752 $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
753 .parents("tr").addClass("marked");
758 * marks all rows and selects its first checkbox inside the given element
759 * the given element is usaly a table or a div containing the table or tables
761 * @param container DOM element
763 function unMarkAllRows( container_id )
766 $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
767 .parents("tr").removeClass("marked");
772 * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
774 * @param string container_id the container id
775 * @param boolean state new value for checkbox (true or false)
776 * @return boolean always true
778 function setCheckboxes( container_id, state )
782 $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
785 $("#"+container_id).find("input:checkbox").removeAttr('checked');
789 } // end of the 'setCheckboxes()' function
792 * Checks/unchecks all options of a <select> element
794 * @param string the form name
795 * @param string the element name
796 * @param boolean whether to check or to uncheck options
798 * @return boolean always true
800 function setSelectOptions(the_form, the_select, do_check)
802 $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
804 } // end of the 'setSelectOptions()' function
807 * Sets current value for query box.
809 function setQuery(query)
811 if (codemirror_editor) {
812 codemirror_editor.setValue(query);
814 document.sqlform.sql_query.value = query;
820 * Create quick sql statements.
823 function insertQuery(queryType)
825 if (queryType == "clear") {
830 var myQuery = document.sqlform.sql_query;
832 var myListBox = document.sqlform.dummy;
833 var table = document.sqlform.table.value;
835 if (myListBox.options.length > 0) {
836 sql_box_locked = true;
841 for (var i=0; i < myListBox.options.length; i++) {
848 chaineAj += myListBox.options[i].value;
849 valDis += "[value-" + NbSelect + "]";
850 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
852 if (queryType == "selectall") {
853 query = "SELECT * FROM `" + table + "` WHERE 1";
854 } else if (queryType == "select") {
855 query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
856 } else if (queryType == "insert") {
857 query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
858 } else if (queryType == "update") {
859 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
860 } else if(queryType == "delete") {
861 query = "DELETE FROM `" + table + "` WHERE 1";
864 sql_box_locked = false;
870 * Inserts multiple fields.
873 function insertValueQuery()
875 var myQuery = document.sqlform.sql_query;
876 var myListBox = document.sqlform.dummy;
878 if(myListBox.options.length > 0) {
879 sql_box_locked = true;
882 for(var i=0; i<myListBox.options.length; i++) {
883 if (myListBox.options[i].selected) {
888 chaineAj += myListBox.options[i].value;
892 /* CodeMirror support */
893 if (codemirror_editor) {
894 codemirror_editor.replaceSelection(chaineAj);
896 } else if (document.selection) {
898 sel = document.selection.createRange();
900 document.sqlform.insert.focus();
902 //MOZILLA/NETSCAPE support
903 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
904 var startPos = document.sqlform.sql_query.selectionStart;
905 var endPos = document.sqlform.sql_query.selectionEnd;
906 var chaineSql = document.sqlform.sql_query.value;
908 myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
910 myQuery.value += chaineAj;
912 sql_box_locked = false;
917 * listbox redirection
919 function goToUrl(selObj, goToLocation)
921 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
925 * Refresh the WYSIWYG scratchboard after changes have been made
927 function refreshDragOption(e)
929 var elm = $('#' + e);
930 if (elm.css('visibility') == 'visible') {
937 * Refresh/resize the WYSIWYG scratchboard
939 function refreshLayout()
941 var elm = $('#pdflayout')
942 var orientation = $('#orientation_opt').val();
943 if($('#paper_opt').length==1){
944 var paper = $('#paper_opt').val();
948 if (orientation == 'P') {
955 elm.css('width', pdfPaperSize(paper, posa) + 'px');
956 elm.css('height', pdfPaperSize(paper, posb) + 'px');
960 * Show/hide the WYSIWYG scratchboard
962 function ToggleDragDrop(e)
964 var elm = $('#' + e);
965 if (elm.css('visibility') == 'hidden') {
966 PDFinit(); /* Defined in pdf_pages.php */
967 elm.css('visibility', 'visible');
968 elm.css('display', 'block');
969 $('#showwysiwyg').val('1')
971 elm.css('visibility', 'hidden');
972 elm.css('display', 'none');
973 $('#showwysiwyg').val('0')
978 * PDF scratchboard: When a position is entered manually, update
979 * the fields inside the scratchboard.
981 function dragPlace(no, axis, value)
983 var elm = $('#table_' + no);
985 elm.css('left', value + 'px');
987 elm.css('top', value + 'px');
992 * Returns paper sizes for a given format
994 function pdfPaperSize(format, axis)
996 switch (format.toUpperCase()) {
998 if (axis == 'x') return 4767.87; else return 6740.79;
1001 if (axis == 'x') return 3370.39; else return 4767.87;
1004 if (axis == 'x') return 2383.94; else return 3370.39;
1007 if (axis == 'x') return 1683.78; else return 2383.94;
1010 if (axis == 'x') return 1190.55; else return 1683.78;
1013 if (axis == 'x') return 841.89; else return 1190.55;
1016 if (axis == 'x') return 595.28; else return 841.89;
1019 if (axis == 'x') return 419.53; else return 595.28;
1022 if (axis == 'x') return 297.64; else return 419.53;
1025 if (axis == 'x') return 209.76; else return 297.64;
1028 if (axis == 'x') return 147.40; else return 209.76;
1031 if (axis == 'x') return 104.88; else return 147.40;
1034 if (axis == 'x') return 73.70; else return 104.88;
1037 if (axis == 'x') return 2834.65; else return 4008.19;
1040 if (axis == 'x') return 2004.09; else return 2834.65;
1043 if (axis == 'x') return 1417.32; else return 2004.09;
1046 if (axis == 'x') return 1000.63; else return 1417.32;
1049 if (axis == 'x') return 708.66; else return 1000.63;
1052 if (axis == 'x') return 498.90; else return 708.66;
1055 if (axis == 'x') return 354.33; else return 498.90;
1058 if (axis == 'x') return 249.45; else return 354.33;
1061 if (axis == 'x') return 175.75; else return 249.45;
1064 if (axis == 'x') return 124.72; else return 175.75;
1067 if (axis == 'x') return 87.87; else return 124.72;
1070 if (axis == 'x') return 2599.37; else return 3676.54;
1073 if (axis == 'x') return 1836.85; else return 2599.37;
1076 if (axis == 'x') return 1298.27; else return 1836.85;
1079 if (axis == 'x') return 918.43; else return 1298.27;
1082 if (axis == 'x') return 649.13; else return 918.43;
1085 if (axis == 'x') return 459.21; else return 649.13;
1088 if (axis == 'x') return 323.15; else return 459.21;
1091 if (axis == 'x') return 229.61; else return 323.15;
1094 if (axis == 'x') return 161.57; else return 229.61;
1097 if (axis == 'x') return 113.39; else return 161.57;
1100 if (axis == 'x') return 79.37; else return 113.39;
1103 if (axis == 'x') return 2437.80; else return 3458.27;
1106 if (axis == 'x') return 1729.13; else return 2437.80;
1109 if (axis == 'x') return 1218.90; else return 1729.13;
1112 if (axis == 'x') return 864.57; else return 1218.90;
1115 if (axis == 'x') return 609.45; else return 864.57;
1118 if (axis == 'x') return 2551.18; else return 3628.35;
1121 if (axis == 'x') return 1814.17; else return 2551.18;
1124 if (axis == 'x') return 1275.59; else return 1814.17;
1127 if (axis == 'x') return 907.09; else return 1275.59;
1130 if (axis == 'x') return 637.80; else return 907.09;
1133 if (axis == 'x') return 612.00; else return 792.00;
1136 if (axis == 'x') return 612.00; else return 1008.00;
1139 if (axis == 'x') return 521.86; else return 756.00;
1142 if (axis == 'x') return 612.00; else return 936.00;
1150 * for playing media from the BLOB repository
1153 * @param var url_params main purpose is to pass the token
1154 * @param var bs_ref BLOB repository reference
1155 * @param var m_type type of BLOB repository media
1156 * @param var w_width width of popup window
1157 * @param var w_height height of popup window
1159 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1161 // if width not specified, use default
1162 if (w_width == undefined) {
1166 // if height not specified, use default
1167 if (w_height == undefined) {
1171 // open popup window (for displaying video/playing audio)
1172 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');
1176 * popups a request for changing MIME types for files in the BLOB repository
1178 * @param var db database name
1179 * @param var table table name
1180 * @param var reference BLOB repository reference
1181 * @param var current_mime_type current MIME type associated with BLOB repository reference
1183 function requestMIMETypeChange(db, table, reference, current_mime_type)
1185 // no mime type specified, set to default (nothing)
1186 if (undefined == current_mime_type) {
1187 current_mime_type = "";
1190 // prompt user for new mime type
1191 var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1193 // if new mime_type is specified and is not the same as the previous type, request for mime type change
1194 if (new_mime_type && new_mime_type != current_mime_type) {
1195 changeMIMEType(db, table, reference, new_mime_type);
1200 * changes MIME types for files in the BLOB repository
1202 * @param var db database name
1203 * @param var table table name
1204 * @param var reference BLOB repository reference
1205 * @param var mime_type new MIME type to be associated with BLOB repository reference
1207 function changeMIMEType(db, table, reference, mime_type)
1209 // specify url and parameters for jQuery POST
1210 var mime_chg_url = 'bs_change_mime_type.php';
1211 var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1214 jQuery.post(mime_chg_url, params);
1218 * Jquery Coding for inline editing SQL_QUERY
1220 $(document).ready(function(){
1221 $(".inline_edit_sql").live('click', function(){
1222 var $form = $(this).prev();
1223 var sql_query = $form.find("input[name='sql_query']").val();
1224 var $inner_sql = $(this).parent().prev().find('.inner_sql');
1225 var old_text = $inner_sql.html();
1227 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1228 new_content += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1229 new_content += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1230 $inner_sql.replaceWith(new_content);
1231 $(".btnSave").click(function(){
1232 var sql_query = $(this).prev().val();
1233 var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1234 .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1235 .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1236 .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1237 $fake_form.appendTo($('body')).submit();
1239 $(".btnDiscard").click(function(){
1240 $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1245 $('.sqlbutton').click(function(evt){
1246 insertQuery(evt.target.id);
1250 $("#export_type").change(function(){
1251 if($("#export_type").val()=='svg'){
1252 $("#show_grid_opt").attr("disabled","disabled");
1253 $("#orientation_opt").attr("disabled","disabled");
1254 $("#with_doc").attr("disabled","disabled");
1255 $("#show_table_dim_opt").removeAttr("disabled");
1256 $("#all_table_same_wide").removeAttr("disabled");
1257 $("#paper_opt").removeAttr("disabled","disabled");
1258 $("#show_color_opt").removeAttr("disabled","disabled");
1259 //$(this).css("background-color","yellow");
1260 }else if($("#export_type").val()=='dia'){
1261 $("#show_grid_opt").attr("disabled","disabled");
1262 $("#with_doc").attr("disabled","disabled");
1263 $("#show_table_dim_opt").attr("disabled","disabled");
1264 $("#all_table_same_wide").attr("disabled","disabled");
1265 $("#paper_opt").removeAttr("disabled","disabled");
1266 $("#show_color_opt").removeAttr("disabled","disabled");
1267 $("#orientation_opt").removeAttr("disabled","disabled");
1268 }else if($("#export_type").val()=='eps'){
1269 $("#show_grid_opt").attr("disabled","disabled");
1270 $("#orientation_opt").removeAttr("disabled");
1271 $("#with_doc").attr("disabled","disabled");
1272 $("#show_table_dim_opt").attr("disabled","disabled");
1273 $("#all_table_same_wide").attr("disabled","disabled");
1274 $("#paper_opt").attr("disabled","disabled");
1275 $("#show_color_opt").attr("disabled","disabled");
1277 }else if($("#export_type").val()=='pdf'){
1278 $("#show_grid_opt").removeAttr("disabled");
1279 $("#orientation_opt").removeAttr("disabled");
1280 $("#with_doc").removeAttr("disabled","disabled");
1281 $("#show_table_dim_opt").removeAttr("disabled","disabled");
1282 $("#all_table_same_wide").removeAttr("disabled","disabled");
1283 $("#paper_opt").removeAttr("disabled","disabled");
1284 $("#show_color_opt").removeAttr("disabled","disabled");
1290 $('#sqlquery').focus().keydown(function (e) {
1291 if (e.ctrlKey && e.keyCode == 13) {
1292 $("#sqlqueryform").submit();
1296 if ($('#input_username')) {
1297 if ($('#input_username').val() == '') {
1298 $('#input_username').focus();
1300 $('#input_password').focus();
1306 * Show a message on the top of the page for an Ajax request
1310 * 1) var $msg = PMA_ajaxShowMessage();
1311 * This will show a message that reads "Loading...". Such a message will not
1312 * disappear automatically and cannot be dismissed by the user. To remove this
1313 * message either the PMA_ajaxRemoveMessage($msg) function must be called or
1314 * another message must be show with PMA_ajaxShowMessage() function.
1316 * 2) var $msg = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1317 * This is a special case. The behaviour is same as above,
1318 * just with a different message
1320 * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
1321 * This will show a message that will disappear automatically and it can also
1322 * be dismissed by the user.
1324 * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
1325 * This will show a message that will not disappear automatically, but it
1326 * can be dismissed by the user after he has finished reading it.
1328 * @param string message string containing the message to be shown.
1329 * optional, defaults to 'Loading...'
1330 * @param mixed timeout number of milliseconds for the message to be visible
1331 * optional, defaults to 5000. If set to 'false', the
1332 * notification will never disappear
1333 * @return jQuery object jQuery Element that holds the message div
1334 * this object can be passed to PMA_ajaxRemoveMessage()
1335 * to remove the notification
1337 function PMA_ajaxShowMessage(message, timeout)
1340 * @var self_closing Whether the notification will automatically disappear
1342 var self_closing = true;
1344 * @var dismissable Whether the user will be able to remove
1345 * the notification by clicking on it
1347 var dismissable = true;
1348 // Handle the case when a empty data.message is passed.
1349 // We don't want the empty message
1350 if (message == '') {
1352 } else if (! message) {
1353 // If the message is undefined, show the default
1354 message = PMA_messages['strLoading'];
1355 dismissable = false;
1356 self_closing = false;
1357 } else if (message == PMA_messages['strProcessingRequest']) {
1358 // This is another case where the message should not disappear
1359 dismissable = false;
1360 self_closing = false;
1362 // Figure out whether (or after how long) to remove the notification
1363 if (timeout == undefined) {
1365 } else if (timeout === false) {
1366 self_closing = false;
1368 // Create a parent element for the AJAX messages, if necessary
1369 if ($('#loading_parent').length == 0) {
1370 $('<div id="loading_parent"></div>')
1373 // Update message count to create distinct message elements every time
1374 ajax_message_count++;
1375 // Remove all old messages, if any
1376 $(".ajax_notification[id^=ajax_message_num]").remove();
1378 * @var $retval a jQuery object containing the reference
1379 * to the created AJAX message
1382 '<span class="ajax_notification" id="ajax_message_num_'
1383 + ajax_message_count +
1387 .appendTo("#loading_parent")
1390 // If the notification is self-closing we should create a callback to remove it
1394 .fadeOut('medium', function() {
1395 if ($(this).is('.dismissable')) {
1396 // Here we should destroy the qtip instance, but
1397 // due to a bug in qtip's implementation we can
1398 // only hide it without throwing JS errors.
1399 $(this).qtip('hide');
1401 // Remove the notification
1405 // If the notification is dismissable we need to add the relevant class to it
1406 // and add a tooltip so that the users know that it can be removed
1408 $retval.addClass('dismissable').css('cursor', 'pointer');
1410 * @var qOpts Options for "Dismiss notification" tooltip
1414 effect: { length: 0 },
1418 effect: { length: 0 },
1423 * Add a tooltip to the notification to let the user know that (s)he
1424 * can dismiss the ajax notification by clicking on it.
1426 PMA_createqTip($retval, PMA_messages['strDismiss'], qOpts);
1433 * Removes the message shown for an Ajax operation when it's completed
1435 * @param jQuery object jQuery Element that holds the notification
1439 function PMA_ajaxRemoveMessage($this_msgbox)
1441 if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1445 if ($this_msgbox.is('.dismissable')) {
1446 // Here we should destroy the qtip instance, but
1447 // due to a bug in qtip's implementation we can
1448 // only hide it without throwing JS errors.
1449 $this_msgbox.qtip('hide');
1451 $this_msgbox.remove();
1456 $(document).ready(function() {
1458 * Allows the user to dismiss a notification
1459 * created with PMA_ajaxShowMessage()
1461 $('.ajax_notification.dismissable').live('click', function () {
1462 PMA_ajaxRemoveMessage($(this));
1465 * The below two functions hide the "Dismiss notification" tooltip when a user
1466 * is hovering a link or button that is inside an ajax message
1468 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1469 .live('mouseover', function () {
1470 $(this).parents('.ajax_notification').qtip('hide');
1472 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1473 .live('mouseout', function () {
1474 $(this).parents('.ajax_notification').qtip('show');
1479 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1481 function PMA_showNoticeForEnum(selectElement)
1483 var enum_notice_id = selectElement.attr("id").split("_")[1];
1484 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1485 var selectedType = selectElement.val();
1486 if (selectedType == "ENUM" || selectedType == "SET") {
1487 $("p[id='enum_notice_" + enum_notice_id + "']").show();
1489 $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1494 * Generates a dialog box to pop up the create_table form
1496 function PMA_createTableDialog( $div, url , target)
1499 * @var button_options Object that stores the options passed to jQueryUI
1502 var button_options = {};
1503 // in the following function we need to use $(this)
1504 button_options[PMA_messages['strCancel']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1506 var button_options_error = {};
1507 button_options_error[PMA_messages['strOK']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1509 var $msgbox = PMA_ajaxShowMessage();
1511 $.get( target , url , function(data) {
1512 //in the case of an error, show the error message returned.
1513 if (data.success != undefined && data.success == false) {
1519 open: PMA_verifyColumnsProperties,
1520 buttons : button_options_error
1521 })// end dialog options
1522 //remove the redundant [Back] link in the error message.
1523 .find('fieldset').remove();
1525 var size = getWindowSize();
1530 dialogClass: 'create-table',
1535 position: ['left','top'],
1536 width: size.width-10,
1537 height: size.height-10,
1539 var dialog_id = $(this).attr('id');
1540 $(window).bind('resize.dialog-resizer', function() {
1541 clearTimeout(timeout);
1542 timeout = setTimeout(function() {
1543 var size = getWindowSize();
1544 $('#'+dialog_id).dialog('option', {
1545 width: size.width-10,
1546 height: size.height-10
1551 var $wrapper = $('<div>', {'id': 'content-hide'}).hide();
1552 $('body > *:not(.ui-dialog)').wrapAll($wrapper);
1555 .scrollTop(0) // for Chrome
1556 .closest('.ui-dialog').css({
1561 PMA_verifyColumnsProperties();
1563 // move the Cancel button next to the Save button
1564 var $button_pane = $('.ui-dialog-buttonpane');
1565 var $cancel_button = $button_pane.find('.ui-button');
1566 var $save_button = $('#create_table_form').find("input[name='do_save_data']");
1567 $cancel_button.insertAfter($save_button);
1568 $button_pane.hide();
1571 $(window).unbind('resize.dialog-resizer');
1572 $('#content-hide > *').unwrap();
1574 buttons: button_options
1575 }); // end dialog options
1577 PMA_convertFootnotesToTooltips($div);
1578 PMA_ajaxRemoveMessage($msgbox);
1584 * Creates a highcharts chart in the given container
1586 * @param var settings object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1587 * requires at least settings.chart.renderTo and settings.series to be set.
1588 * In addition there may be an additional property object 'realtime' that allows for realtime charting:
1590 * url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1591 * type: the GET request will also add type=[value of the type property] to the request
1592 * callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1593 * - the chart object
1594 * - the current response value of the GET request, JSON parsed
1595 * - the previous response value of the GET request, JSON parsed
1596 * - the number of added points
1597 * error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1600 * @return object The created highcharts instance
1602 function PMA_createChart(passedSettings)
1604 var container = passedSettings.chart.renderTo;
1610 backgroundColor: 'none',
1612 /* Live charting support */
1614 var thisChart = this;
1615 var lastValue = null, curValue = null;
1616 var numLoadedPoints = 0, otherSum = 0;
1619 // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1620 // Also don't do live charting if we don't have the server time
1621 if(thisChart.options.chart.forExport == true ||
1622 ! thisChart.options.realtime ||
1623 ! thisChart.options.realtime.callback ||
1624 ! server_time_diff) return;
1626 thisChart.options.realtime.timeoutCallBack = function() {
1627 thisChart.options.realtime.postRequest = $.post(
1628 thisChart.options.realtime.url,
1629 thisChart.options.realtime.postData,
1632 curValue = jQuery.parseJSON(data);
1634 if(thisChart.options.realtime.error)
1635 thisChart.options.realtime.error(err);
1639 if (lastValue==null) {
1640 diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1642 diff = parseInt(curValue.x - lastValue.x);
1645 thisChart.xAxis[0].setExtremes(
1646 thisChart.xAxis[0].getExtremes().min+diff,
1647 thisChart.xAxis[0].getExtremes().max+diff,
1651 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1653 lastValue = curValue;
1656 // Timeout has been cleared => don't start a new timeout
1657 if (chart_activeTimeouts[container] == null) {
1661 chart_activeTimeouts[container] = setTimeout(
1662 thisChart.options.realtime.timeoutCallBack,
1663 thisChart.options.realtime.refreshRate
1668 chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1688 text: PMA_messages['strTotalCount']
1697 formatter: function() {
1698 return '<b>' + this.series.name +'</b><br/>' +
1699 Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1700 Highcharts.numberFormat(this.y, 2);
1709 /* Set/Get realtime chart default values */
1710 if(passedSettings.realtime) {
1711 if(!passedSettings.realtime.refreshRate) {
1712 passedSettings.realtime.refreshRate = 5000;
1715 if(!passedSettings.realtime.numMaxPoints) {
1716 passedSettings.realtime.numMaxPoints = 30;
1719 // Allow custom POST vars to be added
1720 passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1722 if(server_time_diff) {
1723 settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1724 settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1728 // Overwrite/Merge default settings with passedsettings
1729 $.extend(true,settings,passedSettings);
1731 return new Highcharts.Chart(settings);
1736 * Creates a Profiling Chart. Used in sql.php and server_status.js
1738 function PMA_createProfilingChart(data, options)
1740 return PMA_createChart($.extend(true, {
1742 renderTo: 'profilingchart',
1745 title: { text:'', margin:0 },
1748 name: PMA_messages['strQueryExecutionTime'],
1753 allowPointSelect: true,
1758 formatter: function() {
1759 return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1765 formatter: function() {
1766 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1773 * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1775 * @param integer Number to be formatted, should be in the range of microsecond to second
1776 * @param integer Acuracy, how many numbers right to the comma should be
1777 * @return string The formatted number
1779 function PMA_prettyProfilingNum(num, acc)
1784 acc = Math.pow(10,acc);
1785 if (num * 1000 < 0.1) {
1786 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1787 } else if (num < 0.1) {
1788 num = Math.round(acc * (num * 1000)) / acc + 'm';
1790 num = Math.round(acc * num) / acc;
1798 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1800 * @param string Query to be formatted
1801 * @return string The formatted query
1803 function PMA_SQLPrettyPrint(string)
1805 var mode = CodeMirror.getMode({},"text/x-mysql");
1806 var stream = new CodeMirror.StringStream(string);
1807 var state = mode.startState();
1808 var token, tokens = [];
1810 var tabs = function(cnt) {
1812 for (var i=0; i<4*cnt; i++)
1817 // "root-level" statements
1819 'select': ['select', 'from','on','where','having','limit','order by','group by'],
1820 'update': ['update', 'set','where'],
1821 'insert into': ['insert into', 'values']
1823 // don't put spaces before these tokens
1824 var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1825 // don't put spaces after these tokens
1826 var spaceExceptionsAfter = { '.': true };
1828 // Populate tokens array
1830 while (! stream.eol()) {
1831 stream.start = stream.pos;
1832 token = mode.token(stream, state);
1834 tokens.push([token, stream.current().toLowerCase()]);
1838 var currentStatement = tokens[0][1];
1840 if(! statements[currentStatement]) {
1843 // Holds all currently opened code blocks (statement, function or generic)
1844 var blockStack = [];
1845 // Holds the type of block from last iteration (the current is in blockStack[0])
1847 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1848 var newBlock, endBlock;
1849 // How much to indent in the current line
1850 var indentLevel = 0;
1851 // Holds the "root-level" statements
1852 var statementPart, lastStatementPart = statements[currentStatement][0];
1854 blockStack.unshift('statement');
1856 // Iterate through every token and format accordingly
1857 for (var i = 0; i < tokens.length; i++) {
1858 previousBlock = blockStack[0];
1860 // New block => push to stack
1861 if (tokens[i][1] == '(') {
1862 if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1863 blockStack.unshift(newBlock = 'statement');
1864 } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1865 blockStack.unshift(newBlock = 'function');
1867 blockStack.unshift(newBlock = 'generic');
1873 // Block end => pop from stack
1874 if (tokens[i][1] == ')') {
1875 endBlock = blockStack[0];
1881 // A subquery is starting
1882 if (i > 0 && newBlock == 'statement') {
1884 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1885 currentStatement = tokens[i+1][1];
1890 // A subquery is ending
1891 if (endBlock == 'statement' && indentLevel > 0) {
1892 output += "\n" + tabs(indentLevel);
1896 // One less indentation for statement parts (from, where, order by, etc.) and a newline
1897 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1898 if (statementPart != -1) {
1899 if (i > 0) output += "\n";
1900 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1901 output += "\n" + tabs(indentLevel + 1);
1902 lastStatementPart = tokens[i][1];
1904 // Normal indentatin and spaces for everything else
1906 if (! spaceExceptionsBefore[tokens[i][1]]
1907 && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1908 && output.charAt(output.length -1) != ' ' ) {
1911 if (tokens[i][0] == 'keyword') {
1912 output += tokens[i][1].toUpperCase();
1914 output += tokens[i][1];
1918 // split columns in select and 'update set' clauses, but only inside statements blocks
1919 if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
1920 && tokens[i][1]==',' && blockStack[0] == 'statement') {
1922 output += "\n" + tabs(indentLevel + 1);
1925 // split conditions in where clauses, but only inside statements blocks
1926 if (lastStatementPart == 'where'
1927 && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1929 if (blockStack[0] == 'statement') {
1930 output += "\n" + tabs(indentLevel + 1);
1932 // Todo: Also split and or blocks in newlines & identation++
1933 //if(blockStack[0] == 'generic')
1941 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1942 * return a jQuery object yet and hence cannot be chained
1944 * @param string question
1945 * @param string url URL to be passed to the callbackFn to make
1947 * @param function callbackFn callback to execute after user clicks on OK
1950 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1951 if (PMA_messages['strDoYouReally'] == '') {
1956 * @var button_options Object that stores the options passed to jQueryUI
1959 var button_options = {};
1960 button_options[PMA_messages['strOK']] = function(){
1961 $(this).dialog("close").remove();
1963 if($.isFunction(callbackFn)) {
1964 callbackFn.call(this, url);
1967 button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1969 $('<div id="confirm_dialog"></div>')
1971 .dialog({buttons: button_options});
1975 * jQuery function to sort a table's body after a new row has been appended to it.
1976 * Also fixes the even/odd classes of the table rows at the end.
1978 * @param string text_selector string to select the sortKey's text
1980 * @return jQuery Object for chaining purposes
1982 jQuery.fn.PMA_sort_table = function(text_selector) {
1983 return this.each(function() {
1986 * @var table_body Object referring to the table's <tbody> element
1988 var table_body = $(this);
1990 * @var rows Object referring to the collection of rows in {@link table_body}
1992 var rows = $(this).find('tr').get();
1994 //get the text of the field that we will sort by
1995 $.each(rows, function(index, row) {
1996 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1999 //get the sorted order
2000 rows.sort(function(a,b) {
2001 if(a.sortKey < b.sortKey) {
2004 if(a.sortKey > b.sortKey) {
2010 //pull out each row from the table and then append it according to it's order
2011 $.each(rows, function(index, row) {
2012 $(table_body).append(row);
2016 //Re-check the classes of each row
2017 $(this).find('tr:odd')
2018 .removeClass('even').addClass('odd')
2021 .removeClass('odd').addClass('even');
2026 * jQuery coding for 'Create Table'. Used on db_operations.php,
2027 * db_structure.php and db_tracking.php (i.e., wherever
2028 * libraries/display_create_table.lib.php is used)
2030 * Attach Ajax Event handlers for Create Table
2032 $(document).ready(function() {
2035 * Attach event handler to the submit action of the create table minimal form
2036 * and retrieve the full table form and display it in a dialog
2038 $("#create_table_form_minimal.ajax").live('submit', function(event) {
2039 event.preventDefault();
2041 PMA_prepareForAjaxRequest($form);
2043 /*variables which stores the common attributes*/
2044 var url = $form.serialize();
2045 var action = $form.attr('action');
2046 var $div = $('<div id="create_table_dialog"></div>');
2048 /*Calling to the createTableDialog function*/
2049 PMA_createTableDialog($div, url, action);
2051 // empty table name and number of columns from the minimal form
2052 $form.find('input[name=table],input[name=num_fields]').val('');
2056 * Attach event handler for submission of create table form (save)
2058 * @uses PMA_ajaxShowMessage()
2059 * @uses $.PMA_sort_table()
2062 // .live() must be called after a selector, see http://api.jquery.com/live
2063 $("#create_table_form input[name=do_save_data]").live('click', function(event) {
2064 event.preventDefault();
2067 * @var the_form object referring to the create table form
2069 var $form = $("#create_table_form");
2072 * First validate the form; if there is a problem, avoid submitting it
2074 * checkTableEditForm() needs a pure element and not a jQuery object,
2075 * this is why we pass $form[0] as a parameter (the jQuery object
2076 * is actually an array of DOM elements)
2079 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2080 // OK, form passed validation step
2081 if ($form.hasClass('ajax')) {
2082 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2083 PMA_prepareForAjaxRequest($form);
2084 //User wants to submit the form
2085 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
2086 if(data.success == true) {
2087 $('#properties_message')
2088 .removeClass('error')
2090 PMA_ajaxShowMessage(data.message);
2091 // Only if the create table dialog (distinct panel) exists
2092 if ($("#create_table_dialog").length > 0) {
2093 $("#create_table_dialog").dialog("close").remove();
2097 * @var tables_table Object referring to the <tbody> element that holds the list of tables
2099 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
2100 // this is the first table created in this db
2101 if (tables_table.length == 0) {
2102 if (window.parent && window.parent.frame_content) {
2103 window.parent.frame_content.location.reload();
2107 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
2109 var curr_last_row = $(tables_table).find('tr:last');
2111 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
2113 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2115 * @var curr_last_row_index Index of {@link curr_last_row}
2117 var curr_last_row_index = parseFloat(curr_last_row_index_string);
2119 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
2121 var new_last_row_index = curr_last_row_index + 1;
2123 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2125 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2127 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2129 $(data.new_table_string)
2130 .appendTo(tables_table);
2133 $(tables_table).PMA_sort_table('th');
2135 // Adjust summary row
2139 //Refresh navigation frame as a new table has been added
2140 if (window.parent && window.parent.frame_navigation) {
2141 window.parent.frame_navigation.location.reload();
2144 $('#properties_message')
2147 // scroll to the div containing the error message
2148 $('#properties_message')[0].scrollIntoView();
2151 } // end if ($form.hasClass('ajax')
2154 $form.append('<input type="hidden" name="do_save_data" value="save" />');
2157 } // end if (checkTableEditForm() )
2158 }) // end create table form (save)
2161 * Attach event handler for create table form (add fields)
2163 * @uses PMA_ajaxShowMessage()
2164 * @uses $.PMA_sort_table()
2165 * @uses window.parent.refreshNavigation()
2168 // .live() must be called after a selector, see http://api.jquery.com/live
2169 $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2170 event.preventDefault();
2173 * @var the_form object referring to the create table form
2175 var $form = $("#create_table_form");
2177 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2178 PMA_prepareForAjaxRequest($form);
2180 //User wants to add more fields to the table
2181 $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2182 // if 'create_table_dialog' exists
2183 if ($("#create_table_dialog").length > 0) {
2184 $("#create_table_dialog").html(data);
2186 // if 'create_table_div' exists
2187 if ($("#create_table_div").length > 0) {
2188 $("#create_table_div").html(data);
2190 PMA_verifyColumnsProperties();
2191 PMA_ajaxRemoveMessage($msgbox);
2194 }) // end create table form (add fields)
2196 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2199 * jQuery coding for 'Change Table' and 'Add Column'. Used on tbl_structure.php *
2200 * Attach Ajax Event handlers for Change Table
2202 $(document).ready(function() {
2204 *Ajax action for submitting the "Column Change" and "Add Column" form
2206 $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2207 event.preventDefault();
2209 * @var the_form object referring to the export form
2211 var $form = $("#append_fields_form");
2214 * First validate the form; if there is a problem, avoid submitting it
2216 * checkTableEditForm() needs a pure element and not a jQuery object,
2217 * this is why we pass $form[0] as a parameter (the jQuery object
2218 * is actually an array of DOM elements)
2220 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2221 // OK, form passed validation step
2222 if ($form.hasClass('ajax')) {
2223 PMA_prepareForAjaxRequest($form);
2224 //User wants to submit the form
2225 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2226 if ($("#sqlqueryresults").length != 0) {
2227 $("#sqlqueryresults").remove();
2228 } else if ($(".error").length != 0) {
2229 $(".error").remove();
2231 if (data.success == true) {
2232 PMA_ajaxShowMessage(data.message);
2233 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2234 $("#sqlqueryresults").html(data.sql_query);
2235 $("#result_query .notice").remove();
2236 $("#result_query").prepend((data.message));
2237 if ($("#change_column_dialog").length > 0) {
2238 $("#change_column_dialog").dialog("close").remove();
2239 } else if ($("#add_columns").length > 0) {
2240 $("#add_columns").dialog("close").remove();
2242 /*Reload the field form*/
2243 $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2244 $("#fieldsForm").remove();
2245 $("#addColumns").remove();
2246 var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2247 if ($("#sqlqueryresults").length != 0) {
2248 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2250 $temp_div.find("#fieldsForm").insertAfter(".error");
2252 $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2253 /*Call the function to display the more options in table*/
2254 displayMoreTableOpts();
2257 var $temp_div = $("<div id='temp_div'><div>").append(data);
2258 var $error = $temp_div.find(".error code").addClass("error");
2259 PMA_ajaxShowMessage($error, false);
2264 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2268 }) // end change table button "do_save_data"
2270 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2273 * jQuery coding for 'Table operations'. Used on tbl_operations.php
2274 * Attach Ajax Event handlers for Table operations
2276 $(document).ready(function() {
2278 *Ajax action for submitting the "Alter table order by"
2280 $("#alterTableOrderby.ajax").live('submit', function(event) {
2281 event.preventDefault();
2282 var $form = $(this);
2284 PMA_prepareForAjaxRequest($form);
2285 /*variables which stores the common attributes*/
2286 $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2287 if ($("#sqlqueryresults").length != 0) {
2288 $("#sqlqueryresults").remove();
2290 if ($("#result_query").length != 0) {
2291 $("#result_query").remove();
2293 if (data.success == true) {
2294 PMA_ajaxShowMessage(data.message);
2295 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2296 $("#sqlqueryresults").html(data.sql_query);
2297 $("#result_query .notice").remove();
2298 $("#result_query").prepend((data.message));
2300 var $temp_div = $("<div id='temp_div'></div>")
2301 $temp_div.html(data.error);
2302 var $error = $temp_div.find("code").addClass("error");
2303 PMA_ajaxShowMessage($error, false);
2306 });//end of alterTableOrderby ajax submit
2309 *Ajax action for submitting the "Copy table"
2311 $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2312 event.preventDefault();
2313 var $form = $("#copyTable");
2314 if($form.find("input[name='switch_to_new']").attr('checked')) {
2315 $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2316 $form.removeClass('ajax');
2317 $form.find("#ajax_request_hidden").remove();
2320 PMA_prepareForAjaxRequest($form);
2321 /*variables which stores the common attributes*/
2322 $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2323 if ($("#sqlqueryresults").length != 0) {
2324 $("#sqlqueryresults").remove();
2326 if ($("#result_query").length != 0) {
2327 $("#result_query").remove();
2329 if (data.success == true) {
2330 PMA_ajaxShowMessage(data.message);
2331 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2332 $("#sqlqueryresults").html(data.sql_query);
2333 $("#result_query .notice").remove();
2334 $("#result_query").prepend((data.message));
2335 $("#copyTable").find("select[name='target_db'] option").filterByValue(data.db).attr('selected', 'selected');
2337 //Refresh navigation frame when the table is coppied
2338 if (window.parent && window.parent.frame_navigation) {
2339 window.parent.frame_navigation.location.reload();
2342 var $temp_div = $("<div id='temp_div'></div>");
2343 $temp_div.html(data.error);
2344 var $error = $temp_div.find("code").addClass("error");
2345 PMA_ajaxShowMessage($error, false);
2349 });//end of copyTable ajax submit
2352 *Ajax events for actions in the "Table maintenance"
2354 $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2355 event.preventDefault();
2356 var $link = $(this);
2357 var href = $link.attr("href");
2358 href = href.split('?');
2359 if ($("#sqlqueryresults").length != 0) {
2360 $("#sqlqueryresults").remove();
2362 if ($("#result_query").length != 0) {
2363 $("#result_query").remove();
2365 //variables which stores the common attributes
2366 $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2367 if (data.success == undefined) {
2368 var $temp_div = $("<div id='temp_div'></div>");
2369 $temp_div.html(data);
2370 var $success = $temp_div.find("#result_query .success");
2371 PMA_ajaxShowMessage($success);
2372 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2373 $("#sqlqueryresults").html(data);
2375 $("#sqlqueryresults").children("fieldset").remove();
2376 } else if (data.success == true ) {
2377 PMA_ajaxShowMessage(data.message);
2378 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2379 $("#sqlqueryresults").html(data.sql_query);
2381 var $temp_div = $("<div id='temp_div'></div>");
2382 $temp_div.html(data.error);
2383 var $error = $temp_div.find("code").addClass("error");
2384 PMA_ajaxShowMessage($error, false);
2387 });//end of table maintanance ajax click
2389 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2393 * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2394 * as it was also required on db_create.php
2396 * @uses $.PMA_confirm()
2397 * @uses PMA_ajaxShowMessage()
2398 * @uses window.parent.refreshNavigation()
2399 * @uses window.parent.refreshMain()
2400 * @see $cfg['AjaxEnable']
2402 $(document).ready(function() {
2403 $("#drop_db_anchor").live('click', function(event) {
2404 event.preventDefault();
2406 //context is top.frame_content, so we need to use window.parent.db to access the db var
2408 * @var question String containing the question to be asked for confirmation
2410 var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
2412 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2414 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2415 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2416 //Database deleted successfully, refresh both the frames
2417 window.parent.refreshNavigation();
2418 window.parent.refreshMain();
2420 }); // end $.PMA_confirm()
2421 }); //end of Drop Database Ajax action
2422 }) // end of $(document).ready() for Drop Database
2425 * Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
2426 * display_create_database.lib.php is used, ie main.php and server_databases.php
2428 * @uses PMA_ajaxShowMessage()
2429 * @see $cfg['AjaxEnable']
2431 $(document).ready(function() {
2433 $('#create_database_form.ajax').live('submit', function(event) {
2434 event.preventDefault();
2438 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2439 PMA_prepareForAjaxRequest($form);
2441 $.post($form.attr('action'), $form.serialize(), function(data) {
2442 if(data.success == true) {
2443 PMA_ajaxShowMessage(data.message);
2445 //Append database's row to table
2446 $("#tabledatabases")
2448 .append(data.new_db_string)
2449 .PMA_sort_table('.name')
2450 .find('#db_summary_row')
2451 .appendTo('#tabledatabases tbody')
2452 .removeClass('odd even');
2454 var $databases_count_object = $('#databases_count');
2455 var databases_count = parseInt($databases_count_object.text());
2456 $databases_count_object.text(++databases_count);
2457 //Refresh navigation frame as a new database has been added
2458 if (window.parent && window.parent.frame_navigation) {
2459 window.parent.frame_navigation.location.reload();
2463 PMA_ajaxShowMessage(data.error, false);
2466 }) // end $().live()
2467 }) // end $(document).ready() for Create Database
2470 * Attach Ajax event handlers for 'Change Password' on main.php
2472 $(document).ready(function() {
2475 * Attach Ajax event handler on the change password anchor
2476 * @see $cfg['AjaxEnable']
2478 $('#change_password_anchor.dialog_active').live('click',function(event) {
2479 event.preventDefault();
2482 $('#change_password_anchor.ajax').live('click', function(event) {
2483 event.preventDefault();
2484 $(this).removeClass('ajax').addClass('dialog_active');
2486 * @var button_options Object containing options to be passed to jQueryUI's dialog
2488 var button_options = {};
2489 button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2490 $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2491 $('<div id="change_password_dialog"></div>')
2493 title: PMA_messages['strChangePassword'],
2495 close: function(ev,ui) {$(this).remove();},
2496 buttons : button_options,
2497 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2500 displayPasswordGenerateButton();
2502 }) // end handler for change password anchor
2505 * Attach Ajax event handler for Change Password form submission
2507 * @uses PMA_ajaxShowMessage()
2508 * @see $cfg['AjaxEnable']
2510 $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2511 event.preventDefault();
2514 * @var the_form Object referring to the change password form
2516 var the_form = $("#change_password_form");
2519 * @var this_value String containing the value of the submit button.
2520 * Need to append this for the change password form on Server Privileges
2523 var this_value = $(this).val();
2525 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2526 $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2528 $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2529 if(data.success == true) {
2530 $("#floating_menubar").after(data.sql_query);
2531 $("#change_password_dialog").hide().remove();
2532 $("#edit_user_dialog").dialog("close").remove();
2533 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2534 PMA_ajaxRemoveMessage($msgbox);
2537 PMA_ajaxShowMessage(data.error, false);
2540 }) // end handler for Change Password form submission
2541 }) // end $(document).ready() for Change Password
2544 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2545 * the page loads and when the selected data type changes
2547 $(document).ready(function() {
2548 // is called here for normal page loads and also when opening
2549 // the Create table dialog
2550 PMA_verifyColumnsProperties();
2552 // needs live() to work also in the Create Table dialog
2553 $("select[class='column_type']").live('change', function() {
2554 PMA_showNoticeForEnum($(this));
2556 $(".default_type").live('change', function() {
2557 PMA_hideShowDefaultValue($(this));
2561 function PMA_verifyColumnsProperties()
2563 $("select[class='column_type']").each(function() {
2564 PMA_showNoticeForEnum($(this));
2566 $(".default_type").each(function() {
2567 PMA_hideShowDefaultValue($(this));
2572 * Hides/shows the default value input field, depending on the default type
2574 function PMA_hideShowDefaultValue($default_type)
2576 if ($default_type.val() == 'USER_DEFINED') {
2577 $default_type.siblings('.default_value').show().focus();
2579 $default_type.siblings('.default_value').hide();
2584 * @var $enum_editor_dialog An object that points to the jQuery
2585 * dialog of the ENUM/SET editor
2587 var $enum_editor_dialog = null;
2589 * Opens the ENUM/SET editor and controls its functions
2591 $(document).ready(function() {
2592 $("a.open_enum_editor").live('click', function() {
2593 // Get the name of the column that is being edited
2594 var colname = $(this).closest('tr').find('input:first').val();
2595 // And use it to make up a title for the page
2596 if (colname.length < 1) {
2597 var title = PMA_messages['enum_newColumnVals'];
2599 var title = PMA_messages['enum_columnVals'].replace(
2601 '"' + decodeURIComponent(colname) + '"'
2604 // Get the values as a string
2605 var inputstring = $(this)
2609 // Escape html entities
2610 inputstring = $('<div/>')
2613 // Parse the values, escaping quotes and
2614 // slashes on the fly, into an array
2616 // There is a PHP port of the below parser in enum_editor.php
2617 // If you are fixing something here, you need to also update the PHP port.
2619 var in_string = false;
2620 var curr, next, buffer = '';
2621 for (var i=0; i<inputstring.length; i++) {
2622 curr = inputstring.charAt(i);
2623 next = i == inputstring.length ? '' : inputstring.charAt(i+1);
2624 if (! in_string && curr == "'") {
2626 } else if (in_string && curr == "\\" && next == "\\") {
2629 } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
2632 } else if (in_string && curr == "'") {
2634 values.push(buffer);
2636 } else if (in_string) {
2640 if (buffer.length > 0) {
2641 // The leftovers in the buffer are the last value (if any)
2642 values.push(buffer);
2645 // If there are no values, maybe the user is about to make a
2646 // new list so we add a few for him/her to get started with.
2647 if (values.length == 0) {
2648 values.push('','','','');
2650 // Add the parsed values to the editor
2651 var drop_icon = PMA_getImage('b_drop.png');
2652 for (var i=0; i<values.length; i++) {
2653 fields += "<tr><td>"
2654 + "<input type='text' value='" + values[i] + "'/>"
2655 + "</td><td class='drop'>"
2660 * @var dialog HTML code for the ENUM/SET dialog
2662 var dialog = "<div id='enum_editor'>"
2664 + "<legend>" + title + "</legend>"
2665 + "<p>" + PMA_getImage('s_notice.png')
2666 + PMA_messages['enum_hint'] + "</p>"
2667 + "<table class='values'>" + fields + "</table>"
2668 + "</fieldset><fieldset class='tblFooters'>"
2669 + "<table class='add'><tr><td>"
2670 + "<div class='slider'></div>"
2672 + "<form><div><input type='submit' class='add_value' value='"
2673 + PMA_messages['enum_addValue'].replace(/%d/, 1)
2674 + "'/></div></form>"
2675 + "</td></tr></table>"
2676 + "<input type='hidden' value='" // So we know which column's data is being edited
2677 + $(this).closest('td').find("input").attr("id")
2682 * @var Defines functions to be called when the buttons in
2683 * the buttonOptions jQuery dialog bar are pressed
2685 var buttonOptions = {};
2686 buttonOptions[PMA_messages['strGo']] = function () {
2687 // When the submit button is clicked,
2688 // put the data back into the original form
2689 var value_array = new Array();
2690 $(this).find(".values input").each(function(index, elm) {
2691 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
2692 value_array.push("'" + val + "'");
2694 // get the Length/Values text field where this value belongs
2695 var values_id = $(this).find("input[type='hidden']").attr("value");
2696 $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2697 $(this).dialog("close");
2699 buttonOptions[PMA_messages['strClose']] = function () {
2700 $(this).dialog("close");
2703 var width = parseInt(
2704 (parseInt($('html').css('font-size'), 10)/13)*340,
2710 $enum_editor_dialog = $(dialog).dialog({
2713 title: PMA_messages['enum_editor'],
2714 buttons: buttonOptions,
2716 // Focus the "Go" button after opening the dialog
2717 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
2723 // slider for choosing how many fields to add
2724 $enum_editor_dialog.find(".slider").slider({
2730 slide: function( event, ui ) {
2731 $(this).closest('table').find('input[type=submit]').val(
2732 PMA_messages['enum_addValue'].replace(/%d/, ui.value)
2736 // Focus the slider, otherwise it looks nearly transparent
2737 $('.ui-slider-handle').addClass('ui-state-focus');
2741 // When "add a new value" is clicked, append an empty text field
2742 $("input.add_value").live('click', function(e) {
2744 var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
2745 while (num_new_rows--) {
2746 $enum_editor_dialog.find('.values')
2748 "<tr style='display: none;'><td>"
2749 + "<input type='text' />"
2750 + "</td><td class='drop'>"
2751 + PMA_getImage('b_drop.png')
2759 // Removes the specified row from the enum editor
2760 $("#enum_editor td.drop").live('click', function() {
2761 $(this).closest('tr').hide('fast', function () {
2768 * Hides certain table structure actions, replacing them
2769 * with the word "More". They are displayed in a dropdown
2770 * menu when the user hovers over the word "More."
2772 $(document).ready(function() {
2773 displayMoreTableOpts();
2776 function displayMoreTableOpts()
2778 // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2779 // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2780 if($("input[type='hidden'][name='table_type']").val() == "table") {
2781 var $table = $("table[id='tablestructure']");
2782 $table.find("td[class='browse']").remove();
2783 $table.find("td[class='primary']").remove();
2784 $table.find("td[class='unique']").remove();
2785 $table.find("td[class='index']").remove();
2786 $table.find("td[class='fulltext']").remove();
2787 $table.find("td[class='spatial']").remove();
2788 $table.find("th[class='action']").attr("colspan", 3);
2790 // Display the "more" text
2791 $table.find("td[class='more_opts']").show();
2793 // Position the dropdown
2794 $(".structure_actions_dropdown").each(function() {
2795 // Optimize DOM querying
2796 var $this_dropdown = $(this);
2797 // The top offset must be set for IE even if it didn't change
2798 var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2799 var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2800 var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2801 $this_dropdown.offset({ top: top_offset, left: left_offset });
2804 // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2805 // positioning an iframe directly on top of it
2806 var $after_field = $("select[name='after_field']");
2807 $("iframe[class='IE_hack']")
2808 .width($after_field.width())
2809 .height($after_field.height())
2811 top: $after_field.offset().top,
2812 left: $after_field.offset().left
2815 // When "more" is hovered over, show the hidden actions
2816 $table.find("td[class='more_opts']")
2817 .mouseenter(function() {
2818 if($.browser.msie && $.browser.version == "6.0") {
2819 $("iframe[class='IE_hack']")
2821 .width($after_field.width()+4)
2822 .height($after_field.height()+4)
2824 top: $after_field.offset().top,
2825 left: $after_field.offset().left
2828 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2829 $(this).children(".structure_actions_dropdown").show();
2830 // Need to do this again for IE otherwise the offset is wrong
2831 if($.browser.msie) {
2832 var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2833 var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2834 $(this).children(".structure_actions_dropdown").offset({
2836 left: left_offset_IE });
2839 .mouseleave(function() {
2840 $(this).children(".structure_actions_dropdown").hide();
2841 if($.browser.msie && $.browser.version == "6.0") {
2842 $("iframe[class='IE_hack']").hide();
2848 $(document).ready(function(){
2849 PMA_convertFootnotesToTooltips();
2853 * Ensures indexes names are valid according to their type and, for a primary
2854 * key, lock index name to 'PRIMARY'
2855 * @param string form_id Variable which parses the form name as
2857 * @return boolean false if there is no index form, true else
2859 function checkIndexName(form_id)
2861 if ($("#"+form_id).length == 0) {
2865 // Gets the elements pointers
2866 var $the_idx_name = $("#input_index_name");
2867 var $the_idx_type = $("#select_index_type");
2869 // Index is a primary key
2870 if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2871 $the_idx_name.attr("value", 'PRIMARY');
2872 $the_idx_name.attr("disabled", true);
2877 if ($the_idx_name.attr("value") == 'PRIMARY') {
2878 $the_idx_name.attr("value", '');
2880 $the_idx_name.attr("disabled", false);
2884 } // end of the 'checkIndexName()' function
2887 * function to convert the footnotes to tooltips
2889 * @param jquery-Object $div a div jquery object which specifies the
2890 * domain for searching footnootes. If we
2891 * ommit this parameter the function searches
2892 * the footnotes in the whole body
2894 function PMA_convertFootnotesToTooltips($div)
2896 // Hide the footnotes from the footer (which are displayed for
2897 // JavaScript-disabled browsers) since the tooltip is sufficient
2899 if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2903 $footnotes = $div.find(".footnotes");
2906 $footnotes.find('span').each(function() {
2907 $(this).children("sup").remove();
2909 // The border and padding must be removed otherwise a thin yellow box remains visible
2910 $footnotes.css("border", "none");
2911 $footnotes.css("padding", "0px");
2913 // Replace the superscripts with the help icon
2914 $div.find("sup.footnotemarker").hide();
2915 $div.find("img.footnotemarker").show();
2917 $div.find("img.footnotemarker").each(function() {
2918 var img_class = $(this).attr("class");
2919 /** img contains two classes, as example "footnotemarker footnote_1".
2920 * We split it by second class and take it for the id of span
2922 img_class = img_class.split(" ");
2923 for (i = 0; i < img_class.length; i++) {
2924 if (img_class[i].split("_")[0] == "footnote") {
2925 var span_id = img_class[i].split("_")[1];
2929 * Now we get the #id of the span with span_id variable. As an example if we
2930 * initially get the img class as "footnotemarker footnote_2", now we get
2931 * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2933 var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2935 content: tooltip_text,
2937 hide: { delay: 1000 },
2938 style: { background: '#ffffcc' }
2944 * This function handles the resizing of the content frame
2945 * and adjusts the top menu according to the new size of the frame
2947 function menuResize()
2949 var $cnt = $('#topmenu');
2950 var wmax = $cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2951 var $submenu = $cnt.find('.submenu');
2952 var submenu_w = $submenu.outerWidth(true);
2953 var $submenu_ul = $submenu.find('ul');
2954 var $li = $cnt.find('> li');
2955 var $li2 = $submenu_ul.find('li');
2956 var more_shown = $li2.length > 0;
2958 // Calculate the total width used by all the shown tabs
2959 var total_len = more_shown ? submenu_w : 0;
2960 for (var i = 0; i < $li.length-1; i++) {
2961 total_len += $($li[i]).outerWidth(true);
2964 // Now hide menu elements that don't fit into the menubar
2965 var i = $li.length-1;
2966 var hidden = false; // Whether we have hidden any tabs
2967 while (total_len >= wmax && --i >= 0) { // Process the tabs backwards
2970 var el_width = el.outerWidth(true);
2971 el.data('width', el_width);
2973 total_len -= el_width;
2974 el.prependTo($submenu_ul);
2975 total_len += submenu_w;
2978 total_len -= el_width;
2979 el.prependTo($submenu_ul);
2983 // If we didn't hide any tabs, then there might be some space to show some
2985 // Show menu elements that do fit into the menubar
2986 for (var i = 0; i < $li2.length; i++) {
2987 total_len += $($li2[i]).data('width');
2988 // item fits or (it is the last item
2989 // and it would fit if More got removed)
2990 if (total_len < wmax
2991 || (i == $li2.length - 1 && total_len - submenu_w < wmax)
2993 $($li2[i]).insertBefore($submenu);
3000 // Show/hide the "More" tab as needed
3001 if ($submenu_ul.find('li').length > 0) {
3002 $submenu.addClass('shown');
3004 $submenu.removeClass('shown');
3007 if ($cnt.find('> li').length == 1) {
3008 // If there is only the "More" tab left, then we need
3009 // to align the submenu to the left edge of the tab
3010 $submenu_ul.removeClass().addClass('only');
3012 // Otherwise we align the submenu to the right edge of the tab
3013 $submenu_ul.removeClass().addClass('notonly');
3016 if ($submenu.find('.tabactive').length) {
3017 $submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
3019 $submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
3024 var topmenu = $('#topmenu');
3025 if (topmenu.length == 0) {
3028 // create submenu container
3029 var link = $('<a />', {href: '#', 'class': 'tab'})
3030 .text(PMA_messages['strMore'])
3031 .click(function(e) {
3034 var img = topmenu.find('li:first-child img');
3036 $(PMA_getImage('b_more.png').toString()).prependTo(link);
3038 var submenu = $('<li />', {'class': 'submenu'})
3040 .append($('<ul />'))
3041 .mouseenter(function() {
3042 if ($(this).find('ul .tabactive').length == 0) {
3043 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
3046 .mouseleave(function() {
3047 if ($(this).find('ul .tabactive').length == 0) {
3048 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
3051 topmenu.append(submenu);
3053 // populate submenu and register resize event
3055 $(window).resize(menuResize);
3059 * Get the row number from the classlist (for example, row_1)
3061 function PMA_getRowNumber(classlist)
3063 return parseInt(classlist.split(/\s+row_/)[1]);
3067 * Changes status of slider
3069 function PMA_set_status_label($element)
3071 var text = $element.css('display') == 'none'
3074 $element.closest('.slide-wrapper').prev().find('span').text(text);
3078 * Initializes slider effect.
3080 function PMA_init_slider()
3082 $('.pma_auto_slider').each(function() {
3083 var $this = $(this);
3085 if ($this.hasClass('slider_init_done')) {
3088 $this.addClass('slider_init_done');
3090 var $wrapper = $('<div>', {'class': 'slide-wrapper'});
3091 $wrapper.toggle($this.is(':visible'));
3092 $('<a>', {href: '#'+this.id})
3094 .prepend($('<span>'))
3095 .insertBefore($this)
3097 var $wrapper = $this.closest('.slide-wrapper');
3098 var visible = $this.is(':visible');
3102 $this[visible ? 'hide' : 'show']('blind', function() {
3103 $wrapper.toggle(!visible);
3104 PMA_set_status_label($this);
3108 $this.wrap($wrapper);
3109 PMA_set_status_label($this);
3114 * var toggleButton This is a function that creates a toggle
3115 * sliding button given a jQuery reference
3116 * to the correct DOM element
3118 var toggleButton = function ($obj) {
3119 // In rtl mode the toggle switch is flipped horizontally
3120 // so we need to take that into account
3121 if ($('.text_direction', $obj).text() == 'ltr') {
3122 var right = 'right';
3127 * var h Height of the button, used to scale the
3128 * background image and position the layers
3130 var h = $obj.height();
3131 $('img', $obj).height(h);
3132 $('table', $obj).css('bottom', h-1);
3134 * var on Width of the "ON" part of the toggle switch
3135 * var off Width of the "OFF" part of the toggle switch
3137 var on = $('.toggleOn', $obj).width();
3138 var off = $('.toggleOff', $obj).width();
3139 // Make the "ON" and "OFF" parts of the switch the same size
3140 $('.toggleOn > div', $obj).width(Math.max(on, off));
3141 $('.toggleOff > div', $obj).width(Math.max(on, off));
3143 * var w Width of the central part of the switch
3145 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
3146 // Resize the central part of the switch on the top
3147 // layer to match the background
3148 $('table td:nth-child(2) > div', $obj).width(w);
3150 * var imgw Width of the background image
3151 * var tblw Width of the foreground layer
3152 * var offset By how many pixels to move the background
3153 * image, so that it matches the top layer
3155 var imgw = $('img', $obj).width();
3156 var tblw = $('table', $obj).width();
3157 var offset = parseInt(((imgw - tblw) / 2), 10);
3158 // Move the background to match the layout of the top layer
3159 $obj.find('img').css(right, offset);
3161 * var offw Outer width of the "ON" part of the toggle switch
3162 * var btnw Outer width of the central part of the switch
3164 var offw = $('.toggleOff', $obj).outerWidth();
3165 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
3166 // Resize the main div so that exactly one side of
3167 // the switch plus the central part fit into it.
3168 $obj.width(offw + btnw + 2);
3170 * var move How many pixels to move the
3171 * switch by when toggling
3173 var move = $('.toggleOff', $obj).outerWidth();
3174 // If the switch is initialized to the
3175 // OFF state we need to move it now.
3176 if ($('.container', $obj).hasClass('off')) {
3177 if (right == 'right') {
3178 $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
3180 $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
3183 // Attach an 'onclick' event to the switch
3184 $('.container', $obj).click(function () {
3185 if ($(this).hasClass('isActive')) {
3188 $(this).addClass('isActive');
3190 var $msg = PMA_ajaxShowMessage();
3191 var $container = $(this);
3192 var callback = $('.callback', this).text();
3193 // Perform the actual toggle
3194 if ($(this).hasClass('on')) {
3195 if (right == 'right') {
3196 var operator = '-=';
3198 var operator = '+=';
3200 var url = $(this).find('.toggleOff > span').text();
3201 var removeClass = 'on';
3202 var addClass = 'off';
3204 if (right == 'right') {
3205 var operator = '+=';
3207 var operator = '-=';
3209 var url = $(this).find('.toggleOn > span').text();
3210 var removeClass = 'off';
3211 var addClass = 'on';
3213 $.post(url, {'ajax_request': true}, function(data) {
3214 if(data.success == true) {
3215 PMA_ajaxRemoveMessage($msg);
3217 .removeClass(removeClass)
3219 .animate({'left': operator + move + 'px'}, function () {
3220 $container.removeClass('isActive');
3224 PMA_ajaxShowMessage(data.error, false);
3225 $container.removeClass('isActive');
3232 * Initialise all toggle buttons
3234 $(window).load(function () {
3235 $('.toggleAjax').each(function () {
3238 .find('.toggleButton')
3239 toggleButton($(this));
3246 $(document).ready(function() {
3247 $('.vpointer').live('hover',
3250 var $this_td = $(this);
3251 var row_num = PMA_getRowNumber($this_td.attr('class'));
3252 // for all td of the same vertical row, toggle hover
3253 $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
3256 }) // end of $(document).ready() for vertical pointer
3258 $(document).ready(function() {
3262 $('.vmarker').live('click', function(e) {
3263 // do not trigger when clicked on anchor
3264 if ($(e.target).is('a, img, a *')) {
3268 var $this_td = $(this);
3269 var row_num = PMA_getRowNumber($this_td.attr('class'));
3271 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
3273 var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
3274 if ($checkbox.length) {
3275 // checkbox in a row, add or remove class depending on checkbox state
3276 var checked = $checkbox.attr('checked');
3277 if (!$(e.target).is(':checkbox, label')) {
3279 $checkbox.attr('checked', checked);
3281 // for all td of the same vertical row, toggle the marked class
3283 $('.vmarker').filter('.row_' + row_num).addClass('marked');
3285 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
3288 // normaln data table, just toggle class
3289 $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
3294 * Reveal visual builder anchor
3297 $('#visual_builder_anchor').show();
3300 * Page selector in db Structure (non-AJAX)
3302 $('#tableslistcontainer').find('#pageselector').live('change', function() {
3303 $(this).parent("form").submit();
3307 * Page selector in navi panel (non-AJAX)
3309 $('#navidbpageselector').find('#pageselector').live('change', function() {
3310 $(this).parent("form").submit();
3314 * Page selector in browse_foreigners windows (non-AJAX)
3316 $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3317 $(this).closest("form").submit();
3321 * Load version information asynchronously.
3323 if ($('.jsversioncheck').length > 0) {
3324 $.getScript('http://www.phpmyadmin.net/home_page/version.js', PMA_current_version);
3333 * Enables the text generated by PMA_linkOrButton() to be clickable
3335 $('a[class~="formLinkSubmit"]').live('click',function(e) {
3337 if($(this).attr('href').indexOf('=') != -1) {
3338 var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3339 $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3341 $(this).parents('form').submit();
3345 $('#update_recent_tables').ready(function() {
3346 if (window.parent.frame_navigation != undefined
3347 && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3349 window.parent.frame_navigation.PMA_reloadRecentTable();
3353 }) // end of $(document).ready()
3356 * Creates a message inside an object with a sliding effect
3358 * @param msg A string containing the text to display
3359 * @param $obj a jQuery object containing the reference
3360 * to the element where to put the message
3361 * This is optional, if no element is
3362 * provided, one will be created below the
3363 * navigation links at the top of the page
3365 * @return bool True on success, false on failure
3367 function PMA_slidingMessage(msg, $obj)
3369 if (msg == undefined || msg.length == 0) {
3370 // Don't show an empty message
3373 if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3374 // If the second argument was not supplied,
3375 // we might have to create a new DOM node.
3376 if ($('#PMA_slidingMessage').length == 0) {
3377 $('#floating_menubar')
3378 .after('<span id="PMA_slidingMessage" '
3379 + 'style="display: inline-block;"></span>');
3381 $obj = $('#PMA_slidingMessage');
3383 if ($obj.has('div').length > 0) {
3384 // If there already is a message inside the
3385 // target object, we must get rid of it
3389 .fadeOut(function () {
3394 .append('<div style="display: none;">' + msg + '</div>')
3396 height: $obj.find('div').first().height()
3403 // Object does not already have a message
3404 // inside it, so we simply slide it down
3407 .html('<div style="display: none;">' + msg + '</div>')
3419 // Set the height of the parent
3420 // to the height of the child
3431 } // end PMA_slidingMessage()
3434 * Attach Ajax event handlers for Drop Table.
3436 * @uses $.PMA_confirm()
3437 * @uses PMA_ajaxShowMessage()
3438 * @uses window.parent.refreshNavigation()
3439 * @uses window.parent.refreshMain()
3440 * @see $cfg['AjaxEnable']
3442 $(document).ready(function() {
3443 $("#drop_tbl_anchor").live('click', function(event) {
3444 event.preventDefault();
3446 //context is top.frame_content, so we need to use window.parent.table to access the table var
3448 * @var question String containing the question to be asked for confirmation
3450 var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + window.parent.table;
3452 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3454 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3455 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3456 //Database deleted successfully, refresh both the frames
3457 window.parent.refreshNavigation();
3458 window.parent.refreshMain();
3460 }); // end $.PMA_confirm()
3461 }); //end of Drop Table Ajax action
3462 }) // end of $(document).ready() for Drop Table
3465 * Attach Ajax event handlers for Truncate Table.
3467 * @uses $.PMA_confirm()
3468 * @uses PMA_ajaxShowMessage()
3469 * @uses window.parent.refreshNavigation()
3470 * @uses window.parent.refreshMain()
3471 * @see $cfg['AjaxEnable']
3473 $(document).ready(function() {
3474 $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3475 event.preventDefault();
3477 //context is top.frame_content, so we need to use window.parent.table to access the table var
3479 * @var question String containing the question to be asked for confirmation
3481 var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + window.parent.table;
3483 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3485 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3486 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3487 if ($("#sqlqueryresults").length != 0) {
3488 $("#sqlqueryresults").remove();
3490 if ($("#result_query").length != 0) {
3491 $("#result_query").remove();
3493 if (data.success == true) {
3494 PMA_ajaxShowMessage(data.message);
3495 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
3496 $("#sqlqueryresults").html(data.sql_query);
3498 var $temp_div = $("<div id='temp_div'></div>")
3499 $temp_div.html(data.error);
3500 var $error = $temp_div.find("code").addClass("error");
3501 PMA_ajaxShowMessage($error, false);
3504 }); // end $.PMA_confirm()
3505 }); //end of Truncate Table Ajax action
3506 }) // end of $(document).ready() for Truncate Table
3509 * Attach CodeMirror2 editor to SQL edit area.
3511 $(document).ready(function() {
3512 var elm = $('#sqlquery');
3513 if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3514 codemirror_editor = CodeMirror.fromTextArea(elm[0], {lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-mysql"});
3519 * jQuery plugin to cancel selection in HTML code.
3522 $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3523 var prevent = (p == null) ? true : p;
3525 return this.each(function () {
3526 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3529 else if ($.browser.mozilla) {
3530 $(this).css('MozUserSelect', 'none');
3531 $('body').trigger('focus');
3532 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3535 else $(this).attr('unselectable', 'on');
3538 return this.each(function () {
3539 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3540 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3541 else if ($.browser.opera) $(this).unbind('mousedown');
3542 else $(this).removeAttr('unselectable', 'on');
3549 * jQuery plugin to correctly filter input fields by value, needed
3550 * because some nasty values may break selector syntax
3553 $.fn.filterByValue = function (value) {
3554 return this.filter(function () {
3555 return $(this).val() === value
3561 * Create default PMA tooltip for the element specified. The default appearance
3562 * can be overriden by specifying optional "options" parameter (see qTip options).
3564 function PMA_createqTip($elements, content, options)
3566 if ($('#no_hint').length > 0) {
3574 tooltip: 'normalqTip',
3575 content: 'normalqTipContent'
3581 corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3582 adjust: { x: 10, y: 20 }
3599 $elements.qtip($.extend(true, o, options));
3603 * Return value of a cell in a table.
3605 function PMA_getCellValue(td) {
3606 if ($(td).is('.null')) {
3608 } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3609 return $(td).data('original_data');
3611 return $(td).text();
3615 /* Loads a js file, an array may be passed as well */
3616 loadJavascript=function(file) {
3617 if($.isArray(file)) {
3618 for(var i=0; i<file.length; i++) {
3619 $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3622 $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3626 $(document).ready(function() {
3630 $('a.themeselect').live('click', function(e) {
3634 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3640 * Automatic form submission on change.
3642 $('.autosubmit').change(function(e) {
3643 e.target.form.submit();
3649 $('.take_theme').click(function(e) {
3650 var what = this.name;
3651 if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3652 window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3653 window.opener.document.forms['setTheme'].submit();
3662 * Clear text selection
3664 function PMA_clearSelection() {
3665 if(document.selection && document.selection.empty) {
3666 document.selection.empty();
3667 } else if(window.getSelection) {
3668 var sel = window.getSelection();
3669 if(sel.empty) sel.empty();
3670 if(sel.removeAllRanges) sel.removeAllRanges();
3677 function escapeHtml(unsafe) {
3679 .replace(/&/g, "&")
3680 .replace(/</g, "<")
3681 .replace(/>/g, ">")
3682 .replace(/"/g, """)
3683 .replace(/'/g, "'");
3689 function printPage()
3691 // Do print the page
3692 if (typeof(window.print) != 'undefined') {
3697 $(document).ready(function() {
3698 $('input#print').click(printPage);
3702 * Makes the breadcrumbs and the menu bar float at the top of the viewport
3704 $(document).ready(function () {
3705 if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length == 0) {
3706 $("#floating_menubar")
3708 'position': 'fixed',
3714 .append($('#serverinfo'))
3715 .append($('#topmenucontainer'));
3718 $('#floating_menubar').outerHeight(true)