<?php
#--------------------------------------------------------------
# program:    login.php
#
# written by:    John Phillips on 3/5/2003
#
# description:    This script will login a user and transfer them to main.php
#
# call as:    login.php  receiving userNum, pw (password)
#
# revisions:    
# 2003.03.05    Latest version 
#--------------------------------------------------------------

require( 'common.php' );

function 
ValidateUser$user$pw$YSP )
{

  
$q "SELECT userId, first, last, password FROM ${YSP}user WHERE login = '$user'";
  if( !( 
$qResult MYSQL_QUERY$q ) ) )
  {
    die( 
"Database error during ValidateUser routine. Please try again later..." );
  }
  if( (
$qRow MYSQL_FETCH_ARRAY$qResult )) && $pw == $qRow['password'] && $pw != "" )
  {
    
$userId $qRow['userId'];
    return 
$userId;
  }
  else
  { 
    die( 
"Invalid user login or password: $user" ); 
  }
}

function 
CreateSession$userId$YSP 
{
  
# Generate a random 32 character session id from a 62 character pool

  
srand( (double) microtime() * 1000000 );
  
$pool "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for( 
$index 0$index 32$index++ )
  {
    
$sessionString .= substr$pool, ( rand() % 62 ), 1);
  }

  
# Insert a new session record
  
$q "INSERT INTO ${YSP}session ( sessionId, userId, sessionString, timeStamp ) ";
  
$q.= "values ( NULL, '$userId', '$sessionString', NULL )";
  
MYSQL_QUERY$q ) || die( "could not create session: $q" );

  
# Insert a new log record
  
$q "INSERT INTO ${YSP}log ( logId, userId, timeStamp, inOut ) ";
  
$q.= "values ( NULL, $userId, NULL, 'i' )";
  
MYSQL_QUERY$q ) || die( "could not insert new log record: $q" );

  return( 
$sessionString );
}

# *********************************************************************
# ***** The script starts here and then calls the functions above *****

# Check that all of the form fields have data.
$user $_REQUEST['user'];
$pw $_REQUEST['pw'];

if( empty(
$user) or empty($pw) )
{
  
# echo "u=$user and pw=$pw\n";
  
die( "You are missing some required information. Press the back button and check your form." );
}

$userId 0

SqlStart();
$userId ValidateUser$user$pw$YSP );

$sessionString CreateSession$userId$YSP );

# Session must be good so start main page and pass our sessionString to it.
header("Location:main.php?sessionString=$sessionString" );

?>