<?php
if (!defined('SECRET_KEY')){ header("HTTP/1.0 404 Not Found"); exit; }

###
###  Basic Layout Class
###

class userManagement {

	var $_logged_in;
    var $_user_id = '';
    var $_user_name = '';

	var	$_status;
	var $_iPad = false;
	var $_Mobile = false;

	var $_readonly = false;

	function userManagement(){

        ### Check for end device
		$this->_Mobile = detectAppleMobile();
		$this->_iPad = detectAppleMobile("iPad");

		### Std Login 
	    if( isset($_POST['sublogin-std-alone']) && check_admin_referer( 'std_login_page' ) )
			$this->login();
			
		### iPhone Login 
	    if( isset($_POST['iphonelogin']) && check_ajax_referer( 'login' ) )
			$this->login();
		
		### Catch illegit PW Reset Req
		if (!empty($_POST['pw']) && !$this->_logged_in )
			check_admin_referer( 'pwreset_page' );
			
		$this->_logged_in = $this->checkLogin();

 		### Logout button
		if(  isset($_POST['sublogout']) && check_ajax_referer( 'logout', true, $this->_user_name ) ){
			$this->logout();
		}
		
	}



	function logout( $silent=false ){

	    if( isset($_COOKIE['rSname']) && isset($_COOKIE['rSpass']) ){
			setcookie('rSname', '', time()-60*60*24*100, "/");
			setcookie('rSpass', '', time()-60*60*24*100, "/");
	    }

	    if(  $this->_logged_in  ){
	        unset($_SESSION['username']);
	        unset($_SESSION['password']);

			$this->_logged_in	= false;
			$this->_readonly    = false;

			if(session_id())
				session_destroy();
	        $_SESSION = array();
				
	        if( !$silent )
				die ( __('You have successfully <strong>logged out</strong>.','recipeshelf').'|1|' );
	    } else {
			if( !$silent )
	        	die ( __('You are not currently logged in, logout failed.','recipeshelf').'|0|' );
		}
		
    }

	function generatePassword($length=9, $strength=0) {
		$vowels = 'aeuy';
		$consonants = 'bdghjmnpqrstvz';
		if ($strength & 1) {
			$consonants .= 'BDGHJLMNPQRSTVWXZ';
		}
		if ($strength & 2) {
			$vowels .= "AEUY";
		}
		if ($strength & 4) {
			$consonants .= '23456789';
		}
		if ($strength & 8) {
			$consonants .= '@#$%';
		}

		$password = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$password .= $consonants[(rand() % strlen($consonants))];
				$alt = 0;
			} else {
				$password .= $vowels[(rand() % strlen($vowels))];
				$alt = 1;
			}
		}
		return $password;
	}

	function registration(){
	    $err='';

		$user_i = _rem_magic_quote( $_POST['user'] );
		$pass_i = _rem_magic_quote( $_POST['pass'] );
	    
		if( !$user_i || !$pass_i )
	      $err = __('You didn\'t fill in a <strong>required</strong> field.','recipeshelf');

	    $user_i = trim($user_i);

	    if( strlen($user_i) > 30 )
	      $err = __('Please <strong>shorten</strong> the username it.','recipeshelf');

	    if( $this->usernameTaken($user_i) ){
	      $use = $user_i;
	      $err = __('Username:','recipeshelf') . ' <strong>'.esc_html($use).'</strong> '. __('is already taken, please pick another one.','recipeshelf');
	    }

	    if( $err=='' ){
	        $md5pass = md5($pass_i);
	        $_SESSION['reguname']   = $user_i;
	        $_SESSION['regresult']  = $this->addNewUser($user_i, $md5pass, '');
	        $_SESSION['registered'] = true;

	        $temp = $_SESSION['regresult'];

	        unset($_SESSION['reguname']);
	        unset($_SESSION['registered']);
	        unset($_SESSION['regresult']);

	        if( $temp )
	            $this->returnAjaxResult(1,__('Registered! Please login now.','recipeshelf'));
	        else
	            $this->returnAjaxResult(0,__('Registration failed.','recipeshelf'));

	    }
	    else
	        $this->returnAjaxResult(0,$err);
    }


	function login(){
		
		$user_i = _rem_magic_quote( $_POST['user'] );
		$pass_i = _rem_magic_quote( $_POST['pass'] );
		
	    if( $user_i=='' || $pass_i=='' )
	    	return $this->returnAjaxResult(0,__('You didn\'t fill in a <strong>required</strong> field.','recipeshelf'));

	    $user_i = trim($user_i);
	    
	    if(strlen($user_i) > 30)
	    	return $this->returnAjaxResult(0,__('Please <strong>shorten</strong> the username.','recipeshelf'));

	    $md5pass = md5( $pass_i );
		$result  = $this->confirmUser( $user_i, $md5pass);

	    if( $result == 1 )
	    	return $this->returnAjaxResult(0,__('That username <strong>doesn\'t exist</strong> in our database.','recipeshelf'));
	    else if( $result == 2 )
	    	return $this->returnAjaxResult(0,__('<strong>Incorrect password</strong>, please try again.','recipeshelf'));

			
		### new info
	    $_SESSION['username'] = $user_i;
	    $_SESSION['password'] = $md5pass;

        $this->_user_name = $user_i;

	    if(isset($_POST['remember'])){
	        setcookie("rSname", $user_i, time()+60*60*24*100, "/"); ###cookie are always set with slashes in mag.quot.!
	        setcookie("rSpass", $_SESSION['password'], time()+60*60*24*100, "/");
	    }
		
	    return $this->returnAjaxResult(1,__('Welcome back','recipeshelf'). ' <strong>'.esc_html($_SESSION['username']).'</strong>.');

    }


	function checkLogin(){

		if( isset($_COOKIE['rSname']) && isset($_COOKIE['rSpass']) ){
	      $_SESSION['username'] = _rem_magic_quote( $_COOKIE['rSname'] );
	      $_SESSION['password'] = _rem_magic_quote( $_COOKIE['rSpass'] );
          $this->_user_name 	= $_SESSION['username'];
		}
	   
		$ss_user = $_SESSION['username'];
		$ss_pass = $_SESSION['password'];
		
		
		#echo "DO CONFIRM = ".$ss_user.' | '.$ss_pass.'<br/>'; //debug
		if( $ss_user!='' && $ss_pass!='' ){

			$result = $this->confirmUser($ss_user, $ss_pass);

			if( $result != 0 ){
								
				unset($_SESSION['username']);
				unset($_SESSION['password']);
				setcookie('rSname', '', time()-60*60*24*100, "/");
				setcookie('rSpass', '', time()-60*60*24*100, "/");

				$this->_user_name	= '';
				return false;
			}
			return true;
		}
		else
		  return false;

	}


	function checkUser($username){
		global $rSdb;

		//if( !get_magic_quotes_gpc() )
		  //$username = addslashes($username);

		$q = "SELECT object, setting FROM {$rSdb->DBobjects} WHERE object = '".esc_sql($username)."'";
		$result	= $rSdb->fetch($q);
		$user	= mysql_fetch_array($result);

		//user found?
		if(!$result || (mysql_numrows($result) < 1))
			return 0;
		else{
			if( $user[setting]=='readonly' )
				$this->_readonly = true;
		    return 1;
  		}
	}
	

	function confirmUser($username, $password){

	    global $rSdb;

		### Quick install check!
		if( ! $rSdb->InstallCheck()  )
			return 1;
 				
		### Only for rS DB version < v1.0
		if( version_compare($rSdb->getDBVersion(), '1.0') < 0 ){
			$rSdb->_version_check = true;
			$PASSWD_COL = 'type';
		} else
			$PASSWD_COL = 'uid';

		#echo "USERNAME 4 sql: ".esc_html($username);
		
		$q = "SELECT * FROM {$rSdb->DBobjects} WHERE object = '".esc_sql( ($username) )."'";
		$result = $rSdb->fetch($q);
		$dbarray = mysql_fetch_array($result);

//echo "<br>".$password."<br>".$dbarray[$PASSWD_COL]; //debug

		if(!$result || (mysql_numrows($result) < 1) || $dbarray['object']!=$username ){
			return 1;
		}

		$dbpw =  $dbarray[$PASSWD_COL];
		$inpw =  $password ;
		
		### Valid User?
		if( $inpw == $dbpw ){
		
			$this->_user_id = $dbarray['id'];

			### Only for rS DB >= v1.0
			if( $dbarray['setting']=='readonly' )
					$this->_readonly = true;
		}

		return ($inpw == $dbpw) ? 0:2;
	}


	function usernameTaken($username){
	   global $rSdb;

	   //if( !get_magic_quotes_gpc() )
	   //   $username = addslashes($username);

	   $q = "SELECT object FROM {$rSdb->DBobjects} WHERE object = '".esc_sql($username)."'";
	   $result = $rSdb->fetch($q);

       return ( mysql_numrows($result) > 0 );
	}


	function addNewUser($username, $password, $setting){
	   global $rSdb;
	   $q = "INSERT INTO {$rSdb->DBobjects} (type,object,uid,setting) VALUES ('','".esc_sql($username)."','".esc_sql($password)."','".esc_sql($setting)."')";
	   return $rSdb->fetch($q);
	}

	function updatePW($username, $password){
		global $rSdb;

		$q = "SELECT object FROM {$rSdb->DBobjects} WHERE object = '".esc_sql($username)."' ";
		$result = $rSdb->fetch($q);

		if( mysql_numrows($result) > 0 ){
		    $password = md5($password);
			$q = "UPDATE {$rSdb->DBobjects} SET uid='".esc_sql($password)."' WHERE object='".esc_sql($username)."'";
			$Rupdate = $rSdb->fetch($q);
			
			if($Rupdate){
				### update session
			    $_SESSION['password'] = $password;
		        setcookie("rSname", $_SESSION['username'], time()+60*60*24*100, "/");
		        setcookie("rSpass", $_SESSION['password'], time()+60*60*24*100, "/");
			}

	   		return $Rupdate;
	   }
	   return false;
	}

	function returnAjaxResult($flag, $t){
		// for iphone only ajax request!
    	if( $this->_Mobile && !$this->_iPad ){
	        echo $flag.'|'.$t;
	        die();
        }else
        	$this->_status=$t;

        return $flag;
	}


}
?>