1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * general function, usally for data manipulation pages
8 * @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
10 var sql_box_locked = false;
13 * @var array holds elements which content should only selected once
15 var only_once_elements = new Array();
18 * @var int ajax_message_count Number of AJAX messages shown since page load
20 var ajax_message_count = 0;
23 * @var codemirror_editor object containing CodeMirror editor
25 var codemirror_editor = false;
28 * @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
30 var chart_activeTimeouts = new Object();
33 * Add a hidden field to the form to indicate that this will be an
34 * Ajax request (only if this hidden field does not exist)
36 * @param object the form
38 function PMA_prepareForAjaxRequest($form)
40 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
41 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
46 * Generate a new password and copy it to the password input areas
48 * @param object the form that holds the password fields
50 * @return boolean always true
52 function suggestPassword(passwd_form)
54 // restrict the password to just letters and numbers to avoid problems:
55 // "editors and viewers regard the password as multiple words and
56 // things like double click no longer work"
57 var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
58 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
59 var passwd = passwd_form.generated_pw;
62 for ( i = 0; i < passwordlength; i++ ) {
63 passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
65 passwd_form.text_pma_pw.value = passwd.value;
66 passwd_form.text_pma_pw2.value = passwd.value;
71 * Version string to integer conversion.
73 function parseVersionString (str)
75 if (typeof(str) != 'string') { return false; }
77 // Parse possible alpha/beta/rc/
78 var state = str.split('-');
79 if (state.length >= 2) {
80 if (state[1].substr(0, 2) == 'rc') {
81 add = - 20 - parseInt(state[1].substr(2));
82 } else if (state[1].substr(0, 4) == 'beta') {
83 add = - 40 - parseInt(state[1].substr(4));
84 } else if (state[1].substr(0, 5) == 'alpha') {
85 add = - 60 - parseInt(state[1].substr(5));
86 } else if (state[1].substr(0, 3) == 'dev') {
87 /* We don't handle dev, it's git snapshot */
92 var x = str.split('.');
93 // Use 0 for non existing parts
94 var maj = parseInt(x[0]) || 0;
95 var min = parseInt(x[1]) || 0;
96 var pat = parseInt(x[2]) || 0;
97 var hotfix = parseInt(x[3]) || 0;
98 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
102 * Indicates current available version on main page.
104 function PMA_current_version()
106 var current = parseVersionString(pmaversion);
107 var latest = parseVersionString(PMA_latest_version);
108 var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
109 if (latest > current) {
110 var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
111 if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
112 /* Security update */
117 $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
119 if (latest == current) {
120 version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
122 $('#li_pma_version').append(version_information_message);
126 * for libraries/display_change_password.lib.php
127 * libraries/user_password.php
131 function displayPasswordGenerateButton()
133 $('#tr_element_before_generate_password').parent().append('<tr><td>' + PMA_messages['strGeneratePassword'] + '</td><td><input type="button" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /><input type="text" name="generated_pw" id="generated_pw" /></td></tr>');
134 $('#div_element_before_generate_password').parent().append('<div class="item"><label for="button_generate_password">' + PMA_messages['strGeneratePassword'] + ':</label><span class="options"><input type="button" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /></span><input type="text" name="generated_pw" id="generated_pw" /></div>');
138 * Adds a date/time picker to an element
140 * @param object $this_element a jQuery object pointing to the element
142 function PMA_addDatepicker($this_element, options)
144 var showTimeOption = false;
145 if ($this_element.is('.datetimefield')) {
146 showTimeOption = true;
149 var defaultOptions = {
151 buttonImage: themeCalendarImage, // defined in js/messages.php
152 buttonImageOnly: true,
156 showTimepicker: showTimeOption,
157 showButtonPanel: false,
158 dateFormat: 'yy-mm-dd', // yy means year with four digits
159 timeFormat: 'hh:mm:ss',
160 altFieldTimeOnly: false,
162 beforeShow: function(input, inst) {
163 // Remember that we came from the datepicker; this is used
164 // in tbl_change.js by verificationsAfterFieldChange()
165 $this_element.data('comes_from', 'datepicker');
167 // Fix wrong timepicker z-index, doesn't work without timeout
168 setTimeout(function() {
169 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
174 $this_element.datetimepicker($.extend(defaultOptions, options));
178 * selects the content of a given object, f.e. a textarea
180 * @param object element element of which the content will be selected
181 * @param var lock variable which holds the lock for this element
182 * or true, if no lock exists
183 * @param boolean only_once if true this is only done once
184 * f.e. only on first focus
186 function selectContent( element, lock, only_once )
188 if ( only_once && only_once_elements[element.name] ) {
192 only_once_elements[element.name] = true;
202 * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
203 * This function is called while clicking links
205 * @param object the link
206 * @param object the sql query to submit
208 * @return boolean whether to run the query or not
210 function confirmLink(theLink, theSqlQuery)
212 // Confirmation is not required in the configuration file
213 // or browser is Opera (crappy js implementation)
214 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
218 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
220 if ( $(theLink).hasClass('formLinkSubmit') ) {
221 var name = 'is_js_confirmed';
222 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
223 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
226 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
227 } else if ( typeof(theLink.href) != 'undefined' ) {
228 theLink.href += '&is_js_confirmed=1';
229 } else if ( typeof(theLink.form) != 'undefined' ) {
230 theLink.form.action += '?is_js_confirmed=1';
235 } // end of the 'confirmLink()' function
239 * Displays a confirmation box before doing some action
241 * @param object the message to display
243 * @return boolean whether to run the query or not
245 * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
246 * and replace with a jQuery equivalent
248 function confirmAction(theMessage)
250 // TODO: Confirmation is not required in the configuration file
251 // or browser is Opera (crappy js implementation)
252 if (typeof(window.opera) != 'undefined') {
256 var is_confirmed = confirm(theMessage);
259 } // end of the 'confirmAction()' function
263 * Displays an error message if a "DROP DATABASE" statement is submitted
264 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
265 * sumitting it if required.
266 * This function is called by the 'checkSqlQuery()' js function.
268 * @param object the form
269 * @param object the sql query textarea
271 * @return boolean whether to run the query or not
273 * @see checkSqlQuery()
275 function confirmQuery(theForm1, sqlQuery1)
277 // Confirmation is not required in the configuration file
278 if (PMA_messages['strDoYouReally'] == '') {
282 // "DROP DATABASE" statement isn't allowed
283 if (PMA_messages['strNoDropDatabases'] != '') {
284 var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
285 if (drop_re.test(sqlQuery1.value)) {
286 alert(PMA_messages['strNoDropDatabases']);
293 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
295 // TODO: find a way (if possible) to use the parser-analyser
296 // for this kind of verification
297 // For now, I just added a ^ to check for the statement at
298 // beginning of expression
300 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
301 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
302 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
303 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
305 if (do_confirm_re_0.test(sqlQuery1.value)
306 || do_confirm_re_1.test(sqlQuery1.value)
307 || do_confirm_re_2.test(sqlQuery1.value)
308 || do_confirm_re_3.test(sqlQuery1.value)) {
309 var message = (sqlQuery1.value.length > 100)
310 ? sqlQuery1.value.substr(0, 100) + '\n ...'
312 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
313 // statement is confirmed -> update the
314 // "is_js_confirmed" form field so the confirm test won't be
315 // run on the server side and allows to submit the form
317 theForm1.elements['is_js_confirmed'].value = 1;
320 // statement is rejected -> do not submit the form
325 } // end if (handle confirm box result)
326 } // end if (display confirm box)
329 } // end of the 'confirmQuery()' function
333 * Displays a confirmation box before disabling the BLOB repository for a given database.
334 * This function is called while clicking links
336 * @param object the database
338 * @return boolean whether to disable the repository or not
340 function confirmDisableRepository(theDB)
342 // Confirmation is not required in the configuration file
343 // or browser is Opera (crappy js implementation)
344 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
348 var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
351 } // end of the 'confirmDisableBLOBRepository()' function
355 * Displays an error message if the user submitted the sql query form with no
356 * sql query, else checks for "DROP/DELETE/ALTER" statements
358 * @param object the form
360 * @return boolean always false
362 * @see confirmQuery()
364 function checkSqlQuery(theForm)
366 var sqlQuery = theForm.elements['sql_query'];
369 var space_re = new RegExp('\\s+');
370 if (typeof(theForm.elements['sql_file']) != 'undefined' &&
371 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
374 if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
375 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
378 if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
379 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
380 theForm.elements['id_bookmark'].selectedIndex != 0
384 // Checks for "DROP/DELETE/ALTER" statements
385 if (sqlQuery.value.replace(space_re, '') != '') {
386 if (confirmQuery(theForm, sqlQuery)) {
397 alert(PMA_messages['strFormEmpty']);
403 } // end of the 'checkSqlQuery()' function
406 * Check if a form's element is empty.
407 * An element containing only spaces is also considered empty
409 * @param object the form
410 * @param string the name of the form field to put the focus on
412 * @return boolean whether the form field is empty or not
414 function emptyCheckTheField(theForm, theFieldName)
416 var theField = theForm.elements[theFieldName];
417 var space_re = new RegExp('\\s+');
418 return (theField.value.replace(space_re, '') == '') ? 1 : 0;
419 } // end of the 'emptyCheckTheField()' function
423 * Check whether a form field is empty or not
425 * @param object the form
426 * @param string the name of the form field to put the focus on
428 * @return boolean whether the form field is empty or not
430 function emptyFormElements(theForm, theFieldName)
432 var theField = theForm.elements[theFieldName];
433 var isEmpty = emptyCheckTheField(theForm, theFieldName);
437 } // end of the 'emptyFormElements()' function
441 * Ensures a value submitted in a form is numeric and is in a range
443 * @param object the form
444 * @param string the name of the form field to check
445 * @param integer the minimum authorized value
446 * @param integer the maximum authorized value
448 * @return boolean whether a valid number has been submitted or not
450 function checkFormElementInRange(theForm, theFieldName, message, min, max)
452 var theField = theForm.elements[theFieldName];
453 var val = parseInt(theField.value);
455 if (typeof(min) == 'undefined') {
458 if (typeof(max) == 'undefined') {
459 max = Number.MAX_VALUE;
465 alert(PMA_messages['strNotNumber']);
469 // It's a number but it is not between min and max
470 else if (val < min || val > max) {
472 alert(message.replace('%d', val));
476 // It's a valid number
478 theField.value = val;
482 } // end of the 'checkFormElementInRange()' function
485 function checkTableEditForm(theForm, fieldsCnt)
487 // TODO: avoid sending a message if user just wants to add a line
488 // on the form but has not completed at least one field name
490 var atLeastOneField = 0;
491 var i, elm, elm2, elm3, val, id;
493 for (i=0; i<fieldsCnt; i++)
495 id = "#field_" + i + "_2";
498 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
499 elm2 = $("#field_" + i + "_3");
500 val = parseInt(elm2.val());
501 elm3 = $("#field_" + i + "_1");
502 if (isNaN(val) && elm3.val() != "") {
504 alert(PMA_messages['strNotNumber']);
510 if (atLeastOneField == 0) {
511 id = "field_" + i + "_1";
512 if (!emptyCheckTheField(theForm, id)) {
517 if (atLeastOneField == 0) {
518 var theField = theForm.elements["field_0_1"];
519 alert(PMA_messages['strFormEmpty']);
524 // at least this section is under jQuery
525 if ($("input.textfield[name='table']").val() == "") {
526 alert(PMA_messages['strFormEmpty']);
527 $("input.textfield[name='table']").focus();
533 } // enf of the 'checkTableEditForm()' function
537 * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
538 * checkboxes is consistant
540 * @param object the form
541 * @param string a code for the action that causes this function to be run
543 * @return boolean always true
545 function checkTransmitDump(theForm, theAction)
547 var formElts = theForm.elements;
549 // 'zipped' option has been checked
550 if (theAction == 'zip' && formElts['zip'].checked) {
551 if (!formElts['asfile'].checked) {
552 theForm.elements['asfile'].checked = true;
554 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
555 theForm.elements['gzip'].checked = false;
557 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
558 theForm.elements['bzip'].checked = false;
561 // 'gzipped' option has been checked
562 else if (theAction == 'gzip' && formElts['gzip'].checked) {
563 if (!formElts['asfile'].checked) {
564 theForm.elements['asfile'].checked = true;
566 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
567 theForm.elements['zip'].checked = false;
569 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
570 theForm.elements['bzip'].checked = false;
573 // 'bzipped' option has been checked
574 else if (theAction == 'bzip' && formElts['bzip'].checked) {
575 if (!formElts['asfile'].checked) {
576 theForm.elements['asfile'].checked = true;
578 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
579 theForm.elements['zip'].checked = false;
581 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
582 theForm.elements['gzip'].checked = false;
585 // 'transmit' option has been unchecked
586 else if (theAction == 'transmit' && !formElts['asfile'].checked) {
587 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
588 theForm.elements['zip'].checked = false;
590 if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
591 theForm.elements['gzip'].checked = false;
593 if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
594 theForm.elements['bzip'].checked = false;
599 } // end of the 'checkTransmitDump()' function
601 $(document).ready(function() {
603 * Row marking in horizontal mode (use "live" so that it works also for
604 * next pages reached via AJAX); a tr may have the class noclick to remove
607 $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
608 // do not trigger when clicked on anchor
609 if ($(e.target).is('a, img, a *')) {
614 // make the table unselectable (to prevent default highlighting when shift+click)
615 //$tr.parents('table').noSelect();
617 if (!e.shiftKey || last_clicked_row == -1) {
620 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
621 var $checkbox = $tr.find(':checkbox');
622 if ($checkbox.length) {
623 // checkbox in a row, add or remove class depending on checkbox state
624 var checked = $checkbox.attr('checked');
625 if (!$(e.target).is(':checkbox, label')) {
627 $checkbox.attr('checked', checked);
630 $tr.addClass('marked');
632 $tr.removeClass('marked');
634 last_click_checked = checked;
636 // normaln data table, just toggle class
637 $tr.toggleClass('marked');
638 last_click_checked = false;
641 // remember the last clicked row
642 last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
643 last_shift_clicked_row = -1;
645 // handle the shift click
646 PMA_clearSelection();
649 // clear last shift click result
650 if (last_shift_clicked_row >= 0) {
651 if (last_shift_clicked_row >= last_clicked_row) {
652 start = last_clicked_row;
653 end = last_shift_clicked_row;
655 start = last_shift_clicked_row;
656 end = last_clicked_row;
658 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
659 .slice(start, end + 1)
660 .removeClass('marked')
662 .attr('checked', false);
665 // handle new shift click
666 var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
667 if (curr_row >= last_clicked_row) {
668 start = last_clicked_row;
672 end = last_clicked_row;
674 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
675 .slice(start, end + 1)
678 .attr('checked', true);
680 // remember the last shift clicked row
681 last_shift_clicked_row = curr_row;
686 * Add a date/time picker to each element that needs it
687 * (only when timepicker.js is loaded)
689 if ($.timepicker != undefined) {
690 $('.datefield, .datetimefield').each(function() {
691 PMA_addDatepicker($(this));
697 * True if last click is to check a row.
699 var last_click_checked = false;
702 * Zero-based index of last clicked row.
703 * Used to handle the shift + click event in the code above.
705 var last_clicked_row = -1;
708 * Zero-based index of last shift clicked row.
710 var last_shift_clicked_row = -1;
713 * Row highlighting in horizontal mode (use "live"
714 * so that it works also for pages reached via AJAX)
716 /*$(document).ready(function() {
717 $('tr.odd, tr.even').live('hover',function(event) {
719 $tr.toggleClass('hover',event.type=='mouseover');
720 $tr.children().toggleClass('hover',event.type=='mouseover');
725 * This array is used to remember mark status of rows in browse mode
727 var marked_row = new Array;
730 * marks all rows and selects its first checkbox inside the given element
731 * the given element is usaly a table or a div containing the table or tables
733 * @param container DOM element
735 function markAllRows( container_id )
738 $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
739 .parents("tr").addClass("marked");
744 * marks all rows and selects its first checkbox inside the given element
745 * the given element is usaly a table or a div containing the table or tables
747 * @param container DOM element
749 function unMarkAllRows( container_id )
752 $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
753 .parents("tr").removeClass("marked");
758 * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
760 * @param string container_id the container id
761 * @param boolean state new value for checkbox (true or false)
762 * @return boolean always true
764 function setCheckboxes( container_id, state )
768 $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
771 $("#"+container_id).find("input:checkbox").removeAttr('checked');
775 } // end of the 'setCheckboxes()' function
778 * Checks/unchecks all options of a <select> element
780 * @param string the form name
781 * @param string the element name
782 * @param boolean whether to check or to uncheck options
784 * @return boolean always true
786 function setSelectOptions(the_form, the_select, do_check)
788 $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
790 } // end of the 'setSelectOptions()' function
793 * Sets current value for query box.
795 function setQuery(query)
797 if (codemirror_editor) {
798 codemirror_editor.setValue(query);
800 document.sqlform.sql_query.value = query;
806 * Create quick sql statements.
809 function insertQuery(queryType)
811 if (queryType == "clear") {
816 var myQuery = document.sqlform.sql_query;
818 var myListBox = document.sqlform.dummy;
819 var table = document.sqlform.table.value;
821 if (myListBox.options.length > 0) {
822 sql_box_locked = true;
827 for (var i=0; i < myListBox.options.length; i++) {
834 chaineAj += myListBox.options[i].value;
835 valDis += "[value-" + NbSelect + "]";
836 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
838 if (queryType == "selectall") {
839 query = "SELECT * FROM `" + table + "` WHERE 1";
840 } else if (queryType == "select") {
841 query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
842 } else if (queryType == "insert") {
843 query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
844 } else if (queryType == "update") {
845 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
846 } else if(queryType == "delete") {
847 query = "DELETE FROM `" + table + "` WHERE 1";
850 sql_box_locked = false;
856 * Inserts multiple fields.
859 function insertValueQuery()
861 var myQuery = document.sqlform.sql_query;
862 var myListBox = document.sqlform.dummy;
864 if(myListBox.options.length > 0) {
865 sql_box_locked = true;
868 for(var i=0; i<myListBox.options.length; i++) {
869 if (myListBox.options[i].selected) {
874 chaineAj += myListBox.options[i].value;
878 /* CodeMirror support */
879 if (codemirror_editor) {
880 codemirror_editor.replaceSelection(chaineAj);
882 } else if (document.selection) {
884 sel = document.selection.createRange();
886 document.sqlform.insert.focus();
888 //MOZILLA/NETSCAPE support
889 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
890 var startPos = document.sqlform.sql_query.selectionStart;
891 var endPos = document.sqlform.sql_query.selectionEnd;
892 var chaineSql = document.sqlform.sql_query.value;
894 myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
896 myQuery.value += chaineAj;
898 sql_box_locked = false;
903 * listbox redirection
905 function goToUrl(selObj, goToLocation)
907 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
911 * Refresh the WYSIWYG scratchboard after changes have been made
913 function refreshDragOption(e)
915 var elm = $('#' + e);
916 if (elm.css('visibility') == 'visible') {
923 * Refresh/resize the WYSIWYG scratchboard
925 function refreshLayout()
927 var elm = $('#pdflayout')
928 var orientation = $('#orientation_opt').val();
929 if($('#paper_opt').length==1){
930 var paper = $('#paper_opt').val();
934 if (orientation == 'P') {
941 elm.css('width', pdfPaperSize(paper, posa) + 'px');
942 elm.css('height', pdfPaperSize(paper, posb) + 'px');
946 * Show/hide the WYSIWYG scratchboard
948 function ToggleDragDrop(e)
950 var elm = $('#' + e);
951 if (elm.css('visibility') == 'hidden') {
952 PDFinit(); /* Defined in pdf_pages.php */
953 elm.css('visibility', 'visible');
954 elm.css('display', 'block');
955 $('#showwysiwyg').val('1')
957 elm.css('visibility', 'hidden');
958 elm.css('display', 'none');
959 $('#showwysiwyg').val('0')
964 * PDF scratchboard: When a position is entered manually, update
965 * the fields inside the scratchboard.
967 function dragPlace(no, axis, value)
969 var elm = $('#table_' + no);
971 elm.css('left', value + 'px');
973 elm.css('top', value + 'px');
978 * Returns paper sizes for a given format
980 function pdfPaperSize(format, axis)
982 switch (format.toUpperCase()) {
984 if (axis == 'x') return 4767.87; else return 6740.79;
987 if (axis == 'x') return 3370.39; else return 4767.87;
990 if (axis == 'x') return 2383.94; else return 3370.39;
993 if (axis == 'x') return 1683.78; else return 2383.94;
996 if (axis == 'x') return 1190.55; else return 1683.78;
999 if (axis == 'x') return 841.89; else return 1190.55;
1002 if (axis == 'x') return 595.28; else return 841.89;
1005 if (axis == 'x') return 419.53; else return 595.28;
1008 if (axis == 'x') return 297.64; else return 419.53;
1011 if (axis == 'x') return 209.76; else return 297.64;
1014 if (axis == 'x') return 147.40; else return 209.76;
1017 if (axis == 'x') return 104.88; else return 147.40;
1020 if (axis == 'x') return 73.70; else return 104.88;
1023 if (axis == 'x') return 2834.65; else return 4008.19;
1026 if (axis == 'x') return 2004.09; else return 2834.65;
1029 if (axis == 'x') return 1417.32; else return 2004.09;
1032 if (axis == 'x') return 1000.63; else return 1417.32;
1035 if (axis == 'x') return 708.66; else return 1000.63;
1038 if (axis == 'x') return 498.90; else return 708.66;
1041 if (axis == 'x') return 354.33; else return 498.90;
1044 if (axis == 'x') return 249.45; else return 354.33;
1047 if (axis == 'x') return 175.75; else return 249.45;
1050 if (axis == 'x') return 124.72; else return 175.75;
1053 if (axis == 'x') return 87.87; else return 124.72;
1056 if (axis == 'x') return 2599.37; else return 3676.54;
1059 if (axis == 'x') return 1836.85; else return 2599.37;
1062 if (axis == 'x') return 1298.27; else return 1836.85;
1065 if (axis == 'x') return 918.43; else return 1298.27;
1068 if (axis == 'x') return 649.13; else return 918.43;
1071 if (axis == 'x') return 459.21; else return 649.13;
1074 if (axis == 'x') return 323.15; else return 459.21;
1077 if (axis == 'x') return 229.61; else return 323.15;
1080 if (axis == 'x') return 161.57; else return 229.61;
1083 if (axis == 'x') return 113.39; else return 161.57;
1086 if (axis == 'x') return 79.37; else return 113.39;
1089 if (axis == 'x') return 2437.80; else return 3458.27;
1092 if (axis == 'x') return 1729.13; else return 2437.80;
1095 if (axis == 'x') return 1218.90; else return 1729.13;
1098 if (axis == 'x') return 864.57; else return 1218.90;
1101 if (axis == 'x') return 609.45; else return 864.57;
1104 if (axis == 'x') return 2551.18; else return 3628.35;
1107 if (axis == 'x') return 1814.17; else return 2551.18;
1110 if (axis == 'x') return 1275.59; else return 1814.17;
1113 if (axis == 'x') return 907.09; else return 1275.59;
1116 if (axis == 'x') return 637.80; else return 907.09;
1119 if (axis == 'x') return 612.00; else return 792.00;
1122 if (axis == 'x') return 612.00; else return 1008.00;
1125 if (axis == 'x') return 521.86; else return 756.00;
1128 if (axis == 'x') return 612.00; else return 936.00;
1136 * for playing media from the BLOB repository
1139 * @param var url_params main purpose is to pass the token
1140 * @param var bs_ref BLOB repository reference
1141 * @param var m_type type of BLOB repository media
1142 * @param var w_width width of popup window
1143 * @param var w_height height of popup window
1145 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1147 // if width not specified, use default
1148 if (w_width == undefined) {
1152 // if height not specified, use default
1153 if (w_height == undefined) {
1157 // open popup window (for displaying video/playing audio)
1158 var mediaWin = window.open('bs_play_media.php?' + url_params + '&bs_reference=' + bs_ref + '&media_type=' + m_type + '&custom_type=' + is_cust_type, 'viewBSMedia', 'width=' + w_width + ', height=' + w_height + ', resizable=1, scrollbars=1, status=0');
1162 * popups a request for changing MIME types for files in the BLOB repository
1164 * @param var db database name
1165 * @param var table table name
1166 * @param var reference BLOB repository reference
1167 * @param var current_mime_type current MIME type associated with BLOB repository reference
1169 function requestMIMETypeChange(db, table, reference, current_mime_type)
1171 // no mime type specified, set to default (nothing)
1172 if (undefined == current_mime_type) {
1173 current_mime_type = "";
1176 // prompt user for new mime type
1177 var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1179 // if new mime_type is specified and is not the same as the previous type, request for mime type change
1180 if (new_mime_type && new_mime_type != current_mime_type) {
1181 changeMIMEType(db, table, reference, new_mime_type);
1186 * changes MIME types for files in the BLOB repository
1188 * @param var db database name
1189 * @param var table table name
1190 * @param var reference BLOB repository reference
1191 * @param var mime_type new MIME type to be associated with BLOB repository reference
1193 function changeMIMEType(db, table, reference, mime_type)
1195 // specify url and parameters for jQuery POST
1196 var mime_chg_url = 'bs_change_mime_type.php';
1197 var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1200 jQuery.post(mime_chg_url, params);
1204 * Jquery Coding for inline editing SQL_QUERY
1206 $(document).ready(function(){
1207 $(".inline_edit_sql").live('click', function(){
1208 var $form = $(this).prev();
1209 var sql_query = $form.find("input[name='sql_query']").val();
1210 var $inner_sql = $(this).parent().prev().find('.inner_sql');
1211 var old_text = $inner_sql.html();
1213 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1214 new_content += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1215 new_content += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1216 $inner_sql.replaceWith(new_content);
1217 $(".btnSave").click(function(){
1218 var sql_query = $(this).prev().val();
1219 var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1220 .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1221 .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1222 .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1223 $fake_form.appendTo($('body')).submit();
1225 $(".btnDiscard").click(function(){
1226 $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1231 $('.sqlbutton').click(function(evt){
1232 insertQuery(evt.target.id);
1236 $("#export_type").change(function(){
1237 if($("#export_type").val()=='svg'){
1238 $("#show_grid_opt").attr("disabled","disabled");
1239 $("#orientation_opt").attr("disabled","disabled");
1240 $("#with_doc").attr("disabled","disabled");
1241 $("#show_table_dim_opt").removeAttr("disabled");
1242 $("#all_table_same_wide").removeAttr("disabled");
1243 $("#paper_opt").removeAttr("disabled","disabled");
1244 $("#show_color_opt").removeAttr("disabled","disabled");
1245 //$(this).css("background-color","yellow");
1246 }else if($("#export_type").val()=='dia'){
1247 $("#show_grid_opt").attr("disabled","disabled");
1248 $("#with_doc").attr("disabled","disabled");
1249 $("#show_table_dim_opt").attr("disabled","disabled");
1250 $("#all_table_same_wide").attr("disabled","disabled");
1251 $("#paper_opt").removeAttr("disabled","disabled");
1252 $("#show_color_opt").removeAttr("disabled","disabled");
1253 $("#orientation_opt").removeAttr("disabled","disabled");
1254 }else if($("#export_type").val()=='eps'){
1255 $("#show_grid_opt").attr("disabled","disabled");
1256 $("#orientation_opt").removeAttr("disabled");
1257 $("#with_doc").attr("disabled","disabled");
1258 $("#show_table_dim_opt").attr("disabled","disabled");
1259 $("#all_table_same_wide").attr("disabled","disabled");
1260 $("#paper_opt").attr("disabled","disabled");
1261 $("#show_color_opt").attr("disabled","disabled");
1263 }else if($("#export_type").val()=='pdf'){
1264 $("#show_grid_opt").removeAttr("disabled");
1265 $("#orientation_opt").removeAttr("disabled");
1266 $("#with_doc").removeAttr("disabled","disabled");
1267 $("#show_table_dim_opt").removeAttr("disabled","disabled");
1268 $("#all_table_same_wide").removeAttr("disabled","disabled");
1269 $("#paper_opt").removeAttr("disabled","disabled");
1270 $("#show_color_opt").removeAttr("disabled","disabled");
1276 $('#sqlquery').focus().keydown(function (e) {
1277 if (e.ctrlKey && e.keyCode == 13) {
1278 $("#sqlqueryform").submit();
1282 if ($('#input_username')) {
1283 if ($('#input_username').val() == '') {
1284 $('#input_username').focus();
1286 $('#input_password').focus();
1292 * Show a message on the top of the page for an Ajax request
1296 * 1) var $msg = PMA_ajaxShowMessage();
1297 * This will show a message that reads "Loading...". Such a message will not
1298 * disappear automatically and cannot be dismissed by the user. To remove this
1299 * message either the PMA_ajaxRemoveMessage($msg) function must be called or
1300 * another message must be show with PMA_ajaxShowMessage() function.
1302 * 2) var $msg = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1303 * This is a special case. The behaviour is same as above,
1304 * just with a different message
1306 * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
1307 * This will show a message that will disappear automatically and it can also
1308 * be dismissed by the user.
1310 * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
1311 * This will show a message that will not disappear automatically, but it
1312 * can be dismissed by the user after he has finished reading it.
1314 * @param string message string containing the message to be shown.
1315 * optional, defaults to 'Loading...'
1316 * @param mixed timeout number of milliseconds for the message to be visible
1317 * optional, defaults to 5000. If set to 'false', the
1318 * notification will never disappear
1319 * @return jQuery object jQuery Element that holds the message div
1320 * this object can be passed to PMA_ajaxRemoveMessage()
1321 * to remove the notification
1323 function PMA_ajaxShowMessage(message, timeout)
1326 * @var self_closing Whether the notification will automatically disappear
1328 var self_closing = true;
1330 * @var dismissable Whether the user will be able to remove
1331 * the notification by clicking on it
1333 var dismissable = true;
1334 // Handle the case when a empty data.message is passed.
1335 // We don't want the empty message
1336 if (message == '') {
1338 } else if (! message) {
1339 // If the message is undefined, show the default
1340 message = PMA_messages['strLoading'];
1341 dismissable = false;
1342 self_closing = false;
1343 } else if (message == PMA_messages['strProcessingRequest']) {
1344 // This is another case where the message should not disappear
1345 dismissable = false;
1346 self_closing = false;
1348 // Figure out whether (or after how long) to remove the notification
1349 if (timeout == undefined) {
1351 } else if (timeout === false) {
1352 self_closing = false;
1354 // Create a parent element for the AJAX messages, if necessary
1355 if ($('#loading_parent').length == 0) {
1356 $('<div id="loading_parent"></div>')
1357 .insertBefore("#serverinfo");
1359 // Update message count to create distinct message elements every time
1360 ajax_message_count++;
1361 // Remove all old messages, if any
1362 $(".ajax_notification[id^=ajax_message_num]").remove();
1364 * @var $retval a jQuery object containing the reference
1365 * to the created AJAX message
1368 '<span class="ajax_notification" id="ajax_message_num_'
1369 + ajax_message_count +
1373 .appendTo("#loading_parent")
1376 // If the notification is self-closing we should create a callback to remove it
1380 .fadeOut('medium', function() {
1381 if ($(this).is('.dismissable')) {
1382 // Here we should destroy the qtip instance, but
1383 // due to a bug in qtip's implementation we can
1384 // only hide it without throwing JS errors.
1385 $(this).qtip('hide');
1387 // Remove the notification
1391 // If the notification is dismissable we need to add the relevant class to it
1392 // and add a tooltip so that the users know that it can be removed
1394 $retval.addClass('dismissable').css('cursor', 'pointer');
1396 * @var qOpts Options for "Dismiss notification" tooltip
1400 effect: { length: 0 },
1404 effect: { length: 0 },
1409 * Add a tooltip to the notification to let the user know that (s)he
1410 * can dismiss the ajax notification by clicking on it.
1412 PMA_createqTip($retval, PMA_messages['strDismiss'], qOpts);
1419 * Removes the message shown for an Ajax operation when it's completed
1421 * @param jQuery object jQuery Element that holds the notification
1425 function PMA_ajaxRemoveMessage($this_msgbox)
1427 if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1431 if ($this_msgbox.is('.dismissable')) {
1432 // Here we should destroy the qtip instance, but
1433 // due to a bug in qtip's implementation we can
1434 // only hide it without throwing JS errors.
1435 $this_msgbox.qtip('hide');
1437 $this_msgbox.remove();
1442 $(document).ready(function() {
1444 * Allows the user to dismiss a notification
1445 * created with PMA_ajaxShowMessage()
1447 $('.ajax_notification.dismissable').live('click', function () {
1448 PMA_ajaxRemoveMessage($(this));
1451 * The below two functions hide the "Dismiss notification" tooltip when a user
1452 * is hovering a link or button that is inside an ajax message
1454 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1455 .live('mouseover', function () {
1456 $(this).parents('.ajax_notification').qtip('hide');
1458 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1459 .live('mouseout', function () {
1460 $(this).parents('.ajax_notification').qtip('show');
1465 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1467 function PMA_showNoticeForEnum(selectElement)
1469 var enum_notice_id = selectElement.attr("id").split("_")[1];
1470 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1471 var selectedType = selectElement.attr("value");
1472 if (selectedType == "ENUM" || selectedType == "SET") {
1473 $("p[id='enum_notice_" + enum_notice_id + "']").show();
1475 $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1480 * Generates a dialog box to pop up the create_table form
1482 function PMA_createTableDialog( div, url , target)
1485 * @var button_options Object that stores the options passed to jQueryUI
1488 var button_options = {};
1489 // in the following function we need to use $(this)
1490 button_options[PMA_messages['strCancel']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1492 var button_options_error = {};
1493 button_options_error[PMA_messages['strOK']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1495 var $msgbox = PMA_ajaxShowMessage();
1497 $.get( target , url , function(data) {
1498 //in the case of an error, show the error message returned.
1499 if (data.success != undefined && data.success == false) {
1503 title: PMA_messages['strCreateTable'],
1506 open: PMA_verifyTypeOfAllColumns,
1507 buttons : button_options_error
1508 })// end dialog options
1509 //remove the redundant [Back] link in the error message.
1510 .find('fieldset').remove();
1516 title: PMA_messages['strCreateTable'],
1521 position: ['left','top'],
1522 width: window.innerWidth-10,
1523 height: window.innerHeight-10,
1525 var $dialog = $(this);
1526 $(window).bind('resize.dialog-resizer', function() {
1527 clearTimeout(timeout);
1528 timeout = setTimeout(function() {
1529 $dialog.dialog('option', {
1530 width: window.innerWidth-10,
1531 height: window.innerHeight-10
1536 var $wrapper = $('<div>', {'id': 'content-hide'}).hide();
1537 $('body > *:not(.ui-dialog)').wrapAll($wrapper);
1539 $(this).closest('.ui-dialog').css({
1545 $(this).scrollTop(0);
1547 PMA_verifyTypeOfAllColumns();
1550 $(window).unbind('resize.dialog-resizer');
1551 $('#content-hide > *').unwrap();
1553 buttons: button_options
1554 }); // end dialog options
1556 PMA_convertFootnotesToTooltips($(div));
1557 PMA_ajaxRemoveMessage($msgbox);
1563 * Creates a highcharts chart in the given container
1565 * @param var settings object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1566 * requires at least settings.chart.renderTo and settings.series to be set.
1567 * In addition there may be an additional property object 'realtime' that allows for realtime charting:
1569 * url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1570 * type: the GET request will also add type=[value of the type property] to the request
1571 * callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1572 * - the chart object
1573 * - the current response value of the GET request, JSON parsed
1574 * - the previous response value of the GET request, JSON parsed
1575 * - the number of added points
1576 * error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1579 * @return object The created highcharts instance
1581 function PMA_createChart(passedSettings)
1583 var container = passedSettings.chart.renderTo;
1589 backgroundColor: 'none',
1591 /* Live charting support */
1593 var thisChart = this;
1594 var lastValue = null, curValue = null;
1595 var numLoadedPoints = 0, otherSum = 0;
1598 // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1599 // Also don't do live charting if we don't have the server time
1600 if(thisChart.options.chart.forExport == true ||
1601 ! thisChart.options.realtime ||
1602 ! thisChart.options.realtime.callback ||
1603 ! server_time_diff) return;
1605 thisChart.options.realtime.timeoutCallBack = function() {
1606 thisChart.options.realtime.postRequest = $.post(
1607 thisChart.options.realtime.url,
1608 thisChart.options.realtime.postData,
1611 curValue = jQuery.parseJSON(data);
1613 if(thisChart.options.realtime.error)
1614 thisChart.options.realtime.error(err);
1618 if (lastValue==null) {
1619 diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1621 diff = parseInt(curValue.x - lastValue.x);
1624 thisChart.xAxis[0].setExtremes(
1625 thisChart.xAxis[0].getExtremes().min+diff,
1626 thisChart.xAxis[0].getExtremes().max+diff,
1630 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1632 lastValue = curValue;
1635 // Timeout has been cleared => don't start a new timeout
1636 if (chart_activeTimeouts[container] == null) {
1640 chart_activeTimeouts[container] = setTimeout(
1641 thisChart.options.realtime.timeoutCallBack,
1642 thisChart.options.realtime.refreshRate
1647 chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1667 text: PMA_messages['strTotalCount']
1676 formatter: function() {
1677 return '<b>' + this.series.name +'</b><br/>' +
1678 Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1679 Highcharts.numberFormat(this.y, 2);
1688 /* Set/Get realtime chart default values */
1689 if(passedSettings.realtime) {
1690 if(!passedSettings.realtime.refreshRate) {
1691 passedSettings.realtime.refreshRate = 5000;
1694 if(!passedSettings.realtime.numMaxPoints) {
1695 passedSettings.realtime.numMaxPoints = 30;
1698 // Allow custom POST vars to be added
1699 passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1701 if(server_time_diff) {
1702 settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1703 settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1707 // Overwrite/Merge default settings with passedsettings
1708 $.extend(true,settings,passedSettings);
1710 return new Highcharts.Chart(settings);
1715 * Creates a Profiling Chart. Used in sql.php and server_status.js
1717 function PMA_createProfilingChart(data, options)
1719 return PMA_createChart($.extend(true, {
1721 renderTo: 'profilingchart',
1724 title: { text:'', margin:0 },
1727 name: PMA_messages['strQueryExecutionTime'],
1732 allowPointSelect: true,
1737 formatter: function() {
1738 return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1744 formatter: function() {
1745 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1752 * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1754 * @param integer Number to be formatted, should be in the range of microsecond to second
1755 * @param integer Acuracy, how many numbers right to the comma should be
1756 * @return string The formatted number
1758 function PMA_prettyProfilingNum(num, acc)
1763 acc = Math.pow(10,acc);
1764 if (num * 1000 < 0.1) {
1765 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1766 } else if (num < 0.1) {
1767 num = Math.round(acc * (num * 1000)) / acc + 'm';
1769 num = Math.round(acc * num) / acc;
1777 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1779 * @param string Query to be formatted
1780 * @return string The formatted query
1782 function PMA_SQLPrettyPrint(string)
1784 var mode = CodeMirror.getMode({},"text/x-mysql");
1785 var stream = new CodeMirror.StringStream(string);
1786 var state = mode.startState();
1787 var token, tokens = [];
1789 var tabs = function(cnt) {
1791 for (var i=0; i<4*cnt; i++)
1796 // "root-level" statements
1798 'select': ['select', 'from','on','where','having','limit','order by','group by'],
1799 'update': ['update', 'set','where'],
1800 'insert into': ['insert into', 'values']
1802 // don't put spaces before these tokens
1803 var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1804 // don't put spaces after these tokens
1805 var spaceExceptionsAfter = { '.': true };
1807 // Populate tokens array
1809 while (! stream.eol()) {
1810 stream.start = stream.pos;
1811 token = mode.token(stream, state);
1813 tokens.push([token, stream.current().toLowerCase()]);
1817 var currentStatement = tokens[0][1];
1819 if(! statements[currentStatement]) {
1822 // Holds all currently opened code blocks (statement, function or generic)
1823 var blockStack = [];
1824 // Holds the type of block from last iteration (the current is in blockStack[0])
1826 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1827 var newBlock, endBlock;
1828 // How much to indent in the current line
1829 var indentLevel = 0;
1830 // Holds the "root-level" statements
1831 var statementPart, lastStatementPart = statements[currentStatement][0];
1833 blockStack.unshift('statement');
1835 // Iterate through every token and format accordingly
1836 for (var i = 0; i < tokens.length; i++) {
1837 previousBlock = blockStack[0];
1839 // New block => push to stack
1840 if (tokens[i][1] == '(') {
1841 if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1842 blockStack.unshift(newBlock = 'statement');
1843 } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1844 blockStack.unshift(newBlock = 'function');
1846 blockStack.unshift(newBlock = 'generic');
1852 // Block end => pop from stack
1853 if (tokens[i][1] == ')') {
1854 endBlock = blockStack[0];
1860 // A subquery is starting
1861 if (i > 0 && newBlock == 'statement') {
1863 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1864 currentStatement = tokens[i+1][1];
1869 // A subquery is ending
1870 if (endBlock == 'statement' && indentLevel > 0) {
1871 output += "\n" + tabs(indentLevel);
1875 // One less indentation for statement parts (from, where, order by, etc.) and a newline
1876 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1877 if (statementPart != -1) {
1878 if (i > 0) output += "\n";
1879 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1880 output += "\n" + tabs(indentLevel + 1);
1881 lastStatementPart = tokens[i][1];
1883 // Normal indentatin and spaces for everything else
1885 if (! spaceExceptionsBefore[tokens[i][1]]
1886 && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1887 && output.charAt(output.length -1) != ' ' ) {
1890 if (tokens[i][0] == 'keyword') {
1891 output += tokens[i][1].toUpperCase();
1893 output += tokens[i][1];
1897 // split columns in select and 'update set' clauses, but only inside statements blocks
1898 if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
1899 && tokens[i][1]==',' && blockStack[0] == 'statement') {
1901 output += "\n" + tabs(indentLevel + 1);
1904 // split conditions in where clauses, but only inside statements blocks
1905 if (lastStatementPart == 'where'
1906 && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1908 if (blockStack[0] == 'statement') {
1909 output += "\n" + tabs(indentLevel + 1);
1911 // Todo: Also split and or blocks in newlines & identation++
1912 //if(blockStack[0] == 'generic')
1920 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1921 * return a jQuery object yet and hence cannot be chained
1923 * @param string question
1924 * @param string url URL to be passed to the callbackFn to make
1926 * @param function callbackFn callback to execute after user clicks on OK
1929 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1930 if (PMA_messages['strDoYouReally'] == '') {
1935 * @var button_options Object that stores the options passed to jQueryUI
1938 var button_options = {};
1939 button_options[PMA_messages['strOK']] = function(){
1940 $(this).dialog("close").remove();
1942 if($.isFunction(callbackFn)) {
1943 callbackFn.call(this, url);
1946 button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1948 $('<div id="confirm_dialog"></div>')
1950 .dialog({buttons: button_options});
1954 * jQuery function to sort a table's body after a new row has been appended to it.
1955 * Also fixes the even/odd classes of the table rows at the end.
1957 * @param string text_selector string to select the sortKey's text
1959 * @return jQuery Object for chaining purposes
1961 jQuery.fn.PMA_sort_table = function(text_selector) {
1962 return this.each(function() {
1965 * @var table_body Object referring to the table's <tbody> element
1967 var table_body = $(this);
1969 * @var rows Object referring to the collection of rows in {@link table_body}
1971 var rows = $(this).find('tr').get();
1973 //get the text of the field that we will sort by
1974 $.each(rows, function(index, row) {
1975 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1978 //get the sorted order
1979 rows.sort(function(a,b) {
1980 if(a.sortKey < b.sortKey) {
1983 if(a.sortKey > b.sortKey) {
1989 //pull out each row from the table and then append it according to it's order
1990 $.each(rows, function(index, row) {
1991 $(table_body).append(row);
1995 //Re-check the classes of each row
1996 $(this).find('tr:odd')
1997 .removeClass('even').addClass('odd')
2000 .removeClass('odd').addClass('even');
2005 * jQuery coding for 'Create Table'. Used on db_operations.php,
2006 * db_structure.php and db_tracking.php (i.e., wherever
2007 * libraries/display_create_table.lib.php is used)
2009 * Attach Ajax Event handlers for Create Table
2011 $(document).ready(function() {
2014 * Attach event handler to the submit action of the create table minimal form
2015 * and retrieve the full table form and display it in a dialog
2017 * @uses PMA_ajaxShowMessage()
2019 $("#create_table_form_minimal.ajax").live('submit', function(event) {
2020 event.preventDefault();
2022 PMA_prepareForAjaxRequest($form);
2024 /*variables which stores the common attributes*/
2025 var url = $form.serialize();
2026 var action = $form.attr('action');
2027 var div = $('<div id="create_table_dialog"></div>');
2029 /*Calling to the createTableDialog function*/
2030 PMA_createTableDialog(div, url, action);
2032 // empty table name and number of columns from the minimal form
2033 $form.find('input[name=table],input[name=num_fields]').val('');
2037 * Attach event handler for submission of create table form (save)
2039 * @uses PMA_ajaxShowMessage()
2040 * @uses $.PMA_sort_table()
2043 // .live() must be called after a selector, see http://api.jquery.com/live
2044 $("#create_table_form input[name=do_save_data]").live('click', function(event) {
2045 event.preventDefault();
2048 * @var the_form object referring to the create table form
2050 var $form = $("#create_table_form");
2053 * First validate the form; if there is a problem, avoid submitting it
2055 * checkTableEditForm() needs a pure element and not a jQuery object,
2056 * this is why we pass $form[0] as a parameter (the jQuery object
2057 * is actually an array of DOM elements)
2060 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2061 // OK, form passed validation step
2062 if ($form.hasClass('ajax')) {
2063 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2064 PMA_prepareForAjaxRequest($form);
2065 //User wants to submit the form
2066 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
2067 if(data.success == true) {
2068 $('#properties_message')
2069 .removeClass('error')
2071 PMA_ajaxShowMessage(data.message);
2072 // Only if the create table dialog (distinct panel) exists
2073 if ($("#create_table_dialog").length > 0) {
2074 $("#create_table_dialog").dialog("close").remove();
2078 * @var tables_table Object referring to the <tbody> element that holds the list of tables
2080 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
2081 // this is the first table created in this db
2082 if (tables_table.length == 0) {
2083 if (window.parent && window.parent.frame_content) {
2084 window.parent.frame_content.location.reload();
2088 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
2090 var curr_last_row = $(tables_table).find('tr:last');
2092 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
2094 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2096 * @var curr_last_row_index Index of {@link curr_last_row}
2098 var curr_last_row_index = parseFloat(curr_last_row_index_string);
2100 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
2102 var new_last_row_index = curr_last_row_index + 1;
2104 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2106 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2108 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2110 $(data.new_table_string)
2111 .appendTo(tables_table);
2114 $(tables_table).PMA_sort_table('th');
2117 //Refresh navigation frame as a new table has been added
2118 if (window.parent && window.parent.frame_navigation) {
2119 window.parent.frame_navigation.location.reload();
2122 $('#properties_message')
2125 // scroll to the div containing the error message
2126 $('#properties_message')[0].scrollIntoView();
2129 } // end if ($form.hasClass('ajax')
2132 $form.append('<input type="hidden" name="do_save_data" value="save" />');
2135 } // end if (checkTableEditForm() )
2136 }) // end create table form (save)
2139 * Attach event handler for create table form (add fields)
2141 * @uses PMA_ajaxShowMessage()
2142 * @uses $.PMA_sort_table()
2143 * @uses window.parent.refreshNavigation()
2146 // .live() must be called after a selector, see http://api.jquery.com/live
2147 $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2148 event.preventDefault();
2151 * @var the_form object referring to the create table form
2153 var $form = $("#create_table_form");
2155 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2156 PMA_prepareForAjaxRequest($form);
2158 //User wants to add more fields to the table
2159 $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2160 // if 'create_table_dialog' exists
2161 if ($("#create_table_dialog").length > 0) {
2162 $("#create_table_dialog").html(data);
2164 // if 'create_table_div' exists
2165 if ($("#create_table_div").length > 0) {
2166 $("#create_table_div").html(data);
2168 PMA_verifyTypeOfAllColumns();
2169 PMA_ajaxRemoveMessage($msgbox);
2172 }) // end create table form (add fields)
2174 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2177 * jQuery coding for 'Change Table' and 'Add Column'. Used on tbl_structure.php *
2178 * Attach Ajax Event handlers for Change Table
2180 $(document).ready(function() {
2182 *Ajax action for submitting the "Column Change" and "Add Column" form
2184 $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2185 event.preventDefault();
2187 * @var the_form object referring to the export form
2189 var $form = $("#append_fields_form");
2192 * First validate the form; if there is a problem, avoid submitting it
2194 * checkTableEditForm() needs a pure element and not a jQuery object,
2195 * this is why we pass $form[0] as a parameter (the jQuery object
2196 * is actually an array of DOM elements)
2198 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2199 // OK, form passed validation step
2200 if ($form.hasClass('ajax')) {
2201 PMA_prepareForAjaxRequest($form);
2202 //User wants to submit the form
2203 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2204 if ($("#sqlqueryresults").length != 0) {
2205 $("#sqlqueryresults").remove();
2206 } else if ($(".error").length != 0) {
2207 $(".error").remove();
2209 if (data.success == true) {
2210 PMA_ajaxShowMessage(data.message);
2211 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2212 $("#sqlqueryresults").html(data.sql_query);
2213 $("#result_query .notice").remove();
2214 $("#result_query").prepend((data.message));
2215 if ($("#change_column_dialog").length > 0) {
2216 $("#change_column_dialog").dialog("close").remove();
2217 } else if ($("#add_columns").length > 0) {
2218 $("#add_columns").dialog("close").remove();
2220 /*Reload the field form*/
2221 $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2222 $("#fieldsForm").remove();
2223 $("#addColumns").remove();
2224 var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2225 if ($("#sqlqueryresults").length != 0) {
2226 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2228 $temp_div.find("#fieldsForm").insertAfter(".error");
2230 $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2231 /*Call the function to display the more options in table*/
2232 displayMoreTableOpts();
2235 var $temp_div = $("<div id='temp_div'><div>").append(data);
2236 var $error = $temp_div.find(".error code").addClass("error");
2237 PMA_ajaxShowMessage($error);
2242 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2246 }) // end change table button "do_save_data"
2248 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2251 * jQuery coding for 'Table operations'. Used on tbl_operations.php
2252 * Attach Ajax Event handlers for Table operations
2254 $(document).ready(function() {
2256 *Ajax action for submitting the "Alter table order by"
2258 $("#alterTableOrderby.ajax").live('submit', function(event) {
2259 event.preventDefault();
2260 var $form = $(this);
2262 PMA_prepareForAjaxRequest($form);
2263 /*variables which stores the common attributes*/
2264 $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2265 if ($("#sqlqueryresults").length != 0) {
2266 $("#sqlqueryresults").remove();
2268 if ($("#result_query").length != 0) {
2269 $("#result_query").remove();
2271 if (data.success == true) {
2272 PMA_ajaxShowMessage(data.message);
2273 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2274 $("#sqlqueryresults").html(data.sql_query);
2275 $("#result_query .notice").remove();
2276 $("#result_query").prepend((data.message));
2278 var $temp_div = $("<div id='temp_div'></div>")
2279 $temp_div.html(data.error);
2280 var $error = $temp_div.find("code").addClass("error");
2281 PMA_ajaxShowMessage($error);
2284 });//end of alterTableOrderby ajax submit
2287 *Ajax action for submitting the "Copy table"
2289 $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2290 event.preventDefault();
2291 var $form = $("#copyTable");
2292 if($form.find("input[name='switch_to_new']").attr('checked')) {
2293 $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2294 $form.removeClass('ajax');
2295 $form.find("#ajax_request_hidden").remove();
2298 PMA_prepareForAjaxRequest($form);
2299 /*variables which stores the common attributes*/
2300 $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2301 if ($("#sqlqueryresults").length != 0) {
2302 $("#sqlqueryresults").remove();
2304 if ($("#result_query").length != 0) {
2305 $("#result_query").remove();
2307 if (data.success == true) {
2308 PMA_ajaxShowMessage(data.message);
2309 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2310 $("#sqlqueryresults").html(data.sql_query);
2311 $("#result_query .notice").remove();
2312 $("#result_query").prepend((data.message));
2313 $("#copyTable").find("select[name='target_db'] option[value="+data.db+"]").attr('selected', 'selected');
2315 //Refresh navigation frame when the table is coppied
2316 if (window.parent && window.parent.frame_navigation) {
2317 window.parent.frame_navigation.location.reload();
2320 var $temp_div = $("<div id='temp_div'></div>");
2321 $temp_div.html(data.error);
2322 var $error = $temp_div.find("code").addClass("error");
2323 PMA_ajaxShowMessage($error);
2327 });//end of copyTable ajax submit
2330 *Ajax events for actions in the "Table maintenance"
2332 $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2333 event.preventDefault();
2334 var $link = $(this);
2335 var href = $link.attr("href");
2336 href = href.split('?');
2337 if ($("#sqlqueryresults").length != 0) {
2338 $("#sqlqueryresults").remove();
2340 if ($("#result_query").length != 0) {
2341 $("#result_query").remove();
2343 //variables which stores the common attributes
2344 $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2345 if (data.success == undefined) {
2346 var $temp_div = $("<div id='temp_div'></div>");
2347 $temp_div.html(data);
2348 var $success = $temp_div.find("#result_query .success");
2349 PMA_ajaxShowMessage($success);
2350 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2351 $("#sqlqueryresults").html(data);
2353 $("#sqlqueryresults").children("fieldset").remove();
2354 } else if (data.success == true ) {
2355 PMA_ajaxShowMessage(data.message);
2356 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2357 $("#sqlqueryresults").html(data.sql_query);
2359 var $temp_div = $("<div id='temp_div'></div>");
2360 $temp_div.html(data.error);
2361 var $error = $temp_div.find("code").addClass("error");
2362 PMA_ajaxShowMessage($error);
2365 });//end of table maintanance ajax click
2367 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2371 * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2372 * as it was also required on db_create.php
2374 * @uses $.PMA_confirm()
2375 * @uses PMA_ajaxShowMessage()
2376 * @uses window.parent.refreshNavigation()
2377 * @uses window.parent.refreshMain()
2378 * @see $cfg['AjaxEnable']
2380 $(document).ready(function() {
2381 $("#drop_db_anchor").live('click', function(event) {
2382 event.preventDefault();
2384 //context is top.frame_content, so we need to use window.parent.db to access the db var
2386 * @var question String containing the question to be asked for confirmation
2388 var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
2390 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2392 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2393 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2394 //Database deleted successfully, refresh both the frames
2395 window.parent.refreshNavigation();
2396 window.parent.refreshMain();
2398 }); // end $.PMA_confirm()
2399 }); //end of Drop Database Ajax action
2400 }) // end of $(document).ready() for Drop Database
2403 * Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
2404 * display_create_database.lib.php is used, ie main.php and server_databases.php
2406 * @uses PMA_ajaxShowMessage()
2407 * @see $cfg['AjaxEnable']
2409 $(document).ready(function() {
2411 $('#create_database_form.ajax').live('submit', function(event) {
2412 event.preventDefault();
2416 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2417 PMA_prepareForAjaxRequest($form);
2419 $.post($form.attr('action'), $form.serialize(), function(data) {
2420 if(data.success == true) {
2421 PMA_ajaxShowMessage(data.message);
2423 //Append database's row to table
2424 $("#tabledatabases")
2426 .append(data.new_db_string)
2427 .PMA_sort_table('.name')
2428 .find('#db_summary_row')
2429 .appendTo('#tabledatabases tbody')
2430 .removeClass('odd even');
2432 var $databases_count_object = $('#databases_count');
2433 var databases_count = parseInt($databases_count_object.text());
2434 $databases_count_object.text(++databases_count);
2435 //Refresh navigation frame as a new database has been added
2436 if (window.parent && window.parent.frame_navigation) {
2437 window.parent.frame_navigation.location.reload();
2441 PMA_ajaxShowMessage(data.error);
2444 }) // end $().live()
2445 }) // end $(document).ready() for Create Database
2448 * Attach Ajax event handlers for 'Change Password' on main.php
2450 $(document).ready(function() {
2453 * Attach Ajax event handler on the change password anchor
2454 * @see $cfg['AjaxEnable']
2456 $('#change_password_anchor.dialog_active').live('click',function(event) {
2457 event.preventDefault();
2460 $('#change_password_anchor.ajax').live('click', function(event) {
2461 event.preventDefault();
2462 $(this).removeClass('ajax').addClass('dialog_active');
2464 * @var button_options Object containing options to be passed to jQueryUI's dialog
2466 var button_options = {};
2467 button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2468 $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2469 $('<div id="change_password_dialog"></div>')
2471 title: PMA_messages['strChangePassword'],
2473 close: function(ev,ui) {$(this).remove();},
2474 buttons : button_options,
2475 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2478 displayPasswordGenerateButton();
2480 }) // end handler for change password anchor
2483 * Attach Ajax event handler for Change Password form submission
2485 * @uses PMA_ajaxShowMessage()
2486 * @see $cfg['AjaxEnable']
2488 $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2489 event.preventDefault();
2492 * @var the_form Object referring to the change password form
2494 var the_form = $("#change_password_form");
2497 * @var this_value String containing the value of the submit button.
2498 * Need to append this for the change password form on Server Privileges
2501 var this_value = $(this).val();
2503 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2504 $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2506 $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2507 if(data.success == true) {
2508 $("#topmenucontainer").after(data.sql_query);
2509 $("#change_password_dialog").hide().remove();
2510 $("#edit_user_dialog").dialog("close").remove();
2511 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2512 PMA_ajaxRemoveMessage($msgbox);
2515 PMA_ajaxShowMessage(data.error);
2518 }) // end handler for Change Password form submission
2519 }) // end $(document).ready() for Change Password
2522 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2523 * the page loads and when the selected data type changes
2525 $(document).ready(function() {
2526 // is called here for normal page loads and also when opening
2527 // the Create table dialog
2528 PMA_verifyTypeOfAllColumns();
2530 // needs live() to work also in the Create Table dialog
2531 $("select[class='column_type']").live('change', function() {
2532 PMA_showNoticeForEnum($(this));
2536 function PMA_verifyTypeOfAllColumns()
2538 $("select[class='column_type']").each(function() {
2539 PMA_showNoticeForEnum($(this));
2544 * Closes the ENUM/SET editor and removes the data in it
2546 function disable_popup()
2548 $("#popup_background").fadeOut("fast");
2549 $("#enum_editor").fadeOut("fast");
2550 // clear the data from the text boxes
2551 $("#enum_editor #values input").remove();
2552 $("#enum_editor input[type='hidden']").remove();
2556 * Opens the ENUM/SET editor and controls its functions
2558 $(document).ready(function() {
2559 // Needs live() to work also in the Create table dialog
2560 $("a[class='open_enum_editor']").live('click', function() {
2562 var windowWidth = document.documentElement.clientWidth;
2563 var windowHeight = document.documentElement.clientHeight;
2564 var popupWidth = windowWidth/2;
2565 var popupHeight = windowHeight*0.8;
2566 var popupOffsetTop = windowHeight/2 - popupHeight/2;
2567 var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2568 $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2571 $("#popup_background").css({"opacity":"0.7"});
2572 $("#popup_background").fadeIn("fast");
2573 $("#enum_editor").fadeIn("fast");
2574 /**Replacing the column name in the enum editor header*/
2575 var column_name = $("#append_fields_form").find("input[id=field_0_1]").attr("value");
2576 var h3_text = $("#enum_editor h3").html();
2577 $("#enum_editor h3").html(h3_text.split('"')[0]+'"'+column_name+'"');
2580 var values = $(this).parent().prev("input").attr("value").split(",");
2581 $.each(values, function(index, val) {
2582 if(jQuery.trim(val) != "") {
2583 // enclose the string in single quotes if it's not already
2584 if(val.substr(0, 1) != "'") {
2587 if(val.substr(val.length-1, val.length) != "'") {
2590 // escape the single quotes, except the mandatory ones enclosing the entire string
2591 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "'");
2592 // escape the greater-than symbol
2593 val = val.replace(/>/g, ">");
2594 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2597 // So we know which column's data is being edited
2598 $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2602 // If the "close" link is clicked, close the enum editor
2603 // Needs live() to work also in the Create table dialog
2604 $("a[class='close_enum_editor']").live('click', function() {
2608 // If the "cancel" link is clicked, close the enum editor
2609 // Needs live() to work also in the Create table dialog
2610 $("a[class='cancel_enum_editor']").live('click', function() {
2614 // When "add a new value" is clicked, append an empty text field
2615 // Needs live() to work also in the Create table dialog
2616 $("a[class='add_value']").live('click', function() {
2617 $("#enum_editor #values").append("<input type='text' />");
2620 // When the submit button is clicked, put the data back into the original form
2621 // Needs live() to work also in the Create table dialog
2622 $("#enum_editor input[type='submit']").live('click', function() {
2623 var value_array = new Array();
2624 $.each($("#enum_editor #values input"), function(index, input_element) {
2625 val = jQuery.trim(input_element.value);
2627 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2630 // get the Length/Values text field where this value belongs
2631 var values_id = $("#enum_editor input[type='hidden']").attr("value");
2632 $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2637 * Hides certain table structure actions, replacing them with the word "More". They are displayed
2638 * in a dropdown menu when the user hovers over the word "More."
2640 displayMoreTableOpts();
2643 function displayMoreTableOpts()
2645 // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2646 // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2647 if($("input[type='hidden'][name='table_type']").val() == "table") {
2648 var $table = $("table[id='tablestructure']");
2649 $table.find("td[class='browse']").remove();
2650 $table.find("td[class='primary']").remove();
2651 $table.find("td[class='unique']").remove();
2652 $table.find("td[class='index']").remove();
2653 $table.find("td[class='fulltext']").remove();
2654 $table.find("td[class='spatial']").remove();
2655 $table.find("th[class='action']").attr("colspan", 3);
2657 // Display the "more" text
2658 $table.find("td[class='more_opts']").show();
2660 // Position the dropdown
2661 $(".structure_actions_dropdown").each(function() {
2662 // Optimize DOM querying
2663 var $this_dropdown = $(this);
2664 // The top offset must be set for IE even if it didn't change
2665 var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2666 var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2667 var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2668 $this_dropdown.offset({ top: top_offset, left: left_offset });
2671 // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2672 // positioning an iframe directly on top of it
2673 var $after_field = $("select[name='after_field']");
2674 $("iframe[class='IE_hack']")
2675 .width($after_field.width())
2676 .height($after_field.height())
2678 top: $after_field.offset().top,
2679 left: $after_field.offset().left
2682 // When "more" is hovered over, show the hidden actions
2683 $table.find("td[class='more_opts']")
2684 .mouseenter(function() {
2685 if($.browser.msie && $.browser.version == "6.0") {
2686 $("iframe[class='IE_hack']")
2688 .width($after_field.width()+4)
2689 .height($after_field.height()+4)
2691 top: $after_field.offset().top,
2692 left: $after_field.offset().left
2695 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2696 $(this).children(".structure_actions_dropdown").show();
2697 // Need to do this again for IE otherwise the offset is wrong
2698 if($.browser.msie) {
2699 var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2700 var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2701 $(this).children(".structure_actions_dropdown").offset({
2703 left: left_offset_IE });
2706 .mouseleave(function() {
2707 $(this).children(".structure_actions_dropdown").hide();
2708 if($.browser.msie && $.browser.version == "6.0") {
2709 $("iframe[class='IE_hack']").hide();
2715 $(document).ready(function(){
2716 PMA_convertFootnotesToTooltips();
2720 * Ensures indexes names are valid according to their type and, for a primary
2721 * key, lock index name to 'PRIMARY'
2722 * @param string form_id Variable which parses the form name as
2724 * @return boolean false if there is no index form, true else
2726 function checkIndexName(form_id)
2728 if ($("#"+form_id).length == 0) {
2732 // Gets the elements pointers
2733 var $the_idx_name = $("#input_index_name");
2734 var $the_idx_type = $("#select_index_type");
2736 // Index is a primary key
2737 if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2738 $the_idx_name.attr("value", 'PRIMARY');
2739 $the_idx_name.attr("disabled", true);
2744 if ($the_idx_name.attr("value") == 'PRIMARY') {
2745 $the_idx_name.attr("value", '');
2747 $the_idx_name.attr("disabled", false);
2751 } // end of the 'checkIndexName()' function
2754 * function to convert the footnotes to tooltips
2756 * @param jquery-Object $div a div jquery object which specifies the
2757 * domain for searching footnootes. If we
2758 * ommit this parameter the function searches
2759 * the footnotes in the whole body
2761 function PMA_convertFootnotesToTooltips($div)
2763 // Hide the footnotes from the footer (which are displayed for
2764 // JavaScript-disabled browsers) since the tooltip is sufficient
2766 if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2767 $div = $("#serverinfo").parent();
2770 $footnotes = $div.find(".footnotes");
2773 $footnotes.find('span').each(function() {
2774 $(this).children("sup").remove();
2776 // The border and padding must be removed otherwise a thin yellow box remains visible
2777 $footnotes.css("border", "none");
2778 $footnotes.css("padding", "0px");
2780 // Replace the superscripts with the help icon
2781 $div.find("sup.footnotemarker").hide();
2782 $div.find("img.footnotemarker").show();
2784 $div.find("img.footnotemarker").each(function() {
2785 var img_class = $(this).attr("class");
2786 /** img contains two classes, as example "footnotemarker footnote_1".
2787 * We split it by second class and take it for the id of span
2789 img_class = img_class.split(" ");
2790 for (i = 0; i < img_class.length; i++) {
2791 if (img_class[i].split("_")[0] == "footnote") {
2792 var span_id = img_class[i].split("_")[1];
2796 * Now we get the #id of the span with span_id variable. As an example if we
2797 * initially get the img class as "footnotemarker footnote_2", now we get
2798 * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2800 var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2802 content: tooltip_text,
2804 hide: { delay: 1000 },
2805 style: { background: '#ffffcc' }
2810 function menuResize()
2812 var cnt = $('#topmenu');
2813 var wmax = cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2814 var submenu = cnt.find('.submenu');
2815 var submenu_w = submenu.outerWidth(true);
2816 var submenu_ul = submenu.find('ul');
2817 var li = cnt.find('> li');
2818 var li2 = submenu_ul.find('li');
2819 var more_shown = li2.length > 0;
2820 var w = more_shown ? submenu_w : 0;
2824 for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2826 var el_width = el.outerWidth(true);
2827 el.data('width', el_width);
2831 if (w + submenu_w < wmax) {
2835 w -= $(li[i-1]).data('width');
2841 if (hide_start > 0) {
2842 for (var i = hide_start; i < li.length-1; i++) {
2843 $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2845 submenu.addClass('shown');
2846 } else if (more_shown) {
2848 // nothing hidden, maybe something can be restored
2849 for (var i = 0; i < li2.length; i++) {
2850 //console.log(li2[i], submenu_w);
2851 w += $(li2[i]).data('width');
2852 // item fits or (it is the last item and it would fit if More got removed)
2853 if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2854 $(li2[i]).insertBefore(submenu);
2855 if (i == li2.length-1) {
2856 submenu.removeClass('shown');
2863 if (submenu.find('.tabactive').length) {
2864 submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2866 submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2871 var topmenu = $('#topmenu');
2872 if (topmenu.length == 0) {
2875 // create submenu container
2876 var link = $('<a />', {href: '#', 'class': 'tab'})
2877 .text(PMA_messages['strMore'])
2878 .click(function(e) {
2881 var img = topmenu.find('li:first-child img');
2883 $(PMA_getImage('b_more.png').toString()).prependTo(link);
2885 var submenu = $('<li />', {'class': 'submenu'})
2887 .append($('<ul />'))
2888 .mouseenter(function() {
2889 if ($(this).find('ul .tabactive').length == 0) {
2890 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2893 .mouseleave(function() {
2894 if ($(this).find('ul .tabactive').length == 0) {
2895 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2898 topmenu.append(submenu);
2900 // populate submenu and register resize event
2901 $(window).resize(menuResize);
2906 * Get the row number from the classlist (for example, row_1)
2908 function PMA_getRowNumber(classlist)
2910 return parseInt(classlist.split(/\s+row_/)[1]);
2914 * Changes status of slider
2916 function PMA_set_status_label($element)
2918 var text = $element.css('display') == 'none'
2921 $element.closest('.slide-wrapper').prev().find('span').text(text);
2925 * Initializes slider effect.
2927 function PMA_init_slider()
2929 $('.pma_auto_slider').each(function() {
2930 var $this = $(this);
2932 if ($this.hasClass('slider_init_done')) {
2935 $this.addClass('slider_init_done');
2937 var $wrapper = $('<div>', {'class': 'slide-wrapper'}).css('height', $this.outerHeight(true));
2938 $wrapper.toggle($this.is(':visible'));
2939 $('<a>', {href: '#'+this.id})
2941 .prepend($('<span>'))
2942 .insertBefore($this)
2944 var $wrapper = $this.closest('.slide-wrapper');
2945 var visible = $this.is(':visible');
2949 $this[visible ? 'hide' : 'show']('blind', function() {
2950 $wrapper.toggle(!visible);
2951 PMA_set_status_label($this);
2955 $this.wrap($wrapper);
2956 PMA_set_status_label($this);
2961 * var toggleButton This is a function that creates a toggle
2962 * sliding button given a jQuery reference
2963 * to the correct DOM element
2965 var toggleButton = function ($obj) {
2966 // In rtl mode the toggle switch is flipped horizontally
2967 // so we need to take that into account
2968 if ($('.text_direction', $obj).text() == 'ltr') {
2969 var right = 'right';
2974 * var h Height of the button, used to scale the
2975 * background image and position the layers
2977 var h = $obj.height();
2978 $('img', $obj).height(h);
2979 $('table', $obj).css('bottom', h-1);
2981 * var on Width of the "ON" part of the toggle switch
2982 * var off Width of the "OFF" part of the toggle switch
2984 var on = $('.toggleOn', $obj).width();
2985 var off = $('.toggleOff', $obj).width();
2986 // Make the "ON" and "OFF" parts of the switch the same size
2987 $('.toggleOn > div', $obj).width(Math.max(on, off));
2988 $('.toggleOff > div', $obj).width(Math.max(on, off));
2990 * var w Width of the central part of the switch
2992 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
2993 // Resize the central part of the switch on the top
2994 // layer to match the background
2995 $('table td:nth-child(2) > div', $obj).width(w);
2997 * var imgw Width of the background image
2998 * var tblw Width of the foreground layer
2999 * var offset By how many pixels to move the background
3000 * image, so that it matches the top layer
3002 var imgw = $('img', $obj).width();
3003 var tblw = $('table', $obj).width();
3004 var offset = parseInt(((imgw - tblw) / 2), 10);
3005 // Move the background to match the layout of the top layer
3006 $obj.find('img').css(right, offset);
3008 * var offw Outer width of the "ON" part of the toggle switch
3009 * var btnw Outer width of the central part of the switch
3011 var offw = $('.toggleOff', $obj).outerWidth();
3012 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
3013 // Resize the main div so that exactly one side of
3014 // the switch plus the central part fit into it.
3015 $obj.width(offw + btnw + 2);
3017 * var move How many pixels to move the
3018 * switch by when toggling
3020 var move = $('.toggleOff', $obj).outerWidth();
3021 // If the switch is initialized to the
3022 // OFF state we need to move it now.
3023 if ($('.container', $obj).hasClass('off')) {
3024 if (right == 'right') {
3025 $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
3027 $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
3030 // Attach an 'onclick' event to the switch
3031 $('.container', $obj).click(function () {
3032 if ($(this).hasClass('isActive')) {
3035 $(this).addClass('isActive');
3037 var $msg = PMA_ajaxShowMessage();
3038 var $container = $(this);
3039 var callback = $('.callback', this).text();
3040 // Perform the actual toggle
3041 if ($(this).hasClass('on')) {
3042 if (right == 'right') {
3043 var operator = '-=';
3045 var operator = '+=';
3047 var url = $(this).find('.toggleOff > span').text();
3048 var removeClass = 'on';
3049 var addClass = 'off';
3051 if (right == 'right') {
3052 var operator = '+=';
3054 var operator = '-=';
3056 var url = $(this).find('.toggleOn > span').text();
3057 var removeClass = 'off';
3058 var addClass = 'on';
3060 $.post(url, {'ajax_request': true}, function(data) {
3061 if(data.success == true) {
3062 PMA_ajaxRemoveMessage($msg);
3064 .removeClass(removeClass)
3066 .animate({'left': operator + move + 'px'}, function () {
3067 $container.removeClass('isActive');
3071 PMA_ajaxShowMessage(data.error);
3072 $container.removeClass('isActive');
3079 * Initialise all toggle buttons
3081 $(window).load(function () {
3082 $('.toggleAjax').each(function () {
3085 .find('.toggleButton')
3086 toggleButton($(this));
3093 $(document).ready(function() {
3094 $('.vpointer').live('hover',
3097 var $this_td = $(this);
3098 var row_num = PMA_getRowNumber($this_td.attr('class'));
3099 // for all td of the same vertical row, toggle hover
3100 $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
3103 }) // end of $(document).ready() for vertical pointer
3105 $(document).ready(function() {
3109 $('.vmarker').live('click', function(e) {
3110 // do not trigger when clicked on anchor
3111 if ($(e.target).is('a, img, a *')) {
3115 var $this_td = $(this);
3116 var row_num = PMA_getRowNumber($this_td.attr('class'));
3118 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
3120 var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
3121 if ($checkbox.length) {
3122 // checkbox in a row, add or remove class depending on checkbox state
3123 var checked = $checkbox.attr('checked');
3124 if (!$(e.target).is(':checkbox, label')) {
3126 $checkbox.attr('checked', checked);
3128 // for all td of the same vertical row, toggle the marked class
3130 $('.vmarker').filter('.row_' + row_num).addClass('marked');
3132 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
3135 // normaln data table, just toggle class
3136 $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
3141 * Reveal visual builder anchor
3144 $('#visual_builder_anchor').show();
3147 * Page selector in db Structure (non-AJAX)
3149 $('#tableslistcontainer').find('#pageselector').live('change', function() {
3150 $(this).parent("form").submit();
3154 * Page selector in navi panel (non-AJAX)
3156 $('#navidbpageselector').find('#pageselector').live('change', function() {
3157 $(this).parent("form").submit();
3161 * Page selector in browse_foreigners windows (non-AJAX)
3163 $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3164 $(this).closest("form").submit();
3168 * Load version information asynchronously.
3170 if ($('.jsversioncheck').length > 0) {
3172 var s = document.createElement('script');
3173 s.type = 'text/javascript';
3175 s.src = 'http://www.phpmyadmin.net/home_page/version.js';
3176 s.onload = PMA_current_version;
3177 var x = document.getElementsByTagName('script')[0];
3178 x.parentNode.insertBefore(s, x);
3188 * Enables the text generated by PMA_linkOrButton() to be clickable
3190 $('a[class~="formLinkSubmit"]').live('click',function(e) {
3192 if($(this).attr('href').indexOf('=') != -1) {
3193 var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3194 $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3196 $(this).parents('form').submit();
3200 $('#update_recent_tables').ready(function() {
3201 if (window.parent.frame_navigation != undefined
3202 && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3204 window.parent.frame_navigation.PMA_reloadRecentTable();
3208 }) // end of $(document).ready()
3211 * Creates a message inside an object with a sliding effect
3213 * @param msg A string containing the text to display
3214 * @param $obj a jQuery object containing the reference
3215 * to the element where to put the message
3216 * This is optional, if no element is
3217 * provided, one will be created below the
3218 * navigation links at the top of the page
3220 * @return bool True on success, false on failure
3222 function PMA_slidingMessage(msg, $obj)
3224 if (msg == undefined || msg.length == 0) {
3225 // Don't show an empty message
3228 if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3229 // If the second argument was not supplied,
3230 // we might have to create a new DOM node.
3231 if ($('#PMA_slidingMessage').length == 0) {
3232 $('#topmenucontainer')
3233 .after('<span id="PMA_slidingMessage" '
3234 + 'style="display: inline-block;"></span>');
3236 $obj = $('#PMA_slidingMessage');
3238 if ($obj.has('div').length > 0) {
3239 // If there already is a message inside the
3240 // target object, we must get rid of it
3244 .fadeOut(function () {
3249 .append('<div style="display: none;">' + msg + '</div>')
3251 height: $obj.find('div').first().height()
3258 // Object does not already have a message
3259 // inside it, so we simply slide it down
3262 .html('<div style="display: none;">' + msg + '</div>')
3274 // Set the height of the parent
3275 // to the height of the child
3286 } // end PMA_slidingMessage()
3289 * Attach Ajax event handlers for Drop Table.
3291 * @uses $.PMA_confirm()
3292 * @uses PMA_ajaxShowMessage()
3293 * @uses window.parent.refreshNavigation()
3294 * @uses window.parent.refreshMain()
3295 * @see $cfg['AjaxEnable']
3297 $(document).ready(function() {
3298 $("#drop_tbl_anchor").live('click', function(event) {
3299 event.preventDefault();
3301 //context is top.frame_content, so we need to use window.parent.table to access the table var
3303 * @var question String containing the question to be asked for confirmation
3305 var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + window.parent.table;
3307 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3309 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3310 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3311 //Database deleted successfully, refresh both the frames
3312 window.parent.refreshNavigation();
3313 window.parent.refreshMain();
3315 }); // end $.PMA_confirm()
3316 }); //end of Drop Table Ajax action
3317 }) // end of $(document).ready() for Drop Table
3320 * Attach Ajax event handlers for Truncate Table.
3322 * @uses $.PMA_confirm()
3323 * @uses PMA_ajaxShowMessage()
3324 * @uses window.parent.refreshNavigation()
3325 * @uses window.parent.refreshMain()
3326 * @see $cfg['AjaxEnable']
3328 $(document).ready(function() {
3329 $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3330 event.preventDefault();
3332 //context is top.frame_content, so we need to use window.parent.table to access the table var
3334 * @var question String containing the question to be asked for confirmation
3336 var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + window.parent.table;
3338 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3340 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3341 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3342 if ($("#sqlqueryresults").length != 0) {
3343 $("#sqlqueryresults").remove();
3345 if ($("#result_query").length != 0) {
3346 $("#result_query").remove();
3348 if (data.success == true) {
3349 PMA_ajaxShowMessage(data.message);
3350 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
3351 $("#sqlqueryresults").html(data.sql_query);
3353 var $temp_div = $("<div id='temp_div'></div>")
3354 $temp_div.html(data.error);
3355 var $error = $temp_div.find("code").addClass("error");
3356 PMA_ajaxShowMessage($error);
3359 }); // end $.PMA_confirm()
3360 }); //end of Truncate Table Ajax action
3361 }) // end of $(document).ready() for Truncate Table
3364 * Attach CodeMirror2 editor to SQL edit area.
3366 $(document).ready(function() {
3367 var elm = $('#sqlquery');
3368 if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3369 codemirror_editor = CodeMirror.fromTextArea(elm[0], {lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-mysql"});
3374 * jQuery plugin to cancel selection in HTML code.
3377 $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3378 var prevent = (p == null) ? true : p;
3380 return this.each(function () {
3381 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3384 else if ($.browser.mozilla) {
3385 $(this).css('MozUserSelect', 'none');
3386 $('body').trigger('focus');
3387 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3390 else $(this).attr('unselectable', 'on');
3393 return this.each(function () {
3394 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3395 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3396 else if ($.browser.opera) $(this).unbind('mousedown');
3397 else $(this).removeAttr('unselectable', 'on');
3404 * Create default PMA tooltip for the element specified. The default appearance
3405 * can be overriden by specifying optional "options" parameter (see qTip options).
3407 function PMA_createqTip($elements, content, options)
3409 if ($('#no_hint').length > 0) {
3417 tooltip: 'normalqTip',
3418 content: 'normalqTipContent'
3424 corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3425 adjust: { x: 10, y: 20 }
3442 $elements.qtip($.extend(true, o, options));
3446 * Return value of a cell in a table.
3448 function PMA_getCellValue(td) {
3449 if ($(td).is('.null')) {
3451 } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3452 return $(td).data('original_data');
3454 return $(td).text();
3458 /* Loads a js file, an array may be passed as well */
3459 loadJavascript=function(file) {
3460 if($.isArray(file)) {
3461 for(var i=0; i<file.length; i++) {
3462 $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3465 $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3469 $(document).ready(function() {
3473 $('a.themeselect').live('click', function(e) {
3477 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3483 * Automatic form submission on change.
3485 $('.autosubmit').change(function(e) {
3486 e.target.form.submit();
3492 $('.take_theme').click(function(e) {
3493 var what = this.name;
3494 if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3495 window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3496 window.opener.document.forms['setTheme'].submit();
3505 * Clear text selection
3507 function PMA_clearSelection() {
3508 if(document.selection && document.selection.empty) {
3509 document.selection.empty();
3510 } else if(window.getSelection) {
3511 var sel = window.getSelection();
3512 if(sel.empty) sel.empty();
3513 if(sel.removeAllRanges) sel.removeAllRanges();
3520 function escapeHtml(unsafe) {
3522 .replace(/&/g, "&")
3523 .replace(/</g, "<")
3524 .replace(/>/g, ">")
3525 .replace(/"/g, """)
3526 .replace(/'/g, "'");