You are here

public function CaptchaImageRefresh::refreshCaptcha in CAPTCHA 8

Put your code here.

1 string reference to 'CaptchaImageRefresh::refreshCaptcha'
image_captcha.routing.yml in image_captcha/image_captcha.routing.yml
image_captcha/image_captcha.routing.yml

File

image_captcha/src/Controller/CaptchaImageRefresh.php, line 51

Class

CaptchaImageRefresh
Description of CaptchaImageRefresh.

Namespace

Drupal\image_captcha\Controller

Code

public function refreshCaptcha($form_id = NULL) {
  $result = [
    'status' => 0,
    'message' => '',
  ];
  try {
    module_load_include('inc', 'captcha', 'captcha');
    $config = $this
      ->config('image_captcha.settings');
    $captcha_sid = _captcha_generate_captcha_session($form_id);
    $captcha_token = Crypt::randomBytesBase64();
    $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'] = [
      'url' => Url::fromRoute('image_captcha.generator', [
        'session_id' => $captcha_sid,
        'timestamp' => $this->time
          ->getRequestTime(),
      ])
        ->toString(),
      '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);
}