<?php

#######################################################
# set adminpath
#  gets adminpath from stored config file
#######################################################
function set_adminpath()
 {
    if (file_exists("./config.txt"))
     {
        $fpath="./config.txt";
        $f = fopen ($fpath, "r");
        $line = explode("|",fread($f,filesize($fpath)));
        $adminpath = $line[1];
        fclose($f);
     }
     else
     {
        return 0;
     }
    
    if ($adminpath=="")
     {
        return 0;
     }

    $_SESSION['adminpath']=trim($adminpath);

    return 1;
 }

############################################################
# check_cookie
#  automatically logs the user in and configures settings
############################################################
function check_cookie()
{
	get_sl_settings();

	if (isset($_SESSION['user_id'])) {return;}
       
	if ((isset($_COOKIE['token']))&&(!isset($_POST['actAs'])))
	{
		$token=$_COOKIE['token'];
		session_login("","",$token);
    	}
}

#######################################################
# get_sl_settings
#  gets general information for utility functions
#######################################################
function get_sl_settings()
{
	## Set league ID
	if (isset($_GET['league_id'])) {$_SESSION['lgid']=$_GET['league_id'];unset($_SESSION['lgname']);}
	elseif (isset($_GET['lgid'])) {$_SESSION['lgid']=$_GET['lgid'];unset($_SESSION['lgname']);}

	## Get PHP Version
	if (isset($_SESSION['configerr'])) {unset($_SESSION['configerr']);}
	$phpver=phpversion();
	$phpver=$phpver[0];

	## Load Admin Path
	if (!set_adminpath())
	{
		$_SESSION['configerr']="ERROR: OOTP SQL Utilities not configured properly (no config.txt)";
	}
    
	##### Load Utility Configuration #####
	include($_SESSION['adminpath']."/dbopen.php");
    ## Check if admin table exists
	$query="SHOW TABLES LIKE 'ootp_sql_admin';";
    $result=mysqli_query($db, $query);
	if (mysqli_num_rows($result)) 
   	{
		$query="SELECT * FROM ootp_sql_admin WHERE module='admin' AND scope='ALL';";
	 	$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result)) 
		{
			while ($row=mysqli_fetch_array($result))
	     		{
				$field=$row['setting'];
		   		$val=$row['value'];
		   		switch ($field)
				{
				case 'HTMLRoot'    : $_SESSION['htmlroot']=$val;    break;
				case 'HTMLPath'    : $_SESSION['htmlpath']=$val;    break;
				case 'ServerURL'   : $_SESSION['serverurl']=$val;   break;
				case 'StatsLabPath': $_SESSION['StatsLabPath']=$val;break;
				case 'timezone'    : $tzone=$val;                   break;
				case 'noCache'     : $noCache=$val;                 break;
				case 'priLgID'     : $lgid=$val;                    break;
				case 'Ratings'     : $_SESSION['Ratings']=$val;     break;
				case 'Talents'     : $_SESSION['Talents']=$val;     break;
				case 'Others'      : $_SESSION['Others']=$val;      break;
				}
	     		}
			$_SESSION['lgpath']=$_SESSION['serverurl'].$_SESSION['htmlpath'];
	      		if (($tzone!="")&&($phpver>4)) {date_default_timezone_set($tzone);;}
			if ($noCache==1) {$_SESSION['noCache']=1;} else {unset($_SESSION['noCache']);}
	      		if (!isset($_SESSION['lgid'])) {$_SESSION['lgid']=$lgid;unset($_SESSION['lgname']);}
		}
	}
   	else
	{
	 	if (!isset($_SESSION['configerr']))
		{
	      		$_SESSION['configerr']="ERROR: OOTP SQL Utilities not configured properly (no ootp_sql_admin table)";
		}
   	}
     
	##### Check league name and date #####
	if ((!isset($_SESSION['lgname'])) || (!isset($_SESSION['lgdate'])) || (!isset($_SESSION['lgyear'])))
    	{
	  	if ((!isset($_SESSION['lgid']))||($_SESSION['lgid']=="")) {$_SESSION['lgid']=100;}
		$query="SHOW TABLES LIKE 'leagues';";
	  	$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
	 	{
			$query="SELECT name,leagues.current_date,season_year as year FROM leagues WHERE league_id=".$_SESSION['lgid']." GROUP BY leagues.current_date;";
	 		if ($_GET['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);
	 		$row=mysqli_fetch_array($result);
			$_SESSION['lgname']=$row[0];
			$_SESSION['lgdate']=$row[1];
			$_SESSION['lgyear']=$row['year'];
		}
	}
	mysqli_close($db);
}




#######################################################
# session login
#  performs the login check and configures cookie
#######################################################
function session_login($userid="",$password="",$token="",$actAs="")
{
	if ($actAs=="") {$actAs=-1;}

	include($_SESSION['adminpath']."/dbopen.php");

	if ($token!="")    ## Process token
	{
		$query="SELECT human_manager_id FROM ootp_sql_users WHERE token='$token';";
		if ($_POST['showq']==1) {echo "$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))     ## Successful login
		{
			$row=mysqli_fetch_array($result);
			$userid=$row['human_manager_id'];
	
			$query="SELECT first_name,last_name,is_commish,team_id,league_id FROM human_managers WHERE human_manager_id=$userid";
			if ($_POST['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);
			$row=mysqli_fetch_array($result);

			# Configure session variables
			$_SESSION['user_id']=$userid;
			$_SESSION['username']=$row['first_name']." ".$row['last_name'];
			$_SESSION['user_is_commish']=$row['is_commish'];
			$_SESSION['user_league_id']=$row['league_id'];
			if (($row['league_id']>0)&&(!isset($_SESSION['lgid']))) {$_SESSION['lgid']=$row['league_id'];}
			$_SESSION['user_team_id']=$row['team_id'];
			if (isset($_SESSION['user_was_commish'])) {$_SESSION['user_is_commish']=1;}

			$loginSuccess=1;

			# Check for StatsLab commish access
			$query="SELECT setting,value FROM ootp_sql_admin WHERE module='users' AND setting IN ('commish','hideScores','showScores') AND identifier=$userid ORDER BY setting";
			if ($_POST['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);
			if (mysqli_num_rows($result))
			{
				while ($row=mysqli_fetch_array($result))
				{
					$setting=$row['setting'];
					$val=$row['value'];

					switch ($setting)
					{
					case 'commish':
						if ($val==1) {$_SESSION['user_is_commish']=1;}
						break;
					case 'hideScores':
						if ($val==1) {$_SESSION['hideScores']=1;}
						break;
					case 'showScores':
						if ($val==1) {unset($_SESSION['hideScores']);}
						break;
					}
				}
			}

			# Update token
			$now=time();
			$curDate=strftime("%Y-%m-%d",$now);

			$ip=get_ip_address();

			$token = bin2hex(random_bytes(32));
			$query="INSERT INTO ootp_sql_users (human_manager_id, ip_address, last_date, token) VALUES ($userid, '$ip', '$curDate', '$token') ON DUPLICATE KEY UPDATE token='$token', last_date='$curDate'";
			if ($_POST['showq']==1) {echo "$query<br/>\n";}
			mysqli_query($db,$query);

			# Store token to cookie
			$days=7;
			$expire=60*60*24*$days;
			$expire+=time();
			setcookie("token","",time()-1440);    #expire old cookie
			setcookie("token",$token,$expire);    #set new cookie

			##Log Login
			$query="INSERT INTO ootp_sql_admin (scope,module,setting,identifier,value) VALUES (";
			$query.="'ALL','admin','Last Login','".$_SESSION['user_id']."','".$now."') ON DUPLICATE KEY UPDATE value='$now';";
			if ($_POST['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);
		}
	}
	else               ## Process user/password combo
	{
		$escapedPW = mysqli_real_escape_string($db,$password);
		
		$query = "SELECT value as salt FROM  ootp_sql_admin WHERE setting='salt' AND identifier = $userid;";
		if ($_POST['showq']==1) {echo "$query<br/>\n";}
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			$row=mysqli_fetch_array($result);
			$saltedPW =  $escapedPW . $row['salt'];
			$hashedPW = hash('sha256', $saltedPW);

			$query = "SELECT identifier as human_manager_id FROM ootp_sql_admin WHERE identifier=$userid AND setting='password' AND value='$hashedPW'; ";
			if ($_POST['showq']==1) {echo "$query<br/>\n";}
			$result=mysqli_query($db,$query);
			if ((mysqli_num_rows($result))||($actAs==1))     ## Successful login
			{
				$query="SELECT first_name,last_name,is_commish,team_id,league_id FROM human_managers WHERE human_manager_id=$userid";
				if ($_POST['showq']==1) {echo "$query<br/>\n";}
				$result=mysqli_query($db,$query);
				$row=mysqli_fetch_array($result);

				# Configure session variables
				$_SESSION['user_is_commish']=$row['is_commish'];
				if ($actAs==1)
				{
					if (!isset($_SESSION['user_was_commish'])) {$_SESSION['user_was_commish']=$_SESSION['user_id'];}
					$_SESSION['user_is_commish']=1;
				}
				$_SESSION['user_id']=$userid;
				$_SESSION['username']=$row['first_name']." ".$row['last_name'];
				$_SESSION['user_league_id']=$row['league_id'];
				if ($row['league_id']>0) {$_SESSION['lgid']=$row['league_id'];}
				$_SESSION['user_team_id']=$row['team_id'];
	
				# Check for StatsLab commish access
				$query="SELECT setting,value FROM ootp_sql_admin WHERE module='users' AND setting IN ('commish','hideScores','showScores') AND identifier=$userid ORDER BY setting";
				if ($_POST['showq']==1) {echo "$query<br/>\n";}
				$result=mysqli_query($db,$query);
				if (mysqli_num_rows($result))
				{
					while ($row=mysqli_fetch_array($result))
					{
						$setting=$row['setting'];
						$val=$row['value'];

						switch ($setting)
						{
						case 'commish':
							if ($val==1) {$_SESSION['user_is_commish']=1;}
							break;
						case 'hideScores':
							if ($val==1) {$_SESSION['hideScores']=1;}
							break;
						case 'showScores':
							if ($val==1) {unset($_SESSION['hideScores']);}
							break;
						}
					}
				}
	
				# Create/Save Token
				$now=time();
				$curDate=strftime("%Y-%m-%d",$now);
	
				$ip=get_ip_address();
	
				$token = bin2hex(random_bytes(32));
				$query="INSERT INTO ootp_sql_users (human_manager_id, ip_address, last_date, token) VALUES ($userid, '$ip', '$curDate', '$token') ON DUPLICATE KEY UPDATE token='$token', last_date='$curDate'";
				if ($_POST['showq']==1) {echo "$query<br/>\n";}
				mysqli_query($db,$query);

				# Store token to cookie
				$days=7;
				$expire=60*60*24*$days;
				$expire+=time();
				setcookie("token","",time()-1440);    #expire old cookie
				setcookie("token",$token,$expire);    #set new cookie

				##Log Login
			  	$query="INSERT INTO ootp_sql_admin (scope,module,setting,identifier,value) VALUES (";
				$query.="'ALL','admin','Last Login','".$_SESSION['user_id']."','".$now."') ON DUPLICATE KEY UPDATE value='$now';";
				if ($_POST['showq']==1) {echo "$query<br/>\n";}
			  	$result=mysqli_query($db,$query);

				$loginSuccess=1;
			}
			else  ## Unsuccessful login
			{
				$loginSuccess=0;
			}
		}
		else {$loginSuccess=0;}
	}

	mysqli_close($db);

	if ($loginSuccess==0) {$_SESSION['loginerror'].="LOGIN FAILED";clear_session();}

	return $loginSuccess;
}


#######################################################
# clear_session
#  clears session variables used by StatsLab for auth
#######################################################
function clear_session()
{
	unset($_SESSION['user_id']);
	unset($_SESSION['username']);
	unset($_SESSION['user_is_commish']);
	unset($_SESSION['user_was_commish']);
	unset($_SESSION['user_team_id']);
	unset($_SESSION['lgname']);
	unset($_SESSION['lgdate']);
	unset($_SESSION['lgyear']);
	unset($_SESSION['hideScores']);
	setcookie("token","",time()-1440);    #expire old cookie
}

#######################################################
# get_ip_address
#  returns the client IP address
#######################################################
function get_ip_address() {
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                    return $ip;
                }
            }
        }
    }
}
?>