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
43 #protected $container;
46 * The ImageUtil instance
48 protected ImageUtil
$image;
53 protected string $path;
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 $path The public path
68 * @param string $prefix The prefix
70 function __construct(ContainerInterface
$container, ImageUtil
$image, SluggerUtil
$slugger, string $cache = '../var/cache', string $path = './bundles/rapsyspack', string $prefix = 'image') {
72 $this->cache
= $cache.'/'.$prefix;
75 $this->container
= $container;
78 $this->image
= $image;
81 $this->path
= $path.'/'.$prefix;
84 $this->slugger
= $slugger;
88 * Return captcha image
90 * @param Request $request The Request instance
91 * @param string $hash The hash
92 * @param int $updated The updated timestamp
93 * @param string $equation The shorted equation
94 * @param int $width The width
95 * @param int $height The height
96 * @return Response The rendered image
98 public function captcha(Request
$request, string $hash, int $updated, string $equation, int $width, int $height): Response
{
99 //Without matching hash
100 if ($hash !== $this->slugger
->serialize([$updated, $equation, $width, $height])) {
101 //Throw new exception
102 throw new NotFoundHttpException(sprintf('Unable to match captcha hash: %s', $hash));
106 $hashed = array_reverse(str_split(strval($updated)));
109 $captcha = $this->path
.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$equation.'/'.$width.'x'.$height.'.jpeg';
112 $equation = $this->slugger
->unshort($equation);
114 //Without captcha up to date file
115 if (!is_file($captcha) || !($mtime = stat($captcha)['mtime']) || $mtime < $updated) {
116 //Without existing captcha path
117 if (!is_dir($dir = dirname($captcha))) {
118 //Create filesystem object
119 $filesystem = new Filesystem();
123 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
124 //XXX: on CoW filesystems execute a chattr +C before filling
125 $filesystem->mkdir($dir, 0775);
126 } catch (IOExceptionInterface
$e) {
128 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
132 //Create image instance
133 $image = new \
Imagick();
135 //Add imagick draw instance
136 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
137 $draw = new \
ImagickDraw();
140 $draw->setTextAntialias(true);
142 //Set stroke antialias
143 $draw->setStrokeAntialias(true);
146 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
149 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
152 $draw->setFillColor($this->image
->captchaFill
);
155 $draw->setStrokeColor($this->image
->captchaStroke
);
158 $draw->setFontSize($this->image
->captchaFontSize
/1.5);
161 $draw->setStrokeWidth($this->image
->captchaStrokeWidth
/ 2);
164 $draw->rotate($rotate = (rand(25, 75)*(rand(0,1)?-.1:.1)));
167 $metrics2 = $image->queryFontMetrics($draw, strval('stop spam'));
170 $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'));
173 $draw->rotate(-$rotate);
176 $draw->setFontSize($this->image
->captchaFontSize
);
179 $draw->setStrokeWidth($this->image
->captchaStrokeWidth
);
182 $draw->rotate($rotate = (rand(25, 50)*(rand(0,1)?-.1:.1)));
185 $metrics = $image->queryFontMetrics($draw, strval($equation));
188 $draw->annotation($width / 2, ceil($metrics['textHeight'] +
$metrics['descender'] +
$metrics['ascender']) / 2 - $this->image
->captchaStrokeWidth
, strval($equation));
191 $draw->rotate(-$rotate);
194 #$image->newImage(intval(ceil($metrics['textWidth'])), intval(ceil($metrics['textHeight'] + $metrics['descender'])), new \ImagickPixel($this->image->captchaBackground), 'jpeg');
195 $image->newImage($width, $height, new \
ImagickPixel($this->image
->captchaBackground
), 'jpeg');
198 $image->drawImage($draw);
200 //Strip image exif data and properties
201 $image->stripImage();
203 //Set compression quality
204 $image->setImageCompressionQuality(70);
207 if (!$image->writeImage($captcha)) {
209 throw new \
Exception(sprintf('Unable to write image "%s"', $captcha));
213 $mtime = stat($captcha)['mtime'];
216 //Read captcha from cache
217 $response = new BinaryFileResponse($captcha);
220 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'captcha-stop-spam-'.str_replace([' ', '*', '+'], ['-', 'mul', 'add'], $equation).'-'.$width.'x'.$height.'.jpeg');
223 $response->setEtag(md5($hash));
226 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
229 $response->setPublic();
231 //Return 304 response if not modified
232 $response->isNotModified($request);
241 * @param Request $request The Request instance
242 * @param string $hash The hash
243 * @param int $updated The updated timestamp
244 * @param string $path The image path
245 * @param int $width The width
246 * @param int $height The height
247 * @return Response The rendered image
249 public function thumb(Request
$request, string $hash, int $updated, string $path, int $width, int $height): Response
{
250 //Without matching hash
251 if ($hash !== $this->slugger
->serialize([$updated, $path, $width, $height])) {
252 //Throw new exception
253 throw new NotFoundHttpException(sprintf('Unable to match thumb hash: %s', $hash));
257 $hashed = array_reverse(str_split(strval($updated)));
260 $thumb = $this->path
.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$path.'/'.$width.'x'.$height.'.jpeg';
263 $path = $this->slugger
->unshort($path);
265 //Without thumb up to date file
266 if (!is_file($thumb) || !($mtime = stat($thumb)['mtime']) || $mtime < $updated) {
267 //Without existing thumb path
268 if (!is_dir($dir = dirname($thumb))) {
269 //Create filesystem object
270 $filesystem = new Filesystem();
274 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
275 //XXX: on CoW filesystems execute a chattr +C before filling
276 $filesystem->mkdir($dir, 0775);
277 } catch (IOExceptionInterface
$e) {
279 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
283 //Create image instance
284 $image = new \
Imagick();
287 $image->readImage(realpath($path));
289 //Crop using aspect ratio
290 //XXX: for better result upload image directly in aspect ratio :)
291 $image->cropThumbnailImage($width, $height);
293 //Strip image exif data and properties
294 $image->stripImage();
296 //Set compression quality
298 $image->setImageCompressionQuality(70);
301 if (!$image->writeImage($thumb)) {
303 throw new \
Exception(sprintf('Unable to write image "%s"', $thumb));
307 $mtime = stat($thumb)['mtime'];
310 //Read thumb from cache
311 $response = new BinaryFileResponse($thumb);
314 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'thumb-'.str_replace('/', '_', $path).'-'.$width.'x'.$height.'.jpeg');
317 $response->setEtag(md5($hash));
320 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
323 $response->setPublic();
325 //Return 304 response if not modified
326 $response->isNotModified($request);