]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/AbstractController.php
f8a0b9949c3e07b0d09e1802879070381ab21918
[airbundle] / Controller / AbstractController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
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;
11
12 use Rapsys\AirBundle\Entity\Slot;
13
14 use Rapsys\UserBundle\Utils\Slugger;
15
16 /**
17 *
18 * Provides common features needed in controllers.
19 *
20 * @todo: pass request_stack, router, slugger_util, path_package as constructor argument ?
21 *
22 * {@inheritdoc}
23 */
24 abstract class AbstractController extends BaseAbstractController {
25 use ControllerTrait {
26 //Rename render as baseRender
27 render as protected baseRender;
28 }
29
30 /**
31 * Return the facebook image
32 *
33 * @desc Generate image in jpeg format or load it from cache
34 *
35 * @param string $pathInfo The request path info
36 * @param array $parameters The image parameters
37 * @return array The image array
38 */
39 protected function getFacebookImage(string $pathInfo, array $parameters = []): array {
40 //Get asset package
41 //XXX: require asset package to be public
42 $package = $this->container->get('rapsys_pack.path_package');
43
44 //Set texts
45 $texts = $parameters['texts'] ?? [];
46
47 //Set default source
48 $source = $parameters['source'] ?? 'png/facebook.png';
49
50 //Set default source
51 $updated = $parameters['updated'] ?? strtotime('last week');
52
53 //Set source path
54 $src = $this->config['path']['public'].'/'.$source;
55
56 //Set cache path
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';
59
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';
64
65 //With up to date generated image
66 if (
67 is_file($dest) &&
68 ($stat = stat($dest)) &&
69 $stat['mtime'] >= $updated
70 ) {
71 //Get image size
72 list ($width, $height) = getimagesize($dest);
73
74 //Iterate each text
75 foreach($texts as $text => $data) {
76 //With canonical text
77 if (!empty($data['canonical'])) {
78 //Prevent canonical to finish in alt
79 unset($texts[$text]);
80 }
81 }
82
83 //Return image data
84 return [
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
89 ];
90 //With image candidate
91 } elseif (is_file($src)) {
92 //Create image object
93 $image = new \Imagick();
94
95 //With cache image
96 if (is_file($cache)) {
97 //Read image
98 $image->readImage($cache);
99 //Without we generate it
100 } else {
101 //Check target directory
102 if (!is_dir($dir = dirname($cache))) {
103 //Create filesystem object
104 $filesystem = new Filesystem();
105
106 try {
107 //Create dir
108 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
109 $filesystem->mkdir($dir, 0775);
110 } catch (IOExceptionInterface $e) {
111 //Throw error
112 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
113 }
114 }
115
116 //Read image
117 $image->readImage($src);
118
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']);
122
123 //Strip image exif data and properties
124 $image->stripImage();
125
126 //Save cache image
127 if (!$image->writeImage($cache)) {
128 //Throw error
129 throw new \Exception(sprintf('Unable to write image "%s"', $cache));
130 }
131 }
132 //Check target directory
133 if (!is_dir($dir = dirname($dest))) {
134 //Create filesystem object
135 $filesystem = new Filesystem();
136
137 try {
138 //Create dir
139 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
140 $filesystem->mkdir($dir, 0775);
141 } catch (IOExceptionInterface $e) {
142 //Throw error
143 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
144 }
145 }
146
147 //Get image width
148 $width = $image->getImageWidth();
149
150 //Get image height
151 $height = $image->getImageHeight();
152
153 //Create draw
154 $draw = new \ImagickDraw();
155
156 //Set stroke antialias
157 $draw->setStrokeAntialias(true);
158
159 //Set text antialias
160 $draw->setTextAntialias(true);
161
162 //Set font aliases
163 $fonts = [
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'
168 ];
169
170 //Set align aliases
171 $aligns = [
172 'left' => \Imagick::ALIGN_LEFT,
173 'center' => \Imagick::ALIGN_CENTER,
174 'right' => \Imagick::ALIGN_RIGHT
175 ];
176
177 //Set default font
178 $defaultFont = 'dejavusans';
179
180 //Set default align
181 $defaultAlign = 'center';
182
183 //Set default size
184 $defaultSize = 60;
185
186 //Set default stroke
187 $defaultStroke = '#00c3f9';
188
189 //Set default width
190 $defaultWidth = 15;
191
192 //Set default fill
193 $defaultFill = 'white';
194
195 //Init counter
196 $i = 1;
197
198 //Set text count
199 $count = count($texts);
200
201 //Draw each text stroke
202 foreach($texts as $text => $data) {
203 //Set font
204 $draw->setFont($fonts[$data['font']??$defaultFont]);
205
206 //Set font size
207 $draw->setFontSize($data['size']??$defaultSize);
208
209 //Set stroke width
210 $draw->setStrokeWidth($data['width']??$defaultWidth);
211
212 //Set text alignment
213 $draw->setTextAlignment($align = ($aligns[$data['align']??$defaultAlign]));
214
215 //Get font metrics
216 $metrics = $image->queryFontMetrics($draw, $text);
217
218 //Without y
219 if (empty($data['y'])) {
220 //Position verticaly each text evenly
221 $texts[$text]['y'] = $data['y'] = (($height + 100) / (count($texts) + 1) * $i) - 50;
222 }
223
224 //Without x
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;
232 }
233 }
234
235 //Center verticaly
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;
239
240 //Set stroke color
241 $draw->setStrokeColor(new \ImagickPixel($data['stroke']??$defaultStroke));
242
243 //Set fill color
244 $draw->setFillColor(new \ImagickPixel($data['stroke']??$defaultStroke));
245
246 //Add annotation
247 $draw->annotation($data['x'], $data['y'], $text);
248
249 //Increase counter
250 $i++;
251 }
252
253 //Create stroke object
254 $stroke = new \Imagick();
255
256 //Add new image
257 $stroke->newImage($width, $height, new \ImagickPixel('transparent'));
258
259 //Draw on image
260 $stroke->drawImage($draw);
261
262 //Blur image
263 //XXX: blur the stroke canvas only
264 $stroke->blurImage(5,3);
265
266 //Set opacity to 0.5
267 //XXX: see https://www.php.net/manual/en/image.evaluateimage.php
268 $stroke->evaluateImage(\Imagick::EVALUATE_DIVIDE, 1.5, \Imagick::CHANNEL_ALPHA);
269
270 //Compose image
271 $image->compositeImage($stroke, \Imagick::COMPOSITE_OVER, 0, 0);
272
273 //Clear stroke
274 $stroke->clear();
275
276 //Destroy stroke
277 unset($stroke);
278
279 //Clear draw
280 $draw->clear();
281
282 //Set text antialias
283 $draw->setTextAntialias(true);
284
285 //Draw each text
286 foreach($texts as $text => $data) {
287 //Set font
288 $draw->setFont($fonts[$data['font']??$defaultFont]);
289
290 //Set font size
291 $draw->setFontSize($data['size']??$defaultSize);
292
293 //Set text alignment
294 $draw->setTextAlignment($aligns[$data['align']??$defaultAlign]);
295
296 //Set fill color
297 $draw->setFillColor(new \ImagickPixel($data['fill']??$defaultFill));
298
299 //Add annotation
300 $draw->annotation($data['x'], $data['y'], $text);
301
302 //With canonical text
303 if (!empty($data['canonical'])) {
304 //Prevent canonical to finish in alt
305 unset($texts[$text]);
306 }
307 }
308
309 //Draw on image
310 $image->drawImage($draw);
311
312 //Strip image exif data and properties
313 $image->stripImage();
314
315 //Set image format
316 $image->setImageFormat('jpeg');
317
318 //Save image
319 if (!$image->writeImage($dest)) {
320 //Throw error
321 throw new \Exception(sprintf('Unable to write image "%s"', $dest));
322 }
323
324 //Get dest stat
325 $stat = stat($dest);
326
327 //Return image data
328 return [
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
333 ];
334 }
335
336 //Return empty array without image
337 return [];
338 }
339
340
341 /**
342 * Renders a view
343 *
344 * {@inheritdoc}
345 */
346 protected function render(string $view, array $parameters = [], Response $response = null): Response {
347 //Get request stack
348 $stack = $this->container->get('request_stack');
349
350 //Get current request
351 $request = $stack->getCurrentRequest();
352
353 //Get current locale
354 $locale = $request->getLocale();
355
356 //Set locale
357 $parameters['locale'] = str_replace('_', '-', $locale);
358
359 //Get router
360 $router = $this->container->get('router');
361
362 //Get context path
363 $pathInfo = $router->getContext()->getPathInfo();
364
365 //Iterate on locales excluding current one
366 foreach($this->config['locales'] as $current) {
367 //Set titles
368 $titles = [];
369
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);
373 }
374
375 //Retrieve route matching path
376 $route = $router->match($pathInfo);
377
378 //Get route name
379 $name = $route['_route'];
380
381 //Unset route name
382 unset($route['_route']);
383
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);
388 } else {
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)
395 ];
396 }
397
398 //Add shorter locale
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)
406 ];
407 }
408 }
409
410 //Create application form for role_guest
411 if ($this->isGranted('ROLE_GUEST')) {
412 //Without application form
413 if (empty($parameters['forms']['application'])) {
414 //Fetch doctrine
415 $doctrine = $this->getDoctrine();
416
417 //Create ApplicationType form
418 $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
419 //Set the action
420 'action' => $this->generateUrl('rapsys_air_application_add'),
421 //Set the form attribute
422 'attr' => [ 'class' => 'col' ],
423 //Set admin
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)
430 ]);
431
432 //Add form to context
433 $parameters['forms']['application'] = $application->createView();
434 }
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, [
439 //Set the action
440 'action' => $this->generateUrl('rapsys_user_login'),
441 //Disable password repeated
442 'password_repeated' => false,
443 //Set the form attribute
444 'attr' => [ 'class' => 'col' ]
445 ]);
446
447 //Add form to context
448 $parameters['forms']['login'] = $login->createView();
449
450 //Set field
451 $field = [
452 //With mail
453 'mail' => true,
454 //Without civility
455 'civility' => false,
456 //Without pseudonym
457 'pseudonym' => false,
458 //Without forename
459 'forename' => false,
460 //Without surname
461 'surname' => false,
462 //Without password
463 'password' => false,
464 //Without phone
465 'phone' => false
466 ];
467
468 //Get slugger
469 $slugger = $this->container->get('rapsys_pack.slugger_util');
470
471 //Create RegisterType form
472 $register = $this->createForm('Rapsys\AirBundle\Form\RegisterType', null, $field+[
473 //Set the action
474 'action' => $this->generateUrl(
475 'rapsys_user_register',
476 [
477 'mail' => $smail = $slugger->short(''),
478 'field' => $sfield = $slugger->serialize($field),
479 'hash' => $slugger->hash($smail.$sfield)
480 ]
481 ),
482 //Set the form attribute
483 'attr' => [ 'class' => 'col' ]
484 ]);
485
486 //Add form to context
487 $parameters['forms']['register'] = $register->createView();
488 }
489
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'])) {
492 //Set facebook image
493 $parameters['facebook']['texts'] = [
494 $parameters['site']['title'] => [
495 'font' => 'irishgrover',
496 'size' => 110
497 ],
498 $parameters['page']['title'] => [
499 'align' => 'left'
500 ],
501 $parameters['canonical'] => [
502 'align' => 'right',
503 'canonical' => true,
504 'font' => 'labelleaurore',
505 'size' => 50
506 ]
507 ];
508 }
509
510 //With canonical
511 if (!empty($parameters['canonical'])) {
512 //Set facebook url
513 $parameters['facebook']['metas']['og:url'] = $parameters['canonical'];
514 }
515
516 //With page title
517 if (!empty($parameters['page']['title'])) {
518 //Set facebook title
519 $parameters['facebook']['metas']['og:title'] = $parameters['page']['title'];
520 }
521
522 //With page description
523 if (!empty($parameters['page']['description'])) {
524 //Set facebook description
525 $parameters['facebook']['metas']['og:description'] = $parameters['page']['description'];
526 }
527
528 //With locale
529 if (!empty($locale)) {
530 //Set facebook locale
531 $parameters['facebook']['metas']['og:locale'] = $locale;
532
533 //With alternates
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);
542 }
543 }
544 }
545 }
546
547 //Without facebook image defined and texts
548 if (empty($parameters['facebook']['metas']['og:image']) && !empty($parameters['facebook']['texts'])) {
549 //Get facebook image
550 $parameters['facebook']['metas'] += $this->getFacebookImage($pathInfo, $parameters['facebook']);
551 }
552
553 //Call parent method
554 return $this->baseRender($view, $parameters, $response);
555 }
556
557 /**
558 * TODO: define this function to limit subscribed services ???
559 * XXX: see vendor/symfony/framework-bundle/Controller/AbstractController.php
560 *
561 public static function getSubscribedServices() {
562 //TODO: add asset.package ?
563 return [
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,
579 ];
580 }*/
581 }