Merge pull request #431 from xmujay/0609_monitor
[phpmyadmin/aamir.git] / js / server_privileges.js
blob8dacea8ba4e4d63d774f79c418e473d360edc04f
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             PMA_highlightSQL($('#page_content'));
105             $("#result_query").css({
106                 'margin-top' : '0.5em'
107             });
109             //Remove the empty notice div generated due to a NULL query passed to PMA_getMessage()
110             var $notice_class = $("#result_query").find('.notice');
111             if ($notice_class.text() === '') {
112                 $notice_class.remove();
113             }
114             if ($('#fieldset_add_user a.ajax').attr('name') == 'db_specific') {
116                 /*process the fieldset_add_user attribute and get the val of privileges*/
117                 var url = $('#fieldset_add_user a.ajax').attr('rel');
119                 if (url.substring(url.length - 23, url.length) == "&goto=db_operations.php") {
120                     url = url.substring(0, url.length - 23);
121                 }
122                 url = url + "&ajax_request=true&db_specific=true";
124                 /* post request for get the updated userForm table */
125                 $.post($form.attr('action'), url, function (priv_data) {
127                     /*Remove the old userForm table*/
128                     if ($('#userFormDiv').length !== 0) {
129                         $('#userFormDiv').remove();
130                     } else {
131                         $("#usersForm").remove();
132                     }
133                     if (priv_data.success === true) {
134                         $('<div id="userFormDiv"></div>')
135                             .html(priv_data.user_form)
136                             .insertAfter('#result_query');
137                     } else {
138                         PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + priv_data.error, false);
139                     }
140                 });
141             } else {
142                 appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
143             }
144         } else {
145             PMA_ajaxShowMessage(data.error, false);
146         }
147     });
151  * AJAX scripts for server_privileges page.
153  * Actions ajaxified here:
154  * Add user
155  * Revoke a user
156  * Edit privileges
157  * Export privileges
158  * Paginate table of users
159  * Flush privileges
161  * @memberOf    jQuery
162  * @name        document.ready
163  */
167  * Unbind all event handlers before tearing down a page
168  */
169 AJAX.registerTeardown('server_privileges.js', function () {
170     $("#fieldset_add_user_login input[name='username']").die("focusout");
171     $("#fieldset_add_user a.ajax").die("click");
172     $('form[name=usersForm]').unbind('submit');
173     $("#reload_privileges_anchor.ajax").die("click");
174     $("#fieldset_delete_user_footer #buttonGo.ajax").die('click');
175     $("a.edit_user_anchor.ajax").die('click');
176     $("#edit_user_dialog").find("form.ajax").die('submit');
177     $("button.mult_submit[value=export]").die('click');
178     $("a.export_user_anchor.ajax").die('click');
179     $("#initials_table").find("a.ajax").die('click');
180     $('#checkbox_drop_users_db').unbind('click');
181     $(".checkall_box").die("click");
184 AJAX.registerOnload('server_privileges.js', function () {
185     /**
186      * Display a warning if there is already a user by the name entered as the username.
187      */
188     $("#fieldset_add_user_login input[name='username']").live("focusout", function () {
189         var username = $(this).val();
190         var $warning = $("#user_exists_warning");
191         if ($("#select_pred_username").val() == 'userdefined' && username != '') {
192             var href = $("form[name='usersForm']").attr('action');
193             var params = {
194                 'ajax_request' : true,
195                 'token' : PMA_commonParams.get('token'),
196                 'validate_username' : true,
197                 'username' : username
198             };
199             $.get(href, params, function (data) {
200                 if (data.user_exists) {
201                     $warning.show();
202                 } else {
203                     $warning.hide();
204                 }
205             });
206         } else {
207             $warning.hide();
208         }
209     });
210     /**
211      * AJAX event handler for 'Add a New User'
212      *
213      * @see         PMA_ajaxShowMessage()
214      * @see         appendNewUser()
215      * @memberOf    jQuery
216      * @name        add_user_click
217      *
218      */
219     $("#fieldset_add_user a.ajax").live("click", function (event) {
220         /** @lends jQuery */
221         event.preventDefault();
222         var $msgbox = PMA_ajaxShowMessage();
224         $.get($(this).attr("href"), {'ajax_request': true}, function (data) {
225             if (data.success === true) {
226                 $('#page_content').hide();
227                 var $div = $('#add_user_dialog');
228                 if ($div.length === 0) {
229                     $div = $('<div id="add_user_dialog" style="margin: 0.5em;"></div>')
230                         .insertBefore('#page_content');
231                 } else {
232                     $div.empty();
233                 }
234                 $div.html(data.message)
235                     .find("form[name=usersForm]")
236                     .append('<input type="hidden" name="ajax_request" value="true" />')
237                     .end();
238                 PMA_highlightSQL($div);
239                 displayPasswordGenerateButton();
240                 PMA_showHints($div);
241                 PMA_ajaxRemoveMessage($msgbox);
242                 $div.find("input.autofocus").focus();
244                 $div.find('form[name=usersForm]').bind('submit', function (event) {
245                     event.preventDefault();
246                     addUser($(this));
247                 });
248             } else {
249                 PMA_ajaxShowMessage(data.error, false);
250             }
251         }); // end $.get()
253     });//end of Add New User AJAX event handler
256     /**
257      * Ajax event handler for 'Reload Privileges' anchor
258      *
259      * @see         PMA_ajaxShowMessage()
260      * @memberOf    jQuery
261      * @name        reload_privileges_click
262      */
263     $("#reload_privileges_anchor.ajax").live("click", function (event) {
264         event.preventDefault();
266         var $msgbox = PMA_ajaxShowMessage(PMA_messages.strReloadingPrivileges);
268         $.get($(this).attr("href"), {'ajax_request': true}, function (data) {
269             if (data.success === true) {
270                 PMA_ajaxRemoveMessage($msgbox);
271             } else {
272                 PMA_ajaxShowMessage(data.error, false);
273             }
274         }); //end $.get()
276     }); //end of Reload Privileges Ajax event handler
278     /**
279      * AJAX handler for 'Revoke User'
280      *
281      * @see         PMA_ajaxShowMessage()
282      * @memberOf    jQuery
283      * @name        revoke_user_click
284      */
285     $("#fieldset_delete_user_footer #buttonGo.ajax").live('click', function (event) {
286         event.preventDefault();
288         PMA_ajaxShowMessage(PMA_messages.strRemovingSelectedUsers);
290         var $form = $("#usersForm");
292         $.post($form.attr('action'), $form.serialize() + "&delete=" + $(this).val() + "&ajax_request=true", function (data) {
293             if (data.success === true) {
294                 PMA_ajaxShowMessage(data.message);
295                 // Refresh navigation, if we droppped some databases with the name
296                 // that is the same as the username of the deleted user
297                 if ($('#checkbox_drop_users_db:checked').length) {
298                     PMA_reloadNavigation();
299                 }
300                 //Remove the revoked user from the users list
301                 $form.find("input:checkbox:checked").parents("tr").slideUp("medium", function () {
302                     var this_user_initial = $(this).find('input:checkbox').val().charAt(0).toUpperCase();
303                     $(this).remove();
305                     //If this is the last user with this_user_initial, remove the link from #initials_table
306                     if ($("#tableuserrights").find('input:checkbox[value^=' + this_user_initial + ']').length === 0) {
307                         $("#initials_table").find('td > a:contains(' + this_user_initial + ')').parent('td').html(this_user_initial);
308                     }
310                     //Re-check the classes of each row
311                     $form
312                     .find('tbody').find('tr:odd')
313                     .removeClass('even').addClass('odd')
314                     .end()
315                     .find('tr:even')
316                     .removeClass('odd').addClass('even');
318                     //update the checkall checkbox
319                     $(checkboxes_sel).trigger("change");
320                 });
321             } else {
322                 PMA_ajaxShowMessage(data.error, false);
323             }
324         }); // end $.post()
325     }); // end Revoke User
327     /**
328      * AJAX handler for 'Edit User'
329      *
330      * @see         PMA_ajaxShowMessage()
331      *
332      */
334     /**
335      * Step 1: Load Edit User Dialog
336      * @memberOf    jQuery
337      * @name        edit_user_click
338      */
339     $("a.edit_user_anchor.ajax").live('click', function (event) {
340         /** @lends jQuery */
341         event.preventDefault();
343         var $msgbox = PMA_ajaxShowMessage();
345         $(this).parents('tr').addClass('current_row');
347         var token = $(this).parents('form').find('input[name="token"]').val();
348         $.get(
349             $(this).attr('href'),
350             {
351                 'ajax_request': true,
352                 'edit_user_dialog': true,
353                 'token': token
354             },
355             function (data) {
356                 if (data.success === true) {
357                     $('#page_content').hide();
358                     var $div = $('#edit_user_dialog');
359                     if ($div.length === 0) {
360                         $div = $('<div id="edit_user_dialog" style="margin: 0.5em;"></div>')
361                             .insertBefore('#page_content');
362                     } else {
363                         $div.empty();
364                     }
365                     $div.html(data.message);
366                     PMA_highlightSQL($div);
367                     var $div = $('#edit_user_dialog');
368                     displayPasswordGenerateButton();
369                     $(checkboxes_sel).trigger("change");
370                     PMA_ajaxRemoveMessage($msgbox);
371                     PMA_showHints($div);
372                 } else {
373                     PMA_ajaxShowMessage(data.error, false);
374                 }
375             }
376         ); // end $.get()
377     });
379     /**
380      * Step 2: Submit the Edit User Dialog
381      *
382      * @see         PMA_ajaxShowMessage()
383      * @memberOf    jQuery
384      * @name        edit_user_submit
385      */
386     $("#edit_user_dialog").find("form.ajax").live('submit', function (event) {
387         /** @lends jQuery */
388         event.preventDefault();
390         var $t = $(this);
392         if ($t.is('.copyUserForm') && ! PMA_checkPassword($t)) {
393             return false;
394         }
396         PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
398         $t.append('<input type="hidden" name="ajax_request" value="true" />');
400         /**
401          * @var curr_submit_name    name of the current button being submitted
402          */
403         var curr_submit_name = $t.find('.tblFooters').find('input:submit').attr('name');
405         /**
406          * @var curr_submit_value    value of the current button being submitted
407          */
408         var curr_submit_value = $t.find('.tblFooters').find('input:submit').val();
410         // If any option other than 'keep the old one'(option 4) is chosen, we need to remove
411         // the old one from the table.
412         var $row_to_remove;
413         if (curr_submit_name == 'change_copy'
414                 && $('input[name=mode]:checked', '#fieldset_mode').val() != '4') {
415             var old_username = $t.find('input[name="old_username"]').val();
416             var old_hostname = $t.find('input[name="old_hostname"]').val();
417             $('#usersForm tbody tr').each(function () {
418                 var $tr = $(this);
419                 if ($tr.find('td:nth-child(2) label').text() == old_username
420                         && $tr.find('td:nth-child(3)').text() == old_hostname) {
421                     $row_to_remove = $tr;
422                     return false;
423                 }
424             });
425         }
427         $.post($t.attr('action'), $t.serialize() + '&' + curr_submit_name + '=' + curr_submit_value, function (data) {
428             if (data.success === true) {
429                 $('#page_content').show();
430                 $("#edit_user_dialog").remove();
432                 PMA_ajaxShowMessage(data.message);
434                 if (data.sql_query) {
435                     $("#result_query").remove();
436                     $('#page_content').prepend(data.sql_query);
437                     PMA_highlightSQL($('#page_content'));
438                     $("#result_query").css({
439                         'margin-top' : '0.5em'
440                     });
441                     var $notice_class = $("#result_query").find('.notice');
442                     if ($notice_class.text() === '') {
443                         $notice_class.remove();
444                     }
445                 } //Show SQL Query that was executed
447                 // Remove the old row if the old user is deleted
448                 if ($row_to_remove !== null) {
449                     $row_to_remove.remove();
450                 }
452                 //Append new user if necessary
453                 if (data.new_user_string) {
454                     appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
455                 }
457                 //Check if we are on the page of the db-specific privileges
458                 var db_priv_page = !!($('#dbspecificuserrights').length); // the "!!" part is merely there to ensure a value of type boolean
459                 // we always need to reload on the db-specific privilege page
460                 // and on the global page when adjusting global privileges,
461                 // but not on the global page when adjusting db-specific privileges.
462                 var reload_privs = false;
463                 if (data.db_specific_privs === false || (db_priv_page == data.db_specific_privs)) {
464                     reload_privs = true;
465                 }
466                 if (data.db_wildcard_privs) {
467                     reload_privs = false;
468                 }
470                 //Change privileges, if they were edited and need to be reloaded
471                 if (data.new_privileges && reload_privs) {
472                     $("#usersForm")
473                     .find('.current_row')
474                     .find('code')
475                     .html(data.new_privileges);
476                 }
478                 $("#usersForm")
479                 .find('.current_row')
480                 .removeClass('current_row');
481             } else {
482                 PMA_ajaxShowMessage(data.error, false);
483             }
484         });
485     });
486     //end Edit user
488     /**
489      * AJAX handler for 'Export Privileges'
490      *
491      * @see         PMA_ajaxShowMessage()
492      * @memberOf    jQuery
493      * @name        export_user_click
494      */
495     $("button.mult_submit[value=export]").live('click', function (event) {
496         event.preventDefault();
497         // can't export if no users checked
498         if ($(this.form).find("input:checked").length === 0) {
499             return;
500         }
501         var $msgbox = PMA_ajaxShowMessage();
502         var button_options = {};
503         button_options[PMA_messages.strClose] = function () {
504             $(this).dialog("close");
505         };
506         $.post(
507             $(this.form).prop('action'),
508             $(this.form).serialize() + '&submit_mult=export&ajax_request=true',
509             function (data) {
510                 if (data.success === true) {
511                     var $ajaxDialog = $('<div />')
512                     .append(data.message)
513                     .dialog({
514                         title: data.title,
515                         width: 500,
516                         buttons: button_options,
517                         close: function () {
518                             $(this).remove();
519                         }
520                     });
521                     PMA_ajaxRemoveMessage($msgbox);
522                     // Attach syntax highlited editor to export dialog
523                     if (typeof CodeMirror != 'undefined') {
524                         CodeMirror.fromTextArea(
525                             $ajaxDialog.find('textarea')[0],
526                             {
527                                 lineNumbers: true,
528                                 matchBrackets: true,
529                                 indentUnit: 4,
530                                 mode: "text/x-mysql"
531                             }
532                         );
533                     }
534                 } else {
535                     PMA_ajaxShowMessage(data.error, false);
536                 }
537             }
538         ); //end $.post
539     });
540     // if exporting non-ajax, highlight anyways
541     if ($("textarea.export").length > 0
542         && typeof CodeMirror != 'undefined')
543     {
544         CodeMirror.fromTextArea(
545             $('textarea.export')[0],
546             {
547                 lineNumbers: true,
548                 matchBrackets: true,
549                 indentUnit: 4,
550                 mode: "text/x-mysql"
551             }
552         );
553     }
555     $("a.export_user_anchor.ajax").live('click', function (event) {
556         event.preventDefault();
557         var $msgbox = PMA_ajaxShowMessage();
558         /**
559          * @var button_options  Object containing options for jQueryUI dialog buttons
560          */
561         var button_options = {};
562         button_options[PMA_messages.strClose] = function () {
563             $(this).dialog("close");
564         };
565         $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
566             if (data.success === true) {
567                 var $ajaxDialog = $('<div />')
568                 .append(data.message)
569                 .dialog({
570                     title: data.title,
571                     width: 500,
572                     buttons: button_options,
573                     close: function () {
574                         $(this).remove();
575                     }
576                 });
577                 PMA_ajaxRemoveMessage($msgbox);
578                 // Attach syntax highlited editor to export dialog
579                 if (typeof CodeMirror != 'undefined') {
580                     CodeMirror.fromTextArea(
581                         $ajaxDialog.find('textarea')[0],
582                         {
583                             lineNumbers: true,
584                             matchBrackets: true,
585                             indentUnit: 4,
586                             mode: "text/x-mysql"
587                         }
588                     );
589                 }
590             } else {
591                 PMA_ajaxShowMessage(data.error, false);
592             }
593         }); //end $.get
594     }); //end export privileges
596     /**
597      * AJAX handler to Paginate the Users Table
598      *
599      * @see         PMA_ajaxShowMessage()
600      * @name        paginate_users_table_click
601      * @memberOf    jQuery
602      */
603     $("#initials_table").find("a.ajax").live('click', function (event) {
604         event.preventDefault();
605         var $msgbox = PMA_ajaxShowMessage();
606         $.get($(this).attr('href'), {'ajax_request' : true}, function (data) {
607             if (data.success === true) {
608                 PMA_ajaxRemoveMessage($msgbox);
609                 // This form is not on screen when first entering Privileges
610                 // if there are more than 50 users
611                 $("div.notice").remove();
612                 $("#usersForm").hide("medium").remove();
613                 $("#fieldset_add_user").hide("medium").remove();
614                 $("#initials_table")
615                     .after(data.message).show("medium")
616                     .siblings("h2").not(":first").remove();
617             } else {
618                 PMA_ajaxShowMessage(data.error, false);
619             }
620         }); // end $.get
621     }); // end of the paginate users table
623     /*
624      * Additional confirmation dialog after clicking
625      * 'Drop the databases...'
626      */
627     $('#checkbox_drop_users_db').click(function () {
628         var $this_checkbox = $(this);
629         if ($this_checkbox.is(':checked')) {
630             var is_confirmed = confirm(PMA_messages.strDropDatabaseStrongWarning + '\n' + $.sprintf(PMA_messages.strDoYouReally, 'DROP DATABASE'));
631             if (! is_confirmed) {
632                 $this_checkbox.prop('checked', false);
633             }
634         }
635     });
637     displayPasswordGenerateButton();