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 ContainerInterface instance
41 * @var ContainerInterface
46 * The ImageUtil instance
48 protected ImageUtil
$image;
53 protected string $public;
56 * The SluggerUtil instance
58 protected SluggerUtil
$slugger;
61 * Creates a new image controller
63 * @param ContainerInterface $container The ContainerInterface instance
64 * @param ImageUtil $image The MapUtil instance
65 * @param SluggerUtil $slugger The SluggerUtil instance
66 * @param string $cache The cache path
67 * @param string $public The public path
69 function __construct(ContainerInterface
$container, ImageUtil
$image, SluggerUtil
$slugger, string $cache = '../var/cache/image', string $public = './bundles/rapsyspack/image') {
71 $this->cache
= $cache;
74 $this->container
= $container;
77 $this->image
= $image;
80 $this->public = $public;
83 $this->slugger
= $slugger;
87 * Return captcha image
89 * @param Request $request The Request instance
90 * @param string $hash The hash
91 * @param int $updated The updated timestamp
92 * @param string $equation The shorted equation
93 * @param int $width The width
94 * @param int $height The height
95 * @return Response The rendered image
97 public function captcha(Request
$request, string $hash, int $updated, string $equation, int $width, int $height): Response
{
98 //Without matching hash
99 if ($hash !== $this->slugger
->serialize([$updated, $equation, $width, $height])) {
100 //Throw new exception
101 throw new NotFoundHttpException(sprintf('Unable to match captcha hash: %s', $hash));
105 $hashed = array_reverse(str_split(strval($updated)));
108 $captcha = $this->public.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$equation.'/'.$width.'x'.$height.'.jpeg';
111 $equation = $this->slugger
->unshort($equation);
113 //Without captcha up to date file
114 if (!is_file($captcha) || !($mtime = stat($captcha)['mtime']) || $mtime < $updated) {
115 //Without existing captcha path
116 if (!is_dir($dir = dirname($captcha))) {
117 //Create filesystem object
118 $filesystem = new Filesystem();
122 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
123 //XXX: on CoW filesystems execute a chattr +C before filling
124 $filesystem->mkdir($dir, 0775);
125 } catch (IOExceptionInterface
$e) {
127 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
131 //Create image instance
132 $image = new \
Imagick();
134 //Add imagick draw instance
135 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
136 $draw = new \
ImagickDraw();
139 $draw->setTextAntialias(true);
141 //Set stroke antialias
142 $draw->setStrokeAntialias(true);
145 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
148 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
151 $draw->setFillColor($this->image
->captchaFill
);
154 $draw->setStrokeColor($this->image
->captchaStroke
);
157 $draw->setFontSize($this->image
->captchaFontSize
/1.5);
160 $draw->setStrokeWidth($this->image
->captchaStrokeWidth
/ 2);
163 $draw->rotate($rotate = (rand(25, 75)*(rand(0,1)?-.1:.1)));
166 $metrics2 = $image->queryFontMetrics($draw, strval('stop spam'));
169 $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'));
172 $draw->rotate(-$rotate);
175 $draw->setFontSize($this->image
->captchaFontSize
);
178 $draw->setStrokeWidth($this->image
->captchaStrokeWidth
);
181 $draw->rotate($rotate = (rand(25, 50)*(rand(0,1)?-.1:.1)));
184 $metrics = $image->queryFontMetrics($draw, strval($equation));
187 $draw->annotation($width / 2, ceil($metrics['textHeight'] +
$metrics['descender'] +
$metrics['ascender']) / 2 - $this->image
->captchaStrokeWidth
, strval($equation));
190 $draw->rotate(-$rotate);
193 #$image->newImage(intval(ceil($metrics['textWidth'])), intval(ceil($metrics['textHeight'] + $metrics['descender'])), new \ImagickPixel($this->image->captchaBackground), 'jpeg');
194 $image->newImage($width, $height, new \
ImagickPixel($this->image
->captchaBackground
), 'jpeg');
197 $image->drawImage($draw);
199 //Strip image exif data and properties
200 $image->stripImage();
202 //Set compression quality
203 $image->setImageCompressionQuality(70);
206 if (!$image->writeImage($captcha)) {
208 throw new \
Exception(sprintf('Unable to write image "%s"', $captcha));
212 $mtime = stat($captcha)['mtime'];
215 //Read captcha from cache
216 $response = new BinaryFileResponse($captcha);
219 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'captcha-stop-spam-'.str_replace([' ', '*', '+'], ['-', 'mul', 'add'], $equation).'-'.$width.'x'.$height.'.jpeg');
222 $response->setEtag(md5($hash));
225 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
228 $response->setPublic();
230 //Return 304 response if not modified
231 $response->isNotModified($request);
240 * @param Request $request The Request instance
241 * @param string $hash The hash
242 * @param int $updated The updated timestamp
243 * @param string $path The image path
244 * @param int $width The width
245 * @param int $height The height
246 * @return Response The rendered image
248 public function thumb(Request
$request, string $hash, int $updated, string $path, int $width, int $height): Response
{
249 //Without matching hash
250 if ($hash !== $this->slugger
->serialize([$updated, $path, $width, $height])) {
251 //Throw new exception
252 throw new NotFoundHttpException(sprintf('Unable to match thumb hash: %s', $hash));
256 $hashed = array_reverse(str_split(strval($updated)));
259 $thumb = $this->public.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$path.'/'.$width.'x'.$height.'.jpeg';
262 $path = $this->slugger
->unshort($path);
264 //Without thumb up to date file
265 if (!is_file($thumb) || !($mtime = stat($thumb)['mtime']) || $mtime < $updated) {
266 //Without existing thumb path
267 if (!is_dir($dir = dirname($thumb))) {
268 //Create filesystem object
269 $filesystem = new Filesystem();
273 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
274 //XXX: on CoW filesystems execute a chattr +C before filling
275 $filesystem->mkdir($dir, 0775);
276 } catch (IOExceptionInterface
$e) {
278 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
282 //Create image instance
283 $image = new \
Imagick();
286 $image->readImage(realpath($path));
288 //Crop using aspect ratio
289 //XXX: for better result upload image directly in aspect ratio :)
290 $image->cropThumbnailImage($width, $height);
292 //Strip image exif data and properties
293 $image->stripImage();
295 //Set compression quality
297 $image->setImageCompressionQuality(70);
300 if (!$image->writeImage($thumb)) {
302 throw new \
Exception(sprintf('Unable to write image "%s"', $thumb));
306 $mtime = stat($thumb)['mtime'];
309 //Read thumb from cache
310 $response = new BinaryFileResponse($thumb);
313 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'thumb-'.str_replace('/', '_', $path).'-'.$width.'x'.$height.'.jpeg');
316 $response->setEtag(md5($hash));
319 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
322 $response->setPublic();
324 //Return 304 response if not modified
325 $response->isNotModified($request);