]> Raphaël G. Git Repositories - airbundle/blob - Controller/AbstractController.php
Add countries
[airbundle] / Controller / AbstractController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle 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\AirBundle\Controller;
13
14 use Doctrine\Persistence\ManagerRegistry;
15 use Psr\Log\LoggerInterface;
16 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseAbstractController;
17 use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
18 use Symfony\Component\Asset\PackageInterface;
19 use Symfony\Component\DependencyInjection\ContainerInterface;
20 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
21 use Symfony\Component\Filesystem\Filesystem;
22 use Symfony\Component\HttpFoundation\RequestStack;
23 use Symfony\Component\HttpFoundation\Response;
24 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
25 use Symfony\Component\Routing\RouterInterface;
26 use Symfony\Component\Translation\TranslatorInterface;
27 use Symfony\Contracts\Service\ServiceSubscriberInterface;
28
29 use Rapsys\AirBundle\Entity\Dance;
30 use Rapsys\AirBundle\Entity\Location;
31 use Rapsys\AirBundle\Entity\Slot;
32 use Rapsys\AirBundle\Entity\User;
33 use Rapsys\AirBundle\RapsysAirBundle;
34
35 /**
36 * Provides common features needed in controllers.
37 *
38 * {@inheritdoc}
39 */
40 abstract class AbstractController extends BaseAbstractController implements ServiceSubscriberInterface {
41 use ControllerTrait {
42 //Rename render as baseRender
43 render as protected baseRender;
44 }
45
46 ///Config array
47 protected $config;
48
49 ///ContainerInterface instance
50 protected $container;
51
52 ///Context array
53 protected $context;
54
55 ///Router instance
56 protected $router;
57
58 ///Translator instance
59 protected $translator;
60
61 /**
62 * Common constructor
63 *
64 * Stores container, router and translator interfaces
65 * Stores config
66 * Prepares context tree
67 *
68 * @param ContainerInterface $container The container instance
69 */
70 public function __construct(ContainerInterface $container) {
71 //Retrieve config
72 $this->config = $container->getParameter(RapsysAirBundle::getAlias());
73
74 //Set the container
75 $this->container = $container;
76
77 //Set the router
78 $this->router = $container->get('router');
79
80 //Set the translator
81 $this->translator = $container->get('translator');
82
83 //Set the context
84 $this->context = [
85 'description' => null,
86 'section' => null,
87 'title' => null,
88 'contact' => [
89 'title' => $this->translator->trans($this->config['contact']['title']),
90 'mail' => $this->config['contact']['mail']
91 ],
92 'copy' => [
93 'by' => $this->translator->trans($this->config['copy']['by']),
94 'link' => $this->config['copy']['link'],
95 'long' => $this->translator->trans($this->config['copy']['long']),
96 'short' => $this->translator->trans($this->config['copy']['short']),
97 'title' => $this->config['copy']['title']
98 ],
99 'site' => [
100 'donate' => $this->config['site']['donate'],
101 'ico' => $this->config['site']['ico'],
102 'logo' => $this->config['site']['logo'],
103 'png' => $this->config['site']['png'],
104 'svg' => $this->config['site']['svg'],
105 'title' => $this->translator->trans($this->config['site']['title']),
106 'url' => $this->router->generate($this->config['site']['url'])
107 ],
108 'canonical' => null,
109 'alternates' => [],
110 'facebook' => [
111 'prefixes' => [
112 'og' => 'http://ogp.me/ns#',
113 'fb' => 'http://ogp.me/ns/fb#'
114 ],
115 'metas' => [
116 'og:type' => 'article',
117 'og:site_name' => $this->translator->trans($this->config['site']['title']),
118 #'fb:admins' => $this->config['facebook']['admins'],
119 'fb:app_id' => $this->config['facebook']['apps']
120 ],
121 'texts' => []
122 ],
123 'forms' => []
124 ];
125 }
126
127 /**
128 * Return the facebook image
129 *
130 * @desc Generate image in jpeg format or load it from cache
131 *
132 * @param string $pathInfo The request path info
133 * @param array $parameters The image parameters
134 * @return array The image array
135 */
136 protected function getFacebookImage(string $pathInfo, array $parameters = []): array {
137 //Get asset package
138 //XXX: require asset package to be public
139 $package = $this->container->get('rapsys_pack.path_package');
140
141 //Set texts
142 $texts = $parameters['texts'] ?? [];
143
144 //Set default source
145 $source = $parameters['source'] ?? 'png/facebook.png';
146
147 //Set default source
148 $updated = $parameters['updated'] ?? strtotime('last week');
149
150 //Set source path
151 $src = $this->config['path']['public'].'/'.$source;
152
153 //Set cache path
154 //XXX: remove extension and store as png anyway
155 $cache = $this->config['path']['cache'].'/facebook/'.substr($source, 0, strrpos($source, '.')).'.'.$this->config['facebook']['width'].'x'.$this->config['facebook']['height'].'.png';
156
157 //Set destination path
158 //XXX: format <public>/facebook<pathinfo>.jpeg
159 //XXX: was <public>/facebook/<controller>/<action>.<locale>.jpeg
160 $dest = $this->config['path']['public'].'/facebook'.$pathInfo.'.jpeg';
161
162 //With up to date generated image
163 if (
164 is_file($dest) &&
165 ($stat = stat($dest)) &&
166 $stat['mtime'] >= $updated
167 ) {
168 //Get image size
169 list ($width, $height) = getimagesize($dest);
170
171 //Iterate each text
172 foreach($texts as $text => $data) {
173 //With canonical text
174 if (!empty($data['canonical'])) {
175 //Prevent canonical to finish in alt
176 unset($texts[$text]);
177 }
178 }
179
180 //Return image data
181 return [
182 'og:image' => $package->getAbsoluteUrl('@RapsysAir/facebook/'.$stat['mtime'].$pathInfo.'.jpeg'),
183 'og:image:alt' => str_replace("\n", ' ', implode(' - ', array_keys($texts))),
184 'og:image:height' => $height,
185 'og:image:width' => $width
186 ];
187 //With image candidate
188 } elseif (is_file($src)) {
189 //Create image object
190 $image = new \Imagick();
191
192 //With cache image
193 if (is_file($cache)) {
194 //Read image
195 $image->readImage($cache);
196 //Without we generate it
197 } else {
198 //Check target directory
199 if (!is_dir($dir = dirname($cache))) {
200 //Create filesystem object
201 $filesystem = new Filesystem();
202
203 try {
204 //Create dir
205 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
206 $filesystem->mkdir($dir, 0775);
207 } catch (IOExceptionInterface $e) {
208 //Throw error
209 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
210 }
211 }
212
213 //Read image
214 $image->readImage($src);
215
216 //Crop using aspect ratio
217 //XXX: for better result upload image directly in aspect ratio :)
218 $image->cropThumbnailImage($this->config['facebook']['width'], $this->config['facebook']['height']);
219
220 //Strip image exif data and properties
221 $image->stripImage();
222
223 //Save cache image
224 if (!$image->writeImage($cache)) {
225 //Throw error
226 throw new \Exception(sprintf('Unable to write image "%s"', $cache));
227 }
228 }
229 //Check target directory
230 if (!is_dir($dir = dirname($dest))) {
231 //Create filesystem object
232 $filesystem = new Filesystem();
233
234 try {
235 //Create dir
236 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
237 $filesystem->mkdir($dir, 0775);
238 } catch (IOExceptionInterface $e) {
239 //Throw error
240 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
241 }
242 }
243
244 //Get image width
245 $width = $image->getImageWidth();
246
247 //Get image height
248 $height = $image->getImageHeight();
249
250 //Create draw
251 $draw = new \ImagickDraw();
252
253 //Set stroke antialias
254 $draw->setStrokeAntialias(true);
255
256 //Set text antialias
257 $draw->setTextAntialias(true);
258
259 //Set font aliases
260 $fonts = [
261 'irishgrover' => $this->config['path']['public'].'/ttf/irishgrover.v10.ttf',
262 'droidsans' => $this->config['path']['public'].'/ttf/droidsans.regular.ttf',
263 'dejavusans' => $this->config['path']['public'].'/ttf/dejavusans.2.37.ttf',
264 'labelleaurore' => $this->config['path']['public'].'/ttf/labelleaurore.v10.ttf'
265 ];
266
267 //Set align aliases
268 $aligns = [
269 'left' => \Imagick::ALIGN_LEFT,
270 'center' => \Imagick::ALIGN_CENTER,
271 'right' => \Imagick::ALIGN_RIGHT
272 ];
273
274 //Set default font
275 $defaultFont = 'dejavusans';
276
277 //Set default align
278 $defaultAlign = 'center';
279
280 //Set default size
281 $defaultSize = 60;
282
283 //Set default stroke
284 $defaultStroke = '#00c3f9';
285
286 //Set default width
287 $defaultWidth = 15;
288
289 //Set default fill
290 $defaultFill = 'white';
291
292 //Init counter
293 $i = 1;
294
295 //Set text count
296 $count = count($texts);
297
298 //Draw each text stroke
299 foreach($texts as $text => $data) {
300 //Set font
301 $draw->setFont($fonts[$data['font']??$defaultFont]);
302
303 //Set font size
304 $draw->setFontSize($data['size']??$defaultSize);
305
306 //Set stroke width
307 $draw->setStrokeWidth($data['width']??$defaultWidth);
308
309 //Set text alignment
310 $draw->setTextAlignment($align = ($aligns[$data['align']??$defaultAlign]));
311
312 //Get font metrics
313 $metrics = $image->queryFontMetrics($draw, $text);
314
315 //Without y
316 if (empty($data['y'])) {
317 //Position verticaly each text evenly
318 $texts[$text]['y'] = $data['y'] = (($height + 100) / (count($texts) + 1) * $i) - 50;
319 }
320
321 //Without x
322 if (empty($data['x'])) {
323 if ($align == \Imagick::ALIGN_CENTER) {
324 $texts[$text]['x'] = $data['x'] = $width/2;
325 } elseif ($align == \Imagick::ALIGN_LEFT) {
326 $texts[$text]['x'] = $data['x'] = 50;
327 } elseif ($align == \Imagick::ALIGN_RIGHT) {
328 $texts[$text]['x'] = $data['x'] = $width - 50;
329 }
330 }
331
332 //Center verticaly
333 //XXX: add ascender part then center it back by half of textHeight
334 //TODO: maybe add a boundingbox ???
335 $texts[$text]['y'] = $data['y'] += $metrics['ascender'] - $metrics['textHeight']/2;
336
337 //Set stroke color
338 $draw->setStrokeColor(new \ImagickPixel($data['stroke']??$defaultStroke));
339
340 //Set fill color
341 $draw->setFillColor(new \ImagickPixel($data['stroke']??$defaultStroke));
342
343 //Add annotation
344 $draw->annotation($data['x'], $data['y'], $text);
345
346 //Increase counter
347 $i++;
348 }
349
350 //Create stroke object
351 $stroke = new \Imagick();
352
353 //Add new image
354 $stroke->newImage($width, $height, new \ImagickPixel('transparent'));
355
356 //Draw on image
357 $stroke->drawImage($draw);
358
359 //Blur image
360 //XXX: blur the stroke canvas only
361 $stroke->blurImage(5,3);
362
363 //Set opacity to 0.5
364 //XXX: see https://www.php.net/manual/en/image.evaluateimage.php
365 $stroke->evaluateImage(\Imagick::EVALUATE_DIVIDE, 1.5, \Imagick::CHANNEL_ALPHA);
366
367 //Compose image
368 $image->compositeImage($stroke, \Imagick::COMPOSITE_OVER, 0, 0);
369
370 //Clear stroke
371 $stroke->clear();
372
373 //Destroy stroke
374 unset($stroke);
375
376 //Clear draw
377 $draw->clear();
378
379 //Set text antialias
380 $draw->setTextAntialias(true);
381
382 //Draw each text
383 foreach($texts as $text => $data) {
384 //Set font
385 $draw->setFont($fonts[$data['font']??$defaultFont]);
386
387 //Set font size
388 $draw->setFontSize($data['size']??$defaultSize);
389
390 //Set text alignment
391 $draw->setTextAlignment($aligns[$data['align']??$defaultAlign]);
392
393 //Set fill color
394 $draw->setFillColor(new \ImagickPixel($data['fill']??$defaultFill));
395
396 //Add annotation
397 $draw->annotation($data['x'], $data['y'], $text);
398
399 //With canonical text
400 if (!empty($data['canonical'])) {
401 //Prevent canonical to finish in alt
402 unset($texts[$text]);
403 }
404 }
405
406 //Draw on image
407 $image->drawImage($draw);
408
409 //Strip image exif data and properties
410 $image->stripImage();
411
412 //Set image format
413 $image->setImageFormat('jpeg');
414
415 //Save image
416 if (!$image->writeImage($dest)) {
417 //Throw error
418 throw new \Exception(sprintf('Unable to write image "%s"', $dest));
419 }
420
421 //Get dest stat
422 $stat = stat($dest);
423
424 //Return image data
425 return [
426 'og:image' => $package->getAbsoluteUrl('@RapsysAir/facebook/'.$stat['mtime'].$pathInfo.'.jpeg'),
427 'og:image:alt' => str_replace("\n", ' ', implode(' - ', array_keys($texts))),
428 'og:image:height' => $height,
429 'og:image:width' => $width
430 ];
431 }
432
433 //Return empty array without image
434 return [];
435 }
436
437 /**
438 * Renders a view
439 *
440 * {@inheritdoc}
441 */
442 protected function render(string $view, array $parameters = [], Response $response = null): Response {
443 //Get request stack
444 $stack = $this->container->get('request_stack');
445
446 //Get current request
447 $request = $stack->getCurrentRequest();
448
449 //Get current locale
450 $locale = $request->getLocale();
451
452 //Set locale
453 $parameters['locale'] = str_replace('_', '-', $locale);
454
455 //Get context path
456 $pathInfo = $this->router->getContext()->getPathInfo();
457
458 //Iterate on locales excluding current one
459 foreach($this->config['locales'] as $current) {
460 //Set titles
461 $titles = [];
462
463 //Iterate on other locales
464 foreach(array_diff($this->config['locales'], [$current]) as $other) {
465 $titles[$other] = $this->translator->trans($this->config['languages'][$current], [], null, $other);
466 }
467
468 //Retrieve route matching path
469 $route = $this->router->match($pathInfo);
470
471 //Get route name
472 $name = $route['_route'];
473
474 //Unset route name
475 unset($route['_route']);
476
477 //With current locale
478 if ($current == $locale) {
479 //Set locale locales context
480 $parameters['canonical'] = $this->router->generate($name, ['_locale' => $current]+$route, UrlGeneratorInterface::ABSOLUTE_URL);
481 } else {
482 //Set locale locales context
483 $parameters['alternates'][str_replace('_', '-', $current)] = [
484 'absolute' => $this->router->generate($name, ['_locale' => $current]+$route, UrlGeneratorInterface::ABSOLUTE_URL),
485 'relative' => $this->router->generate($name, ['_locale' => $current]+$route),
486 'title' => implode('/', $titles),
487 'translated' => $this->translator->trans($this->config['languages'][$current], [], null, $current)
488 ];
489 }
490
491 //Add shorter locale
492 if (empty($parameters['alternates'][$shortCurrent = substr($current, 0, 2)])) {
493 //Set locale locales context
494 $parameters['alternates'][$shortCurrent] = [
495 'absolute' => $this->router->generate($name, ['_locale' => $current]+$route, UrlGeneratorInterface::ABSOLUTE_URL),
496 'relative' => $this->router->generate($name, ['_locale' => $current]+$route),
497 'title' => implode('/', $titles),
498 'translated' => $this->translator->trans($this->config['languages'][$current], [], null, $current)
499 ];
500 }
501 }
502
503 //Create application form for role_guest
504 if ($this->isGranted('ROLE_GUEST')) {
505 //Without application form
506 if (empty($parameters['forms']['application'])) {
507 //Fetch doctrine
508 $doctrine = $this->get('doctrine');
509
510 //Get favorites dances
511 $danceFavorites = $doctrine->getRepository(Dance::class)->findByUserId($this->getUser()->getId());
512
513 //Set dance default
514 $danceDefault = !empty($danceFavorites)?current($danceFavorites):null;
515
516 //Get favorites locations
517 $locationFavorites = $doctrine->getRepository(Location::class)->findByUserId($this->getUser()->getId());
518
519 //Set location default
520 $locationDefault = !empty($locationFavorites)?current($locationFavorites):null;
521
522 //With admin
523 if ($this->isGranted('ROLE_ADMIN')) {
524 //Get dances
525 $dances = $doctrine->getRepository(Dance::class)->findAll();
526
527 //Get locations
528 $locations = $doctrine->getRepository(Location::class)->findAll();
529 //Without admin
530 } else {
531 //Restrict to favorite dances
532 $dances = $danceFavorites;
533
534 //Reset favorites
535 $danceFavorites = [];
536
537 //Restrict to favorite locations
538 $locations = $locationFavorites;
539
540 //Reset favorites
541 $locationFavorites = [];
542 }
543
544 //With session location id
545 //XXX: set in session controller
546 if (!empty($parameters['session']['location']['id'])) {
547 //Iterate on each location
548 foreach($locations as $location) {
549 //Found location
550 if ($location->getId() == $parameters['session']['location']['id']) {
551 //Set location as default
552 $locationDefault = $location;
553
554 //Stop search
555 break;
556 }
557 }
558 }
559
560 //Create ApplicationType form
561 $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
562 //Set the action
563 'action' => $this->generateUrl('rapsys_air_application_add'),
564 //Set the form attribute
565 'attr' => [ 'class' => 'col' ],
566 //Set dance choices
567 'dance_choices' => $dances,
568 //Set dance default
569 'dance_default' => $danceDefault,
570 //Set dance favorites
571 'dance_favorites' => $danceFavorites,
572 //Set location choices
573 'location_choices' => $locations,
574 //Set location default
575 'location_default' => $locationDefault,
576 //Set location favorites
577 'location_favorites' => $locationFavorites,
578 //With user
579 'user' => $this->isGranted('ROLE_ADMIN'),
580 //Set user choices
581 'user_choices' => $doctrine->getRepository(User::class)->findAllWithTranslatedGroupAndCivility($this->translator),
582 //Set default user to current
583 'user_default' => $this->getUser()->getId(),
584 //Set to session slot or evening by default
585 //XXX: default to Evening (3)
586 'slot_default' => $doctrine->getRepository(Slot::class)->findOneById($parameters['session']['slot']['id']??3)
587 ]);
588
589 //Add form to context
590 $parameters['forms']['application'] = $application->createView();
591 }
592 //Create login form for anonymous
593 } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
594 //Create LoginType form
595 $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [
596 //Set the action
597 'action' => $this->generateUrl('rapsys_user_login'),
598 //Disable password repeated
599 'password_repeated' => false,
600 //Set the form attribute
601 'attr' => [ 'class' => 'col' ]
602 ]);
603
604 //Add form to context
605 $parameters['forms']['login'] = $login->createView();
606
607 //Set field
608 $field = [
609 //With mail
610 'mail' => true,
611 //Without civility
612 'civility' => false,
613 //Without pseudonym
614 'pseudonym' => false,
615 //Without forename
616 'forename' => false,
617 //Without surname
618 'surname' => false,
619 //Without password
620 'password' => false,
621 //Without slug
622 'slug' => false,
623 //Without phone
624 'phone' => false
625 ];
626
627 //Get slugger
628 $slugger = $this->container->get('rapsys_pack.slugger_util');
629
630 //Create RegisterType form
631 $register = $this->createForm('Rapsys\AirBundle\Form\RegisterType', null, $field+[
632 //Set the action
633 'action' => $this->generateUrl(
634 'rapsys_user_register',
635 [
636 'mail' => $smail = $slugger->short(''),
637 'field' => $sfield = $slugger->serialize($field),
638 'hash' => $slugger->hash($smail.$sfield)
639 ]
640 ),
641 //Set the form attribute
642 'attr' => [ 'class' => 'col' ]
643 ]);
644
645 //Add form to context
646 $parameters['forms']['register'] = $register->createView();
647 }
648
649 //With page infos and without facebook texts
650 if (empty($parameters['facebook']['texts']) && !empty($parameters['site']['title']) && !empty($parameters['title']) && !empty($parameters['canonical'])) {
651 //Set facebook image
652 $parameters['facebook']['texts'] = [
653 $parameters['site']['title'] => [
654 'font' => 'irishgrover',
655 'size' => 110
656 ],
657 $parameters['title'] => [
658 'align' => 'left'
659 ],
660 $parameters['canonical'] => [
661 'align' => 'right',
662 'canonical' => true,
663 'font' => 'labelleaurore',
664 'size' => 50
665 ]
666 ];
667 }
668
669 //With canonical
670 if (!empty($parameters['canonical'])) {
671 //Set facebook url
672 $parameters['facebook']['metas']['og:url'] = $parameters['canonical'];
673 }
674
675 //With empty facebook title and title
676 if (empty($parameters['facebook']['metas']['og:title']) && !empty($parameters['title'])) {
677 //Set facebook title
678 $parameters['facebook']['metas']['og:title'] = $parameters['title'];
679 }
680
681 //With empty facebook description and description
682 if (empty($parameters['facebook']['metas']['og:description']) && !empty($parameters['description'])) {
683 //Set facebook description
684 $parameters['facebook']['metas']['og:description'] = $parameters['description'];
685 }
686
687 //With locale
688 if (!empty($locale)) {
689 //Set facebook locale
690 $parameters['facebook']['metas']['og:locale'] = $locale;
691
692 //With alternates
693 //XXX: locale change when fb_locale=xx_xx is provided is done in FacebookSubscriber
694 //XXX: see https://stackoverflow.com/questions/20827882/in-open-graph-markup-whats-the-use-of-oglocalealternate-without-the-locati
695 if (!empty($parameters['alternates'])) {
696 //Iterate on alternates
697 foreach($parameters['alternates'] as $lang => $alternate) {
698 if (strlen($lang) == 5) {
699 //Set facebook locale alternate
700 $parameters['facebook']['metas']['og:locale:alternate'] = str_replace('-', '_', $lang);
701 }
702 }
703 }
704 }
705
706 //Without facebook image defined and texts
707 if (empty($parameters['facebook']['metas']['og:image']) && !empty($parameters['facebook']['texts'])) {
708 //Get facebook image
709 $parameters['facebook']['metas'] += $this->getFacebookImage($pathInfo, $parameters['facebook']);
710 }
711
712 //Call parent method
713 return $this->baseRender($view, $parameters, $response);
714 }
715
716 /**
717 * {@inheritdoc}
718 *
719 * @see vendor/symfony/framework-bundle/Controller/AbstractController.php
720 */
721 public static function getSubscribedServices(): array {
722 //Return subscribed services
723 return [
724 //'logger' => LoggerInterface::class,
725 'doctrine' => ManagerRegistry::class,
726 'rapsys_pack.path_package' => PackageInterface::class,
727 'request_stack' => RequestStack::class,
728 'router' => RouterInterface::class,
729 'translator' => TranslatorInterface::class
730 ];
731 }
732 }