<?php

/**
 * This file is part of an ADDON for use with LEPTON Core.
 * This ADDON is released under the GNU GPL.
 * Additional license terms can be seen in the info.php of this module.
 *
 *
 *	@module			captcha
 *	@version		see info.php of this module
 *	@authors		LEPTON Project, W. Studer
 *	@copyright		2020-2021 LEPTON Project
 *	@link			https://lepton-cms.org
 *	@license		http://www.gnu.org/licenses/gpl.html
 *	@license_terms	please see info.php of this module
 *	@platform		see info.php of this module
 *
 *
 */
 
// include class.secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/class.secure.php' );}
if (defined('LEPTON_PATH')) {	
	include LEPTON_PATH.SEC_FILE;
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.SEC_FILE))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.SEC_FILE)) { 
		include $root.SEC_FILE;   
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include class.secure.php


// Evaluate the captcha
function get_captcha( $kind, $length = 5, $type = "alphanum" )
{
	// init
	$captcha = array();

	// evaluate captcha
	switch( $kind )
	{
		case "calc":
			mt_srand((double)microtime()*1000000);
			$n = mt_rand(1,4);
			switch( $n )
			{
				case 1:
					$x = mt_rand(1,13);
					$y = mt_rand(1,9);
					$captcha = array( "RESULT" => $x + $y, "CAPTCHA" => "$x+$y" );
					break; 
				case 2:
					$x = mt_rand(11,31);
					$y = mt_rand(1,10);
					$captcha = array( "RESULT" => $x - $y, "CAPTCHA" => "$x-$y" );
					break;
				case 3:
					$x = mt_rand(3,10);
					$y = mt_rand(2,7);
					$captcha = array( "RESULT" => $x * $y, "CAPTCHA" => "$x*$y" );
					break;
				default:
					$x = mt_rand(3,10);
					$y = mt_rand(2,7);
					$z = $x * $y;
					$captcha = array( "RESULT" => $y, "CAPTCHA" => "$z/$x" );
					break;
			}

			// get captcha instance
			require_once(LEPTON_PATH . "/modules/captcha_control/classes/captcha.php" );
			$oCAPTCHA = captcha_control::getInstance();

			// define calculation translations for speech
			$trans = array(	"+" => " " . $oCAPTCHA->language[ 'ADD' ] . " ",
							"-" => " " . $oCAPTCHA->language[ 'SUBTRACT' ] . " ",
							"*" => " " . $oCAPTCHA->language[ 'MULTIPLY' ] . " ",
							"/" => " " . $oCAPTCHA->language[ 'DIVIDE' ] . " "
						);
			$captcha[ "SPEECH" ] = strtr( $captcha[ "CAPTCHA" ], $trans );
			break;

		case "random":
			require_once( LEPTON_PATH."/framework/functions/function.random_string.php");
			$string = random_string($length, $type ); 
			$captcha = array( "RESULT" => $string, "CAPTCHA" => $string );

			// split a string into single elements for speech
			$captcha[ "SPEECH" ] = implode(" ", str_split( $string ));
			break;
	}

	return $captcha;
}

