urlshortener/lib/Captcha.class.php

64 lines
1.4 KiB
PHP

<?php
/**
* Captcha logic class
*/
include_once(dirname(__FILE__).'/./config.inc.php');
class Captcha {
private $calcOps;
function __construct() {
$this->calcOps = array("+", "-", "*");
}
function generateAndUseCaptcha() {
$rndType = rand(1, 100);
if ($rndType > 0) {
// build numeric question
$useOp = $this->calcOps[rand(0, 2)];
$firstNum = 0;
$secondNum = 0;
if ($useOp == "*") {
$firstNum = rand(0, 9);
$secondNum = rand(0, 15);
} else {
$firstNum = rand(0, 100);
$secondNum = rand(0, 100);
}
$calc = 0;
if ($useOp == "+") {
$calc = $firstNum + $secondNum;
} else if ($useOp == "-") {
$calc = $firstNum - $secondNum;
} else if ($useOp == "*") {
$calc = $firstNum * $secondNum;
}
$mathStr = "" . $firstNum . " " . $useOp . " " . $secondNum;
$_SESSION['CAPTCHA_QUESTION'] = $mathStr;
$_SESSION['CAPTCHA_VALUE'] = $calc;
// field name
$fieldname = chr(rand(65, 90)) . dechex(rand());
$_SESSION['CAPTCHA_FIELD'] = $fieldname;
return $mathStr;
} else {
// use pooled question
// TODO currently not supported due to missing logic which language to use
}
}
function validateCaptcha($inputStr) {
if (empty($inputStr) == true) {
return false;
}
if (isset($_SESSION['CAPTCHA_VALUE']) == false) {
return false;
}
$valueInSession = $_SESSION['CAPTCHA_VALUE'];
return ($inputStr == $valueInSession . "");
}
}