]> Raphaël G. Git Repositories - airbundle/blob - Controller/AbstractController.php
Remove dance link on session
[airbundle] / Controller / AbstractController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys UserBundle 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\Location;
30 use Rapsys\AirBundle\Entity\Slot;
31 use Rapsys\AirBundle\Entity\User;
32 use Rapsys\AirBundle\RapsysAirBundle;
33
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 locations
511 $locationFavorites = $doctrine->getRepository(Location::class)->findByUserId($this->getUser()->getId());
512
513 //Set location default
514 $locationDefault = current($locationFavorites);
515
516 //With admin
517 if ($this->isGranted('ROLE_ADMIN')) {
518 //Get locations
519 $locations = $doctrine->getRepository(Location::class)->findAll();
520 //Without admin
521 } else {
522 //Restrict to favorite locations
523 $locations = $locationFavorites;
524
525 //Reset favorites
526 $locationFavorites = [];
527 }
528
529 //With session location id
530 //XXX: set in session controller
531 if (!empty($parameters['session']['location']['id'])) {
532 //Iterate on each location
533 foreach($locations as $location) {
534 //Found location
535 if ($location->getId() == $parameters['session']['location']['id']) {
536 //Set location as default
537 $locationDefault = $location;
538
539 //Stop search
540 break;
541 }
542 }
543 }
544
545 //Create ApplicationType form
546 $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
547 //Set the action
548 'action' => $this->generateUrl('rapsys_air_application_add'),
549 //Set the form attribute
550 'attr' => [ 'class' => 'col' ],
551 //Set location choices
552 'location_choices' => $locations,
553 //Set location default
554 'location_default' => $locationDefault,
555 //Set location favorites
556 'location_favorites' => $locationFavorites,
557 //With user
558 'user' => $this->isGranted('ROLE_ADMIN'),
559 //Set user choices
560 'user_choices' => $doctrine->getRepository(User::class)->findAllWithTranslatedGroupAndCivility($this->translator),
561 //Set default user to current
562 'user_default' => $this->getUser()->getId(),
563 //Set to session slot or evening by default
564 //XXX: default to Evening (3)
565 'slot_default' => $doctrine->getRepository(Slot::class)->findOneById($parameters['session']['slot']['id']??3)
566 ]);
567
568 //Add form to context
569 $parameters['forms']['application'] = $application->createView();
570 }
571 //Create login form for anonymous
572 } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
573 //Create LoginType form
574 $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [
575 //Set the action
576 'action' => $this->generateUrl('rapsys_user_login'),
577 //Disable password repeated
578 'password_repeated' => false,
579 //Set the form attribute
580 'attr' => [ 'class' => 'col' ]
581 ]);
582
583 //Add form to context
584 $parameters['forms']['login'] = $login->createView();
585
586 //Set field
587 $field = [
588 //With mail
589 'mail' => true,
590 //Without civility
591 'civility' => false,
592 //Without pseudonym
593 'pseudonym' => false,
594 //Without forename
595 'forename' => false,
596 //Without surname
597 'surname' => false,
598 //Without password
599 'password' => false,
600 //Without slug
601 'slug' => false,
602 //Without phone
603 'phone' => false
604 ];
605
606 //Get slugger
607 $slugger = $this->container->get('rapsys_pack.slugger_util');
608
609 //Create RegisterType form
610 $register = $this->createForm('Rapsys\AirBundle\Form\RegisterType', null, $field+[
611 //Set the action
612 'action' => $this->generateUrl(
613 'rapsys_user_register',
614 [
615 'mail' => $smail = $slugger->short(''),
616 'field' => $sfield = $slugger->serialize($field),
617 'hash' => $slugger->hash($smail.$sfield)
618 ]
619 ),
620 //Set the form attribute
621 'attr' => [ 'class' => 'col' ]
622 ]);
623
624 //Add form to context
625 $parameters['forms']['register'] = $register->createView();
626 }
627
628 //With page infos and without facebook texts
629 if (empty($parameters['facebook']['texts']) && !empty($parameters['site']['title']) && !empty($parameters['title']) && !empty($parameters['canonical'])) {
630 //Set facebook image
631 $parameters['facebook']['texts'] = [
632 $parameters['site']['title'] => [
633 'font' => 'irishgrover',
634 'size' => 110
635 ],
636 $parameters['title'] => [
637 'align' => 'left'
638 ],
639 $parameters['canonical'] => [
640 'align' => 'right',
641 'canonical' => true,
642 'font' => 'labelleaurore',
643 'size' => 50
644 ]
645 ];
646 }
647
648 //With canonical
649 if (!empty($parameters['canonical'])) {
650 //Set facebook url
651 $parameters['facebook']['metas']['og:url'] = $parameters['canonical'];
652 }
653
654 //With empty facebook title and title
655 if (empty($parameters['facebook']['metas']['og:title']) && !empty($parameters['title'])) {
656 //Set facebook title
657 $parameters['facebook']['metas']['og:title'] = $parameters['title'];
658 }
659
660 //With empty facebook description and description
661 if (empty($parameters['facebook']['metas']['og:description']) && !empty($parameters['description'])) {
662 //Set facebook description
663 $parameters['facebook']['metas']['og:description'] = $parameters['description'];
664 }
665
666 //With locale
667 if (!empty($locale)) {
668 //Set facebook locale
669 $parameters['facebook']['metas']['og:locale'] = $locale;
670
671 //With alternates
672 //XXX: locale change when fb_locale=xx_xx is provided is done in FacebookSubscriber
673 //XXX: see https://stackoverflow.com/questions/20827882/in-open-graph-markup-whats-the-use-of-oglocalealternate-without-the-locati
674 if (!empty($parameters['alternates'])) {
675 //Iterate on alternates
676 foreach($parameters['alternates'] as $lang => $alternate) {
677 if (strlen($lang) == 5) {
678 //Set facebook locale alternate
679 $parameters['facebook']['metas']['og:locale:alternate'] = str_replace('-', '_', $lang);
680 }
681 }
682 }
683 }
684
685 //Without facebook image defined and texts
686 if (empty($parameters['facebook']['metas']['og:image']) && !empty($parameters['facebook']['texts'])) {
687 //Get facebook image
688 $parameters['facebook']['metas'] += $this->getFacebookImage($pathInfo, $parameters['facebook']);
689 }
690
691 //Call parent method
692 return $this->baseRender($view, $parameters, $response);
693 }
694
695 /**
696 * {@inheritdoc}
697 *
698 * @see vendor/symfony/framework-bundle/Controller/AbstractController.php
699 */
700 public static function getSubscribedServices(): array {
701 //Return subscribed services
702 return [
703 //'logger' => LoggerInterface::class,
704 'doctrine' => ManagerRegistry::class,
705 'rapsys_pack.path_package' => PackageInterface::class,
706 'request_stack' => RequestStack::class,
707 'router' => RouterInterface::class,
708 'translator' => TranslatorInterface::class
709 ];
710 }
711 }