]> Raphaël G. Git Repositories - packbundle/blob - Controller.php
Use hash instead of coordinate chain to generate map cache filename not too long...
[packbundle] / Controller.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys PackBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\PackBundle;
13
14 use Rapsys\PackBundle\Util\ImageUtil;
15 use Rapsys\PackBundle\Util\SluggerUtil;
16
17 use Psr\Container\ContainerInterface;
18
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;
29
30 /**
31 * {@inheritdoc}
32 */
33 class Controller extends AbstractController implements ServiceSubscriberInterface {
34 /**
35 * Alias string
36 */
37 protected string $alias;
38
39 /**
40 * Config array
41 */
42 protected array $config;
43
44 /**
45 * Stream context
46 */
47 protected mixed $ctx;
48
49 /**
50 * Version string
51 */
52 protected string $version;
53
54 /**
55 * Creates a new image controller
56 *
57 * @param ContainerInterface $container The ContainerInterface instance
58 * @param ImageUtil $image The MapUtil instance
59 * @param SluggerUtil $slugger The SluggerUtil instance
60 */
61 function __construct(protected ContainerInterface $container, protected ImageUtil $image, protected SluggerUtil $slugger) {
62 //Retrieve config
63 $this->config = $container->getParameter($this->alias = RapsysPackBundle::getAlias());
64
65 //Set ctx
66 $this->ctx = stream_context_create($this->config['context']);
67 }
68
69 /**
70 * Return captcha image
71 *
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
78 */
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])) {
82 //Throw new exception
83 throw new NotFoundHttpException(sprintf('Unable to match captcha hash: %s', $hash));
84 //Without valid format
85 } elseif ($_format !== 'jpeg' && $_format !== 'png' && $_format !== 'webp') {
86 //Throw new exception
87 throw new NotFoundHttpException('Invalid thumb format');
88 }
89
90 //Unshort equation
91 $equation = $this->slugger->unshort($short = $equation);
92
93 //Set hashed tree
94 $hashed = str_split(strval($equation));
95
96 //Set captcha
97 $captcha = $this->config['cache'].'/'.$this->config['prefixes']['captcha'].'/'.$hashed[0].'/'.$hashed[4].'/'.$hashed[8].'/'.$short.'.'.$_format;
98
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();
105
106 try {
107 //Create path
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) {
112 //Throw error
113 throw new \Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
114 }
115 }
116
117 //Create image instance
118 $image = new \Imagick();
119
120 //Add imagick draw instance
121 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
122 $draw = new \ImagickDraw();
123
124 //Set text antialias
125 $draw->setTextAntialias(true);
126
127 //Set stroke antialias
128 $draw->setStrokeAntialias(true);
129
130 //Set text alignment
131 $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
132
133 //Set gravity
134 $draw->setGravity(\Imagick::GRAVITY_CENTER);
135
136 //Set fill color
137 $draw->setFillColor($this->config['captcha']['fill']);
138
139 //Set stroke color
140 $draw->setStrokeColor($this->config['captcha']['border']);
141
142 //Set font size
143 $draw->setFontSize($this->config['captcha']['size'] / 1.5);
144
145 //Set stroke width
146 $draw->setStrokeWidth($this->config['captcha']['thickness'] / 3);
147
148 //Set rotation
149 $draw->rotate($rotate = (rand(25, 75)*(rand(0,1)?-.1:.1)));
150
151 //Get font metrics
152 $metrics2 = $image->queryFontMetrics($draw, strval('stop spam'));
153
154 //Add annotation
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'));
156
157 //Set rotation
158 $draw->rotate(-$rotate);
159
160 //Set font size
161 $draw->setFontSize($this->config['captcha']['size']);
162
163 //Set stroke width
164 $draw->setStrokeWidth($this->config['captcha']['thickness']);
165
166 //Set rotation
167 $draw->rotate($rotate = (rand(25, 50)*(rand(0,1)?-.1:.1)));
168
169 //Get font metrics
170 $metrics = $image->queryFontMetrics($draw, strval($equation));
171
172 //Add annotation
173 $draw->annotation($width / 2, ceil($metrics['textHeight'] + $metrics['descender'] + $metrics['ascender']) / 2 - $this->config['captcha']['thickness'], strval($equation));
174
175 //Set rotation
176 $draw->rotate(-$rotate);
177
178 //Add new image
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);
181
182 //Draw on image
183 $image->drawImage($draw);
184
185 //Strip image exif data and properties
186 $image->stripImage();
187
188 //Set compression quality
189 $image->setImageCompressionQuality(70);
190
191 //Save captcha
192 if (!$image->writeImage($captcha)) {
193 //Throw error
194 throw new \Exception(sprintf('Unable to write image "%s"', $captcha));
195 }
196
197 //Set mtime
198 $mtime = stat($captcha)['mtime'];
199 }
200
201 //Read captcha from cache
202 $response = new BinaryFileResponse($captcha);
203
204 //Set file name
205 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'captcha-stop-spam-'.str_replace([' ', '*', '+'], ['-', 'mul', 'add'], $equation).'.'.$_format);
206
207 //Set etag
208 $response->setEtag(md5($hash));
209
210 //Set last modified
211 $response->setLastModified(\DateTime::createFromFormat('U', strval($mtime)));
212
213 //Set as public
214 $response->setPublic();
215
216 //Return 304 response if not modified
217 $response->isNotModified($request);
218
219 //Return response
220 return $response;
221 }
222
223 /**
224 * Return download file
225 *
226 * @param Request $request The Request instance
227 * @param string $hash The hash
228 * @param string $path The image path
229 * @return Response The rendered image
230 */
231 public function download(Request $request, string $hash, string $path/*, string $_format*/): Response {
232 //Without matching hash
233 if ($hash !== $this->slugger->hash($path)) {
234 //Throw new exception
235 throw new NotFoundHttpException('Invalid download hash');
236 //Without valid format
237 #} elseif ($_format !== 'jpeg' && $_format !== 'png' && $_format !== 'webp') {
238 # //Throw new exception
239 # throw new NotFoundHttpException('Invalid download format');
240 }
241
242 //Unshort path
243 $path = $this->slugger->unshort($short = $path);
244
245 //Without file
246 if (!is_file($path) || !($mtime = stat($path)['mtime'])) {
247 //Throw new exception
248 throw new NotFoundHttpException('Unable to get thumb file');
249 }
250
251 //Read thumb from cache
252 $response = new BinaryFileResponse($path);
253
254 //Set file name
255 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, basename($path));
256
257 //Set etag
258 //TODO: set etag to file content md5 ? cache it ?
259 $response->setEtag(md5($hash));
260
261 //Set last modified
262 $response->setLastModified(\DateTime::createFromFormat('U', strval($mtime)));
263
264 //Set as public
265 $response->setPublic();
266
267 //Return 304 response if not modified
268 $response->isNotModified($request);
269
270 //Return response
271 return $response;
272 }
273
274 /**
275 * Return facebook image
276 *
277 * @param Request $request The Request instance
278 * @param string $hash The hash
279 * @param string $path The image path
280 * @param int $height The height
281 * @param int $width The width
282 * @return Response The rendered image
283 */
284 public function facebook(Request $request, string $hash, string $path, int $height, int $width, string $_format): Response {
285 //Without matching hash
286 if ($hash !== $this->slugger->serialize([$path, $height, $width])) {
287 //Throw new exception
288 throw new NotFoundHttpException(sprintf('Unable to match facebook hash: %s', $hash));
289 //Without matching format
290 } elseif ($_format !== 'jpeg' && $_format !== 'png' && $_format !== 'webp') {
291 //Throw new exception
292 throw new NotFoundHttpException(sprintf('Invalid facebook format: %s', $_format));
293 }
294
295 //Unshort path
296 $path = $this->slugger->unshort($short = $path);
297
298 //Without facebook file
299 if (!is_file($facebook = $this->config['cache'].'/'.$this->config['prefixes']['facebook'].$path.'.'.$_format)) {
300 //Throw new exception
301 throw new NotFoundHttpException('Unable to get facebook file');
302 }
303
304 //Read facebook from cache
305 $response = new BinaryFileResponse($facebook);
306
307 //Set file name
308 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'facebook-'.$hash.'.'.$_format);
309
310 //Set etag
311 //TODO: set etag to file content md5 ? cache it ?
312 $response->setEtag(md5($hash));
313
314 //Set last modified
315 $response->setLastModified(\DateTime::createFromFormat('U', strval(stat($facebook)['mtime'])));
316
317 //Set as public
318 $response->setPublic();
319
320 //Return 304 response if not modified
321 $response->isNotModified($request);
322
323 //Return response
324 return $response;
325 }
326
327 /**
328 * Return map image
329 *
330 * @param Request $request The Request instance
331 * @param string $hash The hash
332 * @param int $updated The updated timestamp
333 * @param float $latitude The latitude
334 * @param float $longitude The longitude
335 * @param int $zoom The zoom
336 * @param int $width The width
337 * @param int $height The height
338 * @return Response The rendered image
339 */
340 public function map(Request $request, string $hash, float $latitude, float $longitude, int $height, int $width, int $zoom, string $_format): Response {
341 //Without matching hash
342 if ($hash !== $this->slugger->hash([$height, $width, $zoom, $latitude, $longitude])) {
343 //Throw new exception
344 throw new NotFoundHttpException(sprintf('Unable to match map hash: %s', $hash));
345 }
346
347 //Set map
348 $map = $this->config['cache'].'/'.$this->config['prefixes']['map'].'/'.$zoom.'/'.($latitude*1000000%10).'/'.($longitude*1000000%10).'/'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.'.$_format;
349
350 //Without map file
351 //TODO: refresh after config modification ?
352 if (!is_file($map)) {
353 //Without existing map path
354 if (!is_dir($dir = dirname($map))) {
355 //Create filesystem object
356 $filesystem = new Filesystem();
357
358 try {
359 //Create path
360 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
361 //XXX: on CoW filesystems execute a chattr +C before filling
362 $filesystem->mkdir($dir, 0775);
363 } catch (IOExceptionInterface $e) {
364 //Throw error
365 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
366 }
367 }
368
369 //Create image instance
370 $image = new \Imagick();
371
372 //Add new image
373 $image->newImage($width, $height, new \ImagickPixel('transparent'), $_format);
374
375 //Create tile instance
376 $tile = new \Imagick();
377
378 //Get tile xy
379 $centerX = $this->image->longitudeToX($longitude, $zoom);
380 $centerY = $this->image->latitudeToY($latitude, $zoom);
381
382 //Calculate start xy
383 $startX = floor(floor($centerX) - $width / $this->config['map']['tz']);
384 $startY = floor(floor($centerY) - $height / $this->config['map']['tz']);
385
386 //Calculate end xy
387 $endX = ceil(ceil($centerX) + $width / $this->config['map']['tz']);
388 $endY = ceil(ceil($centerY) + $height / $this->config['map']['tz']);
389
390 for($x = $startX; $x <= $endX; $x++) {
391 for($y = $startY; $y <= $endY; $y++) {
392 //Set cache path
393 $cache = $this->config['cache'].'/'.$this->config['prefixes']['map'].'/'.$zoom.'/'.($x%10).'/'.($y%10).'/'.$x.','.$y.'.png';
394
395 //Without cache image
396 if (!is_file($cache)) {
397 //Set tile url
398 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->config['servers'][$this->config['map']['server']]);
399
400 //Without cache path
401 if (!is_dir($dir = dirname($cache))) {
402 //Create filesystem object
403 $filesystem = new Filesystem();
404
405 try {
406 //Create path
407 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
408 $filesystem->mkdir($dir, 0775);
409 } catch (IOExceptionInterface $e) {
410 //Throw error
411 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
412 }
413 }
414
415 //Store tile in cache
416 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx));
417 }
418
419 //Set dest x
420 $destX = intval(floor($width / 2 - $this->config['map']['tz'] * ($centerX - $x)));
421
422 //Set dest y
423 $destY = intval(floor($height / 2 - $this->config['map']['tz'] * ($centerY - $y)));
424
425 //Read tile from cache
426 $tile->readImage($cache);
427
428 //Compose image
429 $image->compositeImage($tile, \Imagick::COMPOSITE_OVER, $destX, $destY);
430
431 //Clear tile
432 $tile->clear();
433 }
434 }
435
436 //Add imagick draw instance
437 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
438 $draw = new \ImagickDraw();
439
440 //Set text antialias
441 $draw->setTextAntialias(true);
442
443 //Set stroke antialias
444 $draw->setStrokeAntialias(true);
445
446 //Set text alignment
447 $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
448
449 //Set gravity
450 $draw->setGravity(\Imagick::GRAVITY_CENTER);
451
452 //Set fill color
453 $draw->setFillColor($this->config['map']['fill']);
454
455 //Set stroke color
456 $draw->setStrokeColor($this->config['map']['border']);
457
458 //Set stroke width
459 $draw->setStrokeWidth($this->config['map']['thickness']);
460
461 //Draw circle
462 $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']);
463
464 //Draw on image
465 $image->drawImage($draw);
466
467 //Strip image exif data and properties
468 $image->stripImage();
469
470 //Add latitude
471 //XXX: not supported by imagick :'(
472 $image->setImageProperty('exif:GPSLatitude', $this->image->latitudeToSexagesimal($latitude));
473
474 //Add longitude
475 //XXX: not supported by imagick :'(
476 $image->setImageProperty('exif:GPSLongitude', $this->image->longitudeToSexagesimal($longitude));
477
478 //Set progressive jpeg
479 $image->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
480
481 //Set compression quality
482 $image->setImageCompressionQuality($this->config['map']['quality']);
483
484 //Save image
485 if (!$image->writeImage($map)) {
486 //Throw error
487 throw new \Exception(sprintf('Unable to write image "%s"', $map));
488 }
489 }
490
491 //Read map from cache
492 $response = new BinaryFileResponse($map);
493
494 //Set file name
495 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, basename($map));
496
497 //Set etag
498 //TODO: set etag to file content md5 ? cache it ?
499 $response->setEtag(md5(serialize([$height, $width, $zoom, $latitude, $longitude])));
500
501 //Set last modified
502 $response->setLastModified(\DateTime::createFromFormat('U', strval(stat($map)['mtime'])));
503
504 //Disable robot index
505 $response->headers->set('X-Robots-Tag', 'noindex');
506
507 //Set as public
508 $response->setPublic();
509
510 //Return 304 response if not modified
511 $response->isNotModified($request);
512
513 //Return response
514 return $response;
515 }
516
517 /**
518 * Return multi map image
519 *
520 * @param Request $request The Request instance
521 * @param string $hash The hash
522 * @param int $updated The updated timestamp
523 * @param float $latitude The latitude
524 * @param float $longitude The longitude
525 * @param string $coordinates The coordinates
526 * @param int $zoom The zoom
527 * @param int $width The width
528 * @param int $height The height
529 * @return Response The rendered image
530 */
531 public function multi(Request $request, string $hash, string $coordinate, int $height, int $width, int $zoom, string $_format): Response {
532 //Without matching hash
533 if ($hash !== $this->slugger->hash([$height, $width, $zoom, $coordinate])) {
534 //Throw new exception
535 throw new NotFoundHttpException(sprintf('Unable to match multi map hash: %s', $hash));
536 }
537
538 //Set latitudes and longitudes array
539 $latitudes = $longitudes = [];
540
541 //Set coordinates
542 $coordinates = array_map(
543 function ($v) use (&$latitudes, &$longitudes) {
544 list($latitude, $longitude) = explode(',', $v);
545 $latitudes[] = $latitude;
546 $longitudes[] = $longitude;
547 return [ $latitude, $longitude ];
548 },
549 explode('-', $coordinate)
550 );
551
552 //Set latitude
553 $latitude = round((min($latitudes)+max($latitudes))/2, 6);
554
555 //Set longitude
556 $longitude = round((min($longitudes)+max($longitudes))/2, 6);
557
558 //Set map
559 //XXX: use hash with number of coordinates instead of coordinate value, filename over 255 characters isn't supported on many systems
560 $map = $this->config['cache'].'/'.$this->config['prefixes']['multi'].'/'.$zoom.'/'.($latitude*1000000%10).'/'.($longitude*1000000%10).'/'.$hash.'-'.count($coordinates).'-'.$zoom.'-'.$width.'x'.$height.'.'.$_format;
561
562 //Without map file
563 if (!is_file($map)) {
564 //Without existing multi path
565 if (!is_dir($dir = dirname($map))) {
566 //Create filesystem object
567 $filesystem = new Filesystem();
568
569 try {
570 //Create path
571 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
572 //XXX: on CoW filesystems execute a chattr +C before filling
573 $filesystem->mkdir($dir, 0775);
574 } catch (IOExceptionInterface $e) {
575 //Throw error
576 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
577 }
578 }
579
580 //Create image instance
581 $image = new \Imagick();
582
583 //Add new image
584 $image->newImage($width, $height, new \ImagickPixel('transparent'), $_format);
585
586 //Create tile instance
587 $tile = new \Imagick();
588
589 //Get tile xy
590 $centerX = $this->image->longitudeToX($longitude, $zoom);
591 $centerY = $this->image->latitudeToY($latitude, $zoom);
592
593 //Calculate start xy
594 $startX = floor(floor($centerX) - $width / $this->config['multi']['tz']);
595 $startY = floor(floor($centerY) - $height / $this->config['multi']['tz']);
596
597 //Calculate end xy
598 $endX = ceil(ceil($centerX) + $width / $this->config['multi']['tz']);
599 $endY = ceil(ceil($centerY) + $height / $this->config['multi']['tz']);
600
601 for($x = $startX; $x <= $endX; $x++) {
602 for($y = $startY; $y <= $endY; $y++) {
603 //Set cache path
604 $cache = $this->config['cache'].'/'.$this->config['prefixes']['multi'].'/'.$zoom.'/'.($x%10).'/'.($y%10).'/'.$x.','.$y.'.png';
605
606 //Without cache image
607 if (!is_file($cache)) {
608 //Set tile url
609 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->config['servers'][$this->config['multi']['server']]);
610
611 //Without cache path
612 if (!is_dir($dir = dirname($cache))) {
613 //Create filesystem object
614 $filesystem = new Filesystem();
615
616 try {
617 //Create path
618 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
619 $filesystem->mkdir($dir, 0775);
620 } catch (IOExceptionInterface $e) {
621 //Throw error
622 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
623 }
624 }
625
626 //Store tile in cache
627 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx));
628 }
629
630 //Set dest x
631 $destX = intval(floor($width / 2 - $this->config['multi']['tz'] * ($centerX - $x)));
632
633 //Set dest y
634 $destY = intval(floor($height / 2 - $this->config['multi']['tz'] * ($centerY - $y)));
635
636 //Read tile from cache
637 $tile->readImage($cache);
638
639 //Compose image
640 $image->compositeImage($tile, \Imagick::COMPOSITE_OVER, $destX, $destY);
641
642 //Clear tile
643 $tile->clear();
644 }
645 }
646
647 //Add imagick draw instance
648 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
649 $draw = new \ImagickDraw();
650
651 //Set text antialias
652 $draw->setTextAntialias(true);
653
654 //Set stroke antialias
655 $draw->setStrokeAntialias(true);
656
657 //Set text alignment
658 $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
659
660 //Set gravity
661 $draw->setGravity(\Imagick::GRAVITY_CENTER);
662
663 //Iterate on locations
664 foreach($coordinates as $id => $coordinate) {
665 //Get coordinates
666 list($clatitude, $clongitude) = $coordinate;
667
668 //Set dest x
669 $destX = intval(floor($width / 2 - $this->config['multi']['tz'] * ($centerX - $this->image->longitudeToX(floatval($clongitude), $zoom))));
670
671 //Set dest y
672 $destY = intval(floor($height / 2 - $this->config['multi']['tz'] * ($centerY - $this->image->latitudeToY(floatval($clatitude), $zoom))));
673
674 //Set fill color
675 $draw->setFillColor($this->config['multi']['fill']);
676
677 //Set font size
678 $draw->setFontSize($this->config['multi']['size']);
679
680 //Set stroke color
681 $draw->setStrokeColor($this->config['multi']['border']);
682
683 //Set circle radius
684 $radius = $this->config['multi']['radius'];
685
686 //Set stroke width
687 $stroke = $this->config['multi']['thickness'];
688
689 //With matching position
690 if ($clatitude === $latitude && $clongitude == $longitude) {
691 //Set fill color
692 $draw->setFillColor($this->config['multi']['highfill']);
693
694 //Set font size
695 $draw->setFontSize($this->config['multi']['highsize']);
696
697 //Set stroke color
698 $draw->setStrokeColor($this->config['multi']['highborder']);
699
700 //Set circle radius
701 $radius = $this->config['multi']['highradius'];
702
703 //Set stroke width
704 $stroke = $this->config['multi']['highthickness'];
705 }
706
707 //Set stroke width
708 $draw->setStrokeWidth($stroke);
709
710 //Draw circle
711 $draw->circle($destX - $radius, $destY - $radius, $destX + $radius, $destY + $radius);
712
713 //Set fill color
714 $draw->setFillColor($draw->getStrokeColor());
715
716 //Set stroke width
717 $draw->setStrokeWidth($stroke / 4);
718
719 //Get font metrics
720 #$metrics = $image->queryFontMetrics($draw, strval($id));
721
722 //Add annotation
723 $draw->annotation($destX - $radius, $destY + $stroke, strval($id));
724 }
725
726 //Draw on image
727 $image->drawImage($draw);
728
729 //Strip image exif data and properties
730 $image->stripImage();
731
732 //Add latitude
733 //XXX: not supported by imagick :'(
734 $image->setImageProperty('exif:GPSLatitude', $this->image->latitudeToSexagesimal($latitude));
735
736 //Add longitude
737 //XXX: not supported by imagick :'(
738 $image->setImageProperty('exif:GPSLongitude', $this->image->longitudeToSexagesimal($longitude));
739
740 //Add description
741 //XXX: not supported by imagick :'(
742 #$image->setImageProperty('exif:Description', $caption);
743
744 //Set progressive jpeg
745 $image->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
746
747 //Set compression quality
748 $image->setImageCompressionQuality($this->config['multi']['quality']);
749
750 //Save image
751 if (!$image->writeImage($map)) {
752 //Throw error
753 throw new \Exception(sprintf('Unable to write image "%s"', $path));
754 }
755 }
756
757 //Read map from cache
758 $response = new BinaryFileResponse($map);
759
760 //Set file name
761 #$response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'multimap-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
762 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, basename($map));
763
764 //Set etag
765 //TODO: set etag to file content md5 ? cache it ?
766 $response->setEtag(md5(serialize([$height, $width, $zoom, $coordinate])));
767
768 //Set last modified
769 $response->setLastModified(\DateTime::createFromFormat('U', strval(stat($map)['mtime'])));
770
771 //Disable robot index
772 $response->headers->set('X-Robots-Tag', 'noindex');
773
774 //Set as public
775 $response->setPublic();
776
777 //Return 304 response if not modified
778 $response->isNotModified($request);
779
780 //Return response
781 return $response;
782 }
783
784 /**
785 * Return thumb image
786 *
787 * @param Request $request The Request instance
788 * @param string $hash The hash
789 * @param string $path The image path
790 * @param int $height The height
791 * @param int $width The width
792 * @return Response The rendered image
793 */
794 public function thumb(Request $request, string $hash, string $path, int $height, int $width, string $_format): Response {
795 //Without matching hash
796 if ($hash !== $this->slugger->serialize([$path, $height, $width])) {
797 //Throw new exception
798 throw new NotFoundHttpException('Invalid thumb hash');
799 //Without valid format
800 } elseif ($_format !== 'jpeg' && $_format !== 'png' && $_format !== 'webp') {
801 //Throw new exception
802 throw new NotFoundHttpException('Invalid thumb format');
803 }
804
805 //Unshort path
806 $path = $this->slugger->unshort($short = $path);
807
808 //Set thumb
809 $thumb = $this->config['cache'].'/'.$this->config['prefixes']['thumb'].$path.'.'.$width.'x'.$height.'.'.$_format;
810
811 //Without file
812 if (!is_file($path) || !($mtime = stat($path)['mtime'])) {
813 //Throw new exception
814 throw new NotFoundHttpException('Unable to get thumb file');
815 }
816
817 //Without thumb up to date file
818 if (!is_file($thumb) || !($updated = stat($thumb)['mtime']) || $updated < $mtime) {
819 //Without existing thumb path
820 if (!is_dir($dir = dirname($thumb))) {
821 //Create filesystem object
822 $filesystem = new Filesystem();
823
824 try {
825 //Create path
826 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
827 //XXX: on CoW filesystems execute a chattr +C before filling
828 $filesystem->mkdir($dir, 0775);
829 } catch (IOExceptionInterface $e) {
830 //Throw error
831 throw new \Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
832 }
833 }
834
835 //Create image instance
836 $image = new \Imagick();
837
838 //Read image
839 $image->readImage(realpath($path));
840
841 //Crop using aspect ratio
842 //XXX: for better result upload image directly in aspect ratio :)
843 $image->cropThumbnailImage($width, $height);
844
845 //Strip image exif data and properties
846 $image->stripImage();
847
848 //Set compression quality
849 //TODO: ajust that
850 $image->setImageCompressionQuality(70);
851
852 //Set image format
853 #$image->setImageFormat($_format);
854
855 //Save thumb
856 if (!$image->writeImage($thumb)) {
857 //Throw error
858 throw new \Exception(sprintf('Unable to write image "%s"', $thumb));
859 }
860
861 //Set updated
862 $updated = stat($thumb)['mtime'];
863 }
864
865 //Read thumb from cache
866 $response = new BinaryFileResponse($thumb);
867
868 //Set file name
869 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'thumb-'.$hash.'.'.$_format);
870
871 //Set etag
872 //TODO: set etag to file content md5 ? cache it ?
873 $response->setEtag(md5($hash));
874
875 //Set last modified
876 $response->setLastModified(\DateTime::createFromFormat('U', strval($updated)));
877
878 //Set as public
879 $response->setPublic();
880
881 //Return 304 response if not modified
882 $response->isNotModified($request);
883
884 //Return response
885 return $response;
886 }
887 }