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 stream context instance 
  44          * The MapUtil instance 
  46         protected MapUtil 
$map; 
  51         protected string $path; 
  54          * The SluggerUtil instance 
  56         protected SluggerUtil 
$slugger; 
  61         protected string $url; 
  64          * Creates a new osm controller 
  66          * @param ContainerInterface $container The ContainerInterface instance 
  67          * @param MapUtil $map The MapUtil instance 
  68          * @param SluggerUtil $slugger The SluggerUtil instance 
  69          * @param string $cache The cache path 
  70          * @param string $path The public path 
  71 #        * @param string $prefix The prefix 
  72          * @param string $url The tile server url 
  74         function __construct(ContainerInterface 
$container, MapUtil 
$map, SluggerUtil 
$slugger, string $cache = '../var/cache', string $path = './bundles/rapsyspack', string $prefix = 'map', string $url = MapUtil
::osm
) { 
  76                 $this->cache 
= $cache.'/'.$prefix; 
  79                 $this->container 
= $container; 
  82                 $this->ctx 
= stream_context_create( 
  85                                         #'header' => ['Referer: https://www.openstreetmap.org/'], 
  87                                         'timeout' => (int)ini_get('default_socket_timeout'), 
  88                                         #'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36', 
  89                                         'user_agent' => (string)ini_get('user_agent')?:'rapsys_pack/2.0.0', 
  98                 $this->path 
= $path.'/'.$prefix; 
 101                 $this->slugger 
= $slugger; 
 110          * @param Request $request The Request instance 
 111          * @param string $hash The hash 
 112          * @param int $updated The updated timestamp 
 113          * @param float $latitude The latitude 
 114          * @param float $longitude The longitude 
 115          * @param int $zoom The zoom 
 116          * @param int $width The width 
 117          * @param int $height The height 
 118          * @return Response The rendered image 
 120         public function map(Request 
$request, string $hash, int $updated, float $latitude, float $longitude, int $zoom, int $width, int $height): Response 
{ 
 121                 //Without matching hash 
 122                 if ($hash !== $this->slugger
->hash([$updated, $latitude, $longitude, $zoom, $width, $height])) { 
 123                         //Throw new exception 
 124                         throw new NotFoundHttpException(sprintf('Unable to match map hash: %s', $hash)); 
 128                 $map = $this->path
.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$width.'x'.$height.'.jpeg'; 
 130                 //Without multi up to date file 
 131                 if (!is_file($map) || !($mtime = stat($map)['mtime']) || $mtime < $updated) { 
 132                         //Without existing map path 
 133                         if (!is_dir($dir = dirname($map))) { 
 134                                 //Create filesystem object 
 135                                 $filesystem = new Filesystem(); 
 139                                         //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 140                                         //XXX: on CoW filesystems execute a chattr +C before filling 
 141                                         $filesystem->mkdir($dir, 0775); 
 142                                 } catch (IOExceptionInterface 
$e) { 
 144                                         throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e); 
 148                         //Create image instance 
 149                         $image = new \
Imagick(); 
 152                         $image->newImage($width, $height, new \
ImagickPixel('transparent'), 'jpeg'); 
 154                         //Create tile instance 
 155                         $tile = new \
Imagick(); 
 158                         $centerX = $this->map
->longitudeToX($longitude, $zoom); 
 159                         $centerY = $this->map
->latitudeToY($latitude, $zoom); 
 162                         $startX = floor(floor($centerX) - $width / MapUtil
::tz
); 
 163                         $startY = floor(floor($centerY) - $height / MapUtil
::tz
); 
 166                         $endX = ceil(ceil($centerX) + 
$width / MapUtil
::tz
); 
 167                         $endY = ceil(ceil($centerY) + 
$height / MapUtil
::tz
); 
 169                         for($x = $startX; $x <= $endX; $x++
) { 
 170                                 for($y = $startY; $y <= $endY; $y++
) { 
 172                                         $cache = $this->cache
.'/'.$zoom.'/'.$x.'/'.$y.'.png'; 
 174                                         //Without cache image 
 175                                         if (!is_file($cache)) { 
 177                                                 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url
); 
 180                                                 if (!is_dir($dir = dirname($cache))) { 
 181                                                         //Create filesystem object 
 182                                                         $filesystem = new Filesystem(); 
 186                                                                 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 187                                                                 $filesystem->mkdir($dir, 0775); 
 188                                                         } catch (IOExceptionInterface 
$e) { 
 190                                                                 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e); 
 194                                                 //Store tile in cache 
 195                                                 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
)); 
 199                                         $destX = intval(floor($width / 2 - MapUtil
::tz 
* ($centerX - $x))); 
 202                                         $destY = intval(floor($height / 2 - MapUtil
::tz 
* ($centerY - $y))); 
 204                                         //Read tile from cache 
 205                                         $tile->readImage($cache); 
 208                                         $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY); 
 215                         //Add imagick draw instance 
 216                         //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916 
 217                         $draw = new \
ImagickDraw(); 
 220                         $draw->setTextAntialias(true); 
 222                         //Set stroke antialias 
 223                         $draw->setStrokeAntialias(true); 
 226                         $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
); 
 229                         $draw->setGravity(\Imagick
::GRAVITY_CENTER
); 
 232                         $draw->setFillColor('#cff'); 
 235                         $draw->setStrokeColor('#00c3f9'); 
 238                         $draw->setStrokeWidth(2); 
 241                         $draw->circle($width/2 - 5, $height/2 - 5, $width/2 + 
5, $height/2 + 
5); 
 244                         $image->drawImage($draw); 
 246                         //Strip image exif data and properties 
 247                         $image->stripImage(); 
 250                         //XXX: not supported by imagick :'( 
 251                         $image->setImageProperty('exif:GPSLatitude', $this->map
->latitudeToSexagesimal($latitude)); 
 254                         //XXX: not supported by imagick :'( 
 255                         $image->setImageProperty('exif:GPSLongitude', $this->map
->longitudeToSexagesimal($longitude)); 
 258                         //XXX: not supported by imagick :'( 
 259                         #$image->setImageProperty('exif:Description', $caption); 
 261                         //Set progressive jpeg 
 262                         $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
); 
 264                         //Set compression quality 
 266                         $image->setImageCompressionQuality(70); 
 269                         if (!$image->writeImage($map)) { 
 271                                 throw new \
Exception(sprintf('Unable to write image "%s"', $path)); 
 275                         $mtime = stat($map)['mtime']; 
 278                 //Read map from cache 
 279                 $response = new BinaryFileResponse($map); 
 282                 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'map-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg'); 
 285                 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height]))); 
 288                 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime))); 
 290                 //Disable robot index 
 291                 $response->headers
->set('X-Robots-Tag', 'noindex'); 
 294                 $response->setPublic(); 
 296                 //Return 304 response if not modified 
 297                 $response->isNotModified($request); 
 304          * Return multi map image 
 306          * @param Request $request The Request instance 
 307          * @param string $hash The hash 
 308          * @param int $updated The updated timestamp 
 309          * @param float $latitude The latitude 
 310          * @param float $longitude The longitude 
 311          * @param string $coordinates The coordinates 
 312          * @param int $zoom The zoom 
 313          * @param int $width The width 
 314          * @param int $height The height 
 315          * @return Response The rendered image 
 317         public function multiMap(Request 
$request, string $hash, int $updated, float $latitude, float $longitude, string $coordinates, int $zoom, int $width, int $height): Response 
{ 
 318                 //Without matching hash 
 319                 if ($hash !== $this->slugger
->hash([$updated, $latitude, $longitude, $coordinate = $this->slugger
->hash($coordinates), $zoom, $width, $height])) { 
 320                         //Throw new exception 
 321                         throw new NotFoundHttpException(sprintf('Unable to match multi map hash: %s', $hash)); 
 325                 $map = $this->path
.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$coordinate.'/'.$width.'x'.$height.'.jpeg'; 
 327                 //Without multi up to date file 
 328                 if (!is_file($map) || !($mtime = stat($map)['mtime']) || $mtime < $updated) { 
 329                         //Without existing multi path 
 330                         if (!is_dir($dir = dirname($map))) { 
 331                                 //Create filesystem object 
 332                                 $filesystem = new Filesystem(); 
 336                                         //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 337                                         //XXX: on CoW filesystems execute a chattr +C before filling 
 338                                         $filesystem->mkdir($dir, 0775); 
 339                                 } catch (IOExceptionInterface 
$e) { 
 341                                         throw new \
Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e); 
 345                         //Create image instance 
 346                         $image = new \
Imagick(); 
 349                         $image->newImage($width, $height, new \
ImagickPixel('transparent'), 'jpeg'); 
 351                         //Create tile instance 
 352                         $tile = new \
Imagick(); 
 355                         $centerX = $this->map
->longitudeToX($longitude, $zoom); 
 356                         $centerY = $this->map
->latitudeToY($latitude, $zoom); 
 359                         $startX = floor(floor($centerX) - $width / MapUtil
::tz
); 
 360                         $startY = floor(floor($centerY) - $height / MapUtil
::tz
); 
 363                         $endX = ceil(ceil($centerX) + 
$width / MapUtil
::tz
); 
 364                         $endY = ceil(ceil($centerY) + 
$height / MapUtil
::tz
); 
 366                         for($x = $startX; $x <= $endX; $x++
) { 
 367                                 for($y = $startY; $y <= $endY; $y++
) { 
 369                                         $cache = $this->cache
.'/'.$zoom.'/'.$x.'/'.$y.'.png'; 
 371                                         //Without cache image 
 372                                         if (!is_file($cache)) { 
 374                                                 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url
); 
 377                                                 if (!is_dir($dir = dirname($cache))) { 
 378                                                         //Create filesystem object 
 379                                                         $filesystem = new Filesystem(); 
 383                                                                 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 384                                                                 $filesystem->mkdir($dir, 0775); 
 385                                                         } catch (IOExceptionInterface 
$e) { 
 387                                                                 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e); 
 391                                                 //Store tile in cache 
 392                                                 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx
)); 
 396                                         $destX = intval(floor($width / 2 - MapUtil
::tz 
* ($centerX - $x))); 
 399                                         $destY = intval(floor($height / 2 - MapUtil
::tz 
* ($centerY - $y))); 
 401                                         //Read tile from cache 
 402                                         $tile->readImage($cache); 
 405                                         $image->compositeImage($tile, \Imagick
::COMPOSITE_OVER
, $destX, $destY); 
 412                         //Add imagick draw instance 
 413                         //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916 
 414                         $draw = new \
ImagickDraw(); 
 417                         $draw->setTextAntialias(true); 
 419                         //Set stroke antialias 
 420                         $draw->setStrokeAntialias(true); 
 423                         $draw->setTextAlignment(\Imagick
::ALIGN_CENTER
); 
 426                         $draw->setGravity(\Imagick
::GRAVITY_CENTER
); 
 429                         $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); 
 431                         //Iterate on locations 
 432                         foreach($coordinates as $id => $coordinate) { 
 434                                 $destX = intval(floor($width / 2 - MapUtil
::tz 
* ($centerX - $this->map
->longitudeToX(floatval($coordinate['longitude']), $zoom)))); 
 437                                 $destY = intval(floor($height / 2 - MapUtil
::tz 
* ($centerY - $this->map
->latitudeToY(floatval($coordinate['latitude']), $zoom)))); 
 440                                 $draw->setFillColor($this->map
->fill
); 
 443                                 $draw->setFontSize($this->map
->fontSize
); 
 446                                 $draw->setStrokeColor($this->map
->stroke
); 
 449                                 $radius = $this->map
->radius
; 
 452                                 $stroke = $this->map
->strokeWidth
; 
 454                                 //With matching position 
 455                                 if ($coordinate['latitude'] === $latitude && $coordinate['longitude'] == $longitude) { 
 457                                         $draw->setFillColor($this->map
->highFill
); 
 460                                         $draw->setFontSize($this->map
->highFontSize
); 
 463                                         $draw->setStrokeColor($this->map
->highStroke
); 
 466                                         $radius = $this->map
->highRadius
; 
 469                                         $stroke = $this->map
->highStrokeWidth
; 
 473                                 $draw->setStrokeWidth($stroke); 
 476                                 $draw->circle($destX - $radius, $destY - $radius, $destX + 
$radius, $destY + 
$radius); 
 479                                 $draw->setFillColor($draw->getStrokeColor()); 
 482                                 $draw->setStrokeWidth($stroke / 4); 
 485                                 #$metrics = $image->queryFontMetrics($draw, strval($id)); 
 488                                 $draw->annotation($destX - $radius, $destY + 
$stroke, strval($id)); 
 492                         $image->drawImage($draw); 
 494                         //Strip image exif data and properties 
 495                         $image->stripImage(); 
 498                         //XXX: not supported by imagick :'( 
 499                         $image->setImageProperty('exif:GPSLatitude', $this->map
->latitudeToSexagesimal($latitude)); 
 502                         //XXX: not supported by imagick :'( 
 503                         $image->setImageProperty('exif:GPSLongitude', $this->map
->longitudeToSexagesimal($longitude)); 
 506                         //XXX: not supported by imagick :'( 
 507                         #$image->setImageProperty('exif:Description', $caption); 
 509                         //Set progressive jpeg 
 510                         $image->setInterlaceScheme(\Imagick
::INTERLACE_PLANE
); 
 512                         //Set compression quality 
 514                         $image->setImageCompressionQuality(70); 
 517                         if (!$image->writeImage($map)) { 
 519                                 throw new \
Exception(sprintf('Unable to write image "%s"', $path)); 
 523                         $mtime = stat($map)['mtime']; 
 526                 //Read map from cache 
 527                 $response = new BinaryFileResponse($map); 
 530                 $response->setContentDisposition(HeaderUtils
::DISPOSITION_INLINE
, 'multimap-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg'); 
 533                 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height]))); 
 536                 $response->setLastModified(\DateTime
::createFromFormat('U', strval($mtime))); 
 538                 //Disable robot index 
 539                 $response->headers
->set('X-Robots-Tag', 'noindex'); 
 542                 $response->setPublic(); 
 544                 //Return 304 response if not modified 
 545                 $response->isNotModified($request);