WordPress.org

Ready to get started?Download WordPress

Forums

class WP_User_Login ? (5 posts)

  1. vurentjie
    Member
    Posted 5 years ago #

    Hi,

    I decided to work with wordpress for a project at work as it had already had half of what I needed. The other part has been adding custom users and user meta, and other stuff(...),
    but also re-creating a wordpress login to deal with those users,
    what I managed to do was re-organize the wordpress login into a class, that way I can use it in a theme or in any plugin that I need to.

    Although my effort might not be ideal, something similar could greatly benefit plugin and theme development. To keep things compatible I only really re-organized the wordpress login page into a class, with settings to change the form actions, whether to use the entire page, or just the forms etc. Now I can include the file elsewhere if needed.

    This is what I did...hopefully the code will print ok:>

    <?php
    /**
     * WordPress User Page
     *
     * Handles authentication, registering, resetting passwords, forgot password,
     * and other user handling.
     *
     * @package WordPress
     */
    
    /** Make sure that the WordPress bootstrap has ran before continuing. */
    require( dirname(__FILE__) . '/wp-load.php' );
    
    if (!class_exists("WP_Users_Login")) {
    
    	class WP_Users_Login{		
    
    		var $errors,$action,$user_login,$user_email;			
    
    		function WP_Users_Login(){
    
    			if ( force_ssl_admin() &amp;&amp; !is_ssl() ) {
    				if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
    					wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
    					exit();
    				} else {
    					wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    					exit();
    				}
    			}		
    
    			$this->settings_keys = array(
    													'display','cache','backtoblog',
    													'login_action' , 'login_redirect' , 'login_url',
    													'register_action' , 'register_redirect' , 'register_url',
    													'password_action' , 'password_redirect' , 'password_url',
    													'resetpassword_redirect_newpass','resetpassword_redirect_invalidkey'
    													);		
    
    			$this->settings = array(	
    
    											/*
    
    											can set to 'default' -> the default display will be
    											(html header -> document body -> login|register|lostpass form -> page close)
    											can set to 'form' -> will only show the form part
    											can set to anything else -> must then explicitly call the form you want
    
    											*/	
    
    											'display'	=> 'default',
    											'cache'	=> 'nocache',
    											'backtoblog' => 'show',
    
    											'logout_redirect'=>'wp-login.php?loggedout=true',
    
    											'login_action' =>site_url('wp-login.php', 'login_post'),
    											'login_redirect' =>admin_url(),
    											'login_url' =>site_url('wp-login.php', 'login'),	
    
    											'register_action'=> site_url('wp-login.php?action=register', 'login_post'),
    											'register_redirect' => ( !get_option('users_can_register') ) ? 'wp-login.php?registration=disabled' : 'wp-login.php?checkemail=registered',
    											'register_url' =>site_url('wp-login.php?action=register', 'login'),											
    
    											'lostpassword_action'=>site_url('wp-login.php?action=lostpassword', 'login_post'),
    											'lostpassword_redirect'=>'wp-login.php?checkemail=confirm',
    											'lostpassword_url' =>site_url('wp-login.php?action=lostpassword', 'login'),
    
    											'resetpassword_redirect_newpass'=>'wp-login.php?checkemail=newpass',
    											'resetpassword_redirect_invalidkey'=>'wp-login.php?action=lostpassword&amp;error=invalidkey'
    
    											);
    
    			$this->errors = new WP_Error();
    			$this->action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';			
    
    			if ( isset($_GET['key']) ) $this->action = 'resetpass';
    			$this->header_info();
    			$this->relocate_defined();
    
    		}	
    
    		function log_settings($settings=false){
    
    			if(!$settings || !is_array($settings))return false;
    
    			$keys = array_keys($settings);			
    
    			foreach($keys as $k){
    
    				if(in_array($k,$this->settings_keys))$this->settings[$k] = $settings[$k];
    
    			}
    
    			return true;
    
    		}
    
    		//function login_header($title = 'Log In', $message = '', $wp_error = '') {
    		function login_header($title = 'Log In', $message = '') {
    
    			/*no need for this*/
    			//if ( empty($wp_error) )
    			//$wp_error = new WP_Error();
    
    			if('default' == $this->settings['display']){
    
    			?>
    
    				<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    				<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
    				<head>
    				<title><?php bloginfo('name'); ?> &rsaquo; <?php echo $title; ?></title>
    				<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
    
    			<?php
    
    			wp_admin_css( 'login', true );
    			wp_admin_css( 'colors-fresh', true );
    			do_action('login_head'); 
    
    			?>
    
    				</head>
    				<body class="login">
    				<div id="login"><h1><a href="<?php echo apply_filters('login_headerurl', 'http://wordpress.org/'); ?>" title="<?php echo apply_filters('login_headertitle', __('Powered by WordPress')); ?>"><?php bloginfo('name'); ?></a></h1>
    
    			<?php
    
    			if ( !empty( $message ) ) echo apply_filters('login_message', $message) . "\n";
    
    			// Incase a plugin uses $error rather than the $errors object
    			/* no need for this */
    			//if ( !empty( $error ) ) {
    				//$wp_error->add('error', $error);
    				//unset($error);
    			//}
    
    			$this->print_errors_default();
    
    			}  //END display == default
    
    		} 
    
    		function print_errors_default(){
    
    			if ( $this->errors->get_error_code() ) {
    				$err = '';
    				$messages = '';
    
    				foreach ( $this->errors->get_error_codes() as $code ) {
    					$severity = $this->errors->get_error_data($code);
    					foreach ( $this->errors->get_error_messages($code) as $error ) {
    						if ( 'message' == $severity )
    							$messages .= '	' . $error . "<br />\n";
    						else
    							$err .= '	' . $error . "<br />\n";
    					}
    				}
    					if ( !empty($err) )
    						echo '<div id="login_error">' . apply_filters('login_errors', $err) . "</div>\n";
    					if ( !empty($messages) )
    						echo '<p class="message">' . apply_filters('login_messages', $messages) . "</p>\n";
    			}
    
    		}
    
    		function print_errors_custom($how=false){
    
    			if(!$how || !is_array($how)){						
    
    				$this->print_errors_default();		
    
    			}else{
    
    				foreach ( $this->errors->get_error_codes() as $code ) {
    					$severity = $this->errors->get_error_data($code);
    					foreach ( $this->errors->get_error_messages($code) as $error ) {
    						if ( 'message' == $severity )
    							$messages .= ( array_key_exists('message_item_before',$how) ? $how['message_item_before'] : '' )
    												. $error .
    												( array_key_exists('message_item_after',$how) ? $how['message_item_after'] : '' )
    												."\n";
    						else
    							$err .= ( array_key_exists('error_item_before',$how) ? $how['error_item_before'] : '' )
    										. $error .
    										( array_key_exists('error_item_after',$how) ? $how['error_item_after'] : '' )
    										."\n";
    					}
    				}
    					if ( !empty($err) )
    						echo ( array_key_exists('error_block_start',$how) ? $how['error_block_start'] : '' )
    								. apply_filters('login_errors', $err) .
    								( array_key_exists('error_block_end',$how) ? $how['error_block_end'] : '' ) ."\n";
    
    					if ( !empty($messages) )
    						echo ( array_key_exists('message_block_start',$how) ? $how['message_block_start'] : '' )
    								. apply_filters('login_messages', $messages) .
    								( array_key_exists('message_block_end',$how) ? $how['message_block_end'] : '' ) ."\n";		
    
    			}
    
    		}
    
    		function header_info($cache=''){		
    
    			if('cache' == $this->settings['cache'] || $this->settings['display'] == 'default' ) nocache_headers();
    			header('Content-Type: '.get_bloginfo('html_type').'; charset='.get_bloginfo('charset'));		
    
    		}	
    
    		function relocate_defined(){
    
    			if ( defined('RELOCATE') ) { // Move flag is set
    
    				if ( isset( $_SERVER['PATH_INFO'] ) &amp;&amp; ($_SERVER['PATH_INFO'] != $_SERVER['PHP_SELF']) )
    						$_SERVER['PHP_SELF'] = str_replace( $_SERVER['PATH_INFO'], '', $_SERVER['PHP_SELF'] );
    
    				$schema = ( isset($_SERVER['HTTPS']) &amp;&amp; strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
    				if ( dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) != get_option('siteurl') )
    						update_option('siteurl', dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) );
    
    			}
    
    		}		
    
    		function set_cookie(){
    
    			//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);		
    
    		}	
    
    		function log_run(){		
    
    			$http_post = ('POST' == $_SERVER['REQUEST_METHOD']);		
    
    			switch ($this->action) {				
    
    				case 'logout' :
    					check_admin_referer('log-out');
    					wp_logout();
    
    					$redirect_to = $this->settings['logout_redirect'];
    					if ( isset( $_REQUEST['redirect_to'] ) )
    						$redirect_to = $_REQUEST['redirect_to'];
    						wp_safe_redirect($redirect_to);
    						exit();
    				break;	
    
    				case 'lostpassword' :
    				case 'retrievepassword' :
    
    					if ( $http_post ) {
    						$this->errors = $this->retrieve_password();
    						if ( !is_wp_error($this->errors) ) {
    							wp_redirect($this->settings['lostpassword_redirect']);
    							exit();
    						}
    					}
    
    					if ( isset($_GET['error']) &amp;&amp; 'invalidkey' == $_GET['error'] ) $this->errors->add('invalidkey', __('Sorry, that key does not appear to be valid.'));
    
    					do_action('lost_password');
    					$this->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);
    					$this->user_login = isset($_POST['user_login']) ? stripslashes($_POST['user_login']) : '';
    
    				//form-action|filter-messages
    
    					if('default' == $this->settings['display'] || 'form' == $this->settings['display']){ 
    
    						$this->password_form();
    
    					}else{
    
    					//do_action()
    					// the form will be called somewhere else for here...:>
    
    					}		
    
    				break;
    
    			////////////////////////////////////////////////////	
    
    				case 'resetpass' :
    				case 'rp' :				
    
    					$errors = $this->reset_password($_GET['key']);
    					if ( ! is_wp_error($errors) ) {
    						wp_redirect($this->settings['resetpassword_redirect_newpass']);
    						exit();
    					}
    
    					wp_redirect($this->settings['resetpassword_redirect_invalidkey']);
    					exit();
    				break;				
    
    				case 'register' :
    					if ( !get_option('users_can_register') ) {
    						//already checked for get_option in constructor -> ok
    						wp_redirect($this->settings['register_redirect']);
    						exit();
    					}
    
    					$this->user_login = '';
    					$this->user_email = '';
    
    					if ( $http_post ) {
    						require_once( ABSPATH . WPINC . '/registration.php');
    
    						$this->user_login = $_POST['user_login'];
    						$this->user_email = $_POST['user_email'];
    						$this->errors = $this->register_new_user($this->user_login, $this->user_email);
    						if ( !is_wp_error($this->errors) ) {
    
    							//already checked for get_option in constructor -> ok
    							wp_redirect($this->settings['register_redirect']);
    							exit();
    
    						}
    					}
    
    					$this->login_header(__('Registration Form'), '<p class="message register">' . __('Register For This Site') . '</p>', $errors);				
    
    					if('default' == $this->settings['display'] || 'form' == $this->settings['display']){ 
    
    						$this->register_form();
    
    					}else{
    
    					// do_action('custom_registration_form');
    					// the form will be called somewhere else for here...:>
    
    					}								
    
    				break;
    
    				case 'login' :
    				default:
    
    					$secure_cookie = '';
    
    					// If the user wants ssl but the session is not ssl, force a secure cookie.
    					if ( !empty($_POST['log']) &amp;&amp; !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 &amp;&amp; false !== strpos($redirect_to, 'wp-admin') )
    							$redirect_to = preg_replace('|^http://|', 'https://', $redirect_to);
    
    					} else {
    						//check redirect
    						$redirect_to = $this->settings['redirect_url'];  //admin_url();
    					}
    
    					if ( !$secure_cookie &amp;&amp; is_ssl() &amp;&amp; force_ssl_login() &amp;&amp; !force_ssl_admin() &amp;&amp; ( 0 !== strpos($redirect_to, 'https') ) &amp;&amp; ( 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);
    
    					//check for if user not
    					if ( !is_wp_error($user) ) {
    						// If the user can't edit posts, send them to their profile.
    						if ( !$user->has_cap('edit_posts') &amp;&amp; ( empty( $redirect_to ) || $redirect_to == 'wp-admin/' ) )
    							$redirect_to = admin_url('profile.php');
    							wp_safe_redirect($redirect_to);
    							exit();
    					}	
    
    					$this->errors = $user;
    					// Clear errors if loggedout is set.
    					if ( !empty($_GET['loggedout']) )
    						$this->errors = new WP_Error();
    
    					// If cookies are disabled we can't log in even with a valid user+pass
    					if ( isset($_POST['testcookie']) &amp;&amp; empty($_COOKIE[TEST_COOKIE]) )
    					$this->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']) &amp;&amp; TRUE == $_GET['loggedout'] )			   $this->errors->add('loggedout', __('You are now logged out.'), 'message');
    					elseif ( isset($_GET['registration']) &amp;&amp; 'disabled' == $_GET['registration'] )   $this->errors->add('registerdisabled', __('User registration is currently not allowed.'));
    					elseif ( isset($_GET['checkemail']) &amp;&amp; 'confirm' == $_GET['checkemail'] )	   $this->errors->add('confirm', __('Check your e-mail for the confirmation link.'), 'message');
    					elseif ( isset($_GET['checkemail']) &amp;&amp; 'newpass' == $_GET['checkemail'] )    $this->errors->add('newpass', __('Check your e-mail for your new password.'), 'message');
    					elseif ( isset($_GET['checkemail']) &amp;&amp; 'registered' == $_GET['checkemail'] )  $this->errors->add('registered', __('Registration complete. Please check your e-mail.'), 'message');
    
    					//login_header(__('Log In'), '', $errors);
    					if('default' == $this->settings['display'] ) $this->login_header(__('Log In'), '');
    
    					if ( isset($_POST['log']) )
    						$this->user_login = ( 'incorrect_password' == $this->errors->get_error_code() || 'empty_password' == $this->errors->get_error_code() ) ? attribute_escape(stripslashes($_POST['log'])) : '';
    
    					if('default' == $this->settings['display'] || 'form' == $this->settings['display']){ 
    
    						$this->login_form();
    
    					}else{
    
    					// the form will be called somewhere else for here...:>
    
    					}
    
    				break;
    
    			} // end action switch	
    
    		}
    
    		function password_form(){
    
    			?>
    
    				<form name="lostpasswordform" id="lostpasswordform" action="<?php echo $this->settings['lostpassword_action'] ?>" method="post">
    					<p>
    						<label><?php _e('Username or E-mail:') ?><br />
    						<input type="text" name="user_login" id="user_login" class="input" value="<?php echo attribute_escape($this->user_login); ?>" size="20" tabindex="10" /></label>
    					</p>
    						<?php do_action('lostpassword_form'); ?>
    					<p class="submit"><input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Get New Password'); ?>" tabindex="100" /></p>
    				</form>
    
    				<p id="nav">
    					<?php if (get_option('users_can_register')) : ?>
    						<a href="<?php echo $this->settings['login_url'] ?>"><?php _e('Log in') ?></a> |
    						<a href="<?php echo $this->settings['register_url'] ?>"><?php _e('Register') ?></a>
    					<?php else : ?>
    						<a href="<?php $this->settings['login_url'] ?>"><?php _e('Log in') ?></a>
    					<?php endif; ?>
    				</p>
    
    				<?php if( 'default' == $this->settings['display'] ) { ?> </div> <?php } ?>
    
    				<?php if( 'show' == $this->settings['backtoblog'] ){ ?>
    					<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 } ?>
    
    				<script type="text/javascript">
    					try{document.getElementById('user_login').focus();}catch(e){}
    				</script>
    
    				<?php if( 'default' == $this->settings['display'] ) { ?> </body></html> <?php } 			
    
    		}
    
    		function register_form(){	
    
    			?>
    
    				<form name="registerform" id="registerform" action="<?php echo $this->settings['register_action'] ?>" method="post">
    					<p>
    						<label><?php _e('Username') ?><br />
    						<input type="text" name="user_login" id="user_login" class="input" value="<?php echo attribute_escape(stripslashes($user_login)); ?>" size="20" tabindex="10" /></label>
    					</p>
    					<p>
    						<label><?php _e('E-mail') ?><br />
    						<input type="text" name="user_email" id="user_email" class="input" value="<?php echo attribute_escape(stripslashes($user_email)); ?>" size="25" tabindex="20" /></label>
    					</p>
    					<?php do_action('register_form'); ?>
    					<p id="reg_passmail"><?php _e('A password will be e-mailed to you.') ?></p>
    					<p class="submit"><input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Register'); ?>" tabindex="100" /></p>
    				</form>
    
    				<p id="nav">
    					<a href="<?php echo $this->settings['login_url'] ?>"><?php _e('Log in') ?></a> |
    					<a href="<?php echo $this->settings['lostpassword_url'] ?>" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a>
    				</p>
    
    				<?php if( 'default' == $this->settings['display'] ) { ?> </div> <?php } ?>
    
    				<?php if( 'show' == $this->settings['backtoblog'] ){ ?>
    					<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 } ?>
    
    				<script type="text/javascript">
    					try{document.getElementById('user_login').focus();}catch(e){}
    				</script>
    
    			<?php if( 'default' == $this->settings['display'] ) { ?> </body></html> <?php } 
    
    		}
    
    		function login_form(){
    
    			if ( !isset($_GET['checkemail']) || !in_array( $_GET['checkemail'], array('confirm', 'newpass') ) ) : 
    
    			?>
    
    				<form name="loginform" id="loginform" action="<?php echo $this->settings['login_action'] ?>" method="post">
    					<p>
    						<label><?php _e('Username') ?><br />
    						<input type="text" name="log" id="user_login" class="input" value="<?php echo $this->user_login; ?>" size="20" tabindex="10" /></label>
    					</p>
    					<p>
    						<label><?php _e('Password') ?><br />
    						<input type="password" name="pwd" id="user_pass" class="input" value="" size="20" tabindex="20" /></label>
    					</p>
    
    					<?php do_action('login_form'); ?>
    
    					<p class="forgetmenot"><label><input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" /> <?php _e('Remember Me'); ?></label></p>
    					<p class="submit">
    					<input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Log In'); ?>" tabindex="100" />
    					<input type="hidden" name="redirect_to" value="<?php echo attribute_escape($redirect_to); ?>" />
    					<input type="hidden" name="testcookie" value="1" />
    					</p>
    
    				</form>
    
    			<?php endif; ?>
    
    				<p id="nav">
    					<?php if ( isset($_GET['checkemail']) &amp;&amp; in_array( $_GET['checkemail'], array('confirm', 'newpass') ) ) : ?>
    					<?php elseif (get_option('users_can_register')) : ?>
    						<a href="<?php echo $this->settings['register_url'] ?>"><?php _e('Register') ?></a> |
    						<a href="<?php echo $this->settings['lostpassword_url'] ?>" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a>
    					<?php else : ?>
    						<a href="<?php echo $this->settings['lostpassword_url'] ?>" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a>
    					<?php endif; ?>
    				</p>
    
    				<?php if( 'default' == $this->settings['display'] ) { ?> </div> <?php } ?>
    
    				<?php if( 'show' == $this->settings['backtoblog'] ){ ?>
    					<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 } ?>
    
    				<script type="text/javascript">
    					<?php if ( $this->user_login ) { ?>
    						setTimeout( function(){ try{
    							d = document.getElementById('user_pass');
    							d.value = '';
    							d.focus();
    						} catch(e){
    
    						}	}, 200);
    
    					<?php } else { ?>
    
    					try{document.getElementById('user_login').focus();}catch(e){}
    
    					<?php } ?>
    				</script>
    
    				<?php if( 'default' == $this->settings['display'] ) { ?> </body></html> <?php } 
    
    		}
    
    		function retrieve_password() {
    
    			global $wpdb;
    
    			$errors = new WP_Error();
    
    			if ( empty( $_POST['user_login'] ) &amp;&amp; empty( $_POST['user_email'] ) )
    				$errors->add('empty_username', __('<strong>ERROR</strong>: Enter a username or e-mail address.'));
    
    			if ( strpos($_POST['user_login'], '@') ) {
    				$user_data = get_user_by_email(trim($_POST['user_login']));
    				if ( empty($user_data) )
    					$errors->add('invalid_email', __('<strong>ERROR</strong>: There is no user registered with that email address.'));
    			} else {
    					$login = trim($_POST['user_login']);
    					$user_data = get_userdatabylogin($login);
    			}
    
    			do_action('lostpassword_post');
    
    			if ( $errors->get_error_code() ) return $errors;
    
    			if ( !$user_data ) {
    				$errors->add('invalidcombo', __('<strong>ERROR</strong>: Invalid username or e-mail.'));
    				return $errors;
    			}
    
    			// redefining user_login ensures we return the right case in the email
    			$user_login = $user_data->user_login;
    			$user_email = $user_data->user_email;
    
    			do_action('retreive_password', $user_login);  // Misspelled and deprecated
    			do_action('retrieve_password', $user_login);
    
    			$allow = apply_filters('allow_password_reset', true, $user_data->ID);
    
    			if ( ! $allow )
    				return new WP_Error('no_password_reset', __('Password reset is not allowed for this user'));
    			else if ( is_wp_error($allow) )
    				return $allow;
    
    			$key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));
    			if ( empty($key) ) {
    				// Generate something random for a key...
    				$key = wp_generate_password(20, false);
    				do_action('retrieve_password_key', $user_login, $key);
    				// Now insert the new md5 key into the db
    				$wpdb->query($wpdb->prepare("UPDATE $wpdb->users SET user_activation_key = %s WHERE user_login = %s", $key, $user_login));
    			}
    
    				$message = __('Someone has asked to reset the password for the following site and username.') . "\r\n\r\n";
    				$message .= get_option('siteurl') . "\r\n\r\n";
    				$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
    				$message .= __('To reset your password visit the following address, otherwise just ignore this email and nothing will happen.') . "\r\n\r\n";
    				$message .= site_url("wp-login.php?action=rp&amp;key=$key", 'login') . "\r\n";
    
    				if ( !wp_mail($user_email, sprintf(__('[%s] Password Reset'), get_option('blogname')), $message) )
    				die('<p>' . __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') . '</p>');
    
    			return true;
    		}
    
    		function reset_password($key) {
    
    			global $wpdb;
    			$key = preg_replace('/[^a-z0-9]/i', '', $key);
    
    			if ( empty( $key ) )	return new WP_Error('invalid_key', __('Invalid key'));
    
    			$user = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->users WHERE user_activation_key = %s", $key));
    			if ( empty( $user ) )
    				return new WP_Error('invalid_key', __('Invalid key'));
    
    			do_action('password_reset', $user);
    
    			// Generate something random for a password...
    			$new_pass = wp_generate_password();
    			wp_set_password($new_pass, $user->ID);
    			$message  = sprintf(__('Username: %s'), $user->user_login) . "\r\n";
    			$message .= sprintf(__('Password: %s'), $new_pass) . "\r\n";
    			$message .= site_url('wp-login.php', 'login') . "\r\n";
    
    			if (  !wp_mail($user->user_email, sprintf(__('[%s] Your new password'), get_option('blogname')), $message) )
    				die('<p>' . __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') . '</p>');
    
    			wp_password_change_notification($user);
    
    			return true;
    		}
    
    		function register_new_user($user_login, $user_email) {
    
    			$errors = new WP_Error();
    
    			$user_login = sanitize_user( $user_login );
    			$user_email = apply_filters( 'user_registration_email', $user_email );
    
    			// Check the username
    			if ( $user_login == '' )
    				$errors->add('empty_username', __('<strong>ERROR</strong>: Please enter a username.'));
    				elseif ( !validate_username( $user_login ) ) {
    				$errors->add('invalid_username', __('<strong>ERROR</strong>: This username is invalid.  Please enter a valid username.'));
    				$user_login = '';
    			} elseif ( username_exists( $user_login ) )
    				$errors->add('username_exists', __('<strong>ERROR</strong>: This username is already registered, please choose another one.'));
    
    			// Check the e-mail address
    				if ($user_email == '') {
    				$errors->add('empty_email', __('<strong>ERROR</strong>: Please type your e-mail address.'));
    			} elseif ( !is_email( $user_email ) ) {
    				$errors->add('invalid_email', __('<strong>ERROR</strong>: The email address isn’t correct.'));
    				$user_email = '';
    			} elseif ( email_exists( $user_email ) )
    				$errors->add('email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.'));
    
    				do_action('register_post', $user_login, $user_email, $errors);
    
    				$errors = apply_filters( 'registration_errors', $errors );
    
    			if ( $errors->get_error_code() )
    				return $errors;
    
    			$user_pass = wp_generate_password();
    			$user_id = wp_create_user( $user_login, $user_pass, $user_email );
    			if ( !$user_id ) {
    				$this->errors->add('registerfail', sprintf(__('<strong>ERROR</strong>: Couldn’t register you... please contact the <a href="mailto:%s">webmaster</a> !'), get_option('admin_email')));
    				return $this->errors;
    
    			}
    
    			wp_new_user_notification($user_id, $user_pass);
    
    			return $user_id;
    
    		}
    
    	}
    }
    
    ?>

    Then for the default wp-login.php

    require('user_login_class.php');
    $_Login = new WP_Users_Login();
    $_Login->log_run();

    if I want to use this on another page I can do

    $dl_Learners_Login = new Learners_Users_Login();
    $settings = array(						'display'=>'form',
    'register_action'=>site_url('/','login_post').'?action=register',
    'register_url'=>site_url('/','login').'?action=register',							'login_url'=>site_url('/','login'),							'login_action'=>site_url('/','login_post'),							'backtoblog'=>'h'
    							);	
    
    	$dl_Learners_Login->log_settings($settings);
    	$dl_Learners_Login->log_run();

    Is something similar to this a reasonable request for wordpress?

  2. vurentjie
    Member
    Posted 5 years ago #

    by the way this class can replace the wp2.7 login without showing any change.

  3. vurentjie
    Member
    Posted 5 years ago #

    best to copy and paste it into an editor to view it, the column is to narrow here...and my tabs are slightly out in the post

  4. vurentjie
    Member
    Posted 5 years ago #

    minor bug in above code : in function login_form need to change the $redirect_to to $this->settings['login_redirect']

    anyway the idea is the feature request.

  5. vurentjie
    Member
    Posted 5 years ago #

    Hope nobody minds posting all this code here,
    this seems to be bug-free now...removed tabs

    <?php
    /**
    * WordPress User Login Class
    *
    * Handles authentication, registering, resetting passwords, forgot password,
    * and other user handling.
    *
    * @package WordPress
    */
    
    if (!class_exists("WP_Users_Login")) {
    
    class WP_Users_Login{		
    
    var $errors,$action,$user_login,$user_email;			
    
    function WP_Users_Login(){
    
    if ( force_ssl_admin() &amp;&amp; !is_ssl() ) {
    if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
    wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
    exit();
    } else {
    wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
    }
    }		
    
    $this->settings_keys = array(
    'display','cache','backtoblog',
    'login_action' , 'login_redirect' , 'login_url',
    'register_action' , 'register_redirect' , 'register_url',
    'password_action' , 'password_redirect' , 'password_url',
    'resetpassword_redirect_newpass','resetpassword_redirect_invalidkey'
    );		
    
    $this->settings = array(	
    
    /*
    
    can set to 'default' -> the default display will be
    (html header -> document body -> login|register|lostpass form -> page close)
    can set to 'form' -> will only show the form part
    can set to anything else -> must then explicitly call the form you want
    
    */	
    
    'display'	=> 'default',
    'cache'	=> 'nocache',
    'backtoblog' => 'show',
    
    'logout_redirect'=>'wp-login.php?loggedout=true',
    
    'login_action' =>site_url('wp-login.php', 'login_post'),
    'login_redirect' =>admin_url(),
    'login_url' =>site_url('wp-login.php', 'login'),	
    
    'register_action'=> site_url('wp-login.php?action=register', 'login_post'),
    'register_redirect' => ( !get_option('users_can_register') ) ? 'wp-login.php?registration=disabled' : 'wp-login.php?checkemail=registered',
    'register_url' =>site_url('wp-login.php?action=register', 'login'),											
    
    'lostpassword_action'=>site_url('wp-login.php?action=lostpassword', 'login_post'),
    'lostpassword_redirect'=>'wp-login.php?checkemail=confirm',
    'lostpassword_url' =>site_url('wp-login.php?action=lostpassword', 'login'),
    
    'resetpassword_redirect_newpass'=>'wp-login.php?checkemail=newpass',
    'resetpassword_redirect_invalidkey'=>'wp-login.php?action=lostpassword&amp;error=invalidkey'
    
    );
    
    $this->errors = new WP_Error();
    $this->action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';			
    
    if ( isset($_GET['key']) ) $this->action = 'resetpass';
    $this->header_info();
    $this->relocate_defined();
    
    }	
    
    function log_settings($settings=false){
    
    if(!$settings || !is_array($settings))return false;
    
    $keys = array_keys($settings);			
    
    foreach($keys as $k){
    
    if(in_array($k,$this->settings_keys))$this->settings[$k] = $settings[$k];
    
    }
    
    return true;
    
    }
    
    //function login_header($title = 'Log In', $message = '', $wp_error = '') {
    function login_header($title = 'Log In', $message = '') {
    
    /*no need for this*/
    //if ( empty($wp_error) )
    //$wp_error = new WP_Error();
    
    if('default' == $this->settings['display']){
    
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
    <head>
    <title><?php bloginfo('name'); ?> &rsaquo; <?php echo $title; ?></title>
    <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
    
    <?php
    
    wp_admin_css( 'login', true );
    wp_admin_css( 'colors-fresh', true );
    do_action('login_head'); 
    
    ?>
    
    </head>
    <body class="login">
    <div id="login"><h1><a href="<?php echo apply_filters('login_headerurl', 'http://wordpress.org/'); ?>" title="<?php echo apply_filters('login_headertitle', __('Powered by WordPress')); ?>"><?php bloginfo('name'); ?></a></h1>
    
    <?php
    
    if ( !empty( $message ) ) echo apply_filters('login_message', $message) . "\n";
    
    // Incase a plugin uses $error rather than the $errors object
    /* no need for this */
    //if ( !empty( $error ) ) {
    //$wp_error->add('error', $error);
    //unset($error);
    //}
    
    $this->print_errors_default();
    
    }  //END display == default
    
    } 
    
    function print_errors_default(){
    
    if ( $this->errors->get_error_code() ) {
    $err = '';
    $messages = '';
    
    foreach ( $this->errors->get_error_codes() as $code ) {
    $severity = $this->errors->get_error_data($code);
    foreach ( $this->errors->get_error_messages($code) as $error ) {
    if ( 'message' == $severity )
    $messages .= '	' . $error . "<br />\n";
    else
    $err .= '	' . $error . "<br />\n";
    }
    }
    if ( !empty($err) )
    echo '<div id="login_error">' . apply_filters('login_errors', $err) . "</div>\n";
    if ( !empty($messages) )
    echo '<p class="message">' . apply_filters('login_messages', $messages) . "</p>\n";
    }
    
    }
    
    function print_errors_custom($how=false){
    
    if(!$how || !is_array($how)){						
    
    $this->print_errors_default();		
    
    }else{
    
    foreach ( $this->errors->get_error_codes() as $code ) {
    $severity = $this->errors->get_error_data($code);
    foreach ( $this->errors->get_error_messages($code) as $error ) {
    if ( 'message' == $severity )
    $messages .= ( array_key_exists('message_item_before',$how) ? $how['message_item_before'] : '' )
    . $error .
    ( array_key_exists('message_item_after',$how) ? $how['message_item_after'] : '' )
    ."\n";
    else
    $err .= ( array_key_exists('error_item_before',$how) ? $how['error_item_before'] : '' )
    . $error .
    ( array_key_exists('error_item_after',$how) ? $how['error_item_after'] : '' )
    ."\n";
    }
    }
    if ( !empty($err) )
    echo ( array_key_exists('error_block_start',$how) ? $how['error_block_start'] : '' )
    . apply_filters('login_errors', $err) .
    ( array_key_exists('error_block_end',$how) ? $how['error_block_end'] : '' ) ."\n";
    
    if ( !empty($messages) )
    echo ( array_key_exists('message_block_start',$how) ? $how['message_block_start'] : '' )
    . apply_filters('login_messages', $messages) .
    ( array_key_exists('message_block_end',$how) ? $how['message_block_end'] : '' ) ."\n";		
    
    }
    
    }
    
    function header_info($cache=''){		
    
    if('cache' == $this->settings['cache'] || $this->settings['display'] == 'default' ) nocache_headers();
    header('Content-Type: '.get_bloginfo('html_type').'; charset='.get_bloginfo('charset'));		
    
    }	
    
    function relocate_defined(){
    
    if ( defined('RELOCATE') ) { // Move flag is set
    
    if ( isset( $_SERVER['PATH_INFO'] ) &amp;&amp; ($_SERVER['PATH_INFO'] != $_SERVER['PHP_SELF']) )
    $_SERVER['PHP_SELF'] = str_replace( $_SERVER['PATH_INFO'], '', $_SERVER['PHP_SELF'] );
    
    $schema = ( isset($_SERVER['HTTPS']) &amp;&amp; strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
    if ( dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) != get_option('siteurl') )
    update_option('siteurl', dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) );
    
    }
    
    }		
    
    function set_cookie(){
    
    //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);		
    
    }	
    
    function log_run(){		
    
    $http_post = ('POST' == $_SERVER['REQUEST_METHOD']);		
    
    switch ($this->action) {				
    
    case 'logout' :
    check_admin_referer('log-out');
    wp_logout();
    
    $redirect_to = $this->settings['logout_redirect'];
    if ( isset( $_REQUEST['redirect_to'] ) )
    $redirect_to = $_REQUEST['redirect_to'];
    wp_safe_redirect($redirect_to);
    exit();
    break;	
    
    case 'lostpassword' :
    case 'retrievepassword' :
    
    if ( $http_post ) {
    $this->errors = $this->retrieve_password();
    if ( !is_wp_error($this->errors) ) {
    wp_redirect($this->settings['lostpassword_redirect']);
    exit();
    }
    }
    
    if ( isset($_GET['error']) &amp;&amp; 'invalidkey' == $_GET['error'] ) $this->errors->add('invalidkey', __('Sorry, that key does not appear to be valid.'));
    
    do_action('lost_password');
    $this->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);
    $this->user_login = isset($_POST['user_login']) ? stripslashes($_POST['user_login']) : '';
    
    //form-action|filter-messages
    
    if('default' == $this->settings['display'] || 'form' == $this->settings['display']){ 
    
    $this->password_form();
    
    }else{
    
    //do_action()
    // the form will be called somewhere else for here...:>
    
    }		
    
    break;
    
    ////////////////////////////////////////////////////	
    
    case 'resetpass' :
    case 'rp' :				
    
    $errors = $this->reset_password($_GET['key']);
    if ( ! is_wp_error($errors) ) {
    wp_redirect($this->settings['resetpassword_redirect_newpass']);
    exit();
    }
    
    wp_redirect($this->settings['resetpassword_redirect_invalidkey']);
    exit();
    break;				
    
    case 'register' :
    if ( !get_option('users_can_register') ) {
    //already checked for get_option in constructor -> ok
    wp_redirect($this->settings['register_redirect']);
    exit();
    }
    
    $this->user_login = '';
    $this->user_email = '';
    
    if ( $http_post ) {
    require_once( ABSPATH . WPINC . '/registration.php');
    
    $this->user_login = $_POST['user_login'];
    $this->user_email = $_POST['user_email'];
    $this->errors = $this->register_new_user($this->user_login, $this->user_email);
    if ( !is_wp_error($this->errors) ) {
    
    //already checked for get_option in constructor -> ok
    wp_redirect($this->settings['register_redirect']);
    exit();
    
    }
    }
    
    $this->login_header(__('Registration Form'), '<p class="message register">' . __('Register For This Site') . '</p>', $errors);				
    
    if('default' == $this->settings['display'] || 'form' == $this->settings['display']){ 
    
    $this->register_form();
    
    }else{
    
    // do_action('custom_registration_form');
    // the form will be called somewhere else for here...:>
    
    }								
    
    break;
    
    case 'login' :
    default:
    
    $secure_cookie = '';
    
    // If the user wants ssl but the session is not ssl, force a secure cookie.
    if ( !empty($_POST['log']) &amp;&amp; !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 &amp;&amp; false !== strpos($redirect_to, 'wp-admin') )
    $redirect_to = preg_replace('|^http://|', 'https://', $redirect_to);
    
    } else {
    //check redirect
    $redirect_to = $this->settings['login_redirect'];  //admin_url();
    }
    
    if ( !$secure_cookie &amp;&amp; is_ssl() &amp;&amp; force_ssl_login() &amp;&amp; !force_ssl_admin() &amp;&amp; ( 0 !== strpos($redirect_to, 'https') ) &amp;&amp; ( 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);
    
    $redirect .= "?gg=".$GET['where'];
    //check for if user not
    if ( !is_wp_error($user) ) {
    
    // If the user can't edit posts, send them to their profile.
    if ( !$user->has_cap('edit_posts') &amp;&amp; ( empty( $redirect_to ) || $redirect_to == 'wp-admin/' ) )
    $redirect_to = admin_url('profile.php');
    wp_safe_redirect($redirect_to);
    exit();
    
    }	
    
    $this->errors = $user;
    // Clear errors if loggedout is set.
    if ( !empty($_GET['loggedout']) )
    $this->errors = new WP_Error();
    
    // If cookies are disabled we can't log in even with a valid user+pass
    if ( isset($_POST['testcookie']) &amp;&amp; empty($_COOKIE[TEST_COOKIE]) )
    $this->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']) &amp;&amp; TRUE == $_GET['loggedout'] )			   $this->errors->add('loggedout', __('You are now logged out.'), 'message');
    elseif ( isset($_GET['registration']) &amp;&amp; 'disabled' == $_GET['registration'] )   $this->errors->add('registerdisabled', __('User registration is currently not allowed.'));
    elseif ( isset($_GET['checkemail']) &amp;&amp; 'confirm' == $_GET['checkemail'] )	   $this->errors->add('confirm', __('Check your e-mail for the confirmation link.'), 'message');
    elseif ( isset($_GET['checkemail']) &amp;&amp; 'newpass' == $_GET['checkemail'] )    $this->errors->add('newpass', __('Check your e-mail for your new password.'), 'message');
    elseif ( isset($_GET['checkemail']) &amp;&amp; 'registered' == $_GET['checkemail'] )  $this->errors->add('registered', __('Registration complete. Please check your e-mail.'), 'message');
    
    //login_header(__('Log In'), '', $errors);
    if('default' == $this->settings['display'] ) $this->login_header(__('Log In'), '');
    
    if ( isset($_POST['log']) )
    $this->user_login = ( 'incorrect_password' == $this->errors->get_error_code() || 'empty_password' == $this->errors->get_error_code() ) ? attribute_escape(stripslashes($_POST['log'])) : '';
    
    if('default' == $this->settings['display'] || 'form' == $this->settings['display']){ 
    
    $this->login_form();
    
    }else{
    
    // the form will be called somewhere else for here...:>
    
    }
    
    break;
    
    } // end action switch	
    
    }
    
    function password_form(){
    
    ?>
    
    <form name="lostpasswordform" id="lostpasswordform" action="<?php echo $this->settings['lostpassword_action'] ?>" method="post">
    <p>
    <label><?php _e('Username or E-mail:') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo attribute_escape($this->user_login); ?>" size="20" tabindex="10" /></label>
    </p>
    <?php do_action('lostpassword_form'); ?>
    <p class="submit"><input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Get New Password'); ?>" tabindex="100" /></p>
    </form>
    
    <p id="nav">
    <?php if (get_option('users_can_register')) : ?>
    <a href="<?php echo $this->settings['login_url'] ?>"><?php _e('Log in') ?></a> |
    <a href="<?php echo $this->settings['register_url'] ?>"><?php _e('Register') ?></a>
    <?php else : ?>
    <a href="<?php $this->settings['login_url'] ?>"><?php _e('Log in') ?></a>
    <?php endif; ?>
    </p>
    
    <?php if( 'default' == $this->settings['display'] ) { ?> </div> <?php } ?>
    
    <?php if( 'show' == $this->settings['backtoblog'] ){ ?>
    <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 } ?>
    
    <script type="text/javascript">
    try{document.getElementById('user_login').focus();}catch(e){}
    </script>
    
    <?php if( 'default' == $this->settings['display'] ) { ?> </body></html> <?php } 			
    
    }
    
    function register_form(){	
    
    ?>
    
    <form name="registerform" id="registerform" action="<?php echo $this->settings['register_action'] ?>" method="post">
    <p>
    <label><?php _e('Username') ?><br />
    <input type="text" name="user_login" id="user_login" class="input" value="<?php echo attribute_escape(stripslashes($user_login)); ?>" size="20" tabindex="10" /></label>
    </p>
    <p>
    <label><?php _e('E-mail') ?><br />
    <input type="text" name="user_email" id="user_email" class="input" value="<?php echo attribute_escape(stripslashes($user_email)); ?>" size="25" tabindex="20" /></label>
    </p>
    <?php do_action('register_form'); ?>
    <p id="reg_passmail"><?php _e('A password will be e-mailed to you.') ?></p>
    <p class="submit"><input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Register'); ?>" tabindex="100" /></p>
    </form>
    
    <p id="nav">
    <a href="<?php echo $this->settings['login_url'] ?>"><?php _e('Log in') ?></a> |
    <a href="<?php echo $this->settings['lostpassword_url'] ?>" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a>
    </p>
    
    <?php if( 'default' == $this->settings['display'] ) { ?> </div> <?php } ?>
    
    <?php if( 'show' == $this->settings['backtoblog'] ){ ?>
    <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 } ?>
    
    <script type="text/javascript">
    try{document.getElementById('user_login').focus();}catch(e){}
    </script>
    
    <?php if( 'default' == $this->settings['display'] ) { ?> </body></html> <?php } 
    
    }
    
    function login_form(){
    
    if ( !isset($_GET['checkemail']) || !in_array( $_GET['checkemail'], array('confirm', 'newpass') ) ) : 
    
    ?>
    
    <form name="loginform" id="loginform" action="<?php echo $this->settings['login_action'] ?>" method="post">
    <p>
    <label><?php _e('Username') ?><br />
    <input type="text" name="log" id="user_login" class="input" value="<?php echo $this->user_login; ?>" size="20" tabindex="10" /></label>
    </p>
    <p>
    <label><?php _e('Password') ?><br />
    <input type="password" name="pwd" id="user_pass" class="input" value="" size="20" tabindex="20" /></label>
    </p>
    
    <?php do_action('login_form'); ?>
    
    <p class="forgetmenot"><label><input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" /> <?php _e('Remember Me'); ?></label></p>
    <p class="submit">
    <input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Log In'); ?>" tabindex="100" />
    
    <input type="hidden" name="redirect_to" value="<?php echo attribute_escape($this->settings['login_redirect'].'?where='.$this->settings['login_redirect']); ?>" />
    <input type="hidden" name="testcookie" value="1" />
    </p>
    
    </form>
    
    <?php endif; ?>
    
    <p id="nav">
    <?php if ( isset($_GET['checkemail']) &amp;&amp; in_array( $_GET['checkemail'], array('confirm', 'newpass') ) ) : ?>
    <?php elseif (get_option('users_can_register')) : ?>
    <a href="<?php echo $this->settings['register_url'] ?>"><?php _e('Register') ?></a> |
    <a href="<?php echo $this->settings['lostpassword_url'] ?>" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a>
    <?php else : ?>
    <a href="<?php echo $this->settings['lostpassword_url'] ?>" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a>
    <?php endif; ?>
    </p>
    
    <?php if( 'default' == $this->settings['display'] ) { ?> </div> <?php } ?>
    
    <?php if( 'show' == $this->settings['backtoblog'] ){ ?>
    <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 } ?>
    
    <script type="text/javascript">
    <?php if ( $this->user_login ) { ?>
    setTimeout( function(){ try{
    d = document.getElementById('user_pass');
    d.value = '';
    d.focus();
    } catch(e){
    
    }	}, 200);
    
    <?php } else { ?>
    
    try{document.getElementById('user_login').focus();}catch(e){}
    
    <?php } ?>
    </script>
    
    <?php if( 'default' == $this->settings['display'] ) { ?> </body></html> <?php } 
    
    }
    
    function retrieve_password() {
    
    global $wpdb;
    
    $errors = new WP_Error();
    
    if ( empty( $_POST['user_login'] ) &amp;&amp; empty( $_POST['user_email'] ) )
    $errors->add('empty_username', __('<strong>ERROR</strong>: Enter a username or e-mail address.'));
    
    if ( strpos($_POST['user_login'], '@') ) {
    $user_data = get_user_by_email(trim($_POST['user_login']));
    if ( empty($user_data) )
    $errors->add('invalid_email', __('<strong>ERROR</strong>: There is no user registered with that email address.'));
    } else {
    $login = trim($_POST['user_login']);
    $user_data = get_userdatabylogin($login);
    }
    
    do_action('lostpassword_post');
    
    if ( $errors->get_error_code() ) return $errors;
    
    if ( !$user_data ) {
    $errors->add('invalidcombo', __('<strong>ERROR</strong>: Invalid username or e-mail.'));
    return $errors;
    }
    
    // redefining user_login ensures we return the right case in the email
    $user_login = $user_data->user_login;
    $user_email = $user_data->user_email;
    
    do_action('retreive_password', $user_login);  // Misspelled and deprecated
    do_action('retrieve_password', $user_login);
    
    $allow = apply_filters('allow_password_reset', true, $user_data->ID);
    
    if ( ! $allow )
    return new WP_Error('no_password_reset', __('Password reset is not allowed for this user'));
    else if ( is_wp_error($allow) )
    return $allow;
    
    $key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));
    if ( empty($key) ) {
    // Generate something random for a key...
    $key = wp_generate_password(20, false);
    do_action('retrieve_password_key', $user_login, $key);
    // Now insert the new md5 key into the db
    $wpdb->query($wpdb->prepare("UPDATE $wpdb->users SET user_activation_key = %s WHERE user_login = %s", $key, $user_login));
    }
    
    $message = __('Someone has asked to reset the password for the following site and username.') . "\r\n\r\n";
    $message .= get_option('siteurl') . "\r\n\r\n";
    $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
    $message .= __('To reset your password visit the following address, otherwise just ignore this email and nothing will happen.') . "\r\n\r\n";
    $message .= site_url("wp-login.php?action=rp&amp;key=$key", 'login') . "\r\n";
    
    if ( !wp_mail($user_email, sprintf(__('[%s] Password Reset'), get_option('blogname')), $message) )
    die('<p>' . __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') . '</p>');
    
    return true;
    }
    
    function reset_password($key) {
    
    global $wpdb;
    $key = preg_replace('/[^a-z0-9]/i', '', $key);
    
    if ( empty( $key ) )	return new WP_Error('invalid_key', __('Invalid key'));
    
    $user = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->users WHERE user_activation_key = %s", $key));
    if ( empty( $user ) )
    return new WP_Error('invalid_key', __('Invalid key'));
    
    do_action('password_reset', $user);
    
    // Generate something random for a password...
    $new_pass = wp_generate_password();
    wp_set_password($new_pass, $user->ID);
    $message  = sprintf(__('Username: %s'), $user->user_login) . "\r\n";
    $message .= sprintf(__('Password: %s'), $new_pass) . "\r\n";
    $message .= site_url('wp-login.php', 'login') . "\r\n";
    
    if (  !wp_mail($user->user_email, sprintf(__('[%s] Your new password'), get_option('blogname')), $message) )
    die('<p>' . __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') . '</p>');
    
    wp_password_change_notification($user);
    
    return true;
    }
    
    function register_new_user($user_login, $user_email) {
    
    $errors = new WP_Error();
    
    $user_login = sanitize_user( $user_login );
    $user_email = apply_filters( 'user_registration_email', $user_email );
    
    // Check the username
    if ( $user_login == '' )
    $errors->add('empty_username', __('<strong>ERROR</strong>: Please enter a username.'));
    elseif ( !validate_username( $user_login ) ) {
    $errors->add('invalid_username', __('<strong>ERROR</strong>: This username is invalid.  Please enter a valid username.'));
    $user_login = '';
    } elseif ( username_exists( $user_login ) )
    $errors->add('username_exists', __('<strong>ERROR</strong>: This username is already registered, please choose another one.'));
    
    // Check the e-mail address
    if ($user_email == '') {
    $errors->add('empty_email', __('<strong>ERROR</strong>: Please type your e-mail address.'));
    } elseif ( !is_email( $user_email ) ) {
    $errors->add('invalid_email', __('<strong>ERROR</strong>: The email address isn’t correct.'));
    $user_email = '';
    } elseif ( email_exists( $user_email ) )
    $errors->add('email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.'));
    
    do_action('register_post', $user_login, $user_email, $errors);
    
    $errors = apply_filters( 'registration_errors', $errors );
    
    if ( $errors->get_error_code() )
    return $errors;
    
    $user_pass = wp_generate_password();
    $user_id = wp_create_user( $user_login, $user_pass, $user_email );
    if ( !$user_id ) {
    $this->errors->add('registerfail', sprintf(__('<strong>ERROR</strong>: Couldn’t register you... please contact the <a href="mailto:%s">webmaster</a> !'), get_option('admin_email')));
    return $this->errors;
    
    }
    
    wp_new_user_notification($user_id, $user_pass);
    
    return $user_id;
    
    }
    
    }
    }
    
    ?>

    It can then be used in a plugin with a better example like this...

    add_action('get_sidebar', 'Learners_Users_Login');
    
    function Learners_Users_Login(){
    
    //require_once(admin_url"learners-users-login.php");
    require_once(ABSPATH.'/wp-includes/class.wp-user-login.php');
    $dl_Learners_Login = new WP_Users_Login();
    add_action('get_header',create_function('', 'global $dl_Learners_Login; $dl_Learners_Login->login_scripts();'));	
    
    $settings = array(
    'display'	=> '',
    'cache'	=> 'cache',
    'backtoblog' => 'hidden',
    
    'logout_redirect'=>site_url('/','login_post').'?loggedout=true',
    
    'login_action' =>site_url('/','login_post'),
    'login_redirect' =>site_url('/'),
    'login_url' =>site_url('/','login'),	
    
    'register_action'=> site_url('/','login_post').'?action=register', 'login_post',
    'register_redirect' => ( !get_option('users_can_register') ) ? site_url().'?registration=disabled' : site_url().'?checkemail=registered',
    'register_url' =>site_url('/','login').'?action=register', 'login',											
    
    'lostpassword_action'=>site_url('/','login_post').'?action=lostpassword',
    'lostpassword_redirect'=>site_url('/','').'?checkemail=confirm',
    'lostpassword_url' =>site_url('/','login').'?action=lostpassword',
    
    'resetpassword_redirect_newpass'=>site_url('/','').'?checkemail=newpass',
    'resetpassword_redirect_invalidkey'=>site_url('/','').'?action=lostpassword&amp;error=invalidkey'
    
    );	
    
    $dl_Learners_Login->log_settings($settings);
    $dl_Learners_Login->log_run();
    
    if(is_user_logged_in() &amp;&amp; current_user_can('write_learners_tests')){
    ?>
    
    <a href="<?php echo wp_logout_url(site_url('/')) ?>" style='background:#000;color:#fff;' title="<?php _e('Log Out') ?>"><?php _e('Log Out'); ?></a></p>
    
    <?php
    
    }else{
    
    $dl_Learners_Login->errors->add('permission', __('You do not have permisson to log in to this site.'),'message');
    wp_nonce_url( site_url("wp-login.php?action=logout&amp;redirect_to='.site_url('/').'", 'login'), 'log-out' );
    
    }
    
    $how = array(
    'message_item_before' =>'<li>',
    'message_item_after' =>'</li>',
    'error_item_before' =>'<li>',
    'error_item_after' =>'</li>',
    'message_block_start' =>'<ul>',
    'message_block_end' =>'</ul>',
    'error_block_start' =>'<ul>',
    'error_block_end' =>'</ul>',
    
    );
    
    $dl_Learners_Login->print_errors_custom($how);
    $dl_Learners_Login->login_form();
    $dl_Learners_Login->register_form();
    $dl_Learners_Login->password_form();
    
    }

    It would be real nice to have better control in plugins to work with users customization....

    i believe i have now probably abused this post. anyway...hope that somebody out there can second this idea...

Topic Closed

This topic has been closed to new replies.

About this Topic