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
;
14 use Rapsys\PackBundle\Util\ImageUtil
;
15 use Rapsys\PackBundle\Util\SluggerUtil
;
17 use Psr\Container\ContainerInterface
;
19 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController
;
20 use Symfony\Component\Filesystem\Exception\IOExceptionInterface
;
21 use Symfony\Component\Filesystem\Filesystem
;
22 use Symfony\Component\HttpFoundation\BinaryFileResponse
;
23 use Symfony\Component\HttpFoundation\HeaderUtils
;
24 use Symfony\Component\HttpFoundation\Request
;
25 use Symfony\Component\HttpFoundation\Response
;
26 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException
;
27 use Symfony\Component\Routing\RequestContext
;
28 use Symfony\Contracts\Service\ServiceSubscriberInterface
;
33 class Controller
extends AbstractController
implements ServiceSubscriberInterface
{
37 protected string $alias;
42 protected array $config;
52 protected string $version;
55 * Creates a new image controller
57 * @param ContainerInterface $container The ContainerInterface instance
58 * @param ImageUtil $image The MapUtil instance
59 * @param SluggerUtil $slugger The SluggerUtil instance
61 function __construct(protected ContainerInterface
$container, protected ImageUtil
$image, protected SluggerUtil
$slugger) {
63 $this->config
= $container->getParameter($this->alias
= RapsysPackBundle
::getAlias());
66 $this->ctx
= stream_context_create($this->config
['context']);
70 * Return captcha image
72 * @param Request $request The Request instance
73 * @param string $hash The hash
74 * @param string $equation The shorted equation
75 * @param int $height The height
76 * @param int $width The width
77 * @return Response The rendered image
79 public function captcha(Request
$request, string $hash, string $equation, int $height, int $width, string $_format): Response
{
80 //Without matching hash
81 if ($hash !== $this->slugger
->serialize([$equation, $height, $width])) {
83 throw new NotFoundHttpException(sprintf('Unable to match captcha hash: %s', $hash));
84 //Without valid format
85 } elseif ($_format !== 'jpeg' && $_format !== 'png' && $_format !== 'webp') {
87 throw new NotFoundHttpException('Invalid thumb format');
91 $equation = $this->slugger
->unshort($short = $equation);
94 $hashed = str_split(strval($equation));
97 $captcha = $this->config
['cache'].'/'.$this->config
['prefixes']['captcha'].'/'.$hashed[0].'/'.$hashed[4].'/'.$hashed[8].'/'.$short.'.'.$_format;
99 //Without captcha up to date file
100 if (!is_file($captcha) || !($mtime = stat($captcha)['mtime']) || $mtime < (new \
DateTime('-1 hour'))->getTimestamp()) {
101 //Without existing captcha path
102 if (!is_dir($dir = dirname($captcha))) {
103 //Create filesystem object
104 $filesystem = new Filesystem();
108 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
109 //XXX: on CoW filesystems execute a chattr +C before filling
110 $filesystem->mkdir($dir, 0775);
111 } catch (IOExceptionInterface
$e) {
113 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
117 //Create image instance
118 $image = new \
Imagick();
120 //Add imagick draw instance
121 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
122 $draw = new \
ImagickDraw();
125 $draw->setTextAntialias(true);
127 //Set stroke antialias
128 $draw->setStrokeAntialias(true);
131 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
134 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
137 $draw->setFillColor($this->config
['captcha']['fill']);
140 $draw->setStrokeColor($this->config
['captcha']['border']);
143 $draw->setFontSize($this->config
['captcha']['size'] / 1.5);
146 $draw->setStrokeWidth($this->config
['captcha']['thickness'] / 3);
149 $draw->rotate($rotate = (rand(25, 75)*(rand(0,1)?-.1:.1)));
152 $metrics2 = $image->queryFontMetrics($draw, strval('stop spam'));
155 $draw->annotation($width / 2 - ceil(rand(intval(-$metrics2['textWidth']), intval($metrics2['textWidth'])) / 2) - abs($rotate), ceil($metrics2['textHeight'] +
$metrics2['descender'] +
$metrics2['ascender']) / 2 - $this->config
['captcha']['thickness'] - $rotate, strval('stop spam'));
158 $draw->rotate(-$rotate);
161 $draw->setFontSize($this->config
['captcha']['size']);
164 $draw->setStrokeWidth($this->config
['captcha']['thickness']);
167 $draw->rotate($rotate = (rand(25, 50)*(rand(0,1)?-.1:.1)));
170 $metrics = $image->queryFontMetrics($draw, strval($equation));
173 $draw->annotation($width / 2, ceil($metrics['textHeight'] +
$metrics['descender'] +
$metrics['ascender']) / 2 - $this->config
['captcha']['thickness'], strval($equation));
176 $draw->rotate(-$rotate);
179 #$image->newImage(intval(ceil($metrics['textWidth'])), intval(ceil($metrics['textHeight'] + $metrics['descender'])), new \ImagickPixel($this->config['captcha']['background']), 'jpeg');
180 $image->newImage($width, $height, new \
ImagickPixel($this->config
['captcha']['background']), $_format);
183 $image->drawImage($draw);
185 //Strip image exif data and properties
186 $image->stripImage();
188 //Set compression quality
189 $image->setImageCompressionQuality(70);
192 if (!$image->writeImage($captcha)) {
194 throw new \
Exception(sprintf('Unable to write image "%s"', $captcha));
198 $mtime = stat($captcha)['mtime'];
201 //Read captcha from cache
202 $response = new BinaryFileResponse($captcha);
205 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'captcha-stop-spam-'.str_replace([' ', '*', '+'], ['-', 'mul', 'add'], $equation).'.'.$_format);
208 $response->setEtag(md5($hash));
211 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
214 $response->setPublic();
216 //Return 304 response if not modified
217 $response->isNotModified($request);
224 * Return facebook image
226 * @param Request $request The Request instance
227 * @param string $hash The hash
228 * @param string $path The image path
229 * @param int $height The height
230 * @param int $width The width
231 * @return Response The rendered image
233 public function facebook(Request
$request, string $hash, string $path, int $height, int $width, string $_format): Response
{
234 //Without matching hash
235 if ($hash !== $this->slugger
->serialize([$path, $height, $width])) {
236 //Throw new exception
237 throw new NotFoundHttpException(sprintf('Unable to match facebook hash: %s', $hash));
238 //Without matching format
239 } elseif ($_format !== 'jpeg' && $_format !== 'png' && $_format !== 'webp') {
240 //Throw new exception
241 throw new NotFoundHttpException(sprintf('Invalid facebook format: %s', $_format));
245 $path = $this->slugger
->unshort($short = $path);
247 //Without facebook file
248 if (!is_file($facebook = $this->config
['cache'].'/'.$this->config
['prefixes']['facebook'].$path.'.'.$_format)) {
249 //Throw new exception
250 throw new NotFoundHttpException('Unable to get facebook file');
253 //Read facebook from cache
254 $response = new BinaryFileResponse($facebook);
257 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'facebook-'.$hash.'.'.$_format);
260 $response->setEtag(md5($hash));
263 $response->setLastModified(\DateTime
::createFromFormat('U', strval(stat($facebook)['mtime'])));
266 $response->setPublic();
268 //Return 304 response if not modified
269 $response->isNotModified($request);
278 * @param Request $request The Request instance
279 * @param string $hash The hash
280 * @param int $updated The updated timestamp
281 * @param float $latitude The latitude
282 * @param float $longitude The longitude
283 * @param int $zoom The zoom
284 * @param int $width The width
285 * @param int $height The height
286 * @return Response The rendered image
288 public function map(Request
$request, string $hash, float $latitude, float $longitude, int $height, int $width, int $zoom, string $_format): Response
{
289 //Without matching hash
290 if ($hash !== $this->slugger
->hash([$height, $width, $zoom, $latitude, $longitude])) {
291 //Throw new exception
292 throw new NotFoundHttpException(sprintf('Unable to match map hash: %s', $hash));
296 $map = $this->config
['cache'].'/'.$this->config
['prefixes']['map'].'/'.$zoom.'/'.($latitude*1000000%
10).'/'.($longitude*1000000%
10).'/'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.'.$_format;
299 //TODO: refresh after config modification ?
300 if (!is_file($map)) {
301 //Without existing map path
302 if (!is_dir($dir = dirname($map))) {
303 //Create filesystem object
304 $filesystem = new Filesystem();
308 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
309 //XXX: on CoW filesystems execute a chattr +C before filling
310 $filesystem->mkdir($dir, 0775);
311 } catch (IOExceptionInterface
$e) {
313 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
317 //Create image instance
318 $image = new \
Imagick();
321 $image->newImage($width, $height, new \
ImagickPixel('transparent'), $_format);
323 //Create tile instance
324 $tile = new \
Imagick();
327 $centerX = $this->image
->longitudeToX($longitude, $zoom);
328 $centerY = $this->image
->latitudeToY($latitude, $zoom);
331 $startX = floor(floor($centerX) - $width / $this->config
['map']['tz']);
332 $startY = floor(floor($centerY) - $height / $this->config
['map']['tz']);
335 $endX = ceil(ceil($centerX) +
$width / $this->config
['map']['tz']);
336 $endY = ceil(ceil($centerY) +
$height / $this->config
['map']['tz']);
338 for($x = $startX; $x <= $endX; $x++
) {
339 for($y = $startY; $y <= $endY; $y++
) {
341 $cache = $this->config
['cache'].'/'.$this->config
['prefixes']['map'].'/'.$zoom.'/'.($x%
10).'/'.($y%
10).'/'.$x.','.$y.'.png';
343 //Without cache image
344 if (!is_file($cache)) {
346 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->config
['servers'][$this->config
['map']['server']]);
349 if (!is_dir($dir = dirname($cache))) {
350 //Create filesystem object
351 $filesystem = new Filesystem();
355 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
356 $filesystem->mkdir($dir, 0775);
357 } catch (IOExceptionInterface
$e) {
359 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
363 //Store tile in cache
364 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
));
368 $destX = intval(floor($width / 2 - $this->config
['map']['tz'] * ($centerX - $x)));
371 $destY = intval(floor($height / 2 - $this->config
['map']['tz'] * ($centerY - $y)));
373 //Read tile from cache
374 $tile->readImage($cache);
377 $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY);
384 //Add imagick draw instance
385 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
386 $draw = new \
ImagickDraw();
389 $draw->setTextAntialias(true);
391 //Set stroke antialias
392 $draw->setStrokeAntialias(true);
395 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
398 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
401 $draw->setFillColor($this->config
['map']['fill']);
404 $draw->setStrokeColor($this->config
['map']['border']);
407 $draw->setStrokeWidth($this->config
['map']['thickness']);
410 $draw->circle($width/2 - $this->config
['map']['radius'], $height/2 - $this->config
['map']['radius'], $width/2 +
$this->config
['map']['radius'], $height/2 +
$this->config
['map']['radius']);
413 $image->drawImage($draw);
415 //Strip image exif data and properties
416 $image->stripImage();
419 //XXX: not supported by imagick :'(
420 $image->setImageProperty('exif:GPSLatitude', $this->image
->latitudeToSexagesimal($latitude));
423 //XXX: not supported by imagick :'(
424 $image->setImageProperty('exif:GPSLongitude', $this->image
->longitudeToSexagesimal($longitude));
426 //Set progressive jpeg
427 $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
);
429 //Set compression quality
430 $image->setImageCompressionQuality($this->config
['map']['quality']);
433 if (!$image->writeImage($map)) {
435 throw new \
Exception(sprintf('Unable to write image "%s"', $map));
439 //Read map from cache
440 $response = new BinaryFileResponse($map);
443 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, basename($map));
446 $response->setEtag(md5(serialize([$height, $width, $zoom, $latitude, $longitude])));
449 $response->setLastModified(\DateTime
::createFromFormat('U', strval(stat($map)['mtime'])));
451 //Disable robot index
452 $response->headers
->set('X-Robots-Tag', 'noindex');
455 $response->setPublic();
457 //Return 304 response if not modified
458 $response->isNotModified($request);
465 * Return multi map image
467 * @param Request $request The Request instance
468 * @param string $hash The hash
469 * @param int $updated The updated timestamp
470 * @param float $latitude The latitude
471 * @param float $longitude The longitude
472 * @param string $coordinates The coordinates
473 * @param int $zoom The zoom
474 * @param int $width The width
475 * @param int $height The height
476 * @return Response The rendered image
478 public function multi(Request
$request, string $hash, string $coordinate, int $height, int $width, int $zoom, string $_format): Response
{
479 //Without matching hash
480 if ($hash !== $this->slugger
->hash([$height, $width, $zoom, $coordinate])) {
481 //Throw new exception
482 throw new NotFoundHttpException(sprintf('Unable to match multi map hash: %s', $hash));
485 //Set latitudes and longitudes array
486 $latitudes = $longitudes = [];
489 $coordinates = array_map(
490 function ($v) use (&$latitudes, &$longitudes) {
491 list($latitude, $longitude) = explode(',', $v);
492 $latitudes[] = $latitude;
493 $longitudes[] = $longitude;
494 return [ $latitude, $longitude ];
496 explode('-', $coordinate)
500 $latitude = round((min($latitudes)+
max($latitudes))/2, 6);
503 $longitude = round((min($longitudes)+
max($longitudes))/2, 6);
506 $map = $this->config
['cache'].'/'.$this->config
['prefixes']['multi'].'/'.$zoom.'/'.($latitude*1000000%
10).'/'.($longitude*1000000%
10).'/'.$coordinate.'-'.$zoom.'-'.$width.'x'.$height.'.'.$_format;
509 if (!is_file($map)) {
510 //Without existing multi path
511 if (!is_dir($dir = dirname($map))) {
512 //Create filesystem object
513 $filesystem = new Filesystem();
517 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
518 //XXX: on CoW filesystems execute a chattr +C before filling
519 $filesystem->mkdir($dir, 0775);
520 } catch (IOExceptionInterface
$e) {
522 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
526 //Create image instance
527 $image = new \
Imagick();
530 $image->newImage($width, $height, new \
ImagickPixel('transparent'), $_format);
532 //Create tile instance
533 $tile = new \
Imagick();
536 $centerX = $this->image
->longitudeToX($longitude, $zoom);
537 $centerY = $this->image
->latitudeToY($latitude, $zoom);
540 $startX = floor(floor($centerX) - $width / $this->config
['multi']['tz']);
541 $startY = floor(floor($centerY) - $height / $this->config
['multi']['tz']);
544 $endX = ceil(ceil($centerX) +
$width / $this->config
['multi']['tz']);
545 $endY = ceil(ceil($centerY) +
$height / $this->config
['multi']['tz']);
547 for($x = $startX; $x <= $endX; $x++
) {
548 for($y = $startY; $y <= $endY; $y++
) {
550 $cache = $this->config
['cache'].'/'.$this->config
['prefixes']['multi'].'/'.$zoom.'/'.($x%
10).'/'.($y%
10).'/'.$x.','.$y.'.png';
552 //Without cache image
553 if (!is_file($cache)) {
555 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->config
['servers'][$this->config
['multi']['server']]);
558 if (!is_dir($dir = dirname($cache))) {
559 //Create filesystem object
560 $filesystem = new Filesystem();
564 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
565 $filesystem->mkdir($dir, 0775);
566 } catch (IOExceptionInterface
$e) {
568 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
572 //Store tile in cache
573 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
));
577 $destX = intval(floor($width / 2 - $this->config
['multi']['tz'] * ($centerX - $x)));
580 $destY = intval(floor($height / 2 - $this->config
['multi']['tz'] * ($centerY - $y)));
582 //Read tile from cache
583 $tile->readImage($cache);
586 $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY);
593 //Add imagick draw instance
594 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
595 $draw = new \
ImagickDraw();
598 $draw->setTextAntialias(true);
600 //Set stroke antialias
601 $draw->setStrokeAntialias(true);
604 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
607 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
609 //Iterate on locations
610 foreach($coordinates as $id => $coordinate) {
612 list($clatitude, $clongitude) = $coordinate;
615 $destX = intval(floor($width / 2 - $this->config
['multi']['tz'] * ($centerX - $this->image
->longitudeToX(floatval($clongitude), $zoom))));
618 $destY = intval(floor($height / 2 - $this->config
['multi']['tz'] * ($centerY - $this->image
->latitudeToY(floatval($clatitude), $zoom))));
621 $draw->setFillColor($this->config
['multi']['fill']);
624 $draw->setFontSize($this->config
['multi']['size']);
627 $draw->setStrokeColor($this->config
['multi']['border']);
630 $radius = $this->config
['multi']['radius'];
633 $stroke = $this->config
['multi']['thickness'];
635 //With matching position
636 if ($clatitude === $latitude && $clongitude == $longitude) {
638 $draw->setFillColor($this->config
['multi']['highfill']);
641 $draw->setFontSize($this->config
['multi']['highsize']);
644 $draw->setStrokeColor($this->config
['multi']['highborder']);
647 $radius = $this->config
['multi']['highradius'];
650 $stroke = $this->config
['multi']['highthickness'];
654 $draw->setStrokeWidth($stroke);
657 $draw->circle($destX - $radius, $destY - $radius, $destX +
$radius, $destY +
$radius);
660 $draw->setFillColor($draw->getStrokeColor());
663 $draw->setStrokeWidth($stroke / 4);
666 #$metrics = $image->queryFontMetrics($draw, strval($id));
669 $draw->annotation($destX - $radius, $destY +
$stroke, strval($id));
673 $image->drawImage($draw);
675 //Strip image exif data and properties
676 $image->stripImage();
679 //XXX: not supported by imagick :'(
680 $image->setImageProperty('exif:GPSLatitude', $this->image
->latitudeToSexagesimal($latitude));
683 //XXX: not supported by imagick :'(
684 $image->setImageProperty('exif:GPSLongitude', $this->image
->longitudeToSexagesimal($longitude));
687 //XXX: not supported by imagick :'(
688 #$image->setImageProperty('exif:Description', $caption);
690 //Set progressive jpeg
691 $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
);
693 //Set compression quality
694 $image->setImageCompressionQuality($this->config
['multi']['quality']);
697 if (!$image->writeImage($map)) {
699 throw new \
Exception(sprintf('Unable to write image "%s"', $path));
703 //Read map from cache
704 $response = new BinaryFileResponse($map);
707 #$response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'multimap-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
708 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, basename($map));
711 $response->setEtag(md5(serialize([$height, $width, $zoom, $coordinate])));
714 $response->setLastModified(\DateTime
::createFromFormat('U', strval(stat($map)['mtime'])));
716 //Disable robot index
717 $response->headers
->set('X-Robots-Tag', 'noindex');
720 $response->setPublic();
722 //Return 304 response if not modified
723 $response->isNotModified($request);
732 * @param Request $request The Request instance
733 * @param string $hash The hash
734 * @param string $path The image path
735 * @param int $height The height
736 * @param int $width The width
737 * @return Response The rendered image
739 public function thumb(Request
$request, string $hash, string $path, int $height, int $width, string $_format): Response
{
740 //Without matching hash
741 if ($hash !== $this->slugger
->serialize([$path, $height, $width])) {
742 //Throw new exception
743 throw new NotFoundHttpException('Invalid thumb hash');
744 //Without valid format
745 } elseif ($_format !== 'jpeg' && $_format !== 'png' && $_format !== 'webp') {
746 //Throw new exception
747 throw new NotFoundHttpException('Invalid thumb format');
751 $path = $this->slugger
->unshort($short = $path);
754 $thumb = $this->config
['cache'].'/'.$this->config
['prefixes']['thumb'].$path.'.'.$_format;
757 if (!is_file($path) || !($updated = stat($path)['mtime'])) {
758 //Throw new exception
759 throw new NotFoundHttpException('Unable to get thumb file');
762 //Without thumb up to date file
763 if (!is_file($thumb) || !($mtime = stat($thumb)['mtime']) || $mtime < $updated) {
764 //Without existing thumb path
765 if (!is_dir($dir = dirname($thumb))) {
766 //Create filesystem object
767 $filesystem = new Filesystem();
771 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
772 //XXX: on CoW filesystems execute a chattr +C before filling
773 $filesystem->mkdir($dir, 0775);
774 } catch (IOExceptionInterface
$e) {
776 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
780 //Create image instance
781 $image = new \
Imagick();
784 $image->readImage(realpath($path));
786 //Crop using aspect ratio
787 //XXX: for better result upload image directly in aspect ratio :)
788 $image->cropThumbnailImage($width, $height);
790 //Strip image exif data and properties
791 $image->stripImage();
793 //Set compression quality
795 $image->setImageCompressionQuality(70);
798 #$image->setImageFormat($_format);
801 if (!$image->writeImage($thumb)) {
803 throw new \
Exception(sprintf('Unable to write image "%s"', $thumb));
807 $mtime = stat($thumb)['mtime'];
810 //Read thumb from cache
811 $response = new BinaryFileResponse($thumb);
814 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'thumb-'.$hash.'.'.$_format);
817 $response->setEtag(md5($hash));
820 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
823 $response->setPublic();
825 //Return 304 response if not modified
826 $response->isNotModified($request);