Modified it to support the Ajax action on tbl_addfield.php
[phpmyadmin/ninadsp.git] / js / server_privileges.js
blobdbc189c9c985623f0761565951d8b45b6284b06c
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
77 /**
78  * Generate a new password and copy it to the password input areas
79  *
80  * @param   object   the form that holds the password fields
81  *
82  * @return  boolean  always true
83  */
84 function suggestPassword(passwd_form) {
85     // restrict the password to just letters and numbers to avoid problems:
86     // "editors and viewers regard the password as multiple words and
87     // things like double click no longer work"
88     var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
89     var passwordlength = 16;    // do we want that to be dynamic?  no, keep it simple :)
90     var passwd = passwd_form.generated_pw;
91     passwd.value = '';
93     for ( i = 0; i < passwordlength; i++ ) {
94         passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
95     }
96     passwd_form.text_pma_pw.value = passwd.value;
97     passwd_form.text_pma_pw2.value = passwd.value;
98     return true;
102  * When a new user is created and retrieved over Ajax, append the user's row to
103  * the user's table
105  * @param   new_user_string         the html for the new user's row
106  * @param   new_user_initial        the first alphabet of the user's name
107  * @param   new_user_initial_string html to replace the initial for pagination
108  */
109 function appendNewUser(new_user_string, new_user_initial, new_user_initial_string) {
110     //Append the newly retrived user to the table now
112     //Calculate the index for the new row
113     var curr_last_row = $("#usersForm").find('tbody').find('tr:last');
114     var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
115     var curr_last_row_index = parseFloat(curr_last_row_index_string);
116     var new_last_row_index = curr_last_row_index + 1;
117     var new_last_row_id = 'checkbox_sel_users_' + new_last_row_index;
119     //Append to the table and set the id/names correctly
120     $(new_user_string)
121     .insertAfter($(curr_last_row))
122     .find('input:checkbox')
123     .attr('id', new_last_row_id)
124     .val(function() {
125         //the insert messes up the &amp;27; part. let's fix it
126         return $(this).val().replace(/&/,'&amp;');
127     })
128     .end()
129     .find('label')
130     .attr('for', new_last_row_id)
131     .end();
133     //Let us sort the table alphabetically
134     $("#usersForm").find('tbody').PMA_sort_table('label');
136     $("#initials_table").find('td:contains('+new_user_initial+')')
137     .html(new_user_initial_string);
140 /**#@+
141  * @namespace   jQuery
142  */
145  * AJAX scripts for server_privileges page.
147  * Actions ajaxified here:
148  * Add a new user
149  * Revoke a user
150  * Edit privileges
151  * Export privileges
152  * Paginate table of users
153  * Flush privileges
155  * @memberOf    jQuery
156  * @name        document.ready
157  */
159 $(document).ready(function() {
160     /** @lends jQuery */
162     /**
163      * Set a parameter for all Ajax queries made on this page.  Some queries
164      * are affected by cache settings on the server side, and hence, show stale
165      * data.  Don't let the web server serve cached pages
166      */
167     $.ajaxSetup({
168         cache: 'false'
169     });
171     /**
172      * AJAX event handler for 'Add a New User'
173      *
174      * @see         PMA_ajaxShowMessage()
175      * @see         appendNewUser()
176      * @memberOf    jQuery
177      * @name        add_user_click
178      *
179      */
180     $("#fieldset_add_user a").live("click", function(event) {
181         /** @lends jQuery */
182         event.preventDefault();
184         PMA_ajaxShowMessage();
186         /**
187          * @var button_options  Object containing options for jQueryUI dialog buttons
188          */
189         var button_options = {};
190         button_options[PMA_messages['strCreateUser']] = function() {
192                                                         /**
193                                                          * @var the_form    stores reference to current form
194                                                          */
195                                                         var the_form = $(this).find("#addUsersForm");
197                                                         if( ! checkAddUser($(the_form).get(0)) ) {
198                                                             PMA_ajaxShowMessage(PMA_messages['strFormEmpty']);
199                                                             return false;
200                                                         }
202                                                         //We also need to post the value of the submit button in order to get this to work correctly
203                                                         $.post($(the_form).attr('action'), $(the_form).serialize() + "&adduser_submit=" + $(this).find("input[name=adduser_submit]").attr('value'), function(data) {
204                                                             if(data.success == true) {
205                                                                 $("#add_user_dialog").dialog("close").remove();
206                                                                 PMA_ajaxShowMessage(data.message);
207                                                                 $("#topmenucontainer")
208                                                                 .next('div')
209                                                                 .remove()
210                                                                 .end()
211                                                                 .after(data.sql_query);
212                                                                 
213                                                                 //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
214                                                                 var notice_class = $("#topmenucontainer").next("div").find('.notice');
215                                                                 if($(notice_class).text() == '') {
216                                                                     $(notice_class).remove();
217                                                                 }
219                                                                 appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
220                                                             }
221                                                             else {
222                                                                 PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : "+data.error, "7000");
223                                                             }
224                                                         })
225                                                     };
226         button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
228         $.get($(this).attr("href"), {'ajax_request':true}, function(data) {
229             $('<div id="add_user_dialog"></div>')
230             .prepend(data)
231             .find("#fieldset_add_user_footer").hide() //showing the "Go" and "Create User" buttons together will confuse the user
232             .end()
233             .find("#addUsersForm").append('<input type="hidden" name="ajax_request" value="true" />')
234             .end()
235             .dialog({
236                 title: top.frame_content.PMA_messages['strAddNewUser'],
237                 width: 800,
238                 modal: true,
239                 buttons: button_options
240             }); //dialog options end
241         }); // end $.get()
243     });//end of Add New User AJAX event handler
246     /**
247      * Ajax event handler for 'Reload Privileges' anchor
248      *
249      * @see         PMA_ajaxShowMessage()
250      * @memberOf    jQuery
251      * @name        reload_privileges_click
252      */
253     $("#reload_privileges_anchor").live("click", function(event) {
254         event.preventDefault();
256         PMA_ajaxShowMessage(PMA_messages['strReloadingPrivileges']);
258         $.get($(this).attr("href"), {'ajax_request': true}, function(data) {
259             if(data.success == true) {
260                 PMA_ajaxShowMessage(data.message);
261             }
262             else {
263                 PMA_ajaxShowMessage(data.error);
264             }
265         }); //end $.get()
267     }); //end of Reload Privileges Ajax event handler
269     /**
270      * AJAX handler for 'Revoke User'
271      *
272      * @see         PMA_ajaxShowMessage()
273      * @memberOf    jQuery
274      * @name        revoke_user_click
275      */
276     $("#fieldset_delete_user_footer #buttonGo").live('click', function(event) {
277         event.preventDefault();
279         PMA_ajaxShowMessage(PMA_messages['strRemovingSelectedUsers']);
280         
281         $.post($("#usersForm").attr('action'), $("#usersForm").serialize() + "&delete=" + $(this).attr('value') + "&ajax_request=true", function(data) {
282             if(data.success == true) {
283                 PMA_ajaxShowMessage(data.message);
285                 //Remove the revoked user from the users list
286                 $("#usersForm").find("input:checkbox:checked").parents("tr").slideUp("medium", function() {
287                     var this_user_initial = $(this).find('input:checkbox').val().charAt(0).toUpperCase();
288                     $(this).remove();
290                     //If this is the last user with this_user_initial, remove the link from #initials_table
291                     if($("#tableuserrights").find('input:checkbox[value^=' + this_user_initial + ']').length == 0) {
292                         $("#initials_table").find('td > a:contains(' + this_user_initial + ')').parent('td').html(this_user_initial);
293                     }
295                     //Re-check the classes of each row
296                     $("#usersForm")
297                     .find('tbody').find('tr:odd')
298                     .removeClass('even').addClass('odd')
299                     .end()
300                     .find('tr:even')
301                     .removeClass('odd').addClass('even');
302                 })
303             }
304             else {
305                 PMA_ajaxShowMessage(data.error);
306             }
307         }) // end $.post()
308     }) // end Revoke User
310     /**
311      * AJAX handler for 'Edit User'
312      *
313      * @see         PMA_ajaxShowMessage()
314      *
315      */
317     /**
318      * Step 1: Load Edit User Dialog
319      * @memberOf    jQuery
320      * @name        edit_user_click
321      */
322     $(".edit_user_anchor").live('click', function(event) {
323         /** @lends jQuery */
324         event.preventDefault();
326         PMA_ajaxShowMessage();
328         $(this).parents('tr').addClass('current_row');
330         /**
331          * @var button_options  Object containing options for jQueryUI dialog buttons
332          */
333         var button_options = {};
334         button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
336         $.get($(this).attr('href'), {'ajax_request':true, 'edit_user_dialog': true}, function(data) {
337             PMA_ajaxShowMessage('');
338             $('<div id="edit_user_dialog"></div>')
339             .append(data)
340             .dialog({
341                 width: 900,
342                 buttons: button_options
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").live('submit', function(event) {
355         /** @lends jQuery */
356         event.preventDefault();
358         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
360         $(this).append('<input type="hidden" name="ajax_request" value="true" />');
362         /**
363          * @var curr_submit_name    name of the current button being submitted
364          */
365         var curr_submit_name = $(this).find('.tblFooters').find('input:submit').attr('name');
367         /**
368          * @var curr_submit_value    value of the current button being submitted
369          */
370         var curr_submit_value = $(this).find('.tblFooters').find('input:submit').val();
372         $.post($(this).attr('action'), $(this).serialize() + '&' + curr_submit_name + '=' + curr_submit_value, function(data) {
373             if(data.success == true) {
375                 PMA_ajaxShowMessage(data.message);
376                 
377                 //Close the jQueryUI dialog
378                 $("#edit_user_dialog").dialog("close").remove();
380                 if(data.sql_query) {
381                     $("#topmenucontainer")
382                     .next('div')
383                     .remove()
384                     .end()
385                     .after(data.sql_query);
386                     var notice_class = $("#topmenucontainer").next("div").find('.notice');
387                     if($(notice_class).text() == '') {
388                         $(notice_class).remove();
389                     }
390                 } //Show SQL Query that was executed
392                 //Append new user if necessary
393                 if(data.new_user_string) {
394                     appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
395                 }
397                 //Change privileges if they were edited
398                 if(data.new_privileges) {
399                     $("#usersForm")
400                     .find('.current_row')
401                     .find('tt')
402                     .html(data.new_privileges);
403                 }
405                 $("#usersForm")
406                 .find('.current_row')
407                 .removeClass('current_row');
408             }
409             else {
410                 PMA_ajaxShowMessage(data.error);
411             }
412         });
413     })
414     //end Edit user
416     /**
417      * AJAX handler for 'Export Privileges'
418      *
419      * @see         PMA_ajaxShowMessage()
420      * @memberOf    jQuery
421      * @name        export_user_click
422      */
423     $(".export_user_anchor").live('click', function(event) {
424         /** @lends jQuery */
425         event.preventDefault();
427         PMA_ajaxShowMessage();
429         /**
430          * @var button_options  Object containing options for jQueryUI dialog buttons
431          */
432         var button_options = {};
433         button_options[PMA_messages['strClose']] = function() {$(this).dialog("close").remove();}
435         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
436             $('<div id="export_dialog"></div>')
437             .prepend(data)
438             .dialog({
439                 width : 500,
440                 buttons: button_options
441             });
442         }) //end $.get
443     }) //end export privileges
445     /**
446      * AJAX handler to Paginate the Users Table
447      *
448      * @see         PMA_ajaxShowMessage()
449      * @name        paginate_users_table_click
450      * @memberOf    jQuery
451      */
452     $("#initials_table").find("a").live('click', function(event) {
453         event.preventDefault();
455         PMA_ajaxShowMessage();
457         $.get($(this).attr('href'), {'ajax_request' : true}, function(data) {
458             $("#usersForm")
459             .hide("medium")
460             .siblings("#initials_table")
461             .after(data)
462             .show("medium")
463             .end()
464             .remove();
465             $("#initials_table").siblings("h2").not(":first").remove();
466         }) // end $.get
467     })// end of the paginate users table
469 }, 'top.frame_content'); //end $(document).ready()
471 /**#@- */