grant-roles.php 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
<?php
/**
 * Project: User Role Editor plugin
 * Author: Vladimir Garagulya
 * Author email: support@role-editor.com
 * Author URI: https://www.role-editor.com
 * License: GPL v2+
 * 
 * Assign multiple roles to the list of selected users directly from the "Users" page
 * Grant/Revoke single role to/from selected users 
 */

class URE_Grant_Roles {

    const NO_ROLE_FOR_THIS_SITE = 'no-role-for-this-site';
    
    private $lib = null;
    private static $counter = 0;
    
    
    public function __construct() {
        
        $this->lib = URE_Lib::get_instance();        
        
        add_action( 'load-users.php', array( $this, 'load' ) );                
                
    }
    // end of __construct()
    
    
    public function load() {
        
        add_action('restrict_manage_users', array($this, 'show_roles_manage_html') );
        add_action('admin_head', array(User_Role_Editor::get_instance(), 'add_css_to_users_page') );
        add_action('admin_enqueue_scripts', array($this, 'load_js') );
        
        $this->update_roles();  
        
    }
    // end of load()
            
    
    private static function validate_users($users) {
        
        if (!is_array($users)) {
            return false;
        }
        
        foreach ($users as $user_id) {
            if (!is_numeric($user_id)) {
                return false;
            }
            if ( !current_user_can( 'promote_user', $user_id ) ) {
                return false;
            }

            if ( is_multisite() && !is_user_member_of_blog( $user_id ) ) {
                return false;
            }

        }
        
        return true;
    }
    // end of validate_users()            
    
    
    private function add_role( $users ) {
        
        if ( !empty( $_REQUEST['ure_add_role'] ) ) {
            $role = $_REQUEST['ure_add_role'];
        } else {
            $role = $_REQUEST['ure_add_role_2'];
        }

        if ( !self::validate_roles( array($role=>$role) ) ) {
            return;
        }
        
        $done = false;
        foreach( $users as $user_id ) {
            $user = get_user_by( 'id', $user_id );
            if (empty( $user ) ) {
                continue;
            }
            if ( empty($user->roles) || !in_array( $role, $user->roles ) ) {
                $user->add_role( $role );
                $done = true;
            }
        }
        
        if ( $done ) {
            // Redirect to the users screen.
            if ( wp_redirect( add_query_arg( 'update', 'promote', 'users.php' ) ) ) {
                 exit;
            }
        }
    }
    // end of add_role()
    
    
    private function is_try_remove_admin_from_himself( $user_id, $role) {

        $result = false;
        
        $current_user = wp_get_current_user();
        $wp_roles = wp_roles();
        $role_caps = array_keys( $wp_roles->roles[$role]['capabilities'] );
      	$is_current_user = ( $user_id == $current_user->ID );
        $role_can_promote = in_array('promote_users', $role_caps);
        $can_manage_network = is_multisite() && current_user_can( 'manage_network_users' );

        // If the removed role has the `promote_users` cap and user is removing it from himself
        if ( $is_current_user && $role_can_promote && !$can_manage_network ) {
            $result = true;

            // Loop through the current user's roles.
            foreach ($current_user->roles as $_role) {
                $_role_caps = array_keys( $wp_roles->roles[$_role]['capabilities'] );
                // If the current user has another role that can promote users, it's safe to remove the role.  Else, the current user should to keep this role.                
                if ( ($role!==$_role) && in_array( 'promote_users', $_role_caps ) ) {
                    $result = false;
                    break;
                }
            }

        }
        
        return $result;
    }
    
    
    private function revoke_role( $users ) {
        
        if ( !empty( $_REQUEST['ure_revoke_role'] ) ) {
            $role = $_REQUEST['ure_revoke_role'];
        } else {
            $role = $_REQUEST['ure_revoke_role_2'];
        }

        if ( !self::validate_roles( array($role=>$role) ) ) {
            return;
        }
         
        $done = false;
        foreach( $users as $user_id ) {
            $user = get_user_by( 'id', $user_id );
            if (empty( $user ) ) {
                continue;
            }
            if ($this->is_try_remove_admin_from_himself( $user_id, $role ) ) {
                continue;
            }
            if ( is_array($user->roles) && in_array( $role, $user->roles ) ) {
                $user->remove_role( $role );
                $done = true;
            }
        }
        if ( $done ) {
            if ( wp_redirect( add_query_arg( 'update', 'promote', 'users.php' ) ) ) {
                exit;
            }
        }
    }
    // end of revoke_role()


    private function update_roles() {        
                
        if ( empty( $_REQUEST['users'] ) ) {
            return;
        }
        
        if ( !current_user_can('promote_users') ) {            
            return;
        }
        $users = (array) $_REQUEST['users'];
        if ( !self::validate_users( $users ) ) {
            return;
        }
        
        if ( ( !empty( $_REQUEST['ure_add_role'] ) && !empty( $_REQUEST['ure_add_role_submit']) ) || 
             ( !empty( $_REQUEST['ure_add_role_2'] ) && !empty( $_REQUEST['ure_add_role_submit_2'] ) ) ) {
            $this->add_role( $users );
        } else if ( ( !empty( $_REQUEST['ure_revoke_role'] ) && !empty( $_REQUEST['ure_revoke_role_submit'] ) ) || 
                    ( !empty( $_REQUEST['ure_revoke_role_2'] ) && !empty( $_REQUEST['ure_revoke_role_submit_2'] ) ) ) {
            $this->revoke_role( $users );
        }
    }
    // end of update_roles()
    
    
    private static function validate_roles($roles) {

        if (!is_array($roles)) {
            return false;
        }
        
        $lib = URE_Lib::get_instance();
        $editable_roles = $lib->get_all_editable_roles();
        $valid_roles = array_keys($editable_roles);
        foreach($roles as $role) {
            if (!in_array($role, $valid_roles)) {
                return false;
            }
        }
        
        return true;        
    }
    // end of validate_roles()
        
    
    private static function grant_primary_role_to_user($user_id, $role) {
                        
        $user = get_user_by('id', $user_id);
        if (empty($user)) {
            return;
        }
                     
        if ($role===self::NO_ROLE_FOR_THIS_SITE) {
            $role = '';
        }
        $old_roles = $user->roles;  // Save currently granted roles to restore from them the bbPress roles later if there are any...
        $user->set_role($role); 
        
        $lib = URE_Lib::get_instance();
        $bbpress = $lib->get('bbpress');
        if (empty($bbpress)) {
            return;
        }
        
        $bbp_roles = $bbpress->extract_bbp_roles($old_roles);
        if (count($bbp_roles)>0) {  //  restore bbPress roles
            foreach($bbp_roles as $role) {
                $user->add_role($role);
            }        
        }        
        
    }
    // end of grant_primary_role_to_user()
            
    
    private static function grant_other_roles_to_user($user_id, $roles) {
                        
        $user = get_user_by('id', $user_id);
        if (empty($user)) {
            return;
        }
        
        $roles_list = array_values( $user->roles );
        $primary_role = array_shift( $roles_list );    // Get the 1st element from the roles array
        $lib = URE_Lib::get_instance();
        $bbpress = $lib->get( 'bbpress' );
        if ( empty( $bbpress ) ) {
            $bbp_roles = array();
        } else {
            $bbp_roles = $bbpress->extract_bbp_roles( $user->roles );
        }
        $user->remove_all_caps();
        $roles2 = ure_array_merge( array( $primary_role ), $bbp_roles, $roles );
        foreach( $roles2 as $role ) {
            $user->add_role( $role );
        }
        
    }
    // end of grant_other_roles_to_user()
    
    
    /**
     * Decide if primary role should be granted or left as it is
     * 
     * @param string $primary_role
     * @return boolean
     */
    private static function is_select_primary_role($primary_role) {
        
        if (empty($primary_role)) {
            return false;   // Primary role was not selected by user, leave an older one
        }
        
        $lib = URE_Lib::get_instance();
        if ($lib->is_super_admin()) {
            $select_primary_role = true;
        } else {
            $select_primary_role = apply_filters('ure_users_select_primary_role', true);
        }
        
        return $select_primary_role;
    }
    // end of is_select_primary_role()
    
    
    public static function grant_roles() {

        if ( !current_user_can('promote_users') ) {
            $answer = array('result'=>'error', 'message'=>esc_html__('Not enough permissions', 'user-role-editor'));
            return $answer;
        }
                
        $users = $_POST['users'];        
        if (!self::validate_users($users)) {
            $answer = array('result'=>'error', 'message'=>esc_html__('Can not edit user or invalid data at the users list', 'user-role-editor'));
            return $answer;
        }

// Primary role       
        $primary_role = $_POST['primary_role'];        
        if (!empty($primary_role) && ($primary_role!==self::NO_ROLE_FOR_THIS_SITE) && 
            !self::validate_roles(array($primary_role=>$primary_role))) {
            $answer = array('result'=>'error', 'message'=>esc_html__('Invalid primary role', 'user-role-editor'));
            return $answer;
        }
                
        if (self::is_select_primary_role($primary_role)) {            
            foreach ($users as $user_id) {                
                self::grant_primary_role_to_user($user_id, $primary_role);
            }            
        }
        
// Other roles        
        $other_roles = isset($_POST['other_roles']) ? $_POST['other_roles'] : null;
        if (!empty($other_roles) && !self::validate_roles($other_roles)) {
            $answer = array('result'=>'error', 'message'=>esc_html__('Invalid data at the other roles list', 'user-role-editor'));
            return $answer;
        }
        
        if (!empty($other_roles)) {
            foreach($users as $user_id) {
                self::grant_other_roles_to_user($user_id, $other_roles); 
            }                
        }
        $answer = array('result'=>'success', 'message'=>esc_html__('Roles were granted to users successfully', 'user-role-editor'));
        
        return $answer;
    }
    // end of grant_roles()
    
    
    public static function get_user_roles() {

        if ( !current_user_can( 'promote_users' ) ) {
            $answer = array('result'=>'error', 'message'=>esc_html__('Not enough permissions', 'user-role-editor'));
            return $answer;
        }
        
        $lib = URE_Lib::get_instance();
        $user_id = (int) $lib->get_request_var('user_id', 'post', 'int');
        if (empty($user_id)) {
            $answer = array('result'=>'error', 'message'=>esc_html__('Wrong request, valid user ID was missed', 'user-role-editor'));
            return $answer;
        }
    
        $user = get_user_by('id', $user_id);
        if (empty($user)) {
            $answer = array('result'=>'error', 'message'=>esc_html__('Requested user does not exist', 'user-role-editor'));
            return $answer;
        }
        
        $other_roles = array_values($user->roles);
        $primary_role = array_shift($other_roles);
        
        $answer = array('result'=>'success', 'primary_role'=>$primary_role, 'other_roles'=>$other_roles, 'message'=>'User roles were sent');
        
        return $answer;
    }
    // end of get_user_roles()
    
    
    
    private function select_primary_role_html() {
        
        $select_primary_role = apply_filters('ure_users_select_primary_role', true);
        if (!$select_primary_role && !$this->lib->is_super_admin()) {
            return;
        }
?>        
        <span style="font-weight: bold;">
            <?php esc_html_e('Primary Role: ', 'role-editor');?> 
        </span>
        <select name="primary_role" id="primary_role">
<?php            
        // print the full list of roles with the primary one selected.
        wp_dropdown_roles('');
        echo '<option value="'. self::NO_ROLE_FOR_THIS_SITE .'">' . esc_html__('&mdash; No role for this site &mdash;') . '</option>'. PHP_EOL;
?>        
        </select>
        <hr/>
<?php        
    }
    // end of select_primary_role_html()
            
    
    private function select_other_roles_html() {
?>        
        <div id="other_roles_container">
            <span style="font-weight: bold;">
<?php          
        esc_html_e('Other Roles: ', 'role-editor');
?>        
        </span><br>
<?php        
        $show_admin_role = $this->lib->show_admin_role_allowed();        
        $roles = $this->lib->get_all_editable_roles(); 
        foreach ($roles as $role_id => $role) {
            if (!$show_admin_role && $role_id=='administrator') {
                continue;
            }
            echo '<label for="wp_role_' . $role_id . '"><input type="checkbox"	id="wp_role_' . $role_id .
                 '" name="ure_roles[]" value="' . $role_id . '" />&nbsp;' .
            esc_html__($role['name'], 'user-role-editor') .' ('. $role_id .')</label><br />'. PHP_EOL;            
        }
?>
        </div>
<?php        
    }
    // end of select_other_roles_html()
    
    
    private function get_roles_options_list() {
        
        ob_start();
        wp_dropdown_roles();
        $output = ob_get_clean();
        
        return $output;
    }
    // end of get_roles_options_list()
    
    
    public function show_roles_manage_html() {
                      
        if ( !current_user_can( 'promote_users' ) ) {
            return;
        }
        $button_number =  (self::$counter>0) ? '_2': '';
        $roles_options_list = self::get_roles_options_list();
?>        
        &nbsp;&nbsp;
        <input type="button" name="ure_grant_roles<?php echo $button_number;?>" id="ure_grant_roles<?php echo $button_number;?>" class="button"                               
             value="<?php esc_html_e('Grant Roles', 'user-role-editor');?>">
        &nbsp;&nbsp;        
        <label class="screen-reader-text" for="ure_add_role<?php echo $button_number;?>"><?php esc_html_e( 'Add role&hellip;', 'user-role-editor' ); ?></label>
        <select name="ure_add_role<?php echo $button_number;?>" id="ure_add_role<?php echo $button_number;?>" style="display: inline-block; float: none;">
            <option value=""><?php esc_html_e( 'Add role&hellip;', 'user-role-editor' ); ?></option>
            <?php echo $roles_options_list; ?>
        </select>
	<?php submit_button( esc_html__( 'Add', 'user-role-editor' ), 'secondary', 'ure_add_role_submit'.$button_number, false ); ?>
        &nbsp;&nbsp;
        <label class="screen-reader-text" for="ure_revoke_role<?php echo $button_number;?>"><?php esc_html_e( 'Revoke role&hellip;', 'user-role-editor' ); ?></label>
        <select name="ure_revoke_role<?php echo $button_number;?>" id="ure_revoke_role<?php echo $button_number;?>" style="display: inline-block; float: none;">
            <option value=""><?php esc_html_e( 'Revoke role&hellip;', 'user-role-editor' ); ?></option>
            <?php echo $roles_options_list; ?>
        </select>
	<?php submit_button( esc_html__( 'Revoke', 'user-role-editor' ), 'secondary', 'ure_revoke_role_submit'.$button_number, false ); ?>

        
<?php
    if (self::$counter==0) {
?>
            <div id="ure_grant_roles_dialog" class="ure-dialog">
                <div id="ure_grant_roles_content">
<?php                
                $this->select_primary_role_html();
                $this->select_other_roles_html();
?>                
                </div>
            </div>
<?php
        URE_View::output_task_status_div();
        self::$counter++;
    }
        
    }
    // end of show_grant_roles_html()
    
    
    public function load_js() {

        $show_wp_change_role = apply_filters('ure_users_show_wp_change_role', true);
        
        wp_enqueue_script('jquery-ui-dialog', '', array('jquery-ui-core','jquery-ui-button', 'jquery') );
        wp_register_script('ure-users-grant-roles', plugins_url('/js/users-grant-roles.js', URE_PLUGIN_FULL_PATH ), array(), URE_VERSION );
        wp_enqueue_script('ure-users-grant-roles', '', array(), false, true);
        wp_localize_script('ure-users-grant-roles', 'ure_users_grant_roles_data', array(
            'wp_nonce' => wp_create_nonce('user-role-editor'),
            'dialog_title'=> esc_html__('Grant roles to selected users', 'user-role-editor'),
            'select_users_first' => esc_html__('Select users to which you wish to grant roles!', 'user-role-editor'),
            'select_roles_first' => esc_html__('Select role(s) which you wish to grant!', 'user-role-editor'),
            'show_wp_change_role' => $show_wp_change_role ? 1: 0
        ));
    }
    // end of load_js()
    
}
// end of URE_Grant_Roles class