3 namespace Rapsys\AirBundle\Controller
;
5 use Symfony\Component\Filesystem\Exception\IOExceptionInterface
;
6 use Symfony\Component\Filesystem\Filesystem
;
7 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController
as BaseAbstractController
;
8 use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait
;
9 use Symfony\Component\HttpFoundation\Response
;
10 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
12 use Rapsys\AirBundle\Entity\Slot
;
14 use Rapsys\UserBundle\Utils\Slugger
;
18 * Provides common features needed in controllers.
20 * @todo: pass request_stack, router, slugger_util, path_package as constructor argument ?
24 abstract class AbstractController
extends BaseAbstractController
{
26 //Rename render as baseRender
27 render
as protected baseRender
;
31 * Return the facebook image
33 * @desc Generate image in jpeg format or load it from cache
35 * @param string $pathInfo The request path info
36 * @param array $parameters The image parameters
37 * @return array The image array
39 protected function getFacebookImage(string $pathInfo, array $parameters = []): array {
41 //XXX: require asset package to be public
42 $package = $this->container
->get('rapsys_pack.path_package');
45 $texts = $parameters['texts'] ?? [];
48 $source = $parameters['source'] ?? 'png/facebook.png';
51 $updated = $parameters['updated'] ?? strtotime('last week');
54 $src = $this->config
['path']['public'].'/'.$source;
57 //XXX: remove extension and store as png anyway
58 $cache = $this->config
['path']['cache'].'/facebook/'.substr($source, 0, strrpos($source, '.')).'.'.$this->config
['facebook']['width'].'x'.$this->config
['facebook']['height'].'.png';
60 //Set destination path
61 //XXX: format <public>/facebook<pathinfo>.jpeg
62 //XXX: was <public>/facebook/<controller>/<action>.<locale>.jpeg
63 $dest = $this->config
['path']['public'].'/facebook'.$pathInfo.'.jpeg';
65 //With up to date generated image
68 ($stat = stat($dest)) &&
69 $stat['mtime'] >= $updated
72 list ($width, $height) = getimagesize($dest);
75 foreach($texts as $text => $data) {
77 if (!empty($data['canonical'])) {
78 //Prevent canonical to finish in alt
85 'og:image' => $package->getAbsoluteUrl('@RapsysAir/facebook/'.$stat['mtime'].$pathInfo.'.jpeg'),
86 'og:image:alt' => str_replace("\n", ' ', implode(' - ', array_keys($texts))),
87 'og:image:height' => $height,
88 'og:image:width' => $width
90 //With image candidate
91 } elseif (is_file($src)) {
93 $image = new \
Imagick();
96 if (is_file($cache)) {
98 $image->readImage($cache);
99 //Without we generate it
101 //Check target directory
102 if (!is_dir($dir = dirname($cache))) {
103 //Create filesystem object
104 $filesystem = new Filesystem();
108 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
109 $filesystem->mkdir($dir, 0775);
110 } catch (IOExceptionInterface
$e) {
112 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
117 $image->readImage($src);
119 //Crop using aspect ratio
120 //XXX: for better result upload image directly in aspect ratio :)
121 $image->cropThumbnailImage($this->config
['facebook']['width'], $this->config
['facebook']['height']);
123 //Strip image exif data and properties
124 $image->stripImage();
127 if (!$image->writeImage($cache)) {
129 throw new \
Exception(sprintf('Unable to write image "%s"', $cache));
132 //Check target directory
133 if (!is_dir($dir = dirname($dest))) {
134 //Create filesystem object
135 $filesystem = new Filesystem();
139 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
140 $filesystem->mkdir($dir, 0775);
141 } catch (IOExceptionInterface
$e) {
143 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
148 $width = $image->getImageWidth();
151 $height = $image->getImageHeight();
154 $draw = new \
ImagickDraw();
156 //Set stroke antialias
157 $draw->setStrokeAntialias(true);
160 $draw->setTextAntialias(true);
164 'irishgrover' => $this->config
['path']['public'].'/ttf/irishgrover.v10.ttf',
165 'droidsans' => $this->config
['path']['public'].'/ttf/droidsans.regular.ttf',
166 'dejavusans' => $this->config
['path']['public'].'/ttf/dejavusans.2.37.ttf',
167 'labelleaurore' => $this->config
['path']['public'].'/ttf/labelleaurore.v10.ttf'
172 'left' => \Imagick
::ALIGN_LEFT
,
173 'center' => \Imagick
::ALIGN_CENTER
,
174 'right' => \Imagick
::ALIGN_RIGHT
178 $defaultFont = 'dejavusans';
181 $defaultAlign = 'center';
187 $defaultStroke = '#00c3f9';
193 $defaultFill = 'white';
199 $count = count($texts);
201 //Draw each text stroke
202 foreach($texts as $text => $data) {
204 $draw->setFont($fonts[$data['font']??$defaultFont]);
207 $draw->setFontSize($data['size']??$defaultSize);
210 $draw->setStrokeWidth($data['width']??$defaultWidth);
213 $draw->setTextAlignment($align = ($aligns[$data['align']??$defaultAlign]));
216 $metrics = $image->queryFontMetrics($draw, $text);
219 if (empty($data['y'])) {
220 //Position verticaly each text evenly
221 $texts[$text]['y'] = $data['y'] = (($height +
100) / (count($texts) +
1) * $i) - 50;
225 if (empty($data['x'])) {
226 if ($align == \Imagick
::ALIGN_CENTER
) {
227 $texts[$text]['x'] = $data['x'] = $width/2;
228 } elseif ($align == \Imagick
::ALIGN_LEFT
) {
229 $texts[$text]['x'] = $data['x'] = 50;
230 } elseif ($align == \Imagick
::ALIGN_RIGHT
) {
231 $texts[$text]['x'] = $data['x'] = $width - 50;
236 //XXX: add ascender part then center it back by half of textHeight
237 //TODO: maybe add a boundingbox ???
238 $texts[$text]['y'] = $data['y'] +
= $metrics['ascender'] - $metrics['textHeight']/2;
241 $draw->setStrokeColor(new \
ImagickPixel($data['stroke']??$defaultStroke));
244 $draw->setFillColor(new \
ImagickPixel($data['stroke']??$defaultStroke));
247 $draw->annotation($data['x'], $data['y'], $text);
253 //Create stroke object
254 $stroke = new \
Imagick();
257 $stroke->newImage($width, $height, new \
ImagickPixel('transparent'));
260 $stroke->drawImage($draw);
263 //XXX: blur the stroke canvas only
264 $stroke->blurImage(5,3);
267 //XXX: see https://www.php.net/manual/en/image.evaluateimage.php
268 $stroke->evaluateImage(\Imagick
::EVALUATE_DIVIDE
, 1.5, \Imagick
::CHANNEL_ALPHA
);
271 $image->compositeImage($stroke, \Imagick
::COMPOSITE_OVER
, 0, 0);
283 $draw->setTextAntialias(true);
286 foreach($texts as $text => $data) {
288 $draw->setFont($fonts[$data['font']??$defaultFont]);
291 $draw->setFontSize($data['size']??$defaultSize);
294 $draw->setTextAlignment($aligns[$data['align']??$defaultAlign]);
297 $draw->setFillColor(new \
ImagickPixel($data['fill']??$defaultFill));
300 $draw->annotation($data['x'], $data['y'], $text);
302 //With canonical text
303 if (!empty($data['canonical'])) {
304 //Prevent canonical to finish in alt
305 unset($texts[$text]);
310 $image->drawImage($draw);
312 //Strip image exif data and properties
313 $image->stripImage();
316 $image->setImageFormat('jpeg');
319 if (!$image->writeImage($dest)) {
321 throw new \
Exception(sprintf('Unable to write image "%s"', $dest));
329 'og:image' => $package->getAbsoluteUrl('@RapsysAir/facebook/'.$stat['mtime'].$pathInfo.'.jpeg'),
330 'og:image:alt' => str_replace("\n", ' ', implode(' - ', array_keys($texts))),
331 'og:image:height' => $height,
332 'og:image:width' => $width
336 //Return empty array without image
346 protected function render(string $view, array $parameters = [], Response
$response = null): Response
{
348 $stack = $this->container
->get('request_stack');
350 //Get current request
351 $request = $stack->getCurrentRequest();
354 $locale = $request->getLocale();
357 $parameters['locale'] = str_replace('_', '-', $locale);
360 $router = $this->container
->get('router');
363 $pathInfo = $router->getContext()->getPathInfo();
365 //Iterate on locales excluding current one
366 foreach($this->config
['locales'] as $current) {
370 //Iterate on other locales
371 foreach(array_diff($this->config
['locales'], [$current]) as $other) {
372 $titles[$other] = $this->translator
->trans($this->config
['languages'][$current], [], null, $other);
375 //Retrieve route matching path
376 $route = $router->match($pathInfo);
379 $name = $route['_route'];
382 unset($route['_route']);
384 //With current locale
385 if ($current == $locale) {
386 //Set locale locales context
387 $parameters['canonical'] = $router->generate($name, ['_locale' => $current]+
$route, UrlGeneratorInterface
::ABSOLUTE_URL
);
389 //Set locale locales context
390 $parameters['alternates'][str_replace('_', '-', $current)] = [
391 'absolute' => $router->generate($name, ['_locale' => $current]+
$route, UrlGeneratorInterface
::ABSOLUTE_URL
),
392 'relative' => $router->generate($name, ['_locale' => $current]+
$route),
393 'title' => implode('/', $titles),
394 'translated' => $this->translator
->trans($this->config
['languages'][$current], [], null, $current)
399 if (empty($parameters['alternates'][$shortCurrent = substr($current, 0, 2)])) {
400 //Set locale locales context
401 $parameters['alternates'][$shortCurrent] = [
402 'absolute' => $router->generate($name, ['_locale' => $current]+
$route, UrlGeneratorInterface
::ABSOLUTE_URL
),
403 'relative' => $router->generate($name, ['_locale' => $current]+
$route),
404 'title' => implode('/', $titles),
405 'translated' => $this->translator
->trans($this->config
['languages'][$current], [], null, $current)
410 //Create application form for role_guest
411 if ($this->isGranted('ROLE_GUEST')) {
412 //Without application form
413 if (empty($parameters['forms']['application'])) {
415 $doctrine = $this->getDoctrine();
417 //Create ApplicationType form
418 $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
420 'action' => $this->generateUrl('rapsys_air_application_add'),
421 //Set the form attribute
422 'attr' => [ 'class' => 'col' ],
424 'admin' => $this->isGranted('ROLE_ADMIN'),
425 //Set default user to current
426 'user' => $this->getUser()->getId(),
427 //Set default slot to evening
428 //XXX: default to Evening (3)
429 'slot' => $doctrine->getRepository(Slot
::class)->findOneById(3)
432 //Add form to context
433 $parameters['forms']['application'] = $application->createView();
435 //Create login form for anonymous
436 } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
437 //Create LoginType form
438 $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [
440 'action' => $this->generateUrl('rapsys_user_login'),
441 //Disable password repeated
442 'password_repeated' => false,
443 //Set the form attribute
444 'attr' => [ 'class' => 'col' ]
447 //Add form to context
448 $parameters['forms']['login'] = $login->createView();
457 'pseudonym' => false,
469 $slugger = $this->container
->get('rapsys_pack.slugger_util');
471 //Create RegisterType form
472 $register = $this->createForm('Rapsys\AirBundle\Form\RegisterType', null, $field+
[
474 'action' => $this->generateUrl(
475 'rapsys_user_register',
477 'mail' => $smail = $slugger->short(''),
478 'field' => $sfield = $slugger->serialize($field),
479 'hash' => $slugger->hash($smail.$sfield)
482 //Set the form attribute
483 'attr' => [ 'class' => 'col' ]
486 //Add form to context
487 $parameters['forms']['register'] = $register->createView();
490 //With page infos and without facebook texts
491 if (empty($parameters['facebook']['texts']) && !empty($parameters['site']['title']) && !empty($parameters['page']['title']) && !empty($parameters['canonical'])) {
493 $parameters['facebook']['texts'] = [
494 $parameters['site']['title'] => [
495 'font' => 'irishgrover',
498 $parameters['page']['title'] => [
501 $parameters['canonical'] => [
504 'font' => 'labelleaurore',
511 if (!empty($parameters['canonical'])) {
513 $parameters['facebook']['metas']['og:url'] = $parameters['canonical'];
517 if (!empty($parameters['page']['title'])) {
519 $parameters['facebook']['metas']['og:title'] = $parameters['page']['title'];
522 //With page description
523 if (!empty($parameters['page']['description'])) {
524 //Set facebook description
525 $parameters['facebook']['metas']['og:description'] = $parameters['page']['description'];
529 if (!empty($locale)) {
530 //Set facebook locale
531 $parameters['facebook']['metas']['og:locale'] = $locale;
534 //XXX: locale change when fb_locale=xx_xx is provided is done in FacebookSubscriber
535 //XXX: see https://stackoverflow.com/questions/20827882/in-open-graph-markup-whats-the-use-of-oglocalealternate-without-the-locati
536 if (!empty($parameters['alternates'])) {
537 //Iterate on alternates
538 foreach($parameters['alternates'] as $lang => $alternate) {
539 if (strlen($lang) == 5) {
540 //Set facebook locale alternate
541 $parameters['facebook']['metas']['og:locale:alternate'] = str_replace('-', '_', $lang);
547 //Without facebook image defined and texts
548 if (empty($parameters['facebook']['metas']['og:image']) && !empty($parameters['facebook']['texts'])) {
550 $parameters['facebook']['metas'] +
= $this->getFacebookImage($pathInfo, $parameters['facebook']);
554 return $this->baseRender($view, $parameters, $response);
558 * TODO: define this function to limit subscribed services ???
559 * XXX: see vendor/symfony/framework-bundle/Controller/AbstractController.php
561 public static function getSubscribedServices() {
562 //TODO: add asset.package ?
564 'router' => '?'.RouterInterface::class,
565 'request_stack' => '?'.RequestStack::class,
566 'http_kernel' => '?'.HttpKernelInterface::class,
567 'serializer' => '?'.SerializerInterface::class,
568 'session' => '?'.SessionInterface::class,
569 'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
570 'templating' => '?'.EngineInterface::class,
571 'twig' => '?'.Environment::class,
572 'doctrine' => '?'.ManagerRegistry::class,
573 'form.factory' => '?'.FormFactoryInterface::class,
574 'security.token_storage' => '?'.TokenStorageInterface::class,
575 'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
576 'parameter_bag' => '?'.ContainerBagInterface::class,
577 'message_bus' => '?'.MessageBusInterface::class,
578 'messenger.default_bus' => '?'.MessageBusInterface::class,