1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys PackBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\PackBundle\Controller
;
14 use Symfony\Component\HttpFoundation\HeaderUtils
;
15 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController
;
16 use Symfony\Component\DependencyInjection\ContainerInterface
;
17 use Symfony\Component\Filesystem\Exception\IOExceptionInterface
;
18 use Symfony\Component\Filesystem\Filesystem
;
19 use Symfony\Component\HttpFoundation\BinaryFileResponse
;
20 use Symfony\Component\HttpFoundation\Request
;
21 use Symfony\Component\HttpFoundation\Response
;
22 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException
;
23 use Symfony\Component\Routing\RequestContext
;
24 use Symfony\Contracts\Service\ServiceSubscriberInterface
;
26 use Rapsys\PackBundle\Util\ImageUtil
;
27 use Rapsys\PackBundle\Util\SluggerUtil
;
32 class ImageController
extends AbstractController
implements ServiceSubscriberInterface
{
36 protected string $cache;
39 * The ImageUtil instance
41 protected ImageUtil
$image;
46 protected string $path;
49 * The SluggerUtil instance
51 protected SluggerUtil
$slugger;
54 * Creates a new image controller
56 * @param ContainerInterface $container The ContainerInterface instance
57 * @param ImageUtil $image The MapUtil instance
58 * @param SluggerUtil $slugger The SluggerUtil instance
59 * @param string $cache The cache path
60 * @param string $path The public path
61 * @param string $prefix The prefix
63 function __construct(ContainerInterface
$container, ImageUtil
$image, SluggerUtil
$slugger, string $cache = '../var/cache', string $path = './bundles/rapsyspack', string $prefix = 'image') {
65 $this->cache
= $cache.'/'.$prefix;
68 $this->container
= $container;
71 $this->image
= $image;
74 $this->path
= $path.'/'.$prefix;
77 $this->slugger
= $slugger;
81 * Return captcha image
83 * @param Request $request The Request instance
84 * @param string $hash The hash
85 * @param int $updated The updated timestamp
86 * @param string $equation The shorted equation
87 * @param int $width The width
88 * @param int $height The height
89 * @return Response The rendered image
91 public function captcha(Request
$request, string $hash, int $updated, string $equation, int $width, int $height): Response
{
92 //Without matching hash
93 if ($hash !== $this->slugger
->serialize([$updated, $equation, $width, $height])) {
95 throw new NotFoundHttpException(sprintf('Unable to match captcha hash: %s', $hash));
99 $hashed = array_reverse(str_split(strval($updated)));
102 $captcha = $this->path
.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$equation.'/'.$width.'x'.$height.'.jpeg';
105 $equation = $this->slugger
->unshort($equation);
107 //Without captcha up to date file
108 if (!is_file($captcha) || !($mtime = stat($captcha)['mtime']) || $mtime < $updated) {
109 //Without existing captcha path
110 if (!is_dir($dir = dirname($captcha))) {
111 //Create filesystem object
112 $filesystem = new Filesystem();
116 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
117 //XXX: on CoW filesystems execute a chattr +C before filling
118 $filesystem->mkdir($dir, 0775);
119 } catch (IOExceptionInterface
$e) {
121 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
125 //Create image instance
126 $image = new \
Imagick();
128 //Add imagick draw instance
129 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
130 $draw = new \
ImagickDraw();
133 $draw->setTextAntialias(true);
135 //Set stroke antialias
136 $draw->setStrokeAntialias(true);
139 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
142 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
145 $draw->setFillColor($this->image
->captchaFill
);
148 $draw->setStrokeColor($this->image
->captchaStroke
);
151 $draw->setFontSize($this->image
->captchaFontSize
/1.5);
154 $draw->setStrokeWidth($this->image
->captchaStrokeWidth
/ 2);
157 $draw->rotate($rotate = (rand(25, 75)*(rand(0,1)?-.1:.1)));
160 $metrics2 = $image->queryFontMetrics($draw, strval('stop spam'));
163 $draw->annotation($width / 2 - ceil(rand(intval(-$metrics2['textWidth']), intval($metrics2['textWidth'])) / 2) - abs($rotate), ceil($metrics2['textHeight'] +
$metrics2['descender'] +
$metrics2['ascender']) / 2 - $this->image
->captchaStrokeWidth
- $rotate, strval('stop spam'));
166 $draw->rotate(-$rotate);
169 $draw->setFontSize($this->image
->captchaFontSize
);
172 $draw->setStrokeWidth($this->image
->captchaStrokeWidth
);
175 $draw->rotate($rotate = (rand(25, 50)*(rand(0,1)?-.1:.1)));
178 $metrics = $image->queryFontMetrics($draw, strval($equation));
181 $draw->annotation($width / 2, ceil($metrics['textHeight'] +
$metrics['descender'] +
$metrics['ascender']) / 2 - $this->image
->captchaStrokeWidth
, strval($equation));
184 $draw->rotate(-$rotate);
187 #$image->newImage(intval(ceil($metrics['textWidth'])), intval(ceil($metrics['textHeight'] + $metrics['descender'])), new \ImagickPixel($this->image->captchaBackground), 'jpeg');
188 $image->newImage($width, $height, new \
ImagickPixel($this->image
->captchaBackground
), 'jpeg');
191 $image->drawImage($draw);
193 //Strip image exif data and properties
194 $image->stripImage();
196 //Set compression quality
197 $image->setImageCompressionQuality(70);
200 if (!$image->writeImage($captcha)) {
202 throw new \
Exception(sprintf('Unable to write image "%s"', $captcha));
206 $mtime = stat($captcha)['mtime'];
209 //Read captcha from cache
210 $response = new BinaryFileResponse($captcha);
213 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'captcha-stop-spam-'.str_replace([' ', '*', '+'], ['-', 'mul', 'add'], $equation).'-'.$width.'x'.$height.'.jpeg');
216 $response->setEtag(md5($hash));
219 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
222 $response->setPublic();
224 //Return 304 response if not modified
225 $response->isNotModified($request);
234 * @param Request $request The Request instance
235 * @param string $hash The hash
236 * @param int $updated The updated timestamp
237 * @param string $path The image path
238 * @param int $width The width
239 * @param int $height The height
240 * @return Response The rendered image
242 public function thumb(Request
$request, string $hash, int $updated, string $path, int $width, int $height): Response
{
243 //Without matching hash
244 if ($hash !== $this->slugger
->serialize([$updated, $path, $width, $height])) {
245 //Throw new exception
246 throw new NotFoundHttpException(sprintf('Unable to match thumb hash: %s', $hash));
250 $hashed = array_reverse(str_split(strval($updated)));
253 $thumb = $this->path
.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$path.'/'.$width.'x'.$height.'.jpeg';
256 $path = $this->slugger
->unshort($path);
258 //Without thumb up to date file
259 if (!is_file($thumb) || !($mtime = stat($thumb)['mtime']) || $mtime < $updated) {
260 //Without existing thumb path
261 if (!is_dir($dir = dirname($thumb))) {
262 //Create filesystem object
263 $filesystem = new Filesystem();
267 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
268 //XXX: on CoW filesystems execute a chattr +C before filling
269 $filesystem->mkdir($dir, 0775);
270 } catch (IOExceptionInterface
$e) {
272 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
276 //Create image instance
277 $image = new \
Imagick();
280 $image->readImage(realpath($path));
282 //Crop using aspect ratio
283 //XXX: for better result upload image directly in aspect ratio :)
284 $image->cropThumbnailImage($width, $height);
286 //Strip image exif data and properties
287 $image->stripImage();
289 //Set compression quality
291 $image->setImageCompressionQuality(70);
294 if (!$image->writeImage($thumb)) {
296 throw new \
Exception(sprintf('Unable to write image "%s"', $thumb));
300 $mtime = stat($thumb)['mtime'];
303 //Read thumb from cache
304 $response = new BinaryFileResponse($thumb);
307 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'thumb-'.str_replace('/', '_', $path).'-'.$width.'x'.$height.'.jpeg');
310 $response->setEtag(md5($hash));
313 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
316 $response->setPublic();
318 //Return 304 response if not modified
319 $response->isNotModified($request);