Wrapped the "Indexes" and "Information" sections from tbl_structure.php in fieldsets
[phpmyadmin/arisferyanto.git] / js / server_privileges.js
blob6a7e28926736f22041ff32a0793cc64e293b624c
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 password field in a form
14  *
15  * @see     PMA_messages['strPasswordEmpty']
16  * @see     PMA_messages['strPasswordNotSame']
17  * @param   object   the form
18  * @return  boolean  whether the field value is valid or not
19  */
20 function checkPassword(the_form)
22     // Did the user select 'no password'?
23     if (typeof(the_form.elements['nopass']) != 'undefined'
24      && the_form.elements['nopass'][0].checked) {
25         return true;
26     } else if (typeof(the_form.elements['pred_password']) != 'undefined'
27      && (the_form.elements['pred_password'].value == 'none'
28       || the_form.elements['pred_password'].value == 'keep')) {
29         return true;
30     }
32     var password = the_form.elements['pma_pw'];
33     var password_repeat = the_form.elements['pma_pw2'];
34     var alert_msg = false;
36     if (password.value == '') {
37         alert_msg = PMA_messages['strPasswordEmpty'];
38     } else if (password.value != password_repeat.value) {
39         alert_msg = PMA_messages['strPasswordNotSame'];
40     }
42     if (alert_msg) {
43         alert(alert_msg);
44         password.value  = '';
45         password_repeat.value = '';
46         password.focus();
47         return false;
48     }
50     return true;
51 } // end of the 'checkPassword()' function
54 /**
55  * Validates the "add a user" form
56  *
57  * @return  boolean  whether the form is validated or not
58  */
59 function checkAddUser(the_form)
61     if (the_form.elements['pred_hostname'].value == 'userdefined' && the_form.elements['hostname'].value == '') {
62         alert(PMA_messages['strHostEmpty']);
63         the_form.elements['hostname'].focus();
64         return false;
65     }
67     if (the_form.elements['pred_username'].value == 'userdefined' && the_form.elements['username'].value == '') {
68         alert(PMA_messages['strUserEmpty']);
69         the_form.elements['username'].focus();
70         return false;
71     }
73     return checkPassword(the_form);
74 } // end of the 'checkAddUser()' function
76 /**
77  * When a new user is created and retrieved over Ajax, append the user's row to
78  * the user's table
79  *
80  * @param   new_user_string         the html for the new user's row
81  * @param   new_user_initial        the first alphabet of the user's name
82  * @param   new_user_initial_string html to replace the initial for pagination
83  */
84 function appendNewUser(new_user_string, new_user_initial, new_user_initial_string)
86     //Append the newly retrived user to the table now
88     //Calculate the index for the new row
89     var $curr_last_row = $("#usersForm").find('tbody').find('tr:last');
90     var $curr_first_row = $("#usersForm").find('tbody').find('tr:first');
91     var first_row_initial = $curr_first_row.find('label').html().substr(0, 1).toUpperCase();
92     var curr_shown_initial = $curr_last_row.find('label').html().substr(0, 1).toUpperCase();
93     var curr_last_row_index_string = $curr_last_row.find('input:checkbox').attr('id').match(/\d+/)[0];
94     var curr_last_row_index = parseFloat(curr_last_row_index_string);
95     var new_last_row_index = curr_last_row_index + 1;
96     var new_last_row_id = 'checkbox_sel_users_' + new_last_row_index;
97     var is_show_all = (first_row_initial != curr_shown_initial) ? true : false;
99     //Append to the table and set the id/names correctly
100     if((curr_shown_initial == new_user_initial) || is_show_all) {
101         $(new_user_string)
102         .insertAfter($curr_last_row)
103         .find('input:checkbox')
104         .attr('id', new_last_row_id)
105         .val(function() {
106             //the insert messes up the &27; part. let's fix it
107             return $(this).val().replace(/&/,'&');
108         })
109         .end()
110         .find('label')
111         .attr('for', new_last_row_id)
112         .end();
113     }
115     //Let us sort the table alphabetically
116     $("#usersForm").find('tbody').PMA_sort_table('label');
118     $("#initials_table").find('td:contains('+new_user_initial+')')
119     .html(new_user_initial_string);
122 /**#@+
123  * @namespace   jQuery
124  */
127  * AJAX scripts for server_privileges page.
129  * Actions ajaxified here:
130  * Add user
131  * Revoke a user
132  * Edit privileges
133  * Export privileges
134  * Paginate table of users
135  * Flush privileges
137  * @memberOf    jQuery
138  * @name        document.ready
139  */
141 $(document).ready(function() {
142     /** @lends jQuery */
144     /**
145      * Set a parameter for all Ajax queries made on this page.  Some queries
146      * are affected by cache settings on the server side, and hence, show stale
147      * data.  Don't let the web server serve cached pages
148      */
149     $.ajaxSetup({
150         cache: 'false'
151     });
153     /**
154      * AJAX event handler for 'Add a New User'
155      *
156      * @see         PMA_ajaxShowMessage()
157      * @see         appendNewUser()
158      * @see         $cfg['AjaxEnable']
159      * @memberOf    jQuery
160      * @name        add_user_click
161      *
162      */
163     $("#fieldset_add_user a.ajax").live("click", function(event) {
164         /** @lends jQuery */
165         event.preventDefault();
167         var $msgbox = PMA_ajaxShowMessage();
169         /**
170          * @var button_options  Object containing options for jQueryUI dialog buttons
171          */
172         var button_options = {};
173         button_options[PMA_messages['strAddUser']] = function() {
175             /**
176              * @var $form    stores reference to current form
177              */
178             var $form = $(this).find("form[name=usersForm]").last();
180             if (! checkAddUser($form.get(0))) {
181                 PMA_ajaxShowMessage(PMA_messages['strFormEmpty']);
182                 return false;
183             }
185             //We also need to post the value of the submit button in order to get this to work correctly
186             $.post($form.attr('action'), $form.serialize() + "&adduser_submit=" + $(this).find("input[name=adduser_submit]").attr('value'), function(data) {
187                 if (data.success == true) {
188                     $("#add_user_dialog").dialog("close").remove();
189                     PMA_ajaxShowMessage(data.message);
190                     $("#floating_menubar")
191                      .next('div')
192                      .remove()
193                      .end()
194                      .after(data.sql_query);
196                     //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
197                     var $notice_class = $("#floating_menubar").next("div").find('.notice');
198                     if ($notice_class.text() == '') {
199                         $notice_class.remove();
200                     }
201                     if ($('#fieldset_add_user a.ajax').attr('name') == 'db_specific') {
203                         /*process the fieldset_add_user attribute and get the val of privileges*/
204                         var url = $('#fieldset_add_user a.ajax').attr('val');
206                         if (url.substring(url.length - 23, url.length) == "&goto=db_operations.php") {
207                             url = url.substring(0, url.length - 23);
208                         }
209                         url = url + "&ajax_request=true&db_specific=true";
211                         /* post request for get the updated userForm table */
212                         $.post($form.attr('action' ), url, function(priv_data) {
214                             /*Remove the old userForm table*/
215                             if ($('#userFormDiv').length != 0) {
216                                 $('#userFormDiv').remove();
217                             } else {
218                                 $("#usersForm").remove();
219                             }
220                             var user_div = $('<div id="userFormDiv"></div>');
221                             /*If the JSON string parsed correctly*/
222                             if (typeof priv_data.success != 'undefined') {
223                                 if (priv_data.success == true) {
224                                     user_div
225                                      .html(priv_data.user_form)
226                                      .insertAfter('#result_query');
227                                 } else {
228                                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + priv_data.error, "7000");
229                                 }
230                             } else {
231                                 /*parse the JSON string*/
232                                 var obj = $.parseJSON(priv_data);
233                                 user_div
234                                  .html(obj.user_form)
235                                  .insertAfter('#result_query');
236                             }
237                         });
238                     } else {
239                         appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
240                     }
241                 } else {
242                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + data.error, "7000");
243                 }
244             })
245         };
246         button_options[PMA_messages['strCancel']] = function() { $(this).dialog("close").remove(); }
248         $.get($(this).attr("href"), {'ajax_request':true}, function(data) {
249             $('<div id="add_user_dialog"></div>')
250             .prepend(data)
251             .find("#fieldset_add_user_footer").hide() //showing the "Go" and "Create User" buttons together will confuse the user
252             .end()
253             .find("form[name=usersForm]").append('<input type="hidden" name="ajax_request" value="true" />')
254             .end()
255             .dialog({
256                 title: PMA_messages['strAddUser'],
257                 width: 800,
258                 // height is a workaround for this Chrome problem:
259                 // http://bugs.jqueryui.com/ticket/4671
260                 // also it's interesting to be able to scroll this window
261                 height: 600,
262                 modal: true,
263                 buttons: button_options
264             }); //dialog options end
265             displayPasswordGenerateButton();
266             PMA_ajaxRemoveMessage($msgbox);
267         }); // end $.get()
269     });//end of Add New User AJAX event handler
272     /**
273      * Ajax event handler for 'Reload Privileges' anchor
274      *
275      * @see         PMA_ajaxShowMessage()
276      * @see         $cfg['AjaxEnable']
277      * @memberOf    jQuery
278      * @name        reload_privileges_click
279      */
280     $("#reload_privileges_anchor.ajax").live("click", function(event) {
281         event.preventDefault();
283         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strReloadingPrivileges']);
285         $.get($(this).attr("href"), {'ajax_request': true}, function(data) {
286             if(data.success == true) {
287                 PMA_ajaxRemoveMessage($msgbox);
288             }
289             else {
290                 PMA_ajaxShowMessage(data.error);
291             }
292         }); //end $.get()
294     }); //end of Reload Privileges Ajax event handler
296     /**
297      * AJAX handler for 'Revoke User'
298      *
299      * @see         PMA_ajaxShowMessage()
300      * @see         $cfg['AjaxEnable']
301      * @memberOf    jQuery
302      * @name        revoke_user_click
303      */
304     $("#fieldset_delete_user_footer #buttonGo.ajax").live('click', function(event) {
305         event.preventDefault();
307         PMA_ajaxShowMessage(PMA_messages['strRemovingSelectedUsers']);
309         $form = $("#usersForm");
311         $.post($form.attr('action'), $form.serialize() + "&delete=" + $(this).attr('value') + "&ajax_request=true", function(data) {
312             if(data.success == true) {
313                 PMA_ajaxShowMessage(data.message);
315                 //Remove the revoked user from the users list
316                 $form.find("input:checkbox:checked").parents("tr").slideUp("medium", function() {
317                     var this_user_initial = $(this).find('input:checkbox').val().charAt(0).toUpperCase();
318                     $(this).remove();
320                     //If this is the last user with this_user_initial, remove the link from #initials_table
321                     if($("#tableuserrights").find('input:checkbox[value^=' + this_user_initial + ']').length == 0) {
322                         $("#initials_table").find('td > a:contains(' + this_user_initial + ')').parent('td').html(this_user_initial);
323                     }
325                     //Re-check the classes of each row
326                     $form
327                     .find('tbody').find('tr:odd')
328                     .removeClass('even').addClass('odd')
329                     .end()
330                     .find('tr:even')
331                     .removeClass('odd').addClass('even');
332                 })
333             }
334             else {
335                 PMA_ajaxShowMessage(data.error);
336             }
337         }) // end $.post()
338     }) // end Revoke User
340     /**
341      * AJAX handler for 'Edit User'
342      *
343      * @see         PMA_ajaxShowMessage()
344      *
345      */
347     /**
348      * Step 1: Load Edit User Dialog
349      * @memberOf    jQuery
350      * @name        edit_user_click
351      * @see         $cfg['AjaxEnable']
352      */
353     $(".edit_user_anchor.ajax").live('click', function(event) {
354         /** @lends jQuery */
355         event.preventDefault();
357         var $msgbox = PMA_ajaxShowMessage();
359         $(this).parents('tr').addClass('current_row');
361         /**
362          * @var button_options  Object containing options for jQueryUI dialog buttons
363          */
364         var button_options = {};
365         button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
367         var token = $(this).parents('form').find('input[name="token"]').val();
368         $.get($(this).attr('href'), {'ajax_request':true, 'edit_user_dialog': true, 'token': token}, function(data) {
369             $('<div id="edit_user_dialog"></div>')
370             .append(data)
371             .dialog({
372                 width: 900,
373                 height: 600,
374                 buttons: button_options
375             }); //dialog options end
376             displayPasswordGenerateButton();
377             PMA_ajaxRemoveMessage($msgbox);
378         }) // end $.get()
379     })
381     /**
382      * Step 2: Submit the Edit User Dialog
383      *
384      * @see         PMA_ajaxShowMessage()
385      * @see         $cfg['AjaxEnable']
386      * @memberOf    jQuery
387      * @name        edit_user_submit
388      */
389     $("#edit_user_dialog").find("form:not(#db_or_table_specific_priv)").live('submit', function(event) {
390         /** @lends jQuery */
391         event.preventDefault();
393         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
395         $(this).append('<input type="hidden" name="ajax_request" value="true" />');
397         /**
398          * @var curr_submit_name    name of the current button being submitted
399          */
400         var curr_submit_name = $(this).find('.tblFooters').find('input:submit').attr('name');
402         /**
403          * @var curr_submit_value    value of the current button being submitted
404          */
405         var curr_submit_value = $(this).find('.tblFooters').find('input:submit').val();
407         $.post($(this).attr('action'), $(this).serialize() + '&' + curr_submit_name + '=' + curr_submit_value, function(data) {
408             if(data.success == true) {
410                 PMA_ajaxShowMessage(data.message);
412                 //Close the jQueryUI dialog
413                 $("#edit_user_dialog").dialog("close").remove();
415                 if(data.sql_query) {
416                     $("#floating_menubar")
417                     .next('div')
418                     .remove()
419                     .end()
420                     .after(data.sql_query);
421                     var notice_class = $("#floating_menubar").next("div").find('.notice');
422                     if($(notice_class).text() == '') {
423                         $(notice_class).remove();
424                     }
425                 } //Show SQL Query that was executed
427                 //Append new user if necessary
428                 if(data.new_user_string) {
429                     appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
430                 }
432                 //Check if we are on the page of the db-specific privileges
433                 var db_priv_page = !!($('#dbspecificuserrights').length); // the "!!" part is merely there to ensure a value of type boolean
434                 // we always need to reload on the db-specific privilege page
435                 // and on the global page when adjusting global privileges,
436                 // but not on the global page when adjusting db-specific privileges.
437                 var reload_privs = false;
438                 if (data.db_specific_privs == false || (db_priv_page == data.db_specific_privs)) {
439                     reload_privs = true;
440                 }
442                 //Change privileges, if they were edited and need to be reloaded
443                 if(data.new_privileges && reload_privs) {
444                     $("#usersForm")
445                     .find('.current_row')
446                     .find('tt')
447                     .html(data.new_privileges);
448                 }
450                 $("#usersForm")
451                 .find('.current_row')
452                 .removeClass('current_row');
453             }
454             else {
455                 PMA_ajaxShowMessage(data.error);
456             }
457         });
458     })
459     //end Edit user
461     /**
462      * AJAX handler for 'Export Privileges'
463      *
464      * @see         PMA_ajaxShowMessage()
465      * @see         $cfg['AjaxEnable']
466      * @memberOf    jQuery
467      * @name        export_user_click
468      */
469     $(".export_user_anchor.ajax").live('click', function(event) {
470         /** @lends jQuery */
471         event.preventDefault();
473         var $msgbox = PMA_ajaxShowMessage();
475         /**
476          * @var button_options  Object containing options for jQueryUI dialog buttons
477          */
478         var button_options = {};
479         button_options[PMA_messages['strClose']] = function() {$(this).dialog("close").remove();}
481         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
482             $('<div id="export_dialog"></div>')
483             .prepend(data)
484             .dialog({
485                 width : 500,
486                 buttons: button_options
487             });
488             PMA_ajaxRemoveMessage($msgbox);
489         }) //end $.get
490     }) //end export privileges
492     /**
493      * AJAX handler to Paginate the Users Table
494      *
495      * @see         PMA_ajaxShowMessage()
496      * @see         $cfg['AjaxEnable']
497      * @name        paginate_users_table_click
498      * @memberOf    jQuery
499      */
500     $("#initials_table.ajax").find("a").live('click', function(event) {
501         event.preventDefault();
503         var $msgbox = PMA_ajaxShowMessage();
505         $.get($(this).attr('href'), {'ajax_request' : true}, function(data) {
506             // This form is not on screen when first entering Privileges
507             // if there are more than 50 users
508             $("#usersForm").hide("medium").remove();
509             $("#fieldset_add_user").hide("medium").remove();
510             $("#initials_table")
511              .after(data).show("medium")
512              .siblings("h2").not(":first").remove();
514             PMA_ajaxRemoveMessage($msgbox);
515         }) // end $.get
516     })// end of the paginate users table
518     /*
519      * Additional confirmation dialog after clicking
520      * 'Drop the databases...'
521      */
522     $('#checkbox_drop_users_db').click(function() {
523         $this_checkbox = $(this);
524         if ($this_checkbox.is(':checked')) {
525             var is_confirmed = confirm(PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\nDROP DATABASE');
526             if (! is_confirmed) {
527                 $this_checkbox.attr('checked', false);
528             }
529         }
530     });
532     displayPasswordGenerateButton();
533 }, 'top.frame_content'); //end $(document).ready()
535 /**#@- */