mirror of
https://github.com/silverstripe/silverstripe-reports
synced 2024-10-22 11:05:53 +02:00
60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
|
<?php
|
||
|
/**
|
||
|
* Tools for adding an optional protection question to a form.
|
||
|
* Remember to add MathSpamProtection::enabled(true); to _config.php for this question to be added to the comments form.
|
||
|
*/
|
||
|
class MathSpamProtection {
|
||
|
|
||
|
private static $mathProtection = false;
|
||
|
|
||
|
static function isEnabled() {
|
||
|
return (self::$mathProtection != null) ? true : false;
|
||
|
}
|
||
|
|
||
|
static function enabled($math = true) {
|
||
|
MathSpamProtection::$mathProtection = $math;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Creates the question from random variables, which are also saved to the session.
|
||
|
*/
|
||
|
static function getMathQuestion(){
|
||
|
if(!Session::get("mathQuestionV1")&&!Session::get("mathQuestionV2")){
|
||
|
$v1 = rand(1,9);
|
||
|
$v2 = rand(1,9);
|
||
|
Session::set("mathQuestionV1",$v1);
|
||
|
Session::set("mathQuestionV2",$v2);
|
||
|
}
|
||
|
else{
|
||
|
$v1 = Session::get("mathQuestionV1");
|
||
|
$v2 = Session::get("mathQuestionV2");
|
||
|
}
|
||
|
return "What is ".MathSpamProtection::digitToWord($v1)." plus ".MathSpamProtection::digitToWord($v2)."?";
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Checks the given answer if it matches the addition of the saved session variables. Users can answer using words or digits.
|
||
|
*/
|
||
|
static function correctAnswer($answer){
|
||
|
$v1 = Session::get("mathQuestionV1");
|
||
|
$v2 = Session::get("mathQuestionV2");
|
||
|
return (MathSpamProtection::digitToWord($v1 + $v2) == $answer || ($v1 + $v2) == $answer) ? true : false;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Helper method for converting digits to their equivelant english words
|
||
|
*/
|
||
|
static function digitToWord($num){
|
||
|
$numbers = array("zero","one","two","three","four","five","six","seven","eight","nine",
|
||
|
"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen");
|
||
|
if($num < 0){
|
||
|
return "minus ".($numbers[-1*$num]);
|
||
|
}
|
||
|
//TODO: add checking or return null for bad value??
|
||
|
return $numbers[$num];
|
||
|
}
|
||
|
|
||
|
|
||
|
}
|
||
|
?>
|