<?php
/*
|--------------------------------------------------------------------------
| 								AGELOCK V1.3
|--------------------------------------------------------------------------
|--------------------------------------------------------------------------
| Set Ages
|--------------------------------------------------------------------------
|
| $agelock_minimum_age_in_years is the lowest age that a user should be and 
| still be allow to enter. $agelock_maximum_age_in_years is the oldest age 
| that a user should be allowed to enter. 
| 
| At least one of these setting should be set to a number. If one of these 
| variable is not required it should be set to null;
|
| Examples
|
| $agelock_settings['minimum_age_in_years']  	= 	18; 	// user must be 18+ and 
| $agelock_settings['maximum_age_in_years'] 	= 	100;	// younger than 100
|
| $agelock_settings['minimum_age_in_years']  	= 	13; 	// user must be 13+ 
| $agelock_settings['maximum_age_in_years'] 	= 	null;	// 
|
| $agelock_settings['minimum_age_in_years'] 	= 	null; 	// user must be under 30 
| $agelock_settings['maximum_age_in_years'] 	= 	30;		// years old
*/
$agelock_settings['minimum_age_in_years'] 	= 	18; 	// null if not needed
$agelock_settings['maximum_age_in_years'] 	= 	null; // null if not needed

/*
|--------------------------------------------------------------------------
| Installed Folder
|--------------------------------------------------------------------------
|
| This installed_folder variable holds the location where you have saves the 
| agelock to, probably something like http://www.yoursite.com/agelock/
| REMEMBER you need to include the http://www and the forward slash at the end
|
*/

$agelock_settings['installed_folder']	=	'http://'.$SETTINGS['licenseDomainName'].'/agelock/';

/*
|--------------------------------------------------------------------------
| Title / Subtitle / Description
|--------------------------------------------------------------------------
| 
| 
*/
$agelock_settings['title']			=	 "Hi There!";
$agelock_settings['subtitle']		=	 "You must be over 18 to view this site";
$agelock_settings['description']	=	 "";

/*
|--------------------------------------------------------------------------
| Simple Check Mode
|--------------------------------------------------------------------------
|
| If you simply require that the user clicks either of two button to 
| confirm they are the correct age to be grated access should be set to 
| true. If this is not required this should be set to false.
|
| This setting will override setting for day month year order.
|
*/
$agelock_settings['simple_check']		= 	true;

/*
|--------------------------------------------------------------------------
| Day Month Year Order
|--------------------------------------------------------------------------
|
| The order that the day month and the year are displayed to the user can 
| be set in any order by using a 3 character code. d is day, m is month 
| (Jan), M is also month (January) and y is year.
| 
| Examples
| 'dmy'				- 28 Feb 2000
| 'mdy'				- Feb 28 2000
| 'Mdy'				- February 28 2000
| 'yMd'				- 2000 February 28
| 
| if date selectors are displayed to the user a heading/title will also be 
| displayed if dmy_heading is set.
|
*/
$agelock_settings['dmy_order'] 			= 	'dmy';
$agelock_settings['dmy_heading']		=	 "Please enter your date of birth";

/*
|--------------------------------------------------------------------------
| Terms and Conditions
|--------------------------------------------------------------------------
|
| Terms and Conditions are optional with Agelock.
| if t_and_c is set to null; none of the T&C features will be 
| displayed to the user. If t_and_c is set to something other than
| null; then t_and_c_heading will display a title/heading for the
| T&Cs and t_and_c_error will display to the user if the user does 
| not agree to the T&Cs.
|
*/
$agelock_settings['t_and_c'] 			=	null;
$agelock_settings['t_and_c_heading']	= 	"<h4>Terms and Conditions</h4>";
$agelock_settings['t_and_c_error']		=	"<center><p class='alert alert-error'>Terms and Conditions checkbox has not been checked.</p></center>";
	
/*
|--------------------------------------------------------------------------
| Success Page
|--------------------------------------------------------------------------
|
| When the user has successfully passed the AgeLock test the user will be 
| automatically redirected to the success_page. The success_page needs to 
| be set with the full website address (including http://www.)
|
| if the user has been redirect to the AgeLock system while attempting to 
| view another page they will be automatically directed back to that page 
| unless continue_browsing is set to false;
|
| if the user fails the AgeLock test and failure_page is set to a URL 
| (including http://www.) then the user will be redirected to that page.
|
*/
$agelock_settings['success_page']		=	'http://www.murraysbrewingco.com.au/index.php';
$agelock_settings['continue_browsing']	= 	true;
$agelock_settings['failure_page']		= 	'';

/*
|--------------------------------------------------------------------------
| Year Select / Drop-down Options
|--------------------------------------------------------------------------
|
| The dropbox / Selector for the users birth year has two settings. If 
| starting_year_offset is set to 10 and the current year is 2013 the default
| year that the user will see on the date of birth selector will be 2003.
|
| number_of_years_to_show if set to 100 will allow the user to select any
| year between this the current year and 100 years ago   
|
*/
$agelock_settings['starting_year_offset'] 	= 10;
$agelock_settings['number_of_years_to_show'] = 100;

/*
|--------------------------------------------------------------------------
| Error Message
|--------------------------------------------------------------------------
|
| If the user fails the agelock test they will be blocked from locked pages
| and will be shown the error message below  
|
*/
$agelock_settings['error_message'] 	= "<center><p class='alert alert-error'>You are not the correct age to access this site.</p></center>";

/*
|--------------------------------------------------------------------------
| Allow Search Engines / Bots / Spiders and set IP Addresses through
|--------------------------------------------------------------------------
|
| If set to true search engines, bots and spiders will be not need to pass 
| the agelock system. This is also true for IP Addresses if they are set in 
| the allow_spiders_and_ips function below the "Do not edit below here" 
| line.
|
*/
$agelock_settings['allow_spiders_and_ips']	= "true";

/*
|--------------------------------------------------------------------------
| Expire Session
|--------------------------------------------------------------------------
|
| If set to 3 the user will need to repass the agelock test after 3 hours of 
| browsing the site. If set to null; once the agelock test has been passed 
| the user will not need to repass the test until they close their browser 
| and try and visit the site again. Although many browsers ignore this 
| meaning that a user may only see the AgeLock test once if 
| expire_session_in_hours is set to null; For testing '0.033' is 2 mins.
*/
$agelock_settings['expire_session_in_hours']= '240';

/*
|--------------------------------------------------------------------------
| Theme
|--------------------------------------------------------------------------
|
| There are many built in themes available; light, dark, amelia, cerulean, 
| cosmo, cyborg, journal, flatly, readable, simplex, slate, spacelab, 
| superhero, united, and custom.
| custom is a very bare theme made for you to tweak and add your own styling
| to.	
| 
*/
$agelock_settings['theme'] = 'custom';

/*
|--------------------------------------------------------------------------
| Timezone
|--------------------------------------------------------------------------
| 
| 99% of installers do not need to change this. This only needs setting to 
| fix a small date related bug around user living on "the wrong side" of 
| the international date line. This should be set to the best city for your 
| sites timezone, see php.net timezone documentation. 
|
*/
$agelock_settings['time_zone']	=	 "Australia/Sydney";

/*
|--------------------------------------------------------------------------
| Date Errors
|--------------------------------------------------------------------------
| 
| When using the date selector / dropdowns it is possible to enter dates 
| that do not exist, like 30th Feb. If the user enters a nonexisting date 
| the following message will be displayed. 
|
*/
$agelock_settings['date_error'] = "<center><p class='alert alert-error'>Date entered is not a valid date.</p></center>";

/*
|--------------------------------------------------------------------------
| Character Set
|--------------------------------------------------------------------------
| 
| The AgeLock age verification form can include text set by you. If you are
| using non-latin characters or wish to change Character Encoding set them 
| below to something like UTF-8, UTF-16 or ISO-8859-1  
|
*/
$agelock_settings['charset'] = "UTF-8";

/*
|--------------------------------------------------------------------------
| Joomla install
|--------------------------------------------------------------------------
| 
| If AgeLock is being used on a Joomla powered website set as true if not 
| leave as false. If true and Joomla is not installed in your root directory
| you will also need to set the joomla_install_directory, this is the folder
| path that Joomla is installed in. For example if Joomla is installed at
| http://www.example.com/joomla/ then joomla_install_directory = "joomla";
| if Joomla is installed at http://www.impossiblepanda.com/test/joomla/ 
| then joomla_install_directory = "test/joomla";
|
*/
$agelock_settings['joomla'] = false;
$agelock_settings['joomla_install_directory'] = "";

/*
|--------------------------------------------------------------------------
| Others not yet fully documented
|--------------------------------------------------------------------------
|
|
*/
$agelock_settings['debug'] = false;





/*
***************************************************************************
*  Do not edit below here - (unless you know what you're doing) 
***************************************************************************
*/

start_or_reset_agelock_session($agelock_settings);
date_default_timezone_set($agelock_settings['time_zone']);
agelock_page($agelock_settings);


// displays Yes and No buttons and a hidden timestamp
function display_simple_check($agelock_settings)
{
	if($agelock_settings['simple_check'] == true)
	{
		$time = time();
		echo "<center>	
				<input type='hidden' value='$time' name='timestamp' />
				<button class='btn btn-large btn-primary' type='submit' name='simple-yes' value='yes'>Yes</button>
				<button class='btn btn-large btn-primary' type='submit' name='simple-no' value='no'>No</button>
			  </center>";
	}	
}



// displays the select/dropbox day month year to the user
function display_date_selectors($agelock_settings) {

	if($agelock_settings['simple_check'] != true)
	{
		// setup the days of the month
		$day_selector_options = "
		<select name=\"day\" required  class=\"input-medium\" >
		  <option value='01'>01</option>
		  <option value='02'>02</option>
		  <option value='03'>03</option>
		  <option value='04'>04</option>
		  <option value='05'>05</option>
		  <option value='06'>06</option>
		  <option value='07'>07</option>
		  <option value='08'>08</option>
		  <option value='09'>09</option>
		  <option value='10'>10</option>
		  <option value='11'>11</option>
		  <option value='12'>12</option>
		  <option value='13'>13</option>
		  <option value='14'>14</option>
		  <option value='15'>15</option>
		  <option value='16'>16</option>
		  <option value='17'>17</option>
		  <option value='18'>18</option>
		  <option value='19'>19</option>
		  <option value='20'>20</option>
		  <option value='21'>21</option>
		  <option value='22'>22</option>
		  <option value='23'>23</option>
		  <option value='24'>24</option>
		  <option value='25'>25</option>
		  <option value='26'>26</option>
		  <option value='27'>27</option>
		  <option value='28'>28</option>
		  <option value='29'>29</option>
		  <option value='30'>30</option>
		  <option value='31'>31</option>
		</select>";
		
		// setup the months - short format
		$mon_selector_options = "
		<select name=\"month\" required class=\"input-medium\" >
		  <option value='01'>" .  "Jan" . "</option>
		  <option value='02'>" .  "Feb" . "</option>
		  <option value='03'>" .  "Mar" . "</option>
		  <option value='04'>" .  "Apr" . "</option>
		  <option value='05'>" .  "May" . "</option>
		  <option value='06'>" .  "Jun" . "</option>
		  <option value='07'>" .  "Jul" . "</option>
		  <option value='08'>" .  "Aug" . "</option>
		  <option value='09'>" .  "Sep" . "</option>
		  <option value='10'>" .  "Oct" . "</option>
		  <option value='11'>" .  "Nov" . "</option>
		  <option value='12'>" .  "Dec" . "</option>
		</select>";
		
		// setup the months - long format
		$month_selector_options = "
		<select name=\"month\" required class=\"input-medium\" >
		  <option value='01'>January</option>
		  <option value='02'>February</option>
		  <option value='03'>March</option>
		  <option value='04'>April</option>
		  <option value='05'>May</option>
		  <option value='06'>June</option>
		  <option value='07'>July</option>
		  <option value='08'>August</option>
		  <option value='09'>September</option>
		  <option value='10'>October</option>
		  <option value='11'>November</option>
		  <option value='12'>December</option>
		</select>";

		// setup the years
		$year_selector_options = "<select name=\"year\" required class=\"input-medium\" >";
		$year = date('Y');
		$starting_year = $year - $agelock_settings['number_of_years_to_show'];
		$default_year = $year - $agelock_settings['starting_year_offset'];

		while($year >= $starting_year)
		{
			if($year == $default_year)
			{
				$year_selector_options = $year_selector_options . "<option value='$year' selected=\"selected\">$year</option>";
			}
			else
			{
				$year_selector_options = $year_selector_options . "<option value='$year'>$year</option>";
			}
			$year--;
		}		  	  
		$year_selector_options = $year_selector_options . "</select>";


		// Check that $agelock_dmy_order has been set correctly
		if( strlen($agelock_settings['dmy_order']) == 3
			&& stristr($agelock_settings['dmy_order'], 'd') 
			&& stristr($agelock_settings['dmy_order'], 'm')
			&& stristr($agelock_settings['dmy_order'], 'y')
		)
		{	
			// dmy_order set correctly
			$day_position = stripos($agelock_settings['dmy_order'], "d");
			if ($day_position !== false)
			{
	    			$dmy_order_array[$day_position] = $day_selector_options;
			}
	
			$month_position = strpos($agelock_settings['dmy_order'], "m");
			if ($month_position !== false)
			{
	    			$dmy_order_array[$month_position] = $mon_selector_options;
			}
	
			$month_position = strpos($agelock_settings['dmy_order'], "M");
			if ($month_position !== false)
			{
	    			$dmy_order_array[$month_position] = $month_selector_options;
			}
	
			$year_position = stripos($agelock_settings['dmy_order'], "y");
			if ($year_position !== false)
			{
	    			$dmy_order_array[$year_position] = $year_selector_options;
			}
	
		}
		else 	// dmy_order has NOT been set correctly. So we use the default d m y
		{
			echo "<!-- agelock_dmy_order was not correctly set, default order has been used -->";
			$dmy_order_array = array($day_selector_options,$mon_selector_options,$year_selector_options);
		}
		// show dmy heading - of there is one set
		echo "<h4>".$agelock_settings['dmy_heading']."</h4>";
		// show dmy select/drop downs
		echo "$dmy_order_array[0] $dmy_order_array[1] $dmy_order_array[2]";		
	}

}



// remembers the user and redirects to the corect page
function set_session_and_redirect($agelock_settings,$birthday =null) {
    if($agelock_settings['joomla'])
    {
		$session =& JFactory::getSession();
		$session->set('agelock', true);
		$session->set('birthday', $birthday);
		$session->set('timestamp', time());	    
    }
    else
    {	
		$_SESSION['agelock'] =  true;
		$_SESSION['birthday'] = $birthday;
		$_SESSION['timestamp'] = time();	    
    }

  	if($_GET['ref'] != null && $agelock_settings['continue_browsing'] == true )
  	{
		$actual_link =  str_replace("!!!amp;!!!", "&", $_GET['ref']);
		echo " <meta http-equiv='refresh' content='0;url=".$actual_link."' /> "; 	
  	}
  	else
  	{
		echo " <meta http-equiv='refresh' content='0;url=".$agelock_settings['success_page']." ' /> ";
	}
}



// Starts or resets the user session - required to remember the user
function start_or_reset_agelock_session($agelock_settings) { // HTTP_CLIENT_IP
  session_name( "agelock".md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR']));
  session_id( "agelock".md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']));  
  session_start();
  
	if($agelock_settings['joomla'])
	{
		define( '_JEXEC', 1 );
		define( 'JPATH_BASE', $_SERVER['DOCUMENT_ROOT']."/".$agelock_settings['joomla_install_directory']);
		define( 'DS', DIRECTORY_SEPARATOR );
		
		
		// Check users Joomla Settings
		if(!file_exists( JPATH_BASE .DS.'includes'.DS.'defines.php'))
		{
			die("AgeLock Error: Joomla not found in directory");
			exit;
		}
				
		require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
		require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

		$mainframe =& JFactory::getApplication('site');
		$mainframe->initialise();
	}

  if(isset($_GET['resetagelock']))
  {
	if($agelock_settings['joomla'])
	{
	    $session =& JFactory::getSession();
	    $session->set('agelock', null);
	    $session->set('timestamp', null);
	    $session->set('birthday', null);
    }
    else
    {
	    $_SESSION['agelock'] = false;
	    unset($_SESSION['agelock']);  
    }
  }
}

function expired_session($agelock_settings) {
	if($agelock_settings['expire_session_in_hours'] != null)
	{
	    if($agelock_settings['joomla'])
	    {
		   $session =& JFactory::getSession();
		   $session_timestamp = $session->get('timestamp'); 
	    }
	    else
	    {
		    $session_timestamp = $_SESSION['timestamp'];
	    }

		if(isset($session_timestamp))
		{
			$basetime = $session_timestamp;
		}
		else
		{
			$basetime = 0;
		}
//		echo " basetime:$basetime ";
		if($basetime+($agelock_settings['expire_session_in_hours']*3600) < time() )
		{
			return true;
		}
	}
	return false;
}

// blocks unvalidation users
function agelock_page($agelock_settings) {
	if(!isset($agelock_settings['agelock_main_page']))
	{
		if ( detect_spiders_and_ips($agelock_settings) == false )
		{
	    	if($agelock_settings['joomla'])
	    	{
		    	$session =& JFactory::getSession();
				//var_dump($session);
				$session_agelock = $session->get('agelock');
	    	}
	    	else
	    	{
		    	$session_agelock = $_SESSION['agelock'];
	    	}

		 	// test non spiders	
		 	if(isset($session_agelock) && $session_agelock == null
		 	 || expired_session($agelock_settings) || !isset($session_agelock) )
			{
				//redirect
				/*** check for https ***/
				$protocol = check_HTTPS();
				/*** return the full address ***/
				$actual_link =  $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
				// convert &s so that variable can be used later
				$actual_link =  str_replace("&", "!!!amp;!!!", $actual_link);
				
				header( "Location:".$agelock_settings['installed_folder']."?ref=$actual_link" ) ;
				exit();
			}
		}
	}
}

function check_HTTPS() {
    if(!empty($_SERVER['HTTPS']))
        if($_SERVER['HTTPS'] !== 'off')
            return 'https'; //https
        else
            return 'http'; //http
     else
        if($_SERVER['SERVER_PORT'] == 443)
            return 'https'; //https
        else
            return 'http'; //http
}



// this allows google, bing and others access to your protected pages without redirecting them to the AgeLock screen 
function  detect_spiders_and_ips($agelock_settings) {
	if($agelock_settings['allow_spiders_and_ips'] == true)
	{
		// list of bots, or partial bots names
		$spiders_array = array("bot","crawler","msnbot","teoma","Spider", "googlebot", "scooter", "seeker","yahoo","addthis");
		foreach ($spiders_array as $spider) 
		{
			if (stripos($_SERVER["HTTP_USER_AGENT"], $spider) !== false)
		 	{
			 	return true;
			}
		}
		
		// you can also add an IP address to the below array, this will allow access to your protected pages without redirecting them to the AgeLock screen 
		$ip_array = array("67.195.115.105","207.46.199.50","207.46.199.32");
		foreach ($ip_array as $ip_from_list)
		{		
			if($_SERVER["REMOTE_ADDR"] == $ip_from_list)
			{
				return true;			
			}
		}
	}	
	return false;
}


// displays the T&C if set - with a check box
function display_terms_and_conditions($agelock_settings) {
	if($agelock_settings['t_and_c'] != null)
	{
		echo $agelock_settings['t_and_c_heading']."
			<div class='t_and_c'>
				<p>".$agelock_settings['t_and_c']."</p>
			</div>
			<label class='checkbox'>
				<input type='checkbox' value='agree' name='agree' > I agree.
			</label>";
	}		
}


// display the Enter button - with a hidden timestamp
function display_button($agelock_settings) {
	if($agelock_settings['simple_check'] != true)
	{	
		$time = time();
		echo "
			<input type='hidden' value='$time' name='timestamp' />
			<button class='btn btn-large btn-primary' type='submit' name='submit' value='submit'>Enter</button>		
			";
	}		
}




function process_form($agelock_settings) {

	if(isset($_POST['submit']) || isset($_POST['simple-yes']) || isset($_POST['simple-no']))  
	{
		$agree = $simpleyes = $simpleno = null;
		if($agelock_settings['simple_check'] != true)
		{
			$day_from_submit 	= $_POST["day"];
			$month_from_submit	= $_POST["month"];
			$year_from_submit 	= $_POST["year"];
			$birthday 			= strtotime("00:00:01 ". $_POST["day"]."-".$_POST["month"]."-".$_POST["year"]);		
		}
	
		$timestamp 			= $_POST["timestamp"];
		$current_time		= time();
		
		if(isset($_POST["agree"]))
		{
			$agree 				= $_POST["agree"];	
		}
				
		if(isset($_POST["simple-no"]))
		{
			$simpleno 			= $_POST["simple-no"];			
		}
		if(isset($_POST["simple-yes"]))
		{
			$simpleyes			= $_POST["simple-yes"];			
		}
				
		$process_form 		= true;	// variable is reset if processing tests fail

		// if terms and conditions have been set, check that agree checkbox has been ticked
		if($agelock_settings['t_and_c'] != null )
		{
			if($agree != "agree")
			{
				echo $agelock_settings['t_and_c_error'];
				$process_form = false;
			}
		}
		
		// if date of birth is given check that date exists - eg. not 30th of Feb
		if( $agelock_settings['simple_check'] != true && !checkdate($month_from_submit,$day_from_submit,$year_from_submit) )
		{
			echo $agelock_settings['date_error'];
			$process_form = false;
		}
		
		// if form has taken more than one second or less than 30mins/1800 seconds. Process.
		if( ($timestamp < $current_time-1 || $timestamp+1800 < $current_time) && $agelock_settings['simple_check'] == true && $process_form == true )
		{
			if($simpleyes == "yes")
			{
				set_session_and_redirect($agelock_settings);
			}
			if($simpleno == "no")
			{
				validation_failed($agelock_settings);
			}
						
		}
			
		// if form has taken more than one second or less than 30mins/1800 seconds. Process.
		if( ($timestamp < $current_time-1 || $timestamp+1800 < $current_time) && $agelock_settings['simple_check'] != true && $process_form == true)
		{
			
			$lower_age_limit = strtotime("-".$agelock_settings['minimum_age_in_years']." years");
			$higher_age_limit = strtotime("-".$agelock_settings['maximum_age_in_years']." years");
			
			if($lower_age_limit != false && $higher_age_limit != false) // if upper and lower limits are set
			{
				if($birthday < $lower_age_limit && $birthday > $higher_age_limit)
				{
					set_session_and_redirect($agelock_settings,$birthday);
				}
				else
				{
					validation_failed($agelock_settings);
				}			
			}
			
			if($lower_age_limit != false && $higher_age_limit == false) // if lower limit is set
			{
				if($birthday < $lower_age_limit)
				{
					set_session_and_redirect($agelock_settings,$birthday);
				}
				else
				{
					validation_failed($agelock_settings);
				}			
			}	
			
			if($lower_age_limit == false && $higher_age_limit != false) // if higher limit is set
			{
				if($birthday > $higher_age_limit)
				{
					set_session_and_redirect($agelock_settings,$birthday );
				}
				else
				{
					validation_failed($agelock_settings);
				}			
			}						
		}
	}
}

function validation_failed($agelock_settings) {
	if( strtolower(substr($agelock_settings['failure_page'], 0, 4)) == "http" )
	{
		// redirect
		echo " <meta http-equiv='refresh' content='0;url=".$agelock_settings['failure_page']."' /> ";
	}
	else
	{
		// error message
		echo $agelock_settings['error_message'];		
	}
	
}

function get_bootswatch_theme($agelock_settings) {
	if($agelock_settings['theme'] == "default")
	{
		echo "<link href='assets/bootstrap/css/bootstrap.min.css' rel='stylesheet'>";			
	}
	else
	{
		echo "<link href='assets/bootstrap/css/".strtolower($agelock_settings['theme'])."-bootstrap.min.css' rel='stylesheet'>";		
	}
}

function agelock_debug($agelock_settings){
	if($agelock_settings['debug'] == true)
	{
		echo "<pre><h2>Debugger</h2>";
		echo "<h3>agelock_settings details</h3>";
		var_dump($agelock_settings);
		echo "<h3>Session Cookie details</h3>";	
		var_dump($session);
		echo "<h3>Document Root</h3>";
		var_dump($_SERVER['DOCUMENT_ROOT']);
		echo "</pre>";
	}	
}

?>