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();
1564 $(window).unbind('resize.dialog-resizer');
1565 $('#content-hide > *').unwrap();
1567 buttons: button_options
1568 }); // end dialog options
1570 PMA_convertFootnotesToTooltips($div);
1571 PMA_ajaxRemoveMessage($msgbox);
1577 * Creates a highcharts chart in the given container
1579 * @param var settings object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1580 * requires at least settings.chart.renderTo and settings.series to be set.
1581 * In addition there may be an additional property object 'realtime' that allows for realtime charting:
1583 * url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1584 * type: the GET request will also add type=[value of the type property] to the request
1585 * callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1586 * - the chart object
1587 * - the current response value of the GET request, JSON parsed
1588 * - the previous response value of the GET request, JSON parsed
1589 * - the number of added points
1590 * error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1593 * @return object The created highcharts instance
1595 function PMA_createChart(passedSettings)
1597 var container = passedSettings.chart.renderTo;
1603 backgroundColor: 'none',
1605 /* Live charting support */
1607 var thisChart = this;
1608 var lastValue = null, curValue = null;
1609 var numLoadedPoints = 0, otherSum = 0;
1612 // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1613 // Also don't do live charting if we don't have the server time
1614 if(thisChart.options.chart.forExport == true ||
1615 ! thisChart.options.realtime ||
1616 ! thisChart.options.realtime.callback ||
1617 ! server_time_diff) return;
1619 thisChart.options.realtime.timeoutCallBack = function() {
1620 thisChart.options.realtime.postRequest = $.post(
1621 thisChart.options.realtime.url,
1622 thisChart.options.realtime.postData,
1625 curValue = jQuery.parseJSON(data);
1627 if(thisChart.options.realtime.error)
1628 thisChart.options.realtime.error(err);
1632 if (lastValue==null) {
1633 diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1635 diff = parseInt(curValue.x - lastValue.x);
1638 thisChart.xAxis[0].setExtremes(
1639 thisChart.xAxis[0].getExtremes().min+diff,
1640 thisChart.xAxis[0].getExtremes().max+diff,
1644 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1646 lastValue = curValue;
1649 // Timeout has been cleared => don't start a new timeout
1650 if (chart_activeTimeouts[container] == null) {
1654 chart_activeTimeouts[container] = setTimeout(
1655 thisChart.options.realtime.timeoutCallBack,
1656 thisChart.options.realtime.refreshRate
1661 chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1681 text: PMA_messages['strTotalCount']
1690 formatter: function() {
1691 return '<b>' + this.series.name +'</b><br/>' +
1692 Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1693 Highcharts.numberFormat(this.y, 2);
1702 /* Set/Get realtime chart default values */
1703 if(passedSettings.realtime) {
1704 if(!passedSettings.realtime.refreshRate) {
1705 passedSettings.realtime.refreshRate = 5000;
1708 if(!passedSettings.realtime.numMaxPoints) {
1709 passedSettings.realtime.numMaxPoints = 30;
1712 // Allow custom POST vars to be added
1713 passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1715 if(server_time_diff) {
1716 settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1717 settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1721 // Overwrite/Merge default settings with passedsettings
1722 $.extend(true,settings,passedSettings);
1724 return new Highcharts.Chart(settings);
1729 * Creates a Profiling Chart. Used in sql.php and server_status.js
1731 function PMA_createProfilingChart(data, options)
1733 return PMA_createChart($.extend(true, {
1735 renderTo: 'profilingchart',
1738 title: { text:'', margin:0 },
1741 name: PMA_messages['strQueryExecutionTime'],
1746 allowPointSelect: true,
1751 formatter: function() {
1752 return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1758 formatter: function() {
1759 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1766 * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1768 * @param integer Number to be formatted, should be in the range of microsecond to second
1769 * @param integer Acuracy, how many numbers right to the comma should be
1770 * @return string The formatted number
1772 function PMA_prettyProfilingNum(num, acc)
1777 acc = Math.pow(10,acc);
1778 if (num * 1000 < 0.1) {
1779 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1780 } else if (num < 0.1) {
1781 num = Math.round(acc * (num * 1000)) / acc + 'm';
1783 num = Math.round(acc * num) / acc;
1791 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1793 * @param string Query to be formatted
1794 * @return string The formatted query
1796 function PMA_SQLPrettyPrint(string)
1798 var mode = CodeMirror.getMode({},"text/x-mysql");
1799 var stream = new CodeMirror.StringStream(string);
1800 var state = mode.startState();
1801 var token, tokens = [];
1803 var tabs = function(cnt) {
1805 for (var i=0; i<4*cnt; i++)
1810 // "root-level" statements
1812 'select': ['select', 'from','on','where','having','limit','order by','group by'],
1813 'update': ['update', 'set','where'],
1814 'insert into': ['insert into', 'values']
1816 // don't put spaces before these tokens
1817 var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1818 // don't put spaces after these tokens
1819 var spaceExceptionsAfter = { '.': true };
1821 // Populate tokens array
1823 while (! stream.eol()) {
1824 stream.start = stream.pos;
1825 token = mode.token(stream, state);
1827 tokens.push([token, stream.current().toLowerCase()]);
1831 var currentStatement = tokens[0][1];
1833 if(! statements[currentStatement]) {
1836 // Holds all currently opened code blocks (statement, function or generic)
1837 var blockStack = [];
1838 // Holds the type of block from last iteration (the current is in blockStack[0])
1840 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1841 var newBlock, endBlock;
1842 // How much to indent in the current line
1843 var indentLevel = 0;
1844 // Holds the "root-level" statements
1845 var statementPart, lastStatementPart = statements[currentStatement][0];
1847 blockStack.unshift('statement');
1849 // Iterate through every token and format accordingly
1850 for (var i = 0; i < tokens.length; i++) {
1851 previousBlock = blockStack[0];
1853 // New block => push to stack
1854 if (tokens[i][1] == '(') {
1855 if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1856 blockStack.unshift(newBlock = 'statement');
1857 } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1858 blockStack.unshift(newBlock = 'function');
1860 blockStack.unshift(newBlock = 'generic');
1866 // Block end => pop from stack
1867 if (tokens[i][1] == ')') {
1868 endBlock = blockStack[0];
1874 // A subquery is starting
1875 if (i > 0 && newBlock == 'statement') {
1877 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1878 currentStatement = tokens[i+1][1];
1883 // A subquery is ending
1884 if (endBlock == 'statement' && indentLevel > 0) {
1885 output += "\n" + tabs(indentLevel);
1889 // One less indentation for statement parts (from, where, order by, etc.) and a newline
1890 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1891 if (statementPart != -1) {
1892 if (i > 0) output += "\n";
1893 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1894 output += "\n" + tabs(indentLevel + 1);
1895 lastStatementPart = tokens[i][1];
1897 // Normal indentatin and spaces for everything else
1899 if (! spaceExceptionsBefore[tokens[i][1]]
1900 && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1901 && output.charAt(output.length -1) != ' ' ) {
1904 if (tokens[i][0] == 'keyword') {
1905 output += tokens[i][1].toUpperCase();
1907 output += tokens[i][1];
1911 // split columns in select and 'update set' clauses, but only inside statements blocks
1912 if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
1913 && tokens[i][1]==',' && blockStack[0] == 'statement') {
1915 output += "\n" + tabs(indentLevel + 1);
1918 // split conditions in where clauses, but only inside statements blocks
1919 if (lastStatementPart == 'where'
1920 && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1922 if (blockStack[0] == 'statement') {
1923 output += "\n" + tabs(indentLevel + 1);
1925 // Todo: Also split and or blocks in newlines & identation++
1926 //if(blockStack[0] == 'generic')
1934 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1935 * return a jQuery object yet and hence cannot be chained
1937 * @param string question
1938 * @param string url URL to be passed to the callbackFn to make
1940 * @param function callbackFn callback to execute after user clicks on OK
1943 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1944 if (PMA_messages['strDoYouReally'] == '') {
1949 * @var button_options Object that stores the options passed to jQueryUI
1952 var button_options = {};
1953 button_options[PMA_messages['strOK']] = function(){
1954 $(this).dialog("close").remove();
1956 if($.isFunction(callbackFn)) {
1957 callbackFn.call(this, url);
1960 button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1962 $('<div id="confirm_dialog"></div>')
1964 .dialog({buttons: button_options});
1968 * jQuery function to sort a table's body after a new row has been appended to it.
1969 * Also fixes the even/odd classes of the table rows at the end.
1971 * @param string text_selector string to select the sortKey's text
1973 * @return jQuery Object for chaining purposes
1975 jQuery.fn.PMA_sort_table = function(text_selector) {
1976 return this.each(function() {
1979 * @var table_body Object referring to the table's <tbody> element
1981 var table_body = $(this);
1983 * @var rows Object referring to the collection of rows in {@link table_body}
1985 var rows = $(this).find('tr').get();
1987 //get the text of the field that we will sort by
1988 $.each(rows, function(index, row) {
1989 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1992 //get the sorted order
1993 rows.sort(function(a,b) {
1994 if(a.sortKey < b.sortKey) {
1997 if(a.sortKey > b.sortKey) {
2003 //pull out each row from the table and then append it according to it's order
2004 $.each(rows, function(index, row) {
2005 $(table_body).append(row);
2009 //Re-check the classes of each row
2010 $(this).find('tr:odd')
2011 .removeClass('even').addClass('odd')
2014 .removeClass('odd').addClass('even');
2019 * jQuery coding for 'Create Table'. Used on db_operations.php,
2020 * db_structure.php and db_tracking.php (i.e., wherever
2021 * libraries/display_create_table.lib.php is used)
2023 * Attach Ajax Event handlers for Create Table
2025 $(document).ready(function() {
2028 * Attach event handler to the submit action of the create table minimal form
2029 * and retrieve the full table form and display it in a dialog
2031 * @uses PMA_ajaxShowMessage()
2033 $("#create_table_form_minimal.ajax").live('submit', function(event) {
2034 event.preventDefault();
2036 PMA_prepareForAjaxRequest($form);
2038 /*variables which stores the common attributes*/
2039 var url = $form.serialize();
2040 var action = $form.attr('action');
2041 var $div = $('<div id="create_table_dialog"></div>');
2043 /*Calling to the createTableDialog function*/
2044 PMA_createTableDialog($div, url, action);
2046 // empty table name and number of columns from the minimal form
2047 $form.find('input[name=table],input[name=num_fields]').val('');
2051 * Attach event handler for submission of create table form (save)
2053 * @uses PMA_ajaxShowMessage()
2054 * @uses $.PMA_sort_table()
2057 // .live() must be called after a selector, see http://api.jquery.com/live
2058 $("#create_table_form input[name=do_save_data]").live('click', function(event) {
2059 event.preventDefault();
2062 * @var the_form object referring to the create table form
2064 var $form = $("#create_table_form");
2067 * First validate the form; if there is a problem, avoid submitting it
2069 * checkTableEditForm() needs a pure element and not a jQuery object,
2070 * this is why we pass $form[0] as a parameter (the jQuery object
2071 * is actually an array of DOM elements)
2074 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2075 // OK, form passed validation step
2076 if ($form.hasClass('ajax')) {
2077 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2078 PMA_prepareForAjaxRequest($form);
2079 //User wants to submit the form
2080 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
2081 if(data.success == true) {
2082 $('#properties_message')
2083 .removeClass('error')
2085 PMA_ajaxShowMessage(data.message);
2086 // Only if the create table dialog (distinct panel) exists
2087 if ($("#create_table_dialog").length > 0) {
2088 $("#create_table_dialog").dialog("close").remove();
2092 * @var tables_table Object referring to the <tbody> element that holds the list of tables
2094 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
2095 // this is the first table created in this db
2096 if (tables_table.length == 0) {
2097 if (window.parent && window.parent.frame_content) {
2098 window.parent.frame_content.location.reload();
2102 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
2104 var curr_last_row = $(tables_table).find('tr:last');
2106 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
2108 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2110 * @var curr_last_row_index Index of {@link curr_last_row}
2112 var curr_last_row_index = parseFloat(curr_last_row_index_string);
2114 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
2116 var new_last_row_index = curr_last_row_index + 1;
2118 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2120 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2122 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2124 $(data.new_table_string)
2125 .appendTo(tables_table);
2128 $(tables_table).PMA_sort_table('th');
2131 //Refresh navigation frame as a new table has been added
2132 if (window.parent && window.parent.frame_navigation) {
2133 window.parent.frame_navigation.location.reload();
2136 $('#properties_message')
2139 // scroll to the div containing the error message
2140 $('#properties_message')[0].scrollIntoView();
2143 } // end if ($form.hasClass('ajax')
2146 $form.append('<input type="hidden" name="do_save_data" value="save" />');
2149 } // end if (checkTableEditForm() )
2150 }) // end create table form (save)
2153 * Attach event handler for create table form (add fields)
2155 * @uses PMA_ajaxShowMessage()
2156 * @uses $.PMA_sort_table()
2157 * @uses window.parent.refreshNavigation()
2160 // .live() must be called after a selector, see http://api.jquery.com/live
2161 $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2162 event.preventDefault();
2165 * @var the_form object referring to the create table form
2167 var $form = $("#create_table_form");
2169 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2170 PMA_prepareForAjaxRequest($form);
2172 //User wants to add more fields to the table
2173 $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2174 // if 'create_table_dialog' exists
2175 if ($("#create_table_dialog").length > 0) {
2176 $("#create_table_dialog").html(data);
2178 // if 'create_table_div' exists
2179 if ($("#create_table_div").length > 0) {
2180 $("#create_table_div").html(data);
2182 PMA_verifyColumnsProperties();
2183 PMA_ajaxRemoveMessage($msgbox);
2186 }) // end create table form (add fields)
2188 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2191 * jQuery coding for 'Change Table' and 'Add Column'. Used on tbl_structure.php *
2192 * Attach Ajax Event handlers for Change Table
2194 $(document).ready(function() {
2196 *Ajax action for submitting the "Column Change" and "Add Column" form
2198 $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2199 event.preventDefault();
2201 * @var the_form object referring to the export form
2203 var $form = $("#append_fields_form");
2206 * First validate the form; if there is a problem, avoid submitting it
2208 * checkTableEditForm() needs a pure element and not a jQuery object,
2209 * this is why we pass $form[0] as a parameter (the jQuery object
2210 * is actually an array of DOM elements)
2212 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2213 // OK, form passed validation step
2214 if ($form.hasClass('ajax')) {
2215 PMA_prepareForAjaxRequest($form);
2216 //User wants to submit the form
2217 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2218 if ($("#sqlqueryresults").length != 0) {
2219 $("#sqlqueryresults").remove();
2220 } else if ($(".error").length != 0) {
2221 $(".error").remove();
2223 if (data.success == true) {
2224 PMA_ajaxShowMessage(data.message);
2225 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2226 $("#sqlqueryresults").html(data.sql_query);
2227 $("#result_query .notice").remove();
2228 $("#result_query").prepend((data.message));
2229 if ($("#change_column_dialog").length > 0) {
2230 $("#change_column_dialog").dialog("close").remove();
2231 } else if ($("#add_columns").length > 0) {
2232 $("#add_columns").dialog("close").remove();
2234 /*Reload the field form*/
2235 $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2236 $("#fieldsForm").remove();
2237 $("#addColumns").remove();
2238 var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2239 if ($("#sqlqueryresults").length != 0) {
2240 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2242 $temp_div.find("#fieldsForm").insertAfter(".error");
2244 $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2245 /*Call the function to display the more options in table*/
2246 displayMoreTableOpts();
2249 var $temp_div = $("<div id='temp_div'><div>").append(data);
2250 var $error = $temp_div.find(".error code").addClass("error");
2251 PMA_ajaxShowMessage($error);
2256 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2260 }) // end change table button "do_save_data"
2262 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2265 * jQuery coding for 'Table operations'. Used on tbl_operations.php
2266 * Attach Ajax Event handlers for Table operations
2268 $(document).ready(function() {
2270 *Ajax action for submitting the "Alter table order by"
2272 $("#alterTableOrderby.ajax").live('submit', function(event) {
2273 event.preventDefault();
2274 var $form = $(this);
2276 PMA_prepareForAjaxRequest($form);
2277 /*variables which stores the common attributes*/
2278 $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2279 if ($("#sqlqueryresults").length != 0) {
2280 $("#sqlqueryresults").remove();
2282 if ($("#result_query").length != 0) {
2283 $("#result_query").remove();
2285 if (data.success == true) {
2286 PMA_ajaxShowMessage(data.message);
2287 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2288 $("#sqlqueryresults").html(data.sql_query);
2289 $("#result_query .notice").remove();
2290 $("#result_query").prepend((data.message));
2292 var $temp_div = $("<div id='temp_div'></div>")
2293 $temp_div.html(data.error);
2294 var $error = $temp_div.find("code").addClass("error");
2295 PMA_ajaxShowMessage($error);
2298 });//end of alterTableOrderby ajax submit
2301 *Ajax action for submitting the "Copy table"
2303 $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2304 event.preventDefault();
2305 var $form = $("#copyTable");
2306 if($form.find("input[name='switch_to_new']").attr('checked')) {
2307 $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2308 $form.removeClass('ajax');
2309 $form.find("#ajax_request_hidden").remove();
2312 PMA_prepareForAjaxRequest($form);
2313 /*variables which stores the common attributes*/
2314 $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2315 if ($("#sqlqueryresults").length != 0) {
2316 $("#sqlqueryresults").remove();
2318 if ($("#result_query").length != 0) {
2319 $("#result_query").remove();
2321 if (data.success == true) {
2322 PMA_ajaxShowMessage(data.message);
2323 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2324 $("#sqlqueryresults").html(data.sql_query);
2325 $("#result_query .notice").remove();
2326 $("#result_query").prepend((data.message));
2327 $("#copyTable").find("select[name='target_db'] option").filterByValue(data.db).attr('selected', 'selected');
2329 //Refresh navigation frame when the table is coppied
2330 if (window.parent && window.parent.frame_navigation) {
2331 window.parent.frame_navigation.location.reload();
2334 var $temp_div = $("<div id='temp_div'></div>");
2335 $temp_div.html(data.error);
2336 var $error = $temp_div.find("code").addClass("error");
2337 PMA_ajaxShowMessage($error);
2341 });//end of copyTable ajax submit
2344 *Ajax events for actions in the "Table maintenance"
2346 $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2347 event.preventDefault();
2348 var $link = $(this);
2349 var href = $link.attr("href");
2350 href = href.split('?');
2351 if ($("#sqlqueryresults").length != 0) {
2352 $("#sqlqueryresults").remove();
2354 if ($("#result_query").length != 0) {
2355 $("#result_query").remove();
2357 //variables which stores the common attributes
2358 $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2359 if (data.success == undefined) {
2360 var $temp_div = $("<div id='temp_div'></div>");
2361 $temp_div.html(data);
2362 var $success = $temp_div.find("#result_query .success");
2363 PMA_ajaxShowMessage($success);
2364 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2365 $("#sqlqueryresults").html(data);
2367 $("#sqlqueryresults").children("fieldset").remove();
2368 } else if (data.success == true ) {
2369 PMA_ajaxShowMessage(data.message);
2370 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2371 $("#sqlqueryresults").html(data.sql_query);
2373 var $temp_div = $("<div id='temp_div'></div>");
2374 $temp_div.html(data.error);
2375 var $error = $temp_div.find("code").addClass("error");
2376 PMA_ajaxShowMessage($error);
2379 });//end of table maintanance ajax click
2381 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2385 * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2386 * as it was also required on db_create.php
2388 * @uses $.PMA_confirm()
2389 * @uses PMA_ajaxShowMessage()
2390 * @uses window.parent.refreshNavigation()
2391 * @uses window.parent.refreshMain()
2392 * @see $cfg['AjaxEnable']
2394 $(document).ready(function() {
2395 $("#drop_db_anchor").live('click', function(event) {
2396 event.preventDefault();
2398 //context is top.frame_content, so we need to use window.parent.db to access the db var
2400 * @var question String containing the question to be asked for confirmation
2402 var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
2404 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2406 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2407 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2408 //Database deleted successfully, refresh both the frames
2409 window.parent.refreshNavigation();
2410 window.parent.refreshMain();
2412 }); // end $.PMA_confirm()
2413 }); //end of Drop Database Ajax action
2414 }) // end of $(document).ready() for Drop Database
2417 * Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
2418 * display_create_database.lib.php is used, ie main.php and server_databases.php
2420 * @uses PMA_ajaxShowMessage()
2421 * @see $cfg['AjaxEnable']
2423 $(document).ready(function() {
2425 $('#create_database_form.ajax').live('submit', function(event) {
2426 event.preventDefault();
2430 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2431 PMA_prepareForAjaxRequest($form);
2433 $.post($form.attr('action'), $form.serialize(), function(data) {
2434 if(data.success == true) {
2435 PMA_ajaxShowMessage(data.message);
2437 //Append database's row to table
2438 $("#tabledatabases")
2440 .append(data.new_db_string)
2441 .PMA_sort_table('.name')
2442 .find('#db_summary_row')
2443 .appendTo('#tabledatabases tbody')
2444 .removeClass('odd even');
2446 var $databases_count_object = $('#databases_count');
2447 var databases_count = parseInt($databases_count_object.text());
2448 $databases_count_object.text(++databases_count);
2449 //Refresh navigation frame as a new database has been added
2450 if (window.parent && window.parent.frame_navigation) {
2451 window.parent.frame_navigation.location.reload();
2455 PMA_ajaxShowMessage(data.error);
2458 }) // end $().live()
2459 }) // end $(document).ready() for Create Database
2462 * Attach Ajax event handlers for 'Change Password' on main.php
2464 $(document).ready(function() {
2467 * Attach Ajax event handler on the change password anchor
2468 * @see $cfg['AjaxEnable']
2470 $('#change_password_anchor.dialog_active').live('click',function(event) {
2471 event.preventDefault();
2474 $('#change_password_anchor.ajax').live('click', function(event) {
2475 event.preventDefault();
2476 $(this).removeClass('ajax').addClass('dialog_active');
2478 * @var button_options Object containing options to be passed to jQueryUI's dialog
2480 var button_options = {};
2481 button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2482 $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2483 $('<div id="change_password_dialog"></div>')
2485 title: PMA_messages['strChangePassword'],
2487 close: function(ev,ui) {$(this).remove();},
2488 buttons : button_options,
2489 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2492 displayPasswordGenerateButton();
2494 }) // end handler for change password anchor
2497 * Attach Ajax event handler for Change Password form submission
2499 * @uses PMA_ajaxShowMessage()
2500 * @see $cfg['AjaxEnable']
2502 $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2503 event.preventDefault();
2506 * @var the_form Object referring to the change password form
2508 var the_form = $("#change_password_form");
2511 * @var this_value String containing the value of the submit button.
2512 * Need to append this for the change password form on Server Privileges
2515 var this_value = $(this).val();
2517 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2518 $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2520 $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2521 if(data.success == true) {
2522 $("#floating_menubar").after(data.sql_query);
2523 $("#change_password_dialog").hide().remove();
2524 $("#edit_user_dialog").dialog("close").remove();
2525 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2526 PMA_ajaxRemoveMessage($msgbox);
2529 PMA_ajaxShowMessage(data.error);
2532 }) // end handler for Change Password form submission
2533 }) // end $(document).ready() for Change Password
2536 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2537 * the page loads and when the selected data type changes
2539 $(document).ready(function() {
2540 // is called here for normal page loads and also when opening
2541 // the Create table dialog
2542 PMA_verifyColumnsProperties();
2544 // needs live() to work also in the Create Table dialog
2545 $("select[class='column_type']").live('change', function() {
2546 PMA_showNoticeForEnum($(this));
2548 $(".default_type").live('change', function() {
2549 PMA_hideShowDefaultValue($(this));
2553 function PMA_verifyColumnsProperties()
2555 $("select[class='column_type']").each(function() {
2556 PMA_showNoticeForEnum($(this));
2558 $(".default_type").each(function() {
2559 PMA_hideShowDefaultValue($(this));
2564 * Hides/shows the default value input field, depending on the default type
2566 function PMA_hideShowDefaultValue($default_type)
2568 if ($default_type.val() == 'USER_DEFINED') {
2569 $default_type.siblings('.default_value').show().focus();
2571 $default_type.siblings('.default_value').hide();
2576 * @var $enum_editor_dialog An object that points to the jQuery
2577 * dialog of the ENUM/SET editor
2579 var $enum_editor_dialog = null;
2581 * Opens the ENUM/SET editor and controls its functions
2583 $(document).ready(function() {
2584 $("a.open_enum_editor").live('click', function() {
2585 // Get the name of the column that is being edited
2586 var colname = $(this).closest('tr').find('input:first').val();
2587 // And use it to make up a title for the page
2588 if (colname.length < 1) {
2589 var title = PMA_messages['enum_newColumnVals'];
2591 var title = PMA_messages['enum_columnVals'].replace(
2593 '"' + decodeURIComponent(colname) + '"'
2596 // Get the values as a string
2597 var inputstring = $(this)
2601 // Escape html entities
2602 inputstring = $('<div/>')
2605 // Parse the values, escaping quotes and
2606 // slashes on the fly, into an array
2608 // There is a PHP port of the below parser in enum_editor.php
2609 // If you are fixing something here, you need to also update the PHP port.
2611 var in_string = false;
2612 var curr, next, buffer = '';
2613 for (var i=0; i<inputstring.length; i++) {
2614 curr = inputstring.charAt(i);
2615 next = i == inputstring.length ? '' : inputstring.charAt(i+1);
2616 if (! in_string && curr == "'") {
2618 } else if (in_string && curr == "\\" && next == "\\") {
2621 } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
2624 } else if (in_string && curr == "'") {
2626 values.push(buffer);
2628 } else if (in_string) {
2632 if (buffer.length > 0) {
2633 // The leftovers in the buffer are the last value (if any)
2634 values.push(buffer);
2637 // If there are no values, maybe the user is about to make a
2638 // new list so we add a few for him/her to get started with.
2639 if (values.length == 0) {
2640 values.push('','','','');
2642 // Add the parsed values to the editor
2643 var drop_icon = PMA_getImage('b_drop.png');
2644 for (var i=0; i<values.length; i++) {
2645 fields += "<tr><td>"
2646 + "<input type='text' value='" + values[i] + "'/>"
2647 + "</td><td class='drop'>"
2652 * @var dialog HTML code for the ENUM/SET dialog
2654 var dialog = "<div id='enum_editor'>"
2656 + "<legend>" + title + "</legend>"
2657 + "<p>" + PMA_getImage('s_notice.png')
2658 + PMA_messages['enum_hint'] + "</p>"
2659 + "<table class='values'>" + fields + "</table>"
2660 + "</fieldset><fieldset class='tblFooters'>"
2661 + "<table class='add'><tr><td>"
2662 + "<div class='slider'></div>"
2664 + "<form><div><input type='submit' class='add_value' value='"
2665 + PMA_messages['enum_addValue'].replace(/%d/, 1)
2666 + "'/></div></form>"
2667 + "</td></tr></table>"
2668 + "<input type='hidden' value='" // So we know which column's data is being edited
2669 + $(this).closest('td').find("input").attr("id")
2674 * @var Defines functions to be called when the buttons in
2675 * the buttonOptions jQuery dialog bar are pressed
2677 var buttonOptions = {};
2678 buttonOptions[PMA_messages['strGo']] = function () {
2679 // When the submit button is clicked,
2680 // put the data back into the original form
2681 var value_array = new Array();
2682 $(this).find(".values input").each(function(index, elm) {
2683 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
2684 value_array.push("'" + val + "'");
2686 // get the Length/Values text field where this value belongs
2687 var values_id = $(this).find("input[type='hidden']").attr("value");
2688 $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2689 $(this).dialog("close");
2691 buttonOptions[PMA_messages['strClose']] = function () {
2692 $(this).dialog("close");
2695 var width = parseInt(
2696 (parseInt($('html').css('font-size'), 10)/13)*340,
2702 $enum_editor_dialog = $(dialog).dialog({
2705 title: PMA_messages['enum_editor'],
2706 buttons: buttonOptions,
2708 // Focus the "Go" button after opening the dialog
2709 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
2715 // slider for choosing how many fields to add
2716 $enum_editor_dialog.find(".slider").slider({
2722 slide: function( event, ui ) {
2723 $(this).closest('table').find('input[type=submit]').val(
2724 PMA_messages['enum_addValue'].replace(/%d/, ui.value)
2728 // Focus the slider, otherwise it looks nearly transparent
2729 $('.ui-slider-handle').addClass('ui-state-focus');
2733 // When "add a new value" is clicked, append an empty text field
2734 $("input.add_value").live('click', function(e) {
2736 var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
2737 while (num_new_rows--) {
2738 $enum_editor_dialog.find('.values')
2740 "<tr style='display: none;'><td>"
2741 + "<input type='text' />"
2742 + "</td><td class='drop'>"
2743 + PMA_getImage('b_drop.png')
2751 // Removes the specified row from the enum editor
2752 $("#enum_editor td.drop").live('click', function() {
2753 $(this).closest('tr').hide('fast', function () {
2760 * Hides certain table structure actions, replacing them
2761 * with the word "More". They are displayed in a dropdown
2762 * menu when the user hovers over the word "More."
2764 $(document).ready(function() {
2765 displayMoreTableOpts();
2768 function displayMoreTableOpts()
2770 // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2771 // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2772 if($("input[type='hidden'][name='table_type']").val() == "table") {
2773 var $table = $("table[id='tablestructure']");
2774 $table.find("td[class='browse']").remove();
2775 $table.find("td[class='primary']").remove();
2776 $table.find("td[class='unique']").remove();
2777 $table.find("td[class='index']").remove();
2778 $table.find("td[class='fulltext']").remove();
2779 $table.find("td[class='spatial']").remove();
2780 $table.find("th[class='action']").attr("colspan", 3);
2782 // Display the "more" text
2783 $table.find("td[class='more_opts']").show();
2785 // Position the dropdown
2786 $(".structure_actions_dropdown").each(function() {
2787 // Optimize DOM querying
2788 var $this_dropdown = $(this);
2789 // The top offset must be set for IE even if it didn't change
2790 var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2791 var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2792 var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2793 $this_dropdown.offset({ top: top_offset, left: left_offset });
2796 // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2797 // positioning an iframe directly on top of it
2798 var $after_field = $("select[name='after_field']");
2799 $("iframe[class='IE_hack']")
2800 .width($after_field.width())
2801 .height($after_field.height())
2803 top: $after_field.offset().top,
2804 left: $after_field.offset().left
2807 // When "more" is hovered over, show the hidden actions
2808 $table.find("td[class='more_opts']")
2809 .mouseenter(function() {
2810 if($.browser.msie && $.browser.version == "6.0") {
2811 $("iframe[class='IE_hack']")
2813 .width($after_field.width()+4)
2814 .height($after_field.height()+4)
2816 top: $after_field.offset().top,
2817 left: $after_field.offset().left
2820 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2821 $(this).children(".structure_actions_dropdown").show();
2822 // Need to do this again for IE otherwise the offset is wrong
2823 if($.browser.msie) {
2824 var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2825 var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2826 $(this).children(".structure_actions_dropdown").offset({
2828 left: left_offset_IE });
2831 .mouseleave(function() {
2832 $(this).children(".structure_actions_dropdown").hide();
2833 if($.browser.msie && $.browser.version == "6.0") {
2834 $("iframe[class='IE_hack']").hide();
2840 $(document).ready(function(){
2841 PMA_convertFootnotesToTooltips();
2845 * Ensures indexes names are valid according to their type and, for a primary
2846 * key, lock index name to 'PRIMARY'
2847 * @param string form_id Variable which parses the form name as
2849 * @return boolean false if there is no index form, true else
2851 function checkIndexName(form_id)
2853 if ($("#"+form_id).length == 0) {
2857 // Gets the elements pointers
2858 var $the_idx_name = $("#input_index_name");
2859 var $the_idx_type = $("#select_index_type");
2861 // Index is a primary key
2862 if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2863 $the_idx_name.attr("value", 'PRIMARY');
2864 $the_idx_name.attr("disabled", true);
2869 if ($the_idx_name.attr("value") == 'PRIMARY') {
2870 $the_idx_name.attr("value", '');
2872 $the_idx_name.attr("disabled", false);
2876 } // end of the 'checkIndexName()' function
2879 * function to convert the footnotes to tooltips
2881 * @param jquery-Object $div a div jquery object which specifies the
2882 * domain for searching footnootes. If we
2883 * ommit this parameter the function searches
2884 * the footnotes in the whole body
2886 function PMA_convertFootnotesToTooltips($div)
2888 // Hide the footnotes from the footer (which are displayed for
2889 // JavaScript-disabled browsers) since the tooltip is sufficient
2891 if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2895 $footnotes = $div.find(".footnotes");
2898 $footnotes.find('span').each(function() {
2899 $(this).children("sup").remove();
2901 // The border and padding must be removed otherwise a thin yellow box remains visible
2902 $footnotes.css("border", "none");
2903 $footnotes.css("padding", "0px");
2905 // Replace the superscripts with the help icon
2906 $div.find("sup.footnotemarker").hide();
2907 $div.find("img.footnotemarker").show();
2909 $div.find("img.footnotemarker").each(function() {
2910 var img_class = $(this).attr("class");
2911 /** img contains two classes, as example "footnotemarker footnote_1".
2912 * We split it by second class and take it for the id of span
2914 img_class = img_class.split(" ");
2915 for (i = 0; i < img_class.length; i++) {
2916 if (img_class[i].split("_")[0] == "footnote") {
2917 var span_id = img_class[i].split("_")[1];
2921 * Now we get the #id of the span with span_id variable. As an example if we
2922 * initially get the img class as "footnotemarker footnote_2", now we get
2923 * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2925 var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2927 content: tooltip_text,
2929 hide: { delay: 1000 },
2930 style: { background: '#ffffcc' }
2936 * This function handles the resizing of the content frame
2937 * and adjusts the top menu according to the new size of the frame
2939 function menuResize()
2941 var $cnt = $('#topmenu');
2942 var wmax = $cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2943 var $submenu = $cnt.find('.submenu');
2944 var submenu_w = $submenu.outerWidth(true);
2945 var $submenu_ul = $submenu.find('ul');
2946 var $li = $cnt.find('> li');
2947 var $li2 = $submenu_ul.find('li');
2948 var more_shown = $li2.length > 0;
2950 // Calculate the total width used by all the shown tabs
2951 var total_len = more_shown ? submenu_w : 0;
2952 for (var i = 0; i < $li.length-1; i++) {
2953 total_len += $($li[i]).outerWidth(true);
2956 // Now hide menu elements that don't fit into the menubar
2957 var i = $li.length-1;
2958 var hidden = false; // Whether we have hidden any tabs
2959 while (total_len >= wmax && --i >= 0) { // Process the tabs backwards
2962 var el_width = el.outerWidth(true);
2963 el.data('width', el_width);
2965 total_len -= el_width;
2966 el.prependTo($submenu_ul);
2967 total_len += submenu_w;
2970 total_len -= el_width;
2971 el.prependTo($submenu_ul);
2975 // If we didn't hide any tabs, then there might be some space to show some
2977 // Show menu elements that do fit into the menubar
2978 for (var i = 0; i < $li2.length; i++) {
2979 total_len += $($li2[i]).data('width');
2980 // item fits or (it is the last item
2981 // and it would fit if More got removed)
2982 if (total_len < wmax
2983 || (i == $li2.length - 1 && total_len - submenu_w < wmax)
2985 $($li2[i]).insertBefore($submenu);
2992 // Show/hide the "More" tab as needed
2993 if ($submenu_ul.find('li').length > 0) {
2994 $submenu.addClass('shown');
2996 $submenu.removeClass('shown');
2999 if ($cnt.find('> li').length == 1) {
3000 // If there is only the "More" tab left, then we need
3001 // to align the submenu to the left edge of the tab
3002 $submenu_ul.removeClass().addClass('only');
3004 // Otherwise we align the submenu to the right edge of the tab
3005 $submenu_ul.removeClass().addClass('notonly');
3008 if ($submenu.find('.tabactive').length) {
3009 $submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
3011 $submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
3016 var topmenu = $('#topmenu');
3017 if (topmenu.length == 0) {
3020 // create submenu container
3021 var link = $('<a />', {href: '#', 'class': 'tab'})
3022 .text(PMA_messages['strMore'])
3023 .click(function(e) {
3026 var img = topmenu.find('li:first-child img');
3028 $(PMA_getImage('b_more.png').toString()).prependTo(link);
3030 var submenu = $('<li />', {'class': 'submenu'})
3032 .append($('<ul />'))
3033 .mouseenter(function() {
3034 if ($(this).find('ul .tabactive').length == 0) {
3035 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
3038 .mouseleave(function() {
3039 if ($(this).find('ul .tabactive').length == 0) {
3040 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
3043 topmenu.append(submenu);
3045 // populate submenu and register resize event
3047 $(window).resize(menuResize);
3051 * Get the row number from the classlist (for example, row_1)
3053 function PMA_getRowNumber(classlist)
3055 return parseInt(classlist.split(/\s+row_/)[1]);
3059 * Changes status of slider
3061 function PMA_set_status_label($element)
3063 var text = $element.css('display') == 'none'
3066 $element.closest('.slide-wrapper').prev().find('span').text(text);
3070 * Initializes slider effect.
3072 function PMA_init_slider()
3074 $('.pma_auto_slider').each(function() {
3075 var $this = $(this);
3077 if ($this.hasClass('slider_init_done')) {
3080 $this.addClass('slider_init_done');
3082 var $wrapper = $('<div>', {'class': 'slide-wrapper'});
3083 $wrapper.toggle($this.is(':visible'));
3084 $('<a>', {href: '#'+this.id})
3086 .prepend($('<span>'))
3087 .insertBefore($this)
3089 var $wrapper = $this.closest('.slide-wrapper');
3090 var visible = $this.is(':visible');
3094 $this[visible ? 'hide' : 'show']('blind', function() {
3095 $wrapper.toggle(!visible);
3096 PMA_set_status_label($this);
3100 $this.wrap($wrapper);
3101 PMA_set_status_label($this);
3106 * var toggleButton This is a function that creates a toggle
3107 * sliding button given a jQuery reference
3108 * to the correct DOM element
3110 var toggleButton = function ($obj) {
3111 // In rtl mode the toggle switch is flipped horizontally
3112 // so we need to take that into account
3113 if ($('.text_direction', $obj).text() == 'ltr') {
3114 var right = 'right';
3119 * var h Height of the button, used to scale the
3120 * background image and position the layers
3122 var h = $obj.height();
3123 $('img', $obj).height(h);
3124 $('table', $obj).css('bottom', h-1);
3126 * var on Width of the "ON" part of the toggle switch
3127 * var off Width of the "OFF" part of the toggle switch
3129 var on = $('.toggleOn', $obj).width();
3130 var off = $('.toggleOff', $obj).width();
3131 // Make the "ON" and "OFF" parts of the switch the same size
3132 $('.toggleOn > div', $obj).width(Math.max(on, off));
3133 $('.toggleOff > div', $obj).width(Math.max(on, off));
3135 * var w Width of the central part of the switch
3137 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
3138 // Resize the central part of the switch on the top
3139 // layer to match the background
3140 $('table td:nth-child(2) > div', $obj).width(w);
3142 * var imgw Width of the background image
3143 * var tblw Width of the foreground layer
3144 * var offset By how many pixels to move the background
3145 * image, so that it matches the top layer
3147 var imgw = $('img', $obj).width();
3148 var tblw = $('table', $obj).width();
3149 var offset = parseInt(((imgw - tblw) / 2), 10);
3150 // Move the background to match the layout of the top layer
3151 $obj.find('img').css(right, offset);
3153 * var offw Outer width of the "ON" part of the toggle switch
3154 * var btnw Outer width of the central part of the switch
3156 var offw = $('.toggleOff', $obj).outerWidth();
3157 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
3158 // Resize the main div so that exactly one side of
3159 // the switch plus the central part fit into it.
3160 $obj.width(offw + btnw + 2);
3162 * var move How many pixels to move the
3163 * switch by when toggling
3165 var move = $('.toggleOff', $obj).outerWidth();
3166 // If the switch is initialized to the
3167 // OFF state we need to move it now.
3168 if ($('.container', $obj).hasClass('off')) {
3169 if (right == 'right') {
3170 $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
3172 $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
3175 // Attach an 'onclick' event to the switch
3176 $('.container', $obj).click(function () {
3177 if ($(this).hasClass('isActive')) {
3180 $(this).addClass('isActive');
3182 var $msg = PMA_ajaxShowMessage();
3183 var $container = $(this);
3184 var callback = $('.callback', this).text();
3185 // Perform the actual toggle
3186 if ($(this).hasClass('on')) {
3187 if (right == 'right') {
3188 var operator = '-=';
3190 var operator = '+=';
3192 var url = $(this).find('.toggleOff > span').text();
3193 var removeClass = 'on';
3194 var addClass = 'off';
3196 if (right == 'right') {
3197 var operator = '+=';
3199 var operator = '-=';
3201 var url = $(this).find('.toggleOn > span').text();
3202 var removeClass = 'off';
3203 var addClass = 'on';
3205 $.post(url, {'ajax_request': true}, function(data) {
3206 if(data.success == true) {
3207 PMA_ajaxRemoveMessage($msg);
3209 .removeClass(removeClass)
3211 .animate({'left': operator + move + 'px'}, function () {
3212 $container.removeClass('isActive');
3216 PMA_ajaxShowMessage(data.error);
3217 $container.removeClass('isActive');
3224 * Initialise all toggle buttons
3226 $(window).load(function () {
3227 $('.toggleAjax').each(function () {
3230 .find('.toggleButton')
3231 toggleButton($(this));
3238 $(document).ready(function() {
3239 $('.vpointer').live('hover',
3242 var $this_td = $(this);
3243 var row_num = PMA_getRowNumber($this_td.attr('class'));
3244 // for all td of the same vertical row, toggle hover
3245 $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
3248 }) // end of $(document).ready() for vertical pointer
3250 $(document).ready(function() {
3254 $('.vmarker').live('click', function(e) {
3255 // do not trigger when clicked on anchor
3256 if ($(e.target).is('a, img, a *')) {
3260 var $this_td = $(this);
3261 var row_num = PMA_getRowNumber($this_td.attr('class'));
3263 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
3265 var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
3266 if ($checkbox.length) {
3267 // checkbox in a row, add or remove class depending on checkbox state
3268 var checked = $checkbox.attr('checked');
3269 if (!$(e.target).is(':checkbox, label')) {
3271 $checkbox.attr('checked', checked);
3273 // for all td of the same vertical row, toggle the marked class
3275 $('.vmarker').filter('.row_' + row_num).addClass('marked');
3277 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
3280 // normaln data table, just toggle class
3281 $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
3286 * Reveal visual builder anchor
3289 $('#visual_builder_anchor').show();
3292 * Page selector in db Structure (non-AJAX)
3294 $('#tableslistcontainer').find('#pageselector').live('change', function() {
3295 $(this).parent("form").submit();
3299 * Page selector in navi panel (non-AJAX)
3301 $('#navidbpageselector').find('#pageselector').live('change', function() {
3302 $(this).parent("form").submit();
3306 * Page selector in browse_foreigners windows (non-AJAX)
3308 $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3309 $(this).closest("form").submit();
3313 * Load version information asynchronously.
3315 if ($('.jsversioncheck').length > 0) {
3317 var s = document.createElement('script');
3318 s.type = 'text/javascript';
3320 s.src = 'http://www.phpmyadmin.net/home_page/version.js';
3321 s.onload = PMA_current_version;
3322 var x = document.getElementsByTagName('script')[0];
3323 x.parentNode.insertBefore(s, x);
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);
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) {
3706 $("#floating_menubar")
3708 'position': 'fixed',
3714 .append($('#serverinfo'))
3715 .append($('#topmenucontainer'));
3718 $('#floating_menubar').outerHeight(true)