Translation update done using Pootle.
[phpmyadmin.git] / js / server_privileges.js
blob6d425a6f4055be81dd5de50fec62058a5be5bcfc
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     /**
143      * AJAX event handler for 'Add a New User'
144      *
145      * @see         PMA_ajaxShowMessage()
146      * @see         appendNewUser()
147      * @see         $cfg['AjaxEnable']
148      * @memberOf    jQuery
149      * @name        add_user_click
150      *
151      */
152     $("#fieldset_add_user a.ajax").live("click", function(event) {
153         /** @lends jQuery */
154         event.preventDefault();
156         var $msgbox = PMA_ajaxShowMessage();
158         /**
159          * @var button_options  Object containing options for jQueryUI dialog buttons
160          */
161         var button_options = {};
162         button_options[PMA_messages['strAddUser']] = function() {
164             /**
165              * @var $form    stores reference to current form
166              */
167             var $form = $(this).find("form[name=usersForm]").last();
169             if (! checkAddUser($form.get(0))) {
170                 PMA_ajaxShowMessage(PMA_messages['strFormEmpty']);
171                 return false;
172             }
174             //We also need to post the value of the submit button in order to get this to work correctly
175             $.post($form.attr('action'), $form.serialize() + "&adduser_submit=" + $(this).find("input[name=adduser_submit]").attr('value'), function(data) {
176                 if (data.success == true) {
177                     // Refresh navigation, if we created a database with the name
178                     // that is the same as the username of the new user
179                     if ($('#add_user_dialog #createdb_1:checked').length && window.parent) {
180                         window.parent.refreshNavigation(true);
181                     }
183                     $("#add_user_dialog").dialog("close");
184                     PMA_ajaxShowMessage(data.message);
185                     $("#floating_menubar")
186                      .next('div')
187                      .remove()
188                      .end()
189                      .after(data.sql_query);
191                     //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
192                     var $notice_class = $("#floating_menubar").next("div").find('.notice');
193                     if ($notice_class.text() == '') {
194                         $notice_class.remove();
195                     }
196                     if ($('#fieldset_add_user a.ajax').attr('name') == 'db_specific') {
198                         /*process the fieldset_add_user attribute and get the val of privileges*/
199                         var url = $('#fieldset_add_user a.ajax').attr('rel');
201                         if (url.substring(url.length - 23, url.length) == "&goto=db_operations.php") {
202                             url = url.substring(0, url.length - 23);
203                         }
204                         url = url + "&ajax_request=true&db_specific=true";
206                         /* post request for get the updated userForm table */
207                         $.post($form.attr('action' ), url, function(priv_data) {
209                             /*Remove the old userForm table*/
210                             if ($('#userFormDiv').length != 0) {
211                                 $('#userFormDiv').remove();
212                             } else {
213                                 $("#usersForm").remove();
214                             }
215                             var user_div = $('<div id="userFormDiv"></div>');
216                             /*If the JSON string parsed correctly*/
217                             if (typeof priv_data.success != 'undefined') {
218                                 if (priv_data.success == true) {
219                                     user_div
220                                      .html(priv_data.user_form)
221                                      .insertAfter('#result_query');
222                                 } else {
223                                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + priv_data.error, false);
224                                 }
225                             } else {
226                                 /*parse the JSON string*/
227                                 var obj = $.parseJSON(priv_data);
228                                 user_div
229                                  .html(obj.user_form)
230                                  .insertAfter('#result_query');
231                             }
232                         });
233                     } else {
234                         appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
235                     }
236                 } else {
237                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + data.error, false);
238                 }
239             })
240         };
241         button_options[PMA_messages['strCancel']] = function() { $(this).dialog("close"); };
243         $.get($(this).attr("href"), {'ajax_request':true}, function(data) {
244             var $div = $('<div id="add_user_dialog"></div>')
245             .prepend(data)
246             .find("#fieldset_add_user_footer").hide() //showing the "Go" and "Create User" buttons together will confuse the user
247             .end()
248             .find("form[name=usersForm]").append('<input type="hidden" name="ajax_request" value="true" />')
249             .end()
250             .dialog({
251                 title: PMA_messages['strAddUser'],
252                 width: 800,
253                 // height is a workaround for this Chrome problem:
254                 // http://bugs.jqueryui.com/ticket/4671
255                 // also it's interesting to be able to scroll this window
256                 height: 600,
257                 modal: true,
258                 buttons: button_options,
259                 close: function () {
260                     $(this).remove();
261                 }
262             }); //dialog options end
263             displayPasswordGenerateButton();
264             PMA_convertFootnotesToTooltips($div);
265             PMA_ajaxRemoveMessage($msgbox);
266         }); // end $.get()
268     });//end of Add New User AJAX event handler
271     /**
272      * Ajax event handler for 'Reload Privileges' anchor
273      *
274      * @see         PMA_ajaxShowMessage()
275      * @see         $cfg['AjaxEnable']
276      * @memberOf    jQuery
277      * @name        reload_privileges_click
278      */
279     $("#reload_privileges_anchor.ajax").live("click", function(event) {
280         event.preventDefault();
282         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strReloadingPrivileges']);
284         $.get($(this).attr("href"), {'ajax_request': true}, function(data) {
285             if(data.success == true) {
286                 PMA_ajaxRemoveMessage($msgbox);
287             }
288             else {
289                 PMA_ajaxShowMessage(data.error, false);
290             }
291         }); //end $.get()
293     }); //end of Reload Privileges Ajax event handler
295     /**
296      * AJAX handler for 'Revoke User'
297      *
298      * @see         PMA_ajaxShowMessage()
299      * @see         $cfg['AjaxEnable']
300      * @memberOf    jQuery
301      * @name        revoke_user_click
302      */
303     $("#fieldset_delete_user_footer #buttonGo.ajax").live('click', function(event) {
304         event.preventDefault();
306         PMA_ajaxShowMessage(PMA_messages['strRemovingSelectedUsers']);
308         $form = $("#usersForm");
310         $.post($form.attr('action'), $form.serialize() + "&delete=" + $(this).attr('value') + "&ajax_request=true", function(data) {
311             if(data.success == true) {
312                 PMA_ajaxShowMessage(data.message);
313                 // Refresh navigation, if we droppped some databases with the name
314                 // that is the same as the username of the deleted user
315                 if ($('#checkbox_drop_users_db:checked').length && window.parent) {
316                     window.parent.refreshNavigation(true);
317                 }
318                 //Remove the revoked user from the users list
319                 $form.find("input:checkbox:checked").parents("tr").slideUp("medium", function() {
320                     var this_user_initial = $(this).find('input:checkbox').val().charAt(0).toUpperCase();
321                     $(this).remove();
323                     //If this is the last user with this_user_initial, remove the link from #initials_table
324                     if($("#tableuserrights").find('input:checkbox[value^=' + this_user_initial + ']').length == 0) {
325                         $("#initials_table").find('td > a:contains(' + this_user_initial + ')').parent('td').html(this_user_initial);
326                     }
328                     //Re-check the classes of each row
329                     $form
330                     .find('tbody').find('tr:odd')
331                     .removeClass('even').addClass('odd')
332                     .end()
333                     .find('tr:even')
334                     .removeClass('odd').addClass('even');
335                 })
336             }
337             else {
338                 PMA_ajaxShowMessage(data.error, false);
339             }
340         }) // end $.post()
341     }) // end Revoke User
343     /**
344      * AJAX handler for 'Edit User'
345      *
346      * @see         PMA_ajaxShowMessage()
347      *
348      */
350     /**
351      * Step 1: Load Edit User Dialog
352      * @memberOf    jQuery
353      * @name        edit_user_click
354      * @see         $cfg['AjaxEnable']
355      */
356     $(".edit_user_anchor.ajax").live('click', function(event) {
357         /** @lends jQuery */
358         event.preventDefault();
360         var $msgbox = PMA_ajaxShowMessage();
362         $(this).parents('tr').addClass('current_row');
364         /**
365          * @var button_options  Object containing options for jQueryUI dialog buttons
366          */
367         var button_options = {};
368         button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close");};
370         var token = $(this).parents('form').find('input[name="token"]').val();
371         $.get($(this).attr('href'), {'ajax_request':true, 'edit_user_dialog': true, 'token': token}, function(data) {
372             var $div = $('<div id="edit_user_dialog"></div>')
373             .append(data)
374             .dialog({
375                 width: 900,
376                 height: 600,
377                 buttons: button_options,
378                 close: function () {
379                     $(this).remove();
380                 }
381             }); //dialog options end
382             displayPasswordGenerateButton();
383             PMA_ajaxRemoveMessage($msgbox);
384             PMA_convertFootnotesToTooltips($div);
385         }) // end $.get()
386     })
388     /**
389      * Step 2: Submit the Edit User Dialog
390      *
391      * @see         PMA_ajaxShowMessage()
392      * @see         $cfg['AjaxEnable']
393      * @memberOf    jQuery
394      * @name        edit_user_submit
395      */
396     $("#edit_user_dialog").find("form:not(#db_or_table_specific_priv)").live('submit', function(event) {
397         /** @lends jQuery */
398         event.preventDefault();
400         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
402         $(this).append('<input type="hidden" name="ajax_request" value="true" />');
404         /**
405          * @var curr_submit_name    name of the current button being submitted
406          */
407         var curr_submit_name = $(this).find('.tblFooters').find('input:submit').attr('name');
409         /**
410          * @var curr_submit_value    value of the current button being submitted
411          */
412         var curr_submit_value = $(this).find('.tblFooters').find('input:submit').val();
414         $.post($(this).attr('action'), $(this).serialize() + '&' + curr_submit_name + '=' + curr_submit_value, function(data) {
415             if(data.success == true) {
417                 PMA_ajaxShowMessage(data.message);
419                 //Close the jQueryUI dialog
420                 $("#edit_user_dialog").dialog("close");
422                 if(data.sql_query) {
423                     $("#floating_menubar")
424                     .next('div')
425                     .remove()
426                     .end()
427                     .after(data.sql_query);
428                     var notice_class = $("#floating_menubar").next("div").find('.notice');
429                     if($(notice_class).text() == '') {
430                         $(notice_class).remove();
431                     }
432                 } //Show SQL Query that was executed
434                 //Append new user if necessary
435                 if(data.new_user_string) {
436                     appendNewUser(data.new_user_string, data.new_user_initial, data.new_user_initial_string);
437                 }
439                 //Check if we are on the page of the db-specific privileges
440                 var db_priv_page = !!($('#dbspecificuserrights').length); // the "!!" part is merely there to ensure a value of type boolean
441                 // we always need to reload on the db-specific privilege page
442                 // and on the global page when adjusting global privileges,
443                 // but not on the global page when adjusting db-specific privileges.
444                 var reload_privs = false;
445                 if (data.db_specific_privs == false || (db_priv_page == data.db_specific_privs)) {
446                     reload_privs = true;
447                 }
449                 //Change privileges, if they were edited and need to be reloaded
450                 if(data.new_privileges && reload_privs) {
451                     $("#usersForm")
452                     .find('.current_row')
453                     .find('tt')
454                     .html(data.new_privileges);
455                 }
457                 $("#usersForm")
458                 .find('.current_row')
459                 .removeClass('current_row');
460             }
461             else {
462                 PMA_ajaxShowMessage(data.error, false);
463             }
464         });
465     })
466     //end Edit user
468     /**
469      * AJAX handler for 'Export Privileges'
470      *
471      * @see         PMA_ajaxShowMessage()
472      * @see         $cfg['AjaxEnable']
473      * @memberOf    jQuery
474      * @name        export_user_click
475      */
476     $(".export_user_anchor.ajax").live('click', function(event) {
477         event.preventDefault();
478         var $msgbox = PMA_ajaxShowMessage();
479         /**
480          * @var button_options  Object containing options for jQueryUI dialog buttons
481          */
482         var button_options = {};
483         button_options[PMA_messages['strClose']] = function() {
484             $(this).dialog("close");
485         };
486         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
487             var $ajaxDialog = $('<div />')
488             .append(data.message)
489             .dialog({
490                 title: data.title,
491                 width: 500,
492                 buttons: button_options,
493                 close: function () {
494                     $(this).remove();
495                 }
496             });
497             PMA_ajaxRemoveMessage($msgbox);
498             // Attach syntax highlited editor to export dialog
499             CodeMirror.fromTextArea(
500                 $ajaxDialog.find('textarea')[0],
501                 {
502                     lineNumbers: true,
503                     matchBrackets: true,
504                     indentUnit: 4,
505                     mode: "text/x-mysql"
506                 }
507             );
508         }); //end $.get
509     }); //end export privileges
511     /**
512      * AJAX handler to Paginate the Users Table
513      *
514      * @see         PMA_ajaxShowMessage()
515      * @see         $cfg['AjaxEnable']
516      * @name        paginate_users_table_click
517      * @memberOf    jQuery
518      */
519     $("#initials_table.ajax").find("a").live('click', function(event) {
520         event.preventDefault();
522         var $msgbox = PMA_ajaxShowMessage();
524         $.get($(this).attr('href'), {'ajax_request' : true}, function(data) {
525             // This form is not on screen when first entering Privileges
526             // if there are more than 50 users
527             $("#usersForm").hide("medium").remove();
528             $("#fieldset_add_user").hide("medium").remove();
529             $("#initials_table")
530              .after(data).show("medium")
531              .siblings("h2").not(":first").remove();
533             PMA_ajaxRemoveMessage($msgbox);
534         }) // end $.get
535     })// end of the paginate users table
537     /*
538      * Additional confirmation dialog after clicking
539      * 'Drop the databases...'
540      */
541     $('#checkbox_drop_users_db').click(function() {
542         $this_checkbox = $(this);
543         if ($this_checkbox.is(':checked')) {
544             var is_confirmed = confirm(PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\nDROP DATABASE');
545             if (! is_confirmed) {
546                 $this_checkbox.attr('checked', false);
547             }
548         }
549     });
551     displayPasswordGenerateButton();
552 }, 'top.frame_content'); //end $(document).ready()
554 /**#@- */