<?php

/*
Plugin Name: Fix No Role Users
Plugin URI: http://simonwheatley.co.uk/wordpress/fox-no-role-users/
Description: Finds users with no role and makes them subscribers.
Version: 1
Author: Simon Wheatley
Author URI: http://www.simonwheatley.co.uk/wordpress/
*/

/*  Copyright 2009 Simon Wheatley

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

/**
 *
 * @package default
 * @author Simon Wheatley
 **/
class FixNoRoleUsers
{
    protected 
$db;

    public function 
__construct()
    {
        global 
$wpdb;
        
$this->db = & $wpdb;
        
add_action'init', array( & $this'fix_roles' ) );
    }
    
    public function 
fix_roles()
    {
        
// Get some more user IDs
        
$user_ids $this->no_role_user_ids();
        if ( ! 
count$user_ids ) ) $this->finished();
        foreach ( 
$user_ids as $user_id ) {
            
$user = new WP_User$user_id );
            
$user->add_role'subscriber' );
            
error_log"Given user $user->user_login the role of subscriber" );
            unset( 
$user );
        }
    }

    protected function 
no_role_user_ids()
    {
        
$users $this->db->users;
        
$usermeta $this->db->usermeta;
        
// Pretty horrible query, but who cares as it's not for production usage
        // Grab groups of 1,000 for now
        
$sql " SELECT ID FROM $users WHERE ID NOT IN ( SELECT user_id FROM $usermeta WHERE meta_key = 'wp_capabilities' ) LIMIT 1000; "
        
// No need to prepare as no user input
        
return $this->db->get_col$sql );
    }
    
    protected function 
finished()
    {
        
// OK. Bung a rude message up and exit.
        
echo "All users now have roles.";
        exit;
    }
}

/**
 * Instantiate the plugin
 *
 * @global
 **/

$fix_no_role_users = new FixNoRoleUsers();

?>