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 $public;
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 $public The public path
78 * @param string $url The tile server url
80 function __construct(ContainerInterface
$container, MapUtil
$map, SluggerUtil
$slugger, string $cache = '../var/cache/map', string $public = './bundles/rapsyspack/map', string $url = MapUtil
::osm
) {
82 $this->cache
= $cache;
85 $this->container
= $container;
88 $this->ctx
= stream_context_create(
91 #'header' => ['Referer: https://www.openstreetmap.org/'],
93 'timeout' => (int)ini_get('default_socket_timeout'),
94 #'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36',
95 'user_agent' => (string)ini_get('user_agent')?:'rapsys_pack/2.0.0',
104 $this->public = $public;
107 $this->slugger
= $slugger;
116 * @param Request $request The Request instance
117 * @param string $hash The hash
118 * @param int $updated The updated timestamp
119 * @param float $latitude The latitude
120 * @param float $longitude The longitude
121 * @param int $zoom The zoom
122 * @param int $width The width
123 * @param int $height The height
124 * @return Response The rendered image
126 public function map(Request
$request, string $hash, int $updated, float $latitude, float $longitude, int $zoom, int $width, int $height): Response
{
127 //Without matching hash
128 if ($hash !== $this->slugger
->hash([$updated, $latitude, $longitude, $zoom, $width, $height])) {
129 //Throw new exception
130 throw new NotFoundHttpException(sprintf('Unable to match map hash: %s', $hash));
134 $map = $this->public.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$width.'x'.$height.'.jpeg';
136 //Without multi up to date file
137 if (!is_file($map) || !($mtime = stat($map)['mtime']) || $mtime < $updated) {
138 //Without existing map path
139 if (!is_dir($dir = dirname($map))) {
140 //Create filesystem object
141 $filesystem = new Filesystem();
145 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
146 //XXX: on CoW filesystems execute a chattr +C before filling
147 $filesystem->mkdir($dir, 0775);
148 } catch (IOExceptionInterface
$e) {
150 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
154 //Create image instance
155 $image = new \
Imagick();
158 $image->newImage($width, $height, new \
ImagickPixel('transparent'), 'jpeg');
160 //Create tile instance
161 $tile = new \
Imagick();
164 $centerX = $this->map
->longitudeToX($longitude, $zoom);
165 $centerY = $this->map
->latitudeToY($latitude, $zoom);
168 $startX = floor(floor($centerX) - $width / MapUtil
::tz
);
169 $startY = floor(floor($centerY) - $height / MapUtil
::tz
);
172 $endX = ceil(ceil($centerX) +
$width / MapUtil
::tz
);
173 $endY = ceil(ceil($centerY) +
$height / MapUtil
::tz
);
175 for($x = $startX; $x <= $endX; $x++
) {
176 for($y = $startY; $y <= $endY; $y++
) {
178 $cache = $this->cache
.'/'.$zoom.'/'.$x.'/'.$y.'.png';
180 //Without cache image
181 if (!is_file($cache)) {
183 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url
);
186 if (!is_dir($dir = dirname($cache))) {
187 //Create filesystem object
188 $filesystem = new Filesystem();
192 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
193 $filesystem->mkdir($dir, 0775);
194 } catch (IOExceptionInterface
$e) {
196 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
200 //Store tile in cache
201 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
));
205 $destX = intval(floor($width / 2 - MapUtil
::tz
* ($centerX - $x)));
208 $destY = intval(floor($height / 2 - MapUtil
::tz
* ($centerY - $y)));
210 //Read tile from cache
211 $tile->readImage($cache);
214 $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY);
221 //Add imagick draw instance
222 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
223 $draw = new \
ImagickDraw();
226 $draw->setTextAntialias(true);
228 //Set stroke antialias
229 $draw->setStrokeAntialias(true);
232 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
235 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
238 $draw->setFillColor('#cff');
241 $draw->setStrokeColor('#00c3f9');
244 $draw->setStrokeWidth(2);
247 $draw->circle($width/2 - 5, $height/2 - 5, $width/2 +
5, $height/2 +
5);
250 $image->drawImage($draw);
252 //Strip image exif data and properties
253 $image->stripImage();
256 //XXX: not supported by imagick :'(
257 $image->setImageProperty('exif:GPSLatitude', $this->map
->latitudeToSexagesimal($latitude));
260 //XXX: not supported by imagick :'(
261 $image->setImageProperty('exif:GPSLongitude', $this->map
->longitudeToSexagesimal($longitude));
264 //XXX: not supported by imagick :'(
265 #$image->setImageProperty('exif:Description', $caption);
267 //Set progressive jpeg
268 $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
);
270 //Set compression quality
272 $image->setImageCompressionQuality(70);
275 if (!$image->writeImage($map)) {
277 throw new \
Exception(sprintf('Unable to write image "%s"', $path));
281 $mtime = stat($map)['mtime'];
284 //Read map from cache
285 $response = new BinaryFileResponse($map);
288 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'map-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
291 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height])));
294 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
297 $response->setPublic();
299 //Return 304 response if not modified
300 $response->isNotModified($request);
307 * Return multi map image
309 * @param Request $request The Request instance
310 * @param string $hash The hash
311 * @param int $updated The updated timestamp
312 * @param float $latitude The latitude
313 * @param float $longitude The longitude
314 * @param string $coordinates The coordinates
315 * @param int $zoom The zoom
316 * @param int $width The width
317 * @param int $height The height
318 * @return Response The rendered image
320 public function multiMap(Request
$request, string $hash, int $updated, float $latitude, float $longitude, string $coordinates, int $zoom, int $width, int $height): Response
{
321 //Without matching hash
322 if ($hash !== $this->slugger
->hash([$updated, $latitude, $longitude, $coordinate = $this->slugger
->hash($coordinates), $zoom, $width, $height])) {
323 //Throw new exception
324 throw new NotFoundHttpException(sprintf('Unable to match multi map hash: %s', $hash));
328 $map = $this->public.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$coordinate.'/'.$width.'x'.$height.'.jpeg';
330 //Without multi up to date file
331 if (!is_file($map) || !($mtime = stat($map)['mtime']) || $mtime < $updated) {
332 //Without existing multi path
333 if (!is_dir($dir = dirname($map))) {
334 //Create filesystem object
335 $filesystem = new Filesystem();
339 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
340 //XXX: on CoW filesystems execute a chattr +C before filling
341 $filesystem->mkdir($dir, 0775);
342 } catch (IOExceptionInterface
$e) {
344 throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
348 //Create image instance
349 $image = new \
Imagick();
352 $image->newImage($width, $height, new \
ImagickPixel('transparent'), 'jpeg');
354 //Create tile instance
355 $tile = new \
Imagick();
358 $centerX = $this->map
->longitudeToX($longitude, $zoom);
359 $centerY = $this->map
->latitudeToY($latitude, $zoom);
362 $startX = floor(floor($centerX) - $width / MapUtil
::tz
);
363 $startY = floor(floor($centerY) - $height / MapUtil
::tz
);
366 $endX = ceil(ceil($centerX) +
$width / MapUtil
::tz
);
367 $endY = ceil(ceil($centerY) +
$height / MapUtil
::tz
);
369 for($x = $startX; $x <= $endX; $x++
) {
370 for($y = $startY; $y <= $endY; $y++
) {
372 $cache = $this->cache
.'/'.$zoom.'/'.$x.'/'.$y.'.png';
374 //Without cache image
375 if (!is_file($cache)) {
377 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url
);
380 if (!is_dir($dir = dirname($cache))) {
381 //Create filesystem object
382 $filesystem = new Filesystem();
386 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
387 $filesystem->mkdir($dir, 0775);
388 } catch (IOExceptionInterface
$e) {
390 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
394 //Store tile in cache
395 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
));
399 $destX = intval(floor($width / 2 - MapUtil
::tz
* ($centerX - $x)));
402 $destY = intval(floor($height / 2 - MapUtil
::tz
* ($centerY - $y)));
404 //Read tile from cache
405 $tile->readImage($cache);
408 $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY);
415 //Add imagick draw instance
416 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
417 $draw = new \
ImagickDraw();
420 $draw->setTextAntialias(true);
422 //Set stroke antialias
423 $draw->setStrokeAntialias(true);
426 $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
);
429 $draw->setGravity(\Imagick
::GRAVITY_CENTER
);
432 $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);
434 //Iterate on locations
435 foreach($coordinates as $id => $coordinate) {
437 $destX = intval(floor($width / 2 - MapUtil
::tz
* ($centerX - $this->map
->longitudeToX(floatval($coordinate['longitude']), $zoom))));
440 $destY = intval(floor($height / 2 - MapUtil
::tz
* ($centerY - $this->map
->latitudeToY(floatval($coordinate['latitude']), $zoom))));
443 $draw->setFillColor($this->map
->fill
);
446 $draw->setFontSize($this->map
->fontSize
);
449 $draw->setStrokeColor($this->map
->stroke
);
452 $radius = $this->map
->radius
;
455 $stroke = $this->map
->strokeWidth
;
457 //With matching position
458 if ($coordinate['latitude'] === $latitude && $coordinate['longitude'] == $longitude) {
460 $draw->setFillColor($this->map
->highFill
);
463 $draw->setFontSize($this->map
->highFontSize
);
466 $draw->setStrokeColor($this->map
->highStroke
);
469 $radius = $this->map
->highRadius
;
472 $stroke = $this->map
->highStrokeWidth
;
476 $draw->setStrokeWidth($stroke);
479 $draw->circle($destX - $radius, $destY - $radius, $destX +
$radius, $destY +
$radius);
482 $draw->setFillColor($draw->getStrokeColor());
485 $draw->setStrokeWidth($stroke / 4);
488 #$metrics = $image->queryFontMetrics($draw, strval($id));
491 $draw->annotation($destX - $radius, $destY +
$stroke, strval($id));
495 $image->drawImage($draw);
497 //Strip image exif data and properties
498 $image->stripImage();
501 //XXX: not supported by imagick :'(
502 $image->setImageProperty('exif:GPSLatitude', $this->map
->latitudeToSexagesimal($latitude));
505 //XXX: not supported by imagick :'(
506 $image->setImageProperty('exif:GPSLongitude', $this->map
->longitudeToSexagesimal($longitude));
509 //XXX: not supported by imagick :'(
510 #$image->setImageProperty('exif:Description', $caption);
512 //Set progressive jpeg
513 $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
);
515 //Set compression quality
517 $image->setImageCompressionQuality(70);
520 if (!$image->writeImage($map)) {
522 throw new \
Exception(sprintf('Unable to write image "%s"', $path));
526 $mtime = stat($map)['mtime'];
529 //Read map from cache
530 $response = new BinaryFileResponse($map);
533 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'multimap-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
536 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height])));
539 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime)));
542 $response->setPublic();
544 //Return 304 response if not modified
545 $response->isNotModified($request);