<?php
    
/*
    Plugin Name: Custom Authentication System
    Plugin URI: http://www.davidrojo.es
    Description: This plugin allows to customize Login process with a personal system.
    Version: 1.0
    Author: David Rojo
    Author URI: http://www.davidrojo.es
    License: GPL2
    */

    
add_filter('wp_authenticate', 'customAuthentication', 1, 2 );

    function 
customAuthentication( $username, $password) {
        
$user = p_obtenerUsuario($username, $password);
        if (
$user){
            
// HEMOS ENCONTRADO EL USUARIO EN NUESTRO SISTEMA
            
$userarray['user_login'] = $user["username"];
            
$userarray['user_pass'] = $password;
            
$userarray['first_name'] = $user["nombre"];
            
$userarray['last_name'] = $user["apelildos"];
            
$userarray['user_email'] = $user["email"];
            
// COMPROBAMOS SI EL USUARIO YA ESTÁ EN WORDPRESS
            
if ($id = username_exists($username)) {
                
// ACTUALIZAMOS EL USUARIO EN WORDPRESS
                
$userarray['ID'] = $id;
                
wp_update_user($userarray);
            }
            else{
                
// INSERTAMOS EL USUARIO EN WORDPRESS
                
wp_insert_user($userarray);
            }
        }
        else{ 
// USUARIO INCORRECTO
            
remove_action('authenticate', 'wp_authenticate_username_password', 20);
        }
    }

    function 
p_obtenerUsuario($username, $password){
        
$mydb = new wpdb(DB_USER, DB_PASS, DB_NAME, DB_HOST);
        
$r = $mydb->get_row( $mydb->prepare( "SELECT * FROM usuarios WHERE username = %s AND pass = %s AND blog = 1", $username, md5($password)), ARRAY_A);
        return 
$r;
    }
    
    function 
disable_function() {    
        
$errors = new WP_Error();
        
$errors->add('registerdisabled', __('User registration is not available from this site, so you can\'t create an account or retrieve your password from here. See the message above.'));
        
login_header(__('Log In'), '', $errors);
        
?>
        <p id="backtoblog"><a href="<?php bloginfo('url'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('&larr; Back to %s'), get_bloginfo('title', 'display' )); ?></a></p>
        <?php
        
exit();
    }
    
    
add_action('lost_password', 'disable_function');
    
add_action('register_form', 'disable_function_register');
    
add_action('retrieve_password', 'disable_function');
    
add_action('password_reset', 'disable_function');
?>