CaptchaImageRefresh.php 2.54 KB
Newer Older
1
2
3
4
<?php

namespace Drupal\image_captcha\Controller;

5
6
7
8
/**
 * To change template file, choose Tools | Templates and open it in the editor.
 */

9
use Drupal\Component\Datetime\TimeInterface;
10
11
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Database;
12
use Drupal\Core\Url;
13
14
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
15
use Drupal\Component\Utility\Crypt;
16
17
18
19
20
21

/**
 * Description of CaptchaImageRefresh.
 */
class CaptchaImageRefresh extends ControllerBase {

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  /**
   * Obtaining system time.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * The contruct method.
   *
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   Obtaining system time.
   */
  public function __construct(TimeInterface $time) {
    $this->time = $time;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('datetime.time')
    );
  }

48
49
50
51
52
53
54
55
56
57
  /**
   * Put your code here.
   */
  public function refreshCaptcha($form_id = NULL) {
    $result = [
      'status' => 0,
      'message' => '',
    ];
    try {
      module_load_include('inc', 'captcha', 'captcha');
58
      $config = $this->config('image_captcha.settings');
59
      $captcha_sid = _captcha_generate_captcha_session($form_id);
60
      $captcha_token = Crypt::randomBytesBase64();
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
      $allowed_chars = _image_captcha_utf8_split($config->get('image_captcha_image_allowed_chars', IMAGE_CAPTCHA_ALLOWED_CHARACTERS));
      $code_length = (int) $config->get('image_captcha_code_length');
      $code = '';
      for ($i = 0; $i < $code_length; $i++) {
        $code .= $allowed_chars[array_rand($allowed_chars)];
      }
      $connection = Database::getConnection();
      $connection->update('captcha_sessions')
        ->fields([
          'token' => $captcha_token,
          'solution' => $code,
        ])
        ->condition('csid', $captcha_sid, '=')
        ->execute();
      $result['data'] = [
76
        'url' => Url::fromRoute('image_captcha.generator', ['session_id' => $captcha_sid, 'timestamp' => $this->time->getRequestTime()])->toString(),
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
        'token' => $captcha_token,
        'sid' => $captcha_sid,
      ];
      $result['status'] = 1;
    }
    catch (\Exception $e) {
      if ($message = $e->getMessage()) {
        $result['message'] = $message;
      }
      else {
        $result['message'] = $this->t('Error has occurred. Please contact to site administrator.');
      }
    }
    return new JsonResponse($result);
  }

}