Fix merge conflicts
[phpmyadmin.git] / js / server_privileges.js
blobf6c05999f192f9a1294f2f1458acc4dd84222aba
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    functions used in server privilege pages
4  * @name            Server Privileges
5  *
6  * @requires    jQuery
7  * @requires    jQueryUI
8  * @requires    js/functions.js
9  *
10  */
12 /**
13  * Validates the "add a user" form
14  *
15  * @return boolean  whether the form is validated or not
16  */
17 function checkAddUser(the_form)
19     if (the_form.elements['pred_hostname'].value == 'userdefined' && the_form.elements['hostname'].value == '') {
20         alert(PMA_messages['strHostEmpty']);
21         the_form.elements['hostname'].focus();
22         return false;
23     }
25     if (the_form.elements['pred_username'].value == 'userdefined' && the_form.elements['username'].value == '') {
26         alert(PMA_messages['strUserEmpty']);
27         the_form.elements['username'].focus();
28         return false;
29     }
31     return PMA_checkPassword($(the_form));
32 } // end of the 'checkAddUser()' function
34 /**
35  * When a new user is created and retrieved over Ajax, append the user's row to
36  * the user's table
37  *
38  * @param new_user_string         the html for the new user's row
39  * @param new_user_initial        the first alphabet of the user's name
40  * @param new_user_initial_string html to replace the initial for pagination
41  */
42 function appendNewUser(new_user_string, new_user_initial, new_user_initial_string)
44     //Append the newly retrieved user to the table now
46     //Calculate the index for the new row
47     var $curr_last_row = $("#usersForm").find('tbody').find('tr:last');
48     var $curr_first_row = $("#usersForm").find('tbody').find('tr:first');
49     var first_row_initial = $curr_first_row.find('label').html().substr(0, 1).toUpperCase();
50     var curr_shown_initial = $curr_last_row.find('label').html().substr(0, 1).toUpperCase();
51     var curr_last_row_index_string = $curr_last_row.find('input:checkbox').attr('id').match(/\d+/)[0];
52     var curr_last_row_index = parseFloat(curr_last_row_index_string);
53     var new_last_row_index = curr_last_row_index + 1;
54     var new_last_row_id = 'checkbox_sel_users_' + new_last_row_index;
55     var is_show_all = (first_row_initial != curr_shown_initial) ? true : false;
57     //Append to the table and set the id/names correctly
58     if ((curr_shown_initial == new_user_initial) || is_show_all) {
59         $(new_user_string)
60         .insertAfter($curr_last_row)
61         .find('input:checkbox')
62         .attr('id', new_last_row_id)
63         .val(function() {
64             //the insert messes up the &27; part. let's fix it
65             return $(this).val().replace(/&/,'&');
66         })
67         .end()
68         .find('label')
69         .attr('for', new_last_row_id)
70         .end();
71     }
73     //Let us sort the table alphabetically
74     $("#usersForm").find('tbody').PMA_sort_table('label');
76     $("#initials_table").find('td:contains('+new_user_initial+')')
77     .html(new_user_initial_string);
79     //update the checkall checkbox
80     $(checkboxes_sel).trigger("change");
83 function addUser($form)
85     if (! checkAddUser($form.get(0))) {
86         return false;
87     }
89     //We also need to post the value of the submit button in order to get this to work correctly
90     $.post($form.attr('action'), $form.serialize() + "&adduser_submit=" + $("input[name=adduser_submit]").val(), function(data) {
91         if (data.success == true) {
92             // Refresh navigation, if we created a database with the name
93             // that is the same as the username of the new user
94             if ($('#add_user_dialog #createdb-1:checked').length) {
95                 PMA_reloadNavigation();
96             }
98             $('#page_content').show();
99             $("#add_user_dialog").remove();
101             PMA_ajaxShowMessage(data.message);
102             $("#result_query").remove();
103             $('#page_content').prepend(data.sql_query);
104             $("#result_query").css({
105                 'margin-top' : '0.5em'
106             });
108             //Remove the empty notice div generated due to a NULL query passed to PMA_getMessage()
109             var $notice_class = $("#result_query").find('.notice');
110             if ($notice_class.text() == '') {
111                 $notice_class.remove();
112             }
113             if ($('#fieldset_add_user a.ajax').attr('name') == 'db_specific') {
115                 /*process the fieldset_add_user attribute and get the val of privileges*/
116                 var url = $('#fieldset_add_user a.ajax').attr('rel');
118                 if (url.substring(url.length - 23, url.length) == "&goto=db_operations.php") {
119                     url = url.substring(0, url.length - 23);
120                 }
121                 url = url + "&ajax_request=true&db_specific=true";
123                 /* post request for get the updated userForm table */
124                 $.post($form.attr('action'), url, function(priv_data) {
126                     /*Remove the old userForm table*/
127                     if ($('#userFormDiv').length != 0) {
128                         $('#userFormDiv').remove();
129                     } else {
130                         $("#usersForm").remove();
131                     }
132                     if (priv_data.success == true) {
133                         $('<div id="userFormDiv"></div>')
134                             .html(priv_data.user_form)
135                             .insertAfter('#result_query');
136                     } else {
137                         PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + priv_data.error, false);
138                     }
139                 });
140             } else {
141                 appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
142             }
143         } else {
144             PMA_ajaxShowMessage(data.error, false);
145         }
146     });
150  * AJAX scripts for server_privileges page.
152  * Actions ajaxified here:
153  * Add user
154  * Revoke a user
155  * Edit privileges
156  * Export privileges
157  * Paginate table of users
158  * Flush privileges
160  * @memberOf    jQuery
161  * @name        document.ready
162  */
166  * Unbind all event handlers before tearing down a page
167  */
168 AJAX.registerTeardown('server_privileges.js', function() {
169     $("#fieldset_add_user a.ajax").die("click");
170     $('form[name=usersForm]').unbind('submit');
171     $("#reload_privileges_anchor.ajax").die("click");
172     $("#fieldset_delete_user_footer #buttonGo.ajax").die('click');
173     $("a.edit_user_anchor.ajax").die('click');
174     $("#edit_user_dialog").find("form.ajax").die('submit');
175     $("button.mult_submit[value=export]").die('click');
176     $("a.export_user_anchor.ajax").die('click');
177     $("#initials_table").find("a.ajax").die('click');
178     $('#checkbox_drop_users_db').unbind('click');
181 AJAX.registerOnload('server_privileges.js', function() {
182     /**
183      * AJAX event handler for 'Add a New User'
184      *
185      * @see         PMA_ajaxShowMessage()
186      * @see         appendNewUser()
187      * @memberOf    jQuery
188      * @name        add_user_click
189      *
190      */
191     $("#fieldset_add_user a.ajax").live("click", function(event) {
192         /** @lends jQuery */
193         event.preventDefault();
194         var $msgbox = PMA_ajaxShowMessage();
196         $.get($(this).attr("href"), {'ajax_request':true}, function(data) {
197             if (data.success == true) {
198                 $('#page_content').hide();
199                 var $div = $('#add_user_dialog');
200                 if ($div.length == 0) {
201                     $div = $('<div id="add_user_dialog" style="margin: 0.5em;"></div>')
202                         .insertBefore('#page_content');
203                 } else {
204                     $div.empty();
205                 }
206                 $div.html(data.message)
207                     .find("form[name=usersForm]")
208                     .append('<input type="hidden" name="ajax_request" value="true" />')
209                     .end();
210                 displayPasswordGenerateButton();
211                 PMA_showHints($div);
212                 PMA_ajaxRemoveMessage($msgbox);
213                 $div.find("input.autofocus").focus();
215                 $div.find('form[name=usersForm]').bind('submit', function (event) {
216                     event.preventDefault();
217                     addUser($(this));
218                 });
219             } else {
220                 PMA_ajaxShowMessage(data.error, false);
221             }
222         }); // end $.get()
224     });//end of Add New User AJAX event handler
227     /**
228      * Ajax event handler for 'Reload Privileges' anchor
229      *
230      * @see         PMA_ajaxShowMessage()
231      * @memberOf    jQuery
232      * @name        reload_privileges_click
233      */
234     $("#reload_privileges_anchor.ajax").live("click", function(event) {
235         event.preventDefault();
237         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strReloadingPrivileges']);
239         $.get($(this).attr("href"), {'ajax_request': true}, function(data) {
240             if (data.success == true) {
241                 PMA_ajaxRemoveMessage($msgbox);
242             } else {
243                 PMA_ajaxShowMessage(data.error, false);
244             }
245         }); //end $.get()
247     }); //end of Reload Privileges Ajax event handler
249     /**
250      * AJAX handler for 'Revoke User'
251      *
252      * @see         PMA_ajaxShowMessage()
253      * @memberOf    jQuery
254      * @name        revoke_user_click
255      */
256     $("#fieldset_delete_user_footer #buttonGo.ajax").live('click', function(event) {
257         event.preventDefault();
259         PMA_ajaxShowMessage(PMA_messages['strRemovingSelectedUsers']);
261         var $form = $("#usersForm");
263         $.post($form.attr('action'), $form.serialize() + "&delete=" + $(this).val() + "&ajax_request=true", function(data) {
264             if (data.success == true) {
265                 PMA_ajaxShowMessage(data.message);
266                 // Refresh navigation, if we droppped some databases with the name
267                 // that is the same as the username of the deleted user
268                 if ($('#checkbox_drop_users_db:checked').length) {
269                     PMA_reloadNavigation();
270                 }
271                 //Remove the revoked user from the users list
272                 $form.find("input:checkbox:checked").parents("tr").slideUp("medium", function() {
273                     var this_user_initial = $(this).find('input:checkbox').val().charAt(0).toUpperCase();
274                     $(this).remove();
276                     //If this is the last user with this_user_initial, remove the link from #initials_table
277                     if ($("#tableuserrights").find('input:checkbox[value^=' + this_user_initial + ']').length == 0) {
278                         $("#initials_table").find('td > a:contains(' + this_user_initial + ')').parent('td').html(this_user_initial);
279                     }
281                     //Re-check the classes of each row
282                     $form
283                     .find('tbody').find('tr:odd')
284                     .removeClass('even').addClass('odd')
285                     .end()
286                     .find('tr:even')
287                     .removeClass('odd').addClass('even');
289                     //update the checkall checkbox
290                     $(checkboxes_sel).trigger("change");
291                 });
292             } else {
293                 PMA_ajaxShowMessage(data.error, false);
294             }
295         }); // end $.post()
296     }); // end Revoke User
298     /**
299      * AJAX handler for 'Edit User'
300      *
301      * @see         PMA_ajaxShowMessage()
302      *
303      */
305     /**
306      * Step 1: Load Edit User Dialog
307      * @memberOf    jQuery
308      * @name        edit_user_click
309      */
310     $("a.edit_user_anchor.ajax").live('click', function(event) {
311         /** @lends jQuery */
312         event.preventDefault();
314         var $msgbox = PMA_ajaxShowMessage();
316         $(this).parents('tr').addClass('current_row');
318         var token = $(this).parents('form').find('input[name="token"]').val();
319         $.get(
320             $(this).attr('href'),
321             {
322                 'ajax_request':true,
323                 'edit_user_dialog': true,
324                 'token': token
325             },
326             function(data) {
327                 if (data.success == true) {
328                     $('#page_content').hide();
329                     var $div = $('#edit_user_dialog');
330                     if ($div.length == 0) {
331                         $div = $('<div id="edit_user_dialog" style="margin: 0.5em;"></div>')
332                             .insertBefore('#page_content');
333                     } else {
334                         $div.empty();
335                     }
336                     $div.html(data.message);
337                     displayPasswordGenerateButton();
338                     PMA_ajaxRemoveMessage($msgbox);
339                     PMA_showHints($div);
340                 } else {
341                     PMA_ajaxShowMessage(data.error, false);
342                 }
343             }
344         ); // end $.get()
345     });
347     /**
348      * Step 2: Submit the Edit User Dialog
349      *
350      * @see         PMA_ajaxShowMessage()
351      * @memberOf    jQuery
352      * @name        edit_user_submit
353      */
354     $("#edit_user_dialog").find("form.ajax").live('submit', function(event) {
355         /** @lends jQuery */
356         event.preventDefault();
358         var $t = $(this);
360         if ($t.is('.copyUserForm') && ! PMA_checkPassword($t)) {
361             return false;
362         }
364         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
366         $t.append('<input type="hidden" name="ajax_request" value="true" />');
368         /**
369          * @var curr_submit_name    name of the current button being submitted
370          */
371         var curr_submit_name = $t.find('.tblFooters').find('input:submit').attr('name');
373         /**
374          * @var curr_submit_value    value of the current button being submitted
375          */
376         var curr_submit_value = $t.find('.tblFooters').find('input:submit').val();
378         // If any option other than 'keep the old one'(option 4) is chosen, we need to remove 
379         // the old one from the table.
380         var $row_to_remove;
381         if (curr_submit_name == 'change_copy'
382                 && $('input[name=mode]:checked', '#fieldset_mode').val() != '4') {
383             var old_username = $t.find('input[name="old_username"]').val();
384             var old_hostname = $t.find('input[name="old_hostname"]').val();
385             $('#usersForm tbody tr').each(function() {
386                 var $tr = $(this);
387                 if ($tr.find('td:nth-child(2) label').text() == old_username
388                         && $tr.find('td:nth-child(3)').text() == old_hostname) {
389                     $row_to_remove = $tr;
390                     return false;
391                 }
392             });
393         }
395         $.post($t.attr('action'), $t.serialize() + '&' + curr_submit_name + '=' + curr_submit_value, function(data) {
396             if (data.success == true) {
397                 $('#page_content').show();
398                 $("#edit_user_dialog").remove();
400                 PMA_ajaxShowMessage(data.message);
402                 if (data.sql_query) {
403                     $("#result_query").remove();
404                     $('#page_content').prepend(data.sql_query);
405                     $("#result_query").css({
406                         'margin-top' : '0.5em'
407                     });
408                     var $notice_class = $("#result_query").find('.notice');
409                     if ($notice_class.text() == '') {
410                         $notice_class.remove();
411                     }
412                 } //Show SQL Query that was executed
414                 // Remove the old row if the old user is deleted
415                 if ($row_to_remove != null) {
416                     $row_to_remove.remove();
417                 }
419                 //Append new user if necessary
420                 if (data.new_user_string) {
421                     appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
422                 }
424                 //Check if we are on the page of the db-specific privileges
425                 var db_priv_page = !!($('#dbspecificuserrights').length); // the "!!" part is merely there to ensure a value of type boolean
426                 // we always need to reload on the db-specific privilege page
427                 // and on the global page when adjusting global privileges,
428                 // but not on the global page when adjusting db-specific privileges.
429                 var reload_privs = false;
430                 if (data.db_specific_privs == false || (db_priv_page == data.db_specific_privs)) {
431                     reload_privs = true;
432                 }
433                 if (data.db_wildcard_privs) {
434                     reload_privs = false;
435                 }
437                 //Change privileges, if they were edited and need to be reloaded
438                 if (data.new_privileges && reload_privs) {
439                     $("#usersForm")
440                     .find('.current_row')
441                     .find('code')
442                     .html(data.new_privileges);
443                 }
445                 $("#usersForm")
446                 .find('.current_row')
447                 .removeClass('current_row');
448             } else {
449                 PMA_ajaxShowMessage(data.error, false);
450             }
451         });
452     });
453     //end Edit user
455     /**
456      * AJAX handler for 'Export Privileges'
457      *
458      * @see         PMA_ajaxShowMessage()
459      * @memberOf    jQuery
460      * @name        export_user_click
461      */
462     $("button.mult_submit[value=export]").live('click', function(event) {
463         event.preventDefault();
464         // can't export if no users checked
465         if ($(this.form).find("input:checked").length == 0) {
466             return;
467         }
468         var $msgbox = PMA_ajaxShowMessage();
469         var button_options = {};
470         button_options[PMA_messages['strClose']] = function() {
471             $(this).dialog("close");
472         };
473         $.post(
474             $(this.form).prop('action'),
475             $(this.form).serialize() + '&submit_mult=export&ajax_request=true',
476             function(data) {
477                 if (data.success == true) {
478                     var $ajaxDialog = $('<div />')
479                     .append(data.message)
480                     .dialog({
481                         title: data.title,
482                         width: 500,
483                         buttons: button_options,
484                         close: function () {
485                             $(this).remove();
486                         }
487                     });
488                     PMA_ajaxRemoveMessage($msgbox);
489                     // Attach syntax highlited editor to export dialog
490                     if (typeof CodeMirror != 'undefined') {
491                         CodeMirror.fromTextArea(
492                             $ajaxDialog.find('textarea')[0],
493                             {
494                                 lineNumbers: true,
495                                 matchBrackets: true,
496                                 indentUnit: 4,
497                                 mode: "text/x-mysql"
498                             }
499                         );
500                     }
501                 } else {
502                     PMA_ajaxShowMessage(data.error, false);
503                 }
504             }
505         ); //end $.post
506     });
507     // if exporting non-ajax, highlight anyways
508     if ($("textarea.export").length > 0
509         && typeof CodeMirror != 'undefined')
510     {
511         CodeMirror.fromTextArea(
512             $('textarea.export')[0],
513             {
514                 lineNumbers: true,
515                 matchBrackets: true,
516                 indentUnit: 4,
517                 mode: "text/x-mysql"
518             }
519         );
520     }
522     $("a.export_user_anchor.ajax").live('click', function(event) {
523         event.preventDefault();
524         var $msgbox = PMA_ajaxShowMessage();
525         /**
526          * @var button_options  Object containing options for jQueryUI dialog buttons
527          */
528         var button_options = {};
529         button_options[PMA_messages['strClose']] = function() {
530             $(this).dialog("close");
531         };
532         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
533             if (data.success == true) {
534                 var $ajaxDialog = $('<div />')
535                 .append(data.message)
536                 .dialog({
537                     title: data.title,
538                     width: 500,
539                     buttons: button_options,
540                     close: function () {
541                         $(this).remove();
542                     }
543                 });
544                 PMA_ajaxRemoveMessage($msgbox);
545                 // Attach syntax highlited editor to export dialog
546                 if (typeof CodeMirror != 'undefined') {
547                     CodeMirror.fromTextArea(
548                         $ajaxDialog.find('textarea')[0],
549                         {
550                             lineNumbers: true,
551                             matchBrackets: true,
552                             indentUnit: 4,
553                             mode: "text/x-mysql"
554                         }
555                     );
556                 }
557             } else {
558                 PMA_ajaxShowMessage(data.error, false);
559             }
560         }); //end $.get
561     }); //end export privileges
563     /**
564      * AJAX handler to Paginate the Users Table
565      *
566      * @see         PMA_ajaxShowMessage()
567      * @name        paginate_users_table_click
568      * @memberOf    jQuery
569      */
570     $("#initials_table").find("a.ajax").live('click', function(event) {
571         event.preventDefault();
572         var $msgbox = PMA_ajaxShowMessage();
573         $.get($(this).attr('href'), {'ajax_request' : true}, function(data) {
574             if (data.success == true) {
575                 PMA_ajaxRemoveMessage($msgbox);
576                 // This form is not on screen when first entering Privileges
577                 // if there are more than 50 users
578                 $("div.notice").remove();
579                 $("#usersForm").hide("medium").remove();
580                 $("#fieldset_add_user").hide("medium").remove();
581                 $("#initials_table")
582                     .after(data.message).show("medium")
583                     .siblings("h2").not(":first").remove();
584             } else {
585                 PMA_ajaxShowMessage(data.error, false);
586             }
587         }); // end $.get
588     }); // end of the paginate users table
590     /*
591      * Additional confirmation dialog after clicking
592      * 'Drop the databases...'
593      */
594     $('#checkbox_drop_users_db').click(function() {
595         var $this_checkbox = $(this);
596         if ($this_checkbox.is(':checked')) {
597             var is_confirmed = confirm(PMA_messages['strDropDatabaseStrongWarning'] + '\n' + $.sprintf(PMA_messages['strDoYouReally'], 'DROP DATABASE'));
598             if (! is_confirmed) {
599                 $this_checkbox.prop('checked', false);
600             }
601         }
602     });
604     displayPasswordGenerateButton();