Skip to content

Instantly share code, notes, and snippets.

@loxK
Created August 10, 2010 21:42
Show Gist options
  • Save loxK/518077 to your computer and use it in GitHub Desktop.
Save loxK/518077 to your computer and use it in GitHub Desktop.
<?php
require_once 'Plugin/Abstract.php';
class Apreslebac_Login {
static $load_login_js;
protected $PostTypes = 'etablissement,metier,formation';
protected $TextDomain = 'Apreslebac';
protected $UserData2Save;
public function __construct () {
$this->Path = ALB_PATH;
// if( !is_admin() ) {
add_action('apreslebac_login', array($this, 'login'));
add_action('wp_footer', array($this, 'wp_footer'));
/*add_action('wp_ajax_logout', array($this, 'login_process'));
add_action('wp_ajax_nopriv_logout', array($this, 'login_process'));
add_action('wp_ajax_lostpassword', array($this, 'login_process'));
add_action('wp_ajax_nopriv_lostpassword', array($this, 'login_process'));
add_action('wp_ajax_retrievepassword', array($this, 'login_process'));
add_action('wp_ajax_nopriv_retrievepassword', array($this, 'login_process'));
add_action('wp_ajax_rp', array($this, 'login_process'));
add_action('wp_ajax_nopriv_rp', array($this, 'login_process'));*/
add_action('wp_ajax_a_register', array($this, 'login_process'));
add_action('wp_ajax_nopriv_a_register', array($this, 'login_process'));
add_action('wp_ajax__a_login', array($this, 'login_process'));
add_action('wp_ajax__nopriv_a_login', array($this, 'login_process'));
// This is a check to see if you want to make a field required
add_filter('registration_errors', array($this, 'registration_errors') ,10 ,3);
// This inserts the data
add_action('user_register', array($this,'register_extra_fields') );
// add inactive role for inactive users
add_role( 'inactive', 'Inactifs' );
// / }
}
public function template_redirect() {
/* shows the registration page template */
include '';
}
public function login () {
self::$load_login_js = true;
global $user_login;
/*wp_login_form();*/
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'login';
if ( isset($_GET['key']) )
$action = 'resetpass';
// validate action so as to default to the login screen
if ( !in_array($action, array('logout', 'lostpassword', 'retrievepassword', 'resetpass', 'rp', 'register', 'login'), true) && false === has_filter('login_form_' . $action) )
$action = 'login';
$rememberme = ! empty( $_POST['rememberme'] );
if ( isset( $_REQUEST['redirect_to'] ) ) {
$redirect_to = $_REQUEST['redirect_to'];
} else {
$redirect_to = site_url();
}
include ALB_PATH . '/Views/Login.php';
}
public function login_process () {
$action = isset($_REQUEST['action']) ? substr($_REQUEST['action'],2) : 'login';
$errors = new WP_Error();
if ( isset($_GET['key']) )
$action = 'resetpass';
// validate action so as to default to the login screen
if ( !in_array($action, array('logout', 'lostpassword', 'retrievepassword', 'resetpass', 'rp', 'register', 'login'), true) && false === has_filter('login_form_' . $action) )
$action = 'login';
nocache_headers();
//Set a cookie now to see if they are supported by the browser.
setcookie(TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN);
if ( SITECOOKIEPATH != COOKIEPATH )
setcookie(TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN);
// allow plugins to override the default actions, and to add extra actions if they want
do_action('login_form_' . $action);
do_action('alb_login_form_' . $action);
$http_post = ('POST' == $_SERVER['REQUEST_METHOD']);
switch ($action) {
case 'logout' :
check_admin_referer('log-out');
wp_logout();
$redirect_to = !empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : 'wp-login.php?loggedout=true';
wp_safe_redirect( $redirect_to );
exit();
break;
case 'lostpassword' :
case 'retrievepassword' :
if ( $http_post ) {
$errors = retrieve_password();
if ( !is_wp_error($errors) ) {
$redirect_to = !empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : 'wp-login.php?checkemail=confirm';
wp_safe_redirect( $redirect_to );
exit();
}
}
if ( isset($_GET['error']) && 'invalidkey' == $_GET['error'] ) $errors->add('invalidkey', __('Sorry, that key does not appear to be valid.'));
$redirect_to = apply_filters( 'lostpassword_redirect', !empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '' );
do_action('lost_password');
login_header(__('Lost Password'), '<p class="message">' . __('Please enter your username or e-mail address. You will receive a new password via e-mail.') . '</p>', $errors);
$user_login = isset($_POST['user_login']) ? stripslashes($_POST['user_login']) : '';
break;
case 'resetpass' :
case 'rp' :
$errors = reset_password($_GET['key'], $_GET['login']);
if ( ! is_wp_error($errors) ) {
wp_redirect('wp-login.php?checkemail=newpass');
exit();
}
wp_redirect('wp-login.php?action=lostpassword&error=invalidkey');
exit();
break;
/**
* Register a new user using ajax
*/
case 'register' :
if ( !get_option('users_can_register') ) {
$this->ajax_response_json(-1, '', 'redirect_to=' . admin_url('wp-login.php?registration=disabled') );
exit();
}
$user_login = '';
$user_email = '';
if ( $http_post ) {
require_once( ABSPATH . WPINC . '/registration.php');
$user_login = empty($_POST['user_login']) ? '' : $_POST['user_login'];
$user_email = empty($_POST['user_email']) ? '' : $_POST['user_email'];
$errors = $this->register_new_user($user_login, $user_email);
if ( !is_wp_error($errors) ) {
$redirect_to = !empty( $_POST['redirect_to'] ) ? $_POST['redirect_to'] : 'wp-login.php?checkemail=registered';
$this->ajax_response_json(1, 'Enregistrement effectué', $redirect_to );
exit();
}
}
if(is_wp_error($errors)) {
$this->ajax_response_json(0, 'Erreur', array('errors'=>$errors));
}
$redirect_to = apply_filters( 'registration_redirect', !empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '' );
var_dump($errors);
die;
//login_header(__('Registration Form'), '<p class="message register">' . __('Register For This Site') . '</p>', $errors);
break;
case 'login' :
default:
$secure_cookie = '';
$interim_login = isset($_REQUEST['interim-login']);
// If the user wants ssl but the session is not ssl, force a secure cookie.
if ( !empty($_POST['log']) && !force_ssl_admin() ) {
$user_name = sanitize_user($_POST['log']);
if ( $user = get_userdatabylogin($user_name) ) {
if ( get_user_option('use_ssl', $user->ID) ) {
$secure_cookie = true;
force_ssl_admin(true);
}
}
}
if ( isset( $_REQUEST['redirect_to'] ) ) {
$redirect_to = $_REQUEST['redirect_to'];
// Redirect to https if user wants ssl
if ( $secure_cookie && false !== strpos($redirect_to, 'wp-admin') )
$redirect_to = preg_replace('|^http://|', 'https://', $redirect_to);
} else {
$redirect_to = admin_url();
}
$reauth = empty($_REQUEST['reauth']) ? false : true;
// If the user was redirected to a secure login form from a non-secure admin page, and secure login is required but secure admin is not, then don't use a secure
// cookie and redirect back to the referring non-secure admin page. This allows logins to always be POSTed over SSL while allowing the user to choose visiting
// the admin via http or https.
if ( !$secure_cookie && is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
$secure_cookie = false;
$user = wp_signon('', $secure_cookie);
$redirect_to = apply_filters('login_redirect', $redirect_to, isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '', $user);
if ( !is_wp_error($user) && !$reauth ) {
if ( $interim_login ) {
$message = '<p class="message">' . __('You have logged in successfully.') . '</p>';
login_header( '', $message ); ?>
<script type="text/javascript">setTimeout( function(){window.close()}, 8000);</script>
<p class="alignright">
<input type="button" class="button-primary" value="<?php esc_attr_e('Close'); ?>" onclick="window.close()" /></p>
</div></body></html>
<?php exit;
}
// If the user can't edit posts, send them to their profile.
if ( !$user->has_cap('edit_posts') && ( empty( $redirect_to ) || $redirect_to == 'wp-admin/' || $redirect_to == admin_url() ) )
$redirect_to = admin_url('profile.php');
wp_safe_redirect($redirect_to);
exit();
}
$errors = $user;
// Clear errors if loggedout is set.
if ( !empty($_GET['loggedout']) || $reauth )
$errors = new WP_Error();
// If cookies are disabled we can't log in even with a valid user+pass
if ( isset($_POST['testcookie']) && empty($_COOKIE[TEST_COOKIE]) )
$errors->add('test_cookie', __("<strong>ERROR</strong>: Cookies are blocked or not supported by your browser. You must <a href='http://www.google.com/cookies.html'>enable cookies</a> to use WordPress."));
// Some parts of this script use the main login form to display a message
if ( isset($_GET['loggedout']) && TRUE == $_GET['loggedout'] )
$errors->add('loggedout', __('You are now logged out.'), 'message');
elseif ( isset($_GET['registration']) && 'disabled' == $_GET['registration'] )
$errors->add('registerdisabled', __('User registration is currently not allowed.'));
elseif ( isset($_GET['checkemail']) && 'confirm' == $_GET['checkemail'] )
$errors->add('confirm', __('Check your e-mail for the confirmation link.'), 'message');
elseif ( isset($_GET['checkemail']) && 'newpass' == $_GET['checkemail'] )
$errors->add('newpass', __('Check your e-mail for your new password.'), 'message');
elseif ( isset($_GET['checkemail']) && 'registered' == $_GET['checkemail'] )
$errors->add('registered', __('Registration complete. Please check your e-mail.'), 'message');
elseif ( $interim_login )
$errors->add('expired', __('Your session has expired. Please log-in again.'), 'message');
// Clear any stale cookies.
if ( $reauth )
wp_clear_auth_cookie();
login_header(__('Log In'), '', $errors);
if ( isset($_POST['log']) )
$user_login = ( 'incorrect_password' == $errors->get_error_code() || 'empty_password' == $errors->get_error_code() ) ? esc_attr(stripslashes($_POST['log'])) : '';
$rememberme = ! empty( $_POST['rememberme'] );
}
}
public function registration_errors ($errors, $sanitized_user_login, $user_email) {
/* verify INE */
if( !empty($sanitized_user_login) ) {
require_once ALB_PATH . '/Models/Kid.php';
$kid = apreslebac_get_kid ($sanitized_user_login);
if( !$kid->exists() )
$errors->add( 'user_login', __( '<strong>ERREUR</strong> : cet identifiant INE est inconnu.' ), array( 'form-field' => 'user_login' ) );
}
/* first name and last name check */
if ( isset( $_POST['first_name'] ) )
$first_name = sanitize_text_field( $_POST['first_name'] );
if ( isset( $_POST['last_name'] ) )
$last_name = sanitize_text_field( $_POST['last_name'] );
if ( empty($first_name) )
$errors->add( 'first_name', __( '<strong>ERREUR</strong> : merci de renseigner votre prénom.' ), array( 'form-field' => 'first_name' ) );
if ( empty($last_name) )
$errors->add( 'last_name', __( '<strong>ERREUR</strong> : merci de saisir vote nom.' ), array( 'form-field' => 'last_name' ) );
/* checks if ine, first_name and last_name do match */
if(!empty($sanitized_user_login) && !empty($last_name) && !empty($first_name) ) {
if($kid->exists() && !$kid->matches($first_name, $last_name) )
$errors->add( 'user_login', __( "<strong>ERREUR</strong> : votre nom et/ou votre prénom ne correspondent pas à l'identifiant INE saisi." ), array( 'form-field' => 'user_login' ) );
}
$pass1 = $pass2 = '';
if ( isset( $_POST['pass1'] ))
$pass1 = $_POST['pass1'];
if ( isset( $_POST['pass2'] ))
$pass2 = $_POST['pass2'];
if ( empty($pass1) )
$errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password.' ), array( 'form-field' => 'pass1' ) );
elseif ( empty($pass2) )
$errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password twice.' ), array( 'form-field' => 'pass2' ) );
elseif ( empty($pass1) && !empty($pass2) )
$errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass1' ) );
elseif ( !empty($pass1) && empty($pass2) )
$errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass2' ) );
/* Check for "\" in password */
elseif ( false !== strpos( stripslashes($pass1), "\\" ) )
$errors->add( 'pass', __( '<strong>ERROR</strong>: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) );
/* checking the password has been typed twice the same */
elseif ( $pass1 != $pass2 )
$errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter the same password in the two password fields.' ), array( 'form-field' => 'pass1' ) );
elseif ( strlen($pass1) < 7 )
$errors->add( 'pass', __( '<strong>ERREUR</strong> : Le mot de passe doit faire au moins 7 caractères de long.' ), array( 'form-field' => 'pass1' ) );
$_e = $errors->get_error_code();
if( empty($_e) ) {
$this->UserData2Save = array();
$this->UserData2Save['first_name'] = ucfirst($first_name) ;
$this->UserData2Save['last_name'] = strtoupper($last_name);
$this->UserData2Save['display_name'] = ucfirst($first_name);
$this->UserData2Save['user_nicename'] = ucfirst($first_name);
if ( ! empty($pass1) ) {
$this->UserData2Save['user_pass'] = $pass1;
}
}
return $errors;
}
public function register_extra_fields ($user_id) {
if( $this->UserData2Save ) {
$userdata = $this->UserData2Save;
$userdata['ID'] = $user_id;
wp_update_user($userdata);
}
}
private function register_new_user( $user_login, $user_email ) {
$errors = new WP_Error();
$sanitized_user_login = sanitize_user( $user_login );
$user_email = apply_filters( 'user_registration_email', $user_email );
// Check the username
if ( $sanitized_user_login == '' ) {
$errors->add( 'user_login', __( '<strong>ERROR</strong>: Please enter a username.' ), array( 'form-field' => 'user_login' ) );
} elseif ( ! validate_username( $user_login ) ) {
$errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ), array( 'form-field' => 'user_login' ) );
$sanitized_user_login = '';
} elseif ( username_exists( $sanitized_user_login ) ) {
$errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is already registered, please choose another one.' ), array( 'form-field' => 'user_login' ) );
}
// Check the e-mail address
if ( $user_email == '' ) {
$errors->add( 'user_email', __( '<strong>ERROR</strong>: Please type your e-mail address.' ), array( 'form-field' => 'user_email' ) );
} elseif ( ! is_email( $user_email ) ) {
$errors->add( 'user_email', __( '<strong>ERROR</strong>: The email address isn&#8217;t correct.' ), array( 'form-field' => 'user_email' ) );
$user_email = '';
} elseif ( email_exists( $user_email ) ) {
$errors->add( 'user_email', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ), array( 'form-field' => 'user_email' ) );
}
do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
$errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
if ( $errors->get_error_code() )
return $errors;
$user_pass = wp_generate_password();
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
if ( ! $user_id ) {
$errors->add( 'registerfail', sprintf( __( '<strong>ERROR</strong>: Couldn&#8217;t register you... please contact the <a href="mailto:%s">webmaster</a> !' ), get_option( 'admin_email' ) ) );
return $errors;
}
update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
wp_new_user_notification( $user_id, $user_pass );
return $user_id;
}
public function wp_footer () {
if ( self::$load_login_js ) {
wp_register_script('login', ALB_URL.'/Javascript/login.js', array('jquery-form'), '1.0', true);
wp_print_scripts('login');
$suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '.dev' : '';
wp_register_script( 'user-profile', "/wp-admin/js/user-profile$suffix.js", array('jquery'), '20100301' );
wp_register_script( 'password-strength-meter', "/wp-admin/js/password-strength-meter$suffix.js", array('user-profile'), '20100331' );
wp_localize_script( 'password-strength-meter', 'pwsL10n', array(
'empty' => __('Strength indicator'),
'short' => __('Very weak'),
'bad' => __('Weak'),
/* translators: password strength */
'good' => _x('Medium', 'password strength'),
'strong' => __('Strong'),
'mismatch' => __('Mismatch'),
'l10n_print_after' => 'try{convertEntities(pwsL10n);}catch(e){};'
) );
wp_print_scripts('password-strength-meter');
}
}
public function new_user_notification($user_id, $plaintext_pass = '') {
$user = new WP_User($user_id);
$options = get_option('apreslebac_settings');
// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$to_parse = array();
$to_parse['login'] = $user_login = stripslashes($user->user_login);
$to_parse['email'] = $user_email = stripslashes($user->user_email);
$to_parse['firstname'] = stripslashes($user->user_firstname);
$to_parse['lastname'] = stripslashes($user->user_lastname);
$to_parse['blogname'] = stripslashes($blogname);
$to_parse['password'] = '*******';
if($this->UserData2Save && !empty($this->UserData2Save['user_pass']) && $this->UserData2Save['user_pass']) {
$to_parse['password'] = stripslashes($this->UserData2Save['user_pass']);
}
/* admin notification */
$message = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
$message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";
@wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
/* user notification */
$template = Apreslebac::get_template('new-user-notification.php');
if($template !== false) {
$message = file_get_contents($template);
$message = $this->parse_template($message, $to_parse);
$subject = $this->parse_template($options['new_user_notification_subject'], $to_parse);
wp_mail($user_email, $subject, $message);
}
}
static function parse_template ($content, $data) {
foreach ($data as $name=>$value) {
$content = str_replace('['.$name.']', $value, $content);
}
return $content;
}
private function ajax_response_json( $status, $msg, $args=array() )
{
$response = array();
$response['status'] = $status;
$response['msg'] = $msg;
$args = wp_parse_args( $args, array() );
if( isset($args['status']) ) unset ($args['status']);
if( isset($args['msg']) ) unset ($args['msg']);
$response = array_merge($response, $args);
/* parses wp_error */
if( !empty($response['errors']) && is_wp_error($response['errors']) ) {
$errors = array();
$codes = $response['errors']->get_error_codes();
foreach ($codes as $code) {
$errors[$code] = $response['errors']->get_error_messages($code);
}
$response['errors'] = $errors;
}
echo json_encode($response);
die();
}
}
/**
* Notify the blog admin of a new user, normally via email.
*
* @since 2.0
*
* @param int $user_id User ID
* @param string $plaintext_pass Optional. The user's plaintext password
*/
function wp_new_user_notification($user_id, $plaintext_pass = '') {
return $GLOBALS['Apreslebac_Login']->new_user_notification($user_id, $plaintext_pass);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment