<?php
	/**
	 * Icon Captcha Plugin: v2.5.0
	 * Copyright © 2017, Fabian Wennink (https://www.fabianwennink.nl)
	 * patches and customizations: @3G
	 *
	 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
	 */

	// Start a PHP session.

	session_start();

	// Include the captcha classes.
	require(dirname(__FILE__).'/../include/captcha-session.class.php');
	require(dirname(__FILE__).'/../include/captcha.class.php');
#	require(dirname(__FILE__).'/../config/config.php');
	require('/etc/cprot-captcha/config.php');

	IconCaptcha::setIconsFolderPath(dirname(__FILE__).'/../icons/');
	IconCaptcha::setIconNoiseEnabled(true);

	// HTTP GET - Requesting the actual image.
	if((isset($_GET['hash']) && strlen($_GET['hash']) === 48) &&
		(isset($_GET['cid']) && is_numeric($_GET['cid'])) && !isAjaxRequest())
	{
		ic_check_remote_ip();
		IconCaptcha::getIconFromHash($_GET['hash'], $_GET['cid']);
		exit;
	}

	// HTTP POST - Either the captcha has been submitted or an image has been selected by the user.
	if(!empty($_POST) && isAjaxRequest())
	{
		if(isset($_POST['rT']) && is_numeric($_POST['rT']) && isset($_POST['cID']) && is_numeric($_POST['cID']))
		{
			switch((int)$_POST['rT'])
			{
				case 1: // Requesting the image hashes
					ic_check_remote_ip(true);
					$captcha_theme = (isset($_POST['tM']) && ($_POST['tM'] === 'light' || $_POST['tM'] === 'dark')) ? $_POST['tM'] : 'light';

					// Echo the JSON encoded array
					header('Content-type: application/json');
					exit(IconCaptcha::getCaptchaData($captcha_theme, $_POST['cID']));
				case 2: // Setting the user's choice
					ic_check_remote_ip();
					if(IconCaptcha::setSelectedAnswer($_POST))
					{
						sleep(1);

						if ($CONFIG['session']['timeout']==0)
						{
							$sto=NULL;
							$slto=time()+86400;
						}
						else
						{
							$sto=time()+$CONFIG['session']['timeout'];
							$slto=$sto;
						}
						if (array_key_exists('session', $CONFIG) && array_key_exists('secret', $CONFIG['session']))
						{
							//do nginx secure link
							$sl_raw = $slto . " " . $CONFIG['session']['secret'] . " " . $_SERVER['REMOTE_ADDR'];
							$sl_token = rtrim(strtr(base64_encode(md5($sl_raw, true)), '+/', '-_'), '=');
							setcookie('_vis_prot', $sl_token, $sto, '/');
							setcookie('_vis_prot_expires', $slto, $sto, '/');
						}
						else
						{
							setcookie($CONFIG['session']['name'], $CONFIG['session']['value'], $sto, "/");
						}
						header('HTTP/1.0 200 OK');
						exit;
					}
					else
					{
						sleep(5);
					}
					break;
				default:
					break;
			}
		}
	}

	header('HTTP/1.1 400 Bad Request');
	exit;

	// Adds another level of security to the Ajax call.
	// Only requests made through Ajax are allowed.
	// NOTE: THE HEADER CAN BE SPOOFED
	function isAjaxRequest() {
		return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
	}

	// extra protection @3G: check IP address in session
	function ic_check_remote_ip($init=false)
	{
		if (array_key_exists('remote_ip', $_SESSION))
		{
			if ($_SESSION['remote_ip'] != $_SERVER['REMOTE_ADDR'])
			{
				header('HTTP/1.1 400 Bad Request');
				exit;
			}
		}
		else
		{
			if ($init)
			{
				$_SESSION['remote_ip']=$_SERVER['REMOTE_ADDR'];
			}
			else
			{
				header('HTTP/1.1 400 Bad Request');
				exit;
			}
		}
	}
