PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/image_captcha/src/Controller/CaptchaFontPreview.php

https://gitlab.com/Drulenium-bot/captcha
PHP | 73 lines | 46 code | 9 blank | 18 comment | 10 complexity | a5f4de6cdef6878412c50b86eb141e4b MD5 | raw file
  1. <?php
  2. namespace Drupal\image_captcha\Controller;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\StreamedResponse;
  5. /**
  6. * A Controller to preview the captcha font on the settings page.
  7. */
  8. class CaptchaFontPreview extends StreamedResponse {
  9. /**
  10. * {@inheritdoc}
  11. */
  12. public function content(Request $request) {
  13. $token = $request->get('token');
  14. // Get the font from the given font token.
  15. if ($token == 'BUILTIN') {
  16. $font = 'BUILTIN';
  17. }
  18. else {
  19. // Get the mapping of font tokens to font file objects.
  20. $fonts = \Drupal::config('image_captcha.settings')
  21. ->get('image_captcha_fonts_preview_map_cache');
  22. if (!isset($fonts[$token])) {
  23. echo 'bad token';
  24. exit();
  25. }
  26. // Get the font path.
  27. $font = $fonts[$token]['uri'];
  28. // Some sanity checks if the given font is valid.
  29. if (!is_file($font) || !is_readable($font)) {
  30. echo 'bad font';
  31. exit();
  32. }
  33. }
  34. // Settings of the font preview.
  35. $width = 120;
  36. $text = 'AaBbCc123';
  37. $font_size = 14;
  38. $height = 2 * $font_size;
  39. // Allocate image resource.
  40. $image = imagecreatetruecolor($width, $height);
  41. if (!$image) {
  42. exit();
  43. }
  44. // White background and black foreground.
  45. $background_color = imagecolorallocate($image, 255, 255, 255);
  46. $color = imagecolorallocate($image, 0, 0, 0);
  47. imagefilledrectangle($image, 0, 0, $width, $height, $background_color);
  48. // Draw preview text.
  49. if ($font == 'BUILTIN') {
  50. imagestring($image, 5, 1, .5 * $height - 10, $text, $color);
  51. }
  52. else {
  53. imagettftext($image, $font_size, 0, 1, 1.5 * $font_size, $color, realpath($font), $text);
  54. }
  55. // Set content type.
  56. $this->headers->set('Content-Type', 'image/png');
  57. // Dump image data to client.
  58. imagepng($image);
  59. // Release image memory.
  60. imagedestroy($image);
  61. // Close connection.
  62. exit();
  63. }
  64. }