Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- if(!defined('IS_INTERNAL')) { die('Direct file connect attempt.'); }
- class captcha
- {
- // Default bounds of a letter image
- private static $image_default_bounds = [
- // Width
- 'w' => 30,
- // Height
- 'h' => 43,
- // w = (input_string_length + wp) * w
- 'wp' => 1,
- // Height padding.
- 'hp' => 23,
- ];
- public static function GenerateCaptcha($user_id)
- {
- // Insert variables
- $captcha_id = captcha::GenerateCapchaId();
- $captcha_creator = $user_id;
- $captcha_verification_text = cryptography::RandomString(config::GetConfig('CAPCHA_LENGTH'), false, false);
- $captcha_image = GenerateImage($captcha_verification_text);
- $captcha_entry_date = time();
- $captcha_expiry = strtotime(config::GetConfig('CAPCHA_DURATION'));
- // Creating SQL instance
- if(sql::Instance() === false) {
- throw new Exception("SQL failed");
- }
- // Is everything ok variable
- $is_ok = true;
- // Inserting query
- if($stmt = sql::Prepare("INSERT INTO `captchas` (`captcha_id`, `captcha_creator`, `captcha_verification_text`, `captcha_image`, `captcha_entry_date`, `captcha_expiry`, `enabled`) VALUES (?, ?, ?, ?, ?, ?, 'true')")) {
- $stmt->bind_param('ssssii', $captcha_id, $captcha_creator, $captcha_verification_text, $captcha_image, $captcha_entry_date, $captcha_expiry);
- $is_ok = $stmt->execute();
- $stmt->close();
- }
- else {
- throw new Exception("SQL prepare error");
- }
- if($is_ok) {
- return array(
- 'success' => true,
- 'response' => 'Captcha generated successfully',
- 'data' => [
- 'captcha_id' => $captcha_id,
- 'captcha_creator' => $captcha_creator,
- 'captcha_image' => $captcha_image,
- 'captcha_expiry' => $captcha_expiry
- ]
- );
- }
- else {
- return array(
- 'success' => false,
- 'response' => 'Failed to generate Captcha.'
- );
- }
- }
- public static function VerifyCaptcha($captcha_id, $user_input)
- {
- // Creating SQL instance
- if(sql::Instance() === false) {
- throw new Exception("SQL failed");
- }
- // Is everything ok variable
- $is_ok = true;
- $is_valid = false;
- // Inserting query
- if($stmt = sql::Prepare("SELECT * FROM `captchas` WHERE `captcha_id` = ?")) {
- $stmt->bind_param('s', $captcha_id);
- $is_ok = $stmt->execute();
- $stmt->bind_result($captcha_id, $captcha_creator, $captcha_verification_text, $captcha_image, $captcha_entry_date, $captcha_expiry, $captcha_enabled);
- $stmt->store_result();
- $is_valid = $stmt->num_rows > 0;
- $stmt->fetch();
- $stmt->close();
- }
- else {
- throw new Exception("SQL prepare error");
- }
- if($is_ok) {
- // Checking row count
- if(!$is_valid) {
- return [
- 'success' => false,
- 'response' => 'No captcha ID found'
- ];
- }
- // Checking the expiry
- if($captcha_expiry < time()) {
- return [
- 'success' => false,
- 'response' => 'Captcha expired'
- ];
- }
- // Making sure the captcha is enabled.
- if(misc::IsFalse($captcha_enabled)) {
- return [
- 'success' => false,
- 'response' => 'Captcha already been used'
- ];
- }
- // Checking that the user input is valid
- if($captcha_verification_text != $user_input) {
- return [
- 'success' => false,
- 'response' => 'Invalid input'
- ];
- }
- // Disabling this captcha from working again
- if($stmt = sql::Prepare("UPDATE `captchas` SET `enabled` = 'false' WHERE `captcha_id` = ?")) {
- $stmt->bind_param('s', $captcha_id);
- $is_ok = $stmt->execute();
- $stmt->close();
- }
- else {
- throw new Exception("SQL prepare error");
- }
- if($is_ok) {
- return [
- 'success' => true,
- 'response' => 'Captcha is valid'
- ];
- }
- else {
- return [
- 'success' => false,
- 'response' => 'Internal error'
- ];
- }
- }
- else {
- return [
- 'success' => false,
- 'response' => 'Internal error'
- ];
- }
- }
- /**
- * Generates a captcha image from a text input.
- *
- * @param string $text The verification string that will be embeded in the image.
- */
- public static function GenerateImage($text)
- {
- // Generate bounds.
- $generated_image_bounds['w'] = ((strlen($text) + captcha::$image_default_bounds['wp']) * captcha::$image_default_bounds['w']);
- $generated_image_bounds['h'] = (captcha::$image_default_bounds['h'] + captcha::$image_default_bounds['hp']);
- // Variables to keep track of the x/y
- $generated_image_current['x'] = 0;
- $generated_image_current['y'] = 0;
- // Create image.
- $generated_image = imagecreate(
- $generated_image_bounds['w'],
- $generated_image_bounds['h']
- );
- // Going through each character.
- for ($i = 0; $i < strlen($text); $i++) {
- // Checking type of character.
- if(is_numeric($text[$i])) {
- // Number character.
- // Loading image.
- $image_file = "internal/images/".$text[$i].".png";
- $image_insert_temp = imagecreatefrompng($image_file);
- }
- else {
- // Normal character.
- // There are two images for each letter, this is getting one of the two.
- if(rand(-50, 50) >= 0) {
- $rnd_letter_index = "1";
- }
- else {
- $rnd_letter_index = "2";
- }
- //Loading image
- $image_file = "internal/images/".$text[$i]."-".$rnd_letter_index.".png";
- $image_insert_temp = imagecreatefrompng($image_file);
- }
- // Generating random position to insert character into.
- $generated_image_current['y'] = rand(0, $generated_image_bounds['h'] - captcha::$image_default_bounds['h']);
- $generated_image_current['x'] += (($i == 0) ? 1 : rand(captcha::$image_default_bounds['w'], captcha::$image_default_bounds['w'] + captcha::$image_default_bounds['wp']));
- while($generated_image_current['x'] > $generated_image_bounds['w']) {
- $generated_image_current['x']--;
- }
- // Inserting image to output image.
- $image_copy = imagecopy(
- $generated_image,
- $image_insert_temp,
- // dst
- $generated_image_current['x'],
- $generated_image_current['y'],
- // scr
- 0,
- 0,
- captcha::$image_default_bounds['w'],
- captcha::$image_default_bounds['h']
- );
- // Destroy image
- imagedestroy($image_insert_temp);
- }
- // Getting the image data
- ob_start();
- imagepng($generated_image);
- $data = ob_get_contents();
- ob_end_clean();
- // Destroy image
- imagedestroy($generated_image);
- return base64_encode($data);
- }
- /**
- * Generates a random, unqiue, capcha id.
- */
- public static function GenerateCapchaId()
- {
- $len = config::GetConfig('CAPCHA_ID_LENGTH');
- while(true) {
- $id = cryptography::RandomId($len);
- if(!captcha::DoesCapchaExist($id)) {
- break;
- }
- }
- return $id;
- }
- /**
- * Checks if a capcha id exists.
- *
- * @param string $captcha_id The ID of the capcha.
- */
- public static function DoesCapchaExist($captcha_id)
- {
- if(sql::Instance() === false) {
- throw new Exception("SQL failed");
- }
- if($stmt = sql::Prepare('SELECT COUNT(*) FROM `captchas` WHERE `captcha_id` = ?')) {
- $stmt->bind_param('s', $captcha_id);
- $stmt->execute();
- $stmt->bind_result($fetch_count);
- $stmt->fetch();
- $stmt->close();
- }
- else {
- throw new Exception("SQL prepare error");
- }
- return (isset($fetch_count) ? ($fetch_count > 0) : false);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement