<?php 
function userIsLoggedIn(){
	if(isset($_POST['action']) and 
	$_POST['action']=='login'){
		if(!isset($_POST['email']) or 
		$_POST['email']=='' or 
		!isset($_POST['password']) or
		$_POST['password']==''){
			$GLOBALS['loginError']='Please fill in both fields.';
			return false;
		}//if empty fields...
		$password=md5($_POST['password'].'poems');
		if(databaseContainsSender($_POST['email'],$password)){
			session_start();
			$_SESSION['loggedIn']=TRUE;
			$_SESSION['email']=$_POST['email'];
			$_SESSION['password']=$password;
			return TRUE;
		}else{
			session_start();
			unset($_SESSION['loggedIn']);
			unset($_SESSION['email']);
			unset($_SESSION['password']);
			$GLOBALS['loginError']='The specified email address or password was incorrect.';
			return FALSE;
		}
	}//if isset action and action=login
	
	if(isset($_POST['action'])and 
	$_POST['action']=='logout'){
		session_start();
		unset($_SESSION['loggedIn']);
		unset($_SESSION['email']);
		unset($_SESSION['password']);
		header('location:'.$_POST['goto']);
		exit();
	}
	session_start();
	if(isset($_SESSION['loggedIn'])){
		return databaseContainsSender(
		$_SESSION['email'],$_SESSION['password']);
	}
}//function userIsLoggedIn

function userHasRole($role){
	include 'db.inc.php';
	try{
		$sql='select count(*) from sender 
		inner join senderrole on sender.id=senderid
		inner join role on roleid=role.id
		where email=:email and role.id=:roleid';
		$s=$pdo->prepare($sql);
		$s->bindValue(':email',$_SESSION['email']);
		$s->bindValue(':roleid',$role);
		$s->execute();
	}
	catch(PDOException $e){
		$error='Error searching for sender role.';
		include 'error.html.php';
		exit();
	}
	$row=$s->fetch();
	if($row[0]>0){
		return TRUE;
	}else{
		return FALSE;
	}
}//function userHasRole

function databaseContainsSender($email, $password){
	include 'db.inc.php';
	
	try{
		$sql='select count(*) from sender 
		where email=:email and password=:password';
		$s=$pdo->prepare($sql);
		$s->bindValue(':email',$email);
		$s->bindValue(':password',$password);
		$s->execute();
	}catch(PDOException $e){
		$error='Error searching for sender.';
		include 'error.html.php';
		exit();
	}
	$row=$s->fetch();
	
	if($row[0]>0){
		return TRUE;
	}else{
		return FALSE;
	}
}//function databaseContainsSender


