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\MapUtil
;
27 use Rapsys\PackBundle\Util\SluggerUtil
;
32 class MapController
extends AbstractController
implements ServiceSubscriberInterface
{
36 protected string $cache;
39 * The ContainerInterface instance
41 * @var ContainerInterface
46 * The stream context instance
51 * The MapUtil instance
53 protected MapUtil
$map;
58 protected string $path;
61 * The SluggerUtil instance
63 protected SluggerUtil
$slugger;
68 protected string $url;
71 * Creates a new osm controller
73 * @param ContainerInterface $container The ContainerInterface instance
74 * @param MapUtil $map The MapUtil instance
75 * @param SluggerUtil $slugger The SluggerUtil instance
76 * @param string $cache The cache path
77 * @param string $path The public path
78 # * @param string $prefix The prefix
79 * @param string $url The tile server url
81 function __construct(ContainerInterface
$container, MapUtil
$map, SluggerUtil
$slugger, string $cache = '../var/cache', string $path = './bundles/rapsyspack', string $prefix = 'map', string $url = MapUtil
::osm
) {
83 $this->cache
= $cache.'/'.$prefix;
86 $this->container
= $container;
89 $this->ctx
= stream_context_create(
92 #'header' => ['Referer: https://www.openstreetmap.org/'],
94 'timeout' => (int)ini_get('default_socket_timeout'),
95 #'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36',
96 'user_agent' => (string)ini_get('user_agent')?:'rapsys_pack/2.0.0',
105 $this->path
= $path.'/'.$prefix;
108 $this->slugger
= $slugger;
117 * @param Request $request The Request instance
118 * @param string $hash The hash
119 * @param int $updated The updated timestamp
120 * @param float $latitude The latitude
121 * @param float $longitude The longitude
122 * @param int $zoom The zoom
123 * @param int $width The width
124 * @param int $height The height
125 * @return Response The rendered image
127 public function map(Request
$request, string $hash, int $updated, float $latitude, float $longitude, int $zoom, int $width, int $height): Response
{
128 //Without matching hash
129 if ($hash !== $this->slugger
->hash([$updated, $latitude, $longitude, $zoom, $width, $height])) {
130 //Throw new exception
131 throw new NotFoundHttpException(sprintf('Unable to match map hash: %s', $hash));
135 $map = $this->path
.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$width.'x'.$height.'.jpeg';
137 //Without multi up to date file
138 if (!is_file($map) || !($mtime = stat($map)['mtime']) || $mtime < $updated) {
139 //Without existing map path
140 if (!is_dir($dir = dirname($map))) {
141 //Create filesystem object
142 $filesystem = new Filesystem();
146 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
147 //XXX: on CoW filesystems execute a chattr +C before filling
148 $filesystem->mkdir($dir, 0775);
149 } catch (IOExceptionInterface
$e) {
151 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
155 //Create image instance
156 $image = new \
Imagick();
159 $image->newImage($width, $height, new \
ImagickPixel('transparent'), 'jpeg');
161 //Create tile instance
162 $tile = new \
Imagick();
165 $centerX = $this->map
->longitudeToX($longitude, $zoom);
166 $centerY = $this->map
->latitudeToY($latitude, $zoom);
169 $startX = floor(floor($centerX) - $width / MapUtil
::tz
);
170 $startY = floor(floor($centerY) - $height / MapUtil
::tz
);
173 $endX = ceil(ceil($centerX) +
$width / MapUtil
::tz
);
174 $endY = ceil(ceil($centerY) +
$height / MapUtil
::tz
);
176 for($x = $startX; $x <= $endX; $x++
) {
177 for($y = $startY; $y <= $endY; $y++
) {
179 $cache = $this->cache
.'/'.$zoom.'/'.$x.'/'.$y.'.png';
181 //Without cache image
182 if (!is_file($cache)) {
184 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url
);
187 if (!is_dir($dir = dirname($cache))) {
188 //Create filesystem object
189 $filesystem = new Filesystem();
193 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
194 $filesystem->mkdir($dir, 0775);
195 } catch (IOExceptionInterface
$e) {
197 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
201 //Store tile in cache
202 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
));
206 $destX = intval(floor($width / 2 - MapUtil
::tz
* ($centerX - $x)));
209 $destY = intval(floor($height / 2 - MapUtil
::tz
* ($centerY - $y)));
211 //Read tile from cache
212 $tile->readImage($cache);
215 $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY);
222 //Add imagick draw instance
223 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
224 $draw = new \
ImagickDraw();
227 $draw->setTextAntialias(true);
229 //Set stroke antialias
230 $draw->setStrokeAntialias(true);
233 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
236 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
239 $draw->setFillColor('#cff');
242 $draw->setStrokeColor('#00c3f9');
245 $draw->setStrokeWidth(2);
248 $draw->circle($width/2 - 5, $height/2 - 5, $width/2 +
5, $height/2 +
5);
251 $image->drawImage($draw);
253 //Strip image exif data and properties
254 $image->stripImage();
257 //XXX: not supported by imagick :'(
258 $image->setImageProperty('exif:GPSLatitude', $this->map
->latitudeToSexagesimal($latitude));
261 //XXX: not supported by imagick :'(
262 $image->setImageProperty('exif:GPSLongitude', $this->map
->longitudeToSexagesimal($longitude));
265 //XXX: not supported by imagick :'(
266 #$image->setImageProperty('exif:Description', $caption);
268 //Set progressive jpeg
269 $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
);
271 //Set compression quality
273 $image->setImageCompressionQuality(70);
276 if (!$image->writeImage($map)) {
278 throw new \
Exception(sprintf('Unable to write image "%s"', $path));
282 $mtime = stat($map)['mtime'];
285 //Read map from cache
286 $response = new BinaryFileResponse($map);
289 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'map-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
292 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height])));
295 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
298 $response->setPublic();
300 //Return 304 response if not modified
301 $response->isNotModified($request);
308 * Return multi map image
310 * @param Request $request The Request instance
311 * @param string $hash The hash
312 * @param int $updated The updated timestamp
313 * @param float $latitude The latitude
314 * @param float $longitude The longitude
315 * @param string $coordinates The coordinates
316 * @param int $zoom The zoom
317 * @param int $width The width
318 * @param int $height The height
319 * @return Response The rendered image
321 public function multiMap(Request
$request, string $hash, int $updated, float $latitude, float $longitude, string $coordinates, int $zoom, int $width, int $height): Response
{
322 //Without matching hash
323 if ($hash !== $this->slugger
->hash([$updated, $latitude, $longitude, $coordinate = $this->slugger
->hash($coordinates), $zoom, $width, $height])) {
324 //Throw new exception
325 throw new NotFoundHttpException(sprintf('Unable to match multi map hash: %s', $hash));
329 $map = $this->path
.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$coordinate.'/'.$width.'x'.$height.'.jpeg';
331 //Without multi up to date file
332 if (!is_file($map) || !($mtime = stat($map)['mtime']) || $mtime < $updated) {
333 //Without existing multi path
334 if (!is_dir($dir = dirname($map))) {
335 //Create filesystem object
336 $filesystem = new Filesystem();
340 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
341 //XXX: on CoW filesystems execute a chattr +C before filling
342 $filesystem->mkdir($dir, 0775);
343 } catch (IOExceptionInterface
$e) {
345 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
349 //Create image instance
350 $image = new \
Imagick();
353 $image->newImage($width, $height, new \
ImagickPixel('transparent'), 'jpeg');
355 //Create tile instance
356 $tile = new \
Imagick();
359 $centerX = $this->map
->longitudeToX($longitude, $zoom);
360 $centerY = $this->map
->latitudeToY($latitude, $zoom);
363 $startX = floor(floor($centerX) - $width / MapUtil
::tz
);
364 $startY = floor(floor($centerY) - $height / MapUtil
::tz
);
367 $endX = ceil(ceil($centerX) +
$width / MapUtil
::tz
);
368 $endY = ceil(ceil($centerY) +
$height / MapUtil
::tz
);
370 for($x = $startX; $x <= $endX; $x++
) {
371 for($y = $startY; $y <= $endY; $y++
) {
373 $cache = $this->cache
.'/'.$zoom.'/'.$x.'/'.$y.'.png';
375 //Without cache image
376 if (!is_file($cache)) {
378 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url
);
381 if (!is_dir($dir = dirname($cache))) {
382 //Create filesystem object
383 $filesystem = new Filesystem();
387 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
388 $filesystem->mkdir($dir, 0775);
389 } catch (IOExceptionInterface
$e) {
391 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
395 //Store tile in cache
396 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
));
400 $destX = intval(floor($width / 2 - MapUtil
::tz
* ($centerX - $x)));
403 $destY = intval(floor($height / 2 - MapUtil
::tz
* ($centerY - $y)));
405 //Read tile from cache
406 $tile->readImage($cache);
409 $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY);
416 //Add imagick draw instance
417 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
418 $draw = new \
ImagickDraw();
421 $draw->setTextAntialias(true);
423 //Set stroke antialias
424 $draw->setStrokeAntialias(true);
427 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
430 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
433 $coordinates = array_reverse(array_map(function ($v) { $p
= strpos($v
, ','); return ['latitude' => floatval(substr($v
, 0, $p
)), 'longitude' => floatval(substr($v
, $p +
1))]; }, explode('-', $coordinates)), true);
435 //Iterate on locations
436 foreach($coordinates as $id => $coordinate) {
438 $destX = intval(floor($width / 2 - MapUtil
::tz
* ($centerX - $this->map
->longitudeToX(floatval($coordinate['longitude']), $zoom))));
441 $destY = intval(floor($height / 2 - MapUtil
::tz
* ($centerY - $this->map
->latitudeToY(floatval($coordinate['latitude']), $zoom))));
444 $draw->setFillColor($this->map
->fill
);
447 $draw->setFontSize($this->map
->fontSize
);
450 $draw->setStrokeColor($this->map
->stroke
);
453 $radius = $this->map
->radius
;
456 $stroke = $this->map
->strokeWidth
;
458 //With matching position
459 if ($coordinate['latitude'] === $latitude && $coordinate['longitude'] == $longitude) {
461 $draw->setFillColor($this->map
->highFill
);
464 $draw->setFontSize($this->map
->highFontSize
);
467 $draw->setStrokeColor($this->map
->highStroke
);
470 $radius = $this->map
->highRadius
;
473 $stroke = $this->map
->highStrokeWidth
;
477 $draw->setStrokeWidth($stroke);
480 $draw->circle($destX - $radius, $destY - $radius, $destX +
$radius, $destY +
$radius);
483 $draw->setFillColor($draw->getStrokeColor());
486 $draw->setStrokeWidth($stroke / 4);
489 #$metrics = $image->queryFontMetrics($draw, strval($id));
492 $draw->annotation($destX - $radius, $destY +
$stroke, strval($id));
496 $image->drawImage($draw);
498 //Strip image exif data and properties
499 $image->stripImage();
502 //XXX: not supported by imagick :'(
503 $image->setImageProperty('exif:GPSLatitude', $this->map
->latitudeToSexagesimal($latitude));
506 //XXX: not supported by imagick :'(
507 $image->setImageProperty('exif:GPSLongitude', $this->map
->longitudeToSexagesimal($longitude));
510 //XXX: not supported by imagick :'(
511 #$image->setImageProperty('exif:Description', $caption);
513 //Set progressive jpeg
514 $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
);
516 //Set compression quality
518 $image->setImageCompressionQuality(70);
521 if (!$image->writeImage($map)) {
523 throw new \
Exception(sprintf('Unable to write image "%s"', $path));
527 $mtime = stat($map)['mtime'];
530 //Read map from cache
531 $response = new BinaryFileResponse($map);
534 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'multimap-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
537 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height])));
540 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
543 $response->setPublic();
545 //Return 304 response if not modified
546 $response->isNotModified($request);