]> Raphaël G. Git Repositories - packbundle/blob - Controller/MapController.php
Add rapsys_pack.facebook_util and rapsys_pack.image_util services
[packbundle] / Controller / MapController.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\Controller;
13
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;
25
26 use Rapsys\PackBundle\Util\MapUtil;
27 use Rapsys\PackBundle\Util\SluggerUtil;
28
29 /**
30 * {@inheritdoc}
31 */
32 class MapController extends AbstractController implements ServiceSubscriberInterface {
33 /**
34 * The cache path
35 */
36 protected string $cache;
37
38 /**
39 * The ContainerInterface instance
40 *
41 * @var ContainerInterface
42 */
43 protected $container;
44
45 /**
46 * The stream context instance
47 */
48 protected mixed $ctx;
49
50 /**
51 * The MapUtil instance
52 */
53 protected MapUtil $map;
54
55 /**
56 * The public path
57 */
58 protected string $path;
59
60 /**
61 * The SluggerUtil instance
62 */
63 protected SluggerUtil $slugger;
64
65 /**
66 * The tile server url
67 */
68 protected string $url;
69
70 /**
71 * Creates a new osm controller
72 *
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
80 */
81 function __construct(ContainerInterface $container, MapUtil $map, SluggerUtil $slugger, string $cache = '../var/cache', string $path = './bundles/rapsyspack', string $prefix = 'map', string $url = MapUtil::osm) {
82 //Set cache
83 $this->cache = $cache.'/'.$prefix;
84
85 //Set container
86 $this->container = $container;
87
88 //Set ctx
89 $this->ctx = stream_context_create(
90 [
91 'http' => [
92 #'header' => ['Referer: https://www.openstreetmap.org/'],
93 'max_redirects' => 5,
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',
97 ]
98 ]
99 );
100
101 //Set map
102 $this->map = $map;
103
104 //Set path
105 $this->path = $path.'/'.$prefix;
106
107 //Set slugger
108 $this->slugger = $slugger;
109
110 //Set url
111 $this->url = $url;
112 }
113
114 /**
115 * Return map image
116 *
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
126 */
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));
132 }
133
134 //Set map
135 $map = $this->path.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$width.'x'.$height.'.jpeg';
136
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();
143
144 try {
145 //Create path
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) {
150 //Throw error
151 throw new \Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
152 }
153 }
154
155 //Create image instance
156 $image = new \Imagick();
157
158 //Add new image
159 $image->newImage($width, $height, new \ImagickPixel('transparent'), 'jpeg');
160
161 //Create tile instance
162 $tile = new \Imagick();
163
164 //Get tile xy
165 $centerX = $this->map->longitudeToX($longitude, $zoom);
166 $centerY = $this->map->latitudeToY($latitude, $zoom);
167
168 //Calculate start xy
169 $startX = floor(floor($centerX) - $width / MapUtil::tz);
170 $startY = floor(floor($centerY) - $height / MapUtil::tz);
171
172 //Calculate end xy
173 $endX = ceil(ceil($centerX) + $width / MapUtil::tz);
174 $endY = ceil(ceil($centerY) + $height / MapUtil::tz);
175
176 for($x = $startX; $x <= $endX; $x++) {
177 for($y = $startY; $y <= $endY; $y++) {
178 //Set cache path
179 $cache = $this->cache.'/'.$zoom.'/'.$x.'/'.$y.'.png';
180
181 //Without cache image
182 if (!is_file($cache)) {
183 //Set tile url
184 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url);
185
186 //Without cache path
187 if (!is_dir($dir = dirname($cache))) {
188 //Create filesystem object
189 $filesystem = new Filesystem();
190
191 try {
192 //Create path
193 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
194 $filesystem->mkdir($dir, 0775);
195 } catch (IOExceptionInterface $e) {
196 //Throw error
197 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
198 }
199 }
200
201 //Store tile in cache
202 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx));
203 }
204
205 //Set dest x
206 $destX = intval(floor($width / 2 - MapUtil::tz * ($centerX - $x)));
207
208 //Set dest y
209 $destY = intval(floor($height / 2 - MapUtil::tz * ($centerY - $y)));
210
211 //Read tile from cache
212 $tile->readImage($cache);
213
214 //Compose image
215 $image->compositeImage($tile, \Imagick::COMPOSITE_OVER, $destX, $destY);
216
217 //Clear tile
218 $tile->clear();
219 }
220 }
221
222 //Add imagick draw instance
223 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
224 $draw = new \ImagickDraw();
225
226 //Set text antialias
227 $draw->setTextAntialias(true);
228
229 //Set stroke antialias
230 $draw->setStrokeAntialias(true);
231
232 //Set text alignment
233 $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
234
235 //Set gravity
236 $draw->setGravity(\Imagick::GRAVITY_CENTER);
237
238 //Set fill color
239 $draw->setFillColor('#cff');
240
241 //Set stroke color
242 $draw->setStrokeColor('#00c3f9');
243
244 //Set stroke width
245 $draw->setStrokeWidth(2);
246
247 //Draw circle
248 $draw->circle($width/2 - 5, $height/2 - 5, $width/2 + 5, $height/2 + 5);
249
250 //Draw on image
251 $image->drawImage($draw);
252
253 //Strip image exif data and properties
254 $image->stripImage();
255
256 //Add latitude
257 //XXX: not supported by imagick :'(
258 $image->setImageProperty('exif:GPSLatitude', $this->map->latitudeToSexagesimal($latitude));
259
260 //Add longitude
261 //XXX: not supported by imagick :'(
262 $image->setImageProperty('exif:GPSLongitude', $this->map->longitudeToSexagesimal($longitude));
263
264 //Add description
265 //XXX: not supported by imagick :'(
266 #$image->setImageProperty('exif:Description', $caption);
267
268 //Set progressive jpeg
269 $image->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
270
271 //Set compression quality
272 //TODO: ajust that
273 $image->setImageCompressionQuality(70);
274
275 //Save image
276 if (!$image->writeImage($map)) {
277 //Throw error
278 throw new \Exception(sprintf('Unable to write image "%s"', $path));
279 }
280
281 //Set mtime
282 $mtime = stat($map)['mtime'];
283 }
284
285 //Read map from cache
286 $response = new BinaryFileResponse($map);
287
288 //Set file name
289 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'map-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
290
291 //Set etag
292 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height])));
293
294 //Set last modified
295 $response->setLastModified(\DateTime::createFromFormat('U', strval($mtime)));
296
297 //Set as public
298 $response->setPublic();
299
300 //Return 304 response if not modified
301 $response->isNotModified($request);
302
303 //Return response
304 return $response;
305 }
306
307 /**
308 * Return multi map image
309 *
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
320 */
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));
326 }
327
328 //Set multi
329 $map = $this->path.'/'.$zoom.'/'.$latitude.'/'.$longitude.'/'.$coordinate.'/'.$width.'x'.$height.'.jpeg';
330
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();
337
338 try {
339 //Create path
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) {
344 //Throw error
345 throw new \Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
346 }
347 }
348
349 //Create image instance
350 $image = new \Imagick();
351
352 //Add new image
353 $image->newImage($width, $height, new \ImagickPixel('transparent'), 'jpeg');
354
355 //Create tile instance
356 $tile = new \Imagick();
357
358 //Get tile xy
359 $centerX = $this->map->longitudeToX($longitude, $zoom);
360 $centerY = $this->map->latitudeToY($latitude, $zoom);
361
362 //Calculate start xy
363 $startX = floor(floor($centerX) - $width / MapUtil::tz);
364 $startY = floor(floor($centerY) - $height / MapUtil::tz);
365
366 //Calculate end xy
367 $endX = ceil(ceil($centerX) + $width / MapUtil::tz);
368 $endY = ceil(ceil($centerY) + $height / MapUtil::tz);
369
370 for($x = $startX; $x <= $endX; $x++) {
371 for($y = $startY; $y <= $endY; $y++) {
372 //Set cache path
373 $cache = $this->cache.'/'.$zoom.'/'.$x.'/'.$y.'.png';
374
375 //Without cache image
376 if (!is_file($cache)) {
377 //Set tile url
378 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->url);
379
380 //Without cache path
381 if (!is_dir($dir = dirname($cache))) {
382 //Create filesystem object
383 $filesystem = new Filesystem();
384
385 try {
386 //Create path
387 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
388 $filesystem->mkdir($dir, 0775);
389 } catch (IOExceptionInterface $e) {
390 //Throw error
391 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
392 }
393 }
394
395 //Store tile in cache
396 file_put_contents($cache, file_get_contents($tileUri, false, $this->ctx));
397 }
398
399 //Set dest x
400 $destX = intval(floor($width / 2 - MapUtil::tz * ($centerX - $x)));
401
402 //Set dest y
403 $destY = intval(floor($height / 2 - MapUtil::tz * ($centerY - $y)));
404
405 //Read tile from cache
406 $tile->readImage($cache);
407
408 //Compose image
409 $image->compositeImage($tile, \Imagick::COMPOSITE_OVER, $destX, $destY);
410
411 //Clear tile
412 $tile->clear();
413 }
414 }
415
416 //Add imagick draw instance
417 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
418 $draw = new \ImagickDraw();
419
420 //Set text antialias
421 $draw->setTextAntialias(true);
422
423 //Set stroke antialias
424 $draw->setStrokeAntialias(true);
425
426 //Set text alignment
427 $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
428
429 //Set gravity
430 $draw->setGravity(\Imagick::GRAVITY_CENTER);
431
432 //Convert to array
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);
434
435 //Iterate on locations
436 foreach($coordinates as $id => $coordinate) {
437 //Set dest x
438 $destX = intval(floor($width / 2 - MapUtil::tz * ($centerX - $this->map->longitudeToX(floatval($coordinate['longitude']), $zoom))));
439
440 //Set dest y
441 $destY = intval(floor($height / 2 - MapUtil::tz * ($centerY - $this->map->latitudeToY(floatval($coordinate['latitude']), $zoom))));
442
443 //Set fill color
444 $draw->setFillColor($this->map->fill);
445
446 //Set font size
447 $draw->setFontSize($this->map->fontSize);
448
449 //Set stroke color
450 $draw->setStrokeColor($this->map->stroke);
451
452 //Set circle radius
453 $radius = $this->map->radius;
454
455 //Set stroke width
456 $stroke = $this->map->strokeWidth;
457
458 //With matching position
459 if ($coordinate['latitude'] === $latitude && $coordinate['longitude'] == $longitude) {
460 //Set fill color
461 $draw->setFillColor($this->map->highFill);
462
463 //Set font size
464 $draw->setFontSize($this->map->highFontSize);
465
466 //Set stroke color
467 $draw->setStrokeColor($this->map->highStroke);
468
469 //Set circle radius
470 $radius = $this->map->highRadius;
471
472 //Set stroke width
473 $stroke = $this->map->highStrokeWidth;
474 }
475
476 //Set stroke width
477 $draw->setStrokeWidth($stroke);
478
479 //Draw circle
480 $draw->circle($destX - $radius, $destY - $radius, $destX + $radius, $destY + $radius);
481
482 //Set fill color
483 $draw->setFillColor($draw->getStrokeColor());
484
485 //Set stroke width
486 $draw->setStrokeWidth($stroke / 4);
487
488 //Get font metrics
489 #$metrics = $image->queryFontMetrics($draw, strval($id));
490
491 //Add annotation
492 $draw->annotation($destX - $radius, $destY + $stroke, strval($id));
493 }
494
495 //Draw on image
496 $image->drawImage($draw);
497
498 //Strip image exif data and properties
499 $image->stripImage();
500
501 //Add latitude
502 //XXX: not supported by imagick :'(
503 $image->setImageProperty('exif:GPSLatitude', $this->map->latitudeToSexagesimal($latitude));
504
505 //Add longitude
506 //XXX: not supported by imagick :'(
507 $image->setImageProperty('exif:GPSLongitude', $this->map->longitudeToSexagesimal($longitude));
508
509 //Add description
510 //XXX: not supported by imagick :'(
511 #$image->setImageProperty('exif:Description', $caption);
512
513 //Set progressive jpeg
514 $image->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
515
516 //Set compression quality
517 //TODO: ajust that
518 $image->setImageCompressionQuality(70);
519
520 //Save image
521 if (!$image->writeImage($map)) {
522 //Throw error
523 throw new \Exception(sprintf('Unable to write image "%s"', $path));
524 }
525
526 //Set mtime
527 $mtime = stat($map)['mtime'];
528 }
529
530 //Read map from cache
531 $response = new BinaryFileResponse($map);
532
533 //Set file name
534 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'multimap-'.$latitude.','.$longitude.'-'.$zoom.'-'.$width.'x'.$height.'.jpeg');
535
536 //Set etag
537 $response->setEtag(md5(serialize([$updated, $latitude, $longitude, $zoom, $width, $height])));
538
539 //Set last modified
540 $response->setLastModified(\DateTime::createFromFormat('U', strval($mtime)));
541
542 //Set as public
543 $response->setPublic();
544
545 //Return 304 response if not modified
546 $response->isNotModified($request);
547
548 //Return response
549 return $response;
550 }
551 }