src/Service/Internal/HomePageService.php line 166

Open in your IDE?
  1. <?php
  2. namespace App\Service\Internal;
  3. use App\Event\ModeEvent;
  4. use App\Manager\AccountManager;
  5. use App\Model\PreferenceProfiles;
  6. use App\Security\KasUserAuthenticator;
  7. use App\Service\Internal\User\PreferenceService;
  8. use App\Service\Internal\Schedule\FavoriteService;
  9. use App\Manager\BookingSecureBikeParkManager;
  10. use App\Manager\InteractiveMapManager;
  11. use App\Manager\DisruptionManager;
  12. use App\Normalizer\DisruptionNormalizer;
  13. use App\Normalizer\LineNormalizer;
  14. use App\Normalizer\UserPreferencesNormalizer;
  15. use App\Normalizer\Schedule\FavoriteNormalizer as ScheduleFavoriteNormalizer;
  16. use App\Normalizer\Line\FavoriteNormalizer as LineFavoriteNormalizer;
  17. use App\Utils\DeviceInfo;
  18. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  19. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  20. use Symfony\Component\HttpFoundation\RequestStack;
  21. use Symfony\Component\Security\Core\Security;
  22. class HomePageService
  23. {
  24. public const TRANSITPASS_KEY = 'TRANSITPASS';
  25. protected string $networkId;
  26. protected array $network;
  27. protected string $ticketingModule;
  28. protected string $geoserverUrl;
  29. protected PreferenceService $preferenceService;
  30. protected UserPreferencesNormalizer $userPreferencesNormalizer;
  31. protected NetworkService $networkService;
  32. protected UserService $userService;
  33. protected DisruptionService $disruptionService;
  34. protected DisruptionNormalizer $disruptionNormalizer;
  35. protected FavoriteService $favoriteService;
  36. protected CmsService $cmsService;
  37. protected ScheduleFavoriteNormalizer $scheduleFavoriteNormalizer;
  38. protected LineFavoriteNormalizer $lineFavoriteNormalizer;
  39. protected MetaService$metaService;
  40. protected LocalizationService $localizationService;
  41. protected RequestStack $requestStack;
  42. protected Security $security;
  43. protected LineNormalizer $lineNormalizer;
  44. protected BookingSecureBikeParkManager $bookingSecureBikeParkManager;
  45. protected EventDispatcherInterface $eventDispatcher;
  46. protected InteractiveMapManager $interactiveMapManager;
  47. protected ParameterBagInterface $params;
  48. protected DisruptionManager $disruptionManager;
  49. protected Line\FavoriteService $lineFavoriteService;
  50. protected AccountManager $accountManager;
  51. public function __construct(
  52. string $networkId,
  53. string $ticketingModule,
  54. string $geoserverUrl,
  55. PreferenceService $preferenceService,
  56. UserPreferencesNormalizer $userPreferencesNormalizer,
  57. NetworkService $networkService,
  58. UserService $userService,
  59. DisruptionService $disruptionService,
  60. DisruptionNormalizer $disruptionNormalizer,
  61. Schedule\FavoriteService $favoriteService,
  62. Line\FavoriteService $lineFavoriteService,
  63. ScheduleFavoriteNormalizer $scheduleFavoriteNormalizer,
  64. LineFavoriteNormalizer $lineFavoriteNormalizer,
  65. CmsService $cmsService,
  66. MetaService $metaService,
  67. LocalizationService $localizationService,
  68. RequestStack $requestStack,
  69. Security $security,
  70. LineNormalizer $lineNormalizer,
  71. BookingSecureBikeParkManager $bookingSecureBikeParkManager,
  72. EventDispatcherInterface $eventDispatcher,
  73. InteractiveMapManager $interactiveMapManager,
  74. AccountManager $accountManager,
  75. ParameterBagInterface $parameterBag,
  76. DisruptionManager $disruptionManager
  77. ) {
  78. $this->networkId = $networkId;
  79. $this->ticketingModule = $ticketingModule;
  80. $this->geoserverUrl = $geoserverUrl;
  81. $this->preferenceService = $preferenceService;
  82. $this->userPreferencesNormalizer = $userPreferencesNormalizer;
  83. $this->disruptionNormalizer = $disruptionNormalizer;
  84. $this->networkService = $networkService;
  85. $this->userService = $userService;
  86. $this->disruptionService = $disruptionService;
  87. $this->favoriteService = $favoriteService;
  88. $this->lineFavoriteService = $lineFavoriteService;
  89. $this->scheduleFavoriteNormalizer = $scheduleFavoriteNormalizer;
  90. $this->lineFavoriteNormalizer = $lineFavoriteNormalizer;
  91. $this->cmsService = $cmsService;
  92. $this->metaService = $metaService;
  93. $this->localizationService = $localizationService;
  94. $this->requestStack = $requestStack;
  95. $this->security = $security;
  96. $this->lineNormalizer = $lineNormalizer;
  97. $this->bookingSecureBikeParkManager = $bookingSecureBikeParkManager;
  98. $this->eventDispatcher = $eventDispatcher;
  99. $this->interactiveMapManager = $interactiveMapManager;
  100. $this->accountManager = $accountManager;
  101. $this->params = $parameterBag;
  102. $this->disruptionManager = $disruptionManager;
  103. $this->network = $this->networkService->getNetwork();
  104. }
  105. /**
  106. * @return array
  107. * @throws \Exception
  108. */
  109. public function getRenderParameters(array $get = [], array $parameters = [])
  110. {
  111. //TODO: Temporaire, à supprimer quand la conf par réseau et environnement sera externalisée
  112. $parameters['baseUrl'] = 'https://' . $_SERVER['SERVER_NAME'];
  113. $parameters = DeviceInfo::addDeviceParameters($parameters);
  114. $session = $this->requestStack->getSession();
  115. $body = $get;
  116. $nbDayFuture = $this->networkService->getNbDayFuture();
  117. $maxDate = new \DateTime('now');
  118. $maxDate = $maxDate->add(new \DateInterval('P'.$nbDayFuture.'D'));
  119. $parameters['maxDate'] = $maxDate->format('Y-d-m');
  120. $parameters['networkId'] = isset($this->networkId) ? $this->networkId : '';
  121. $parameters['default_latlon'] = $this->networkService->getLatLon();
  122. $parameters['network_lat'] = $this->networkService->getLat();
  123. $parameters['network_lon'] = $this->networkService->getLon();
  124. $parameters['external'] = $this->networkService->isExternalNetwork();
  125. $parameters['operators'] = json_encode($this->networkService->getOperatorInfos());
  126. $parameters['geoserverUrl'] = isset($this->geoserverUrl) ? $this->geoserverUrl : '';
  127. $parameters['journeys'] = isset($parameters['journeys']) ? $parameters['journeys'] : [];
  128. $parameters['directions'] = isset($parameters['directions']) ? $parameters['directions'] : [];
  129. $parameters['stopPoints'] = isset($parameters['stopPoints']) ? $parameters['stopPoints'] : [];
  130. $parameters['languages'] = $this->localizationService->getLanguages();
  131. $parameters['bookingIsEnabled'] = $this->bookingSecureBikeParkManager->isEnabled($this->network);
  132. $parameters['fromSEO'] = preg_match('/(google|yahoo|bing|qwant)/i', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '') === 1;
  133. $parameters['fromWidget'] = $session->get('context', null) === 'WIDGET';
  134. $parameters['referer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
  135. if($parameters['fromWidget']){
  136. $request = $this->requestStack->getCurrentRequest();
  137. $url = $request->headers->get('referer') ?? $request->getSchemeAndHttpHost();
  138. $parameters['isAuthorizedDomainForBookingSbp'] = $this->bookingSecureBikeParkManager->isAuthorizedDomain($url);
  139. }
  140. $layoutScheduleLine = $this->networkService->getLayoutScheduleLine();
  141. $session->set('layoutScheduleLine', $layoutScheduleLine);
  142. if (empty($parameters['activeTab'])) {
  143. $parameters['activeTab'] = 'journey';
  144. }
  145. if (!isset($parameters['displayDisruptionWithAjax']) || false === $parameters['displayDisruptionWithAjax'] || $parameters['activeTab'] == 'traffic') {
  146. $this->getDisruption($parameters);
  147. }
  148. if ($parameters['activeTab'] == 'interactiveMap') {
  149. $poi = $this->requestStack->getCurrentRequest()->get('poi');
  150. $parameters['poi'] = explode(',', $poi);
  151. $interactiveMapData = $this->interactiveMapManager->interactiveMapData();
  152. $parameters = array_merge($parameters, $interactiveMapData);
  153. }
  154. $userPreferences = [];
  155. if ($this->security->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  156. $userPreferences = $this->preferenceService->getUserPreferences();
  157. $parameters = $this->accountManager->getRenderParameters($parameters);
  158. }
  159. $context['itineraryOptions'] = $this->networkService->getItineraryOptions();
  160. if ($this->params->get('global.login_mode') === KasUserAuthenticator::LOGIN_MODE
  161. && $this->security->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  162. $settings = $this->accountManager->getItineraryPreferences();
  163. $parameters['preferences']['tripPlanner'] = $settings->body;
  164. $parameters['preferences'] = $this->userPreferencesNormalizer->normalize(json_decode(json_encode($parameters['preferences'] ?? []), true), $context);
  165. } else {
  166. $parameters['preferences'] = $this->userPreferencesNormalizer->normalize($userPreferences, $context, true);
  167. }
  168. $parameters['isTransitPassEnabled'] = in_array(self::TRANSITPASS_KEY, $context['itineraryOptions'], true);
  169. $includedModes = $body['modes'] ?? null;
  170. $excludedModesPreferences = !empty($parameters['preferences']['tripPlanner']['excludedModes']) ? $parameters['preferences']['tripPlanner']['excludedModes'] : [];
  171. $modeEvent = new ModeEvent($includedModes, $excludedModesPreferences);
  172. $this->eventDispatcher->dispatch($modeEvent, ModeEvent::NAME);
  173. $parameters['modes'] = $modeEvent->getDefaultModes();
  174. $parameters['modesLayout'] = $modeEvent->getLayoutModes();
  175. $scheduleFavorites = [];
  176. $parameters['lineFavorites'] = [];
  177. if ($this->security->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  178. $scheduleFavorites = $this->favoriteService->getScheduleFavorites();
  179. $scheduleFavorites = $this->scheduleFavoriteNormalizer->normalize($scheduleFavorites);
  180. $userResponse = $this->userService->myAccount();
  181. if (isset($userResponse->body) && isset($userResponse->status) && $userResponse->status === 200) {
  182. $parameters['userData'] = $userResponse->body;
  183. }
  184. $parameters['lineFavorites'] = $this->lineFavoriteService->getFavoriteLines([]);
  185. $parameters['lineFavorites'] = $this
  186. ->lineFavoriteNormalizer
  187. ->normalize($parameters['lineFavorites'], $parameters['linesDisruptions'] ?? []);
  188. }
  189. $parameters['scheduleFavorites'] = isset($scheduleFavorites) ? $scheduleFavorites : [];
  190. $parameters['activeWidgets'] = [
  191. 'journey' => 1,
  192. 'schedule' => 1,
  193. 'traffic' => 1,
  194. 'linesAndPoi' => 1
  195. ];
  196. if (!isset($parameters['departurePlace'])) {
  197. $parameters['departurePlace']['id'] = '';
  198. $parameters['departurePlace']['value'] = '';
  199. $parameters['departurePlace']['latlon'] = '';
  200. $parameters['departurePlace']['latitude'] = '';
  201. $parameters['departurePlace']['longitude'] = '';
  202. }
  203. if (!isset($parameters['arrivalPlace'])) {
  204. $parameters['arrivalPlace']['id'] = '';
  205. $parameters['arrivalPlace']['value'] = '';
  206. $parameters['arrivalPlace']['latlon'] = '';
  207. $parameters['arrivalPlace']['latitude'] = '';
  208. $parameters['arrivalPlace']['longitude'] = '';
  209. }
  210. $menu = $this->cmsService->getMenu();
  211. $parameters['menuPages'] = $menu['menuPages'];
  212. $parameters['footerPages'] = $menu['footerPages'];
  213. $parameters['items'] = $menu['items'];
  214. $banners = $this->cmsService->getBanners();
  215. foreach($banners as $banner) {
  216. $banner->id = str_replace(':', '-', $banner->id);
  217. }
  218. $launchNews = $this->cmsService->getLaunchNews();
  219. $parameters['banners'] = $banners;
  220. $parameters['launchNews'] = $launchNews;
  221. $ids = [];
  222. foreach ($launchNews as $popupPost) {
  223. $ids[] = $popupPost->id;
  224. }
  225. $parameters['launchNewsId'] = isset($launchNews[0]->id) ? $launchNews[0]->id : '';
  226. $parameters['ticketingModule'] = $this->ticketingModule;
  227. $posts = $this->cmsService->getPosts();
  228. $parameters['posts'] = $posts;
  229. // Preferences
  230. $speedProfiles = [0 => 'SLOW', 1 => 'NORMAL', 2 => 'FAST', 3 => 'VTT', 4 => 'VAE'];
  231. $parameters['preferences']['tripPlanner']['excludedModes'] = $modeEvent->getExcludedModes();
  232. $parameters['preferences']['tripPlanner']['showAccessibility'] = isset($body['showAccessibility']) ? filter_var($body['showAccessibility'], FILTER_VALIDATE_BOOLEAN) : $parameters['preferences']['tripPlanner']['showAccessibility'];
  233. $parameters['preferences']['tripPlanner']['wheelchairAccessible'] = isset($body['accessible']) ? filter_var($body['accessible'], FILTER_VALIDATE_BOOLEAN) : $parameters['preferences']['tripPlanner']['wheelchairAccessible'];
  234. $parameters['preferences']['tripPlanner']['accessibilityProfile'] = isset($body['disabilityType']) && in_array($body['disabilityType'], PreferenceProfiles::ACCESSIBILITY_PROFILES, true) ? $body['disabilityType'] : ($parameters['preferences']['tripPlanner']['accessibilityProfile'] ?? PreferenceProfiles::ACCESSIBILITY_PROFILE_NONE);
  235. $parameters['preferences']['tripPlanner']['walkProfile'] = isset($body['walk']['speed']) ? $speedProfiles[$body['walk']['speed']] : $parameters['preferences']['tripPlanner']['walkProfile'];
  236. $parameters['preferences']['tripPlanner']['bikeProfile'] = isset($body['bike']['speed']) ? $speedProfiles[$body['bike']['speed']] : $parameters['preferences']['tripPlanner']['bikeProfile'];
  237. $this->generateMetas($parameters);
  238. return $parameters;
  239. }
  240. /**
  241. * @param array $parameters
  242. * @throws \Exception
  243. */
  244. public function getDisruption(array &$parameters = [])
  245. {
  246. $currentSubNetworksDisruptions = 0;
  247. $futureSubNetworksDisruptions = 0;
  248. $disruptionLayout = $this->networkService->getDisruptionLayout();
  249. $subNetworks = $this->networkService->getSubNetworks();
  250. $isSubNetworks = $parameters['issubnetworks'] ?? '';
  251. $currentDisruptions = $this->disruptionService->getDisruptions($isSubNetworks, DisruptionNormalizer::STATUS_ONGOING);
  252. $futureDisruptions = $this->disruptionService->getDisruptions($isSubNetworks, DisruptionNormalizer::STATUS_COMING);
  253. $parameters['nbSubNetworks'] = count($subNetworks) ?? 0;
  254. $parameters['currentDisruptions'] = $currentDisruptions['disruptions'] ?? [];
  255. $parameters['futureDisruptions'] = $futureDisruptions['disruptions'] ?? [];
  256. $withDisruptionOnly = null;
  257. if (in_array("FAV_WITH_DISRUPTIONS_BOARDS_LINES", $disruptionLayout)) {
  258. $withDisruptionOnly = 0;
  259. } elseif (in_array("FAV_WITH_DISRUPTIONS_BOARDS_LINES_WITHDISRUPTIONSONLY", $disruptionLayout)) {
  260. $withDisruptionOnly = 1;
  261. }
  262. if ($withDisruptionOnly !== null) {
  263. $parameters['currentDisruptions']['subNetworks'] = [];
  264. $parameters['futureDisruptions']['subNetworks'] = [];
  265. } else {
  266. $parameters['currentDisruptions']['subNetworks'] = $this->disruptionManager->getSubNetworksDisruptions($currentDisruptions, 'currents',$isSubNetworks);
  267. $parameters['futureDisruptions']['subNetworks'] = $this->disruptionManager->getSubNetworksDisruptions($futureDisruptions, 'futures', $isSubNetworks);
  268. $currentSubNetworksDisruptions = $this->getDisruptionsCountForSubNetworkOrLine($parameters['currentDisruptions']['subNetworks'], 'currents');
  269. $futureSubNetworksDisruptions = $this->getDisruptionsCountForSubNetworkOrLine($parameters['futureDisruptions']['subNetworks'], 'futures');
  270. }
  271. $parameters['currentDisruptions']['lines'] = $this->disruptionManager->getLinesDisruptions($currentDisruptions, 'currents');
  272. $parameters['futureDisruptions']['lines'] = $this->disruptionManager->getLinesDisruptions($futureDisruptions, 'futures');
  273. $parameters['currentDisruptions']['stopPoints'] = $this->disruptionManager->getStopPointsDisruptions($currentDisruptions, 'currents');
  274. $parameters['futureDisruptions']['stopPoints'] = $this->disruptionManager->getStopPointsDisruptions($futureDisruptions, 'futures');
  275. $parameters['currentDisruptions']['general'] = $this->disruptionManager->getGeneralDisruptions($currentDisruptions, 'currents');
  276. $parameters['futureDisruptions']['general'] = $this->disruptionManager->getGeneralDisruptions($futureDisruptions, 'futures');
  277. if ($this->security->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  278. $parameters['lineFavorites'] = $this->lineFavoriteService->getFavoriteLines([]);
  279. $parameters['lineFavorites'] = $this
  280. ->lineFavoriteNormalizer
  281. ->normalize($parameters['lineFavorites'], $parameters['linesDisruptions'] ?? []);
  282. }
  283. $parameters['withDisruptionOnly'] = $withDisruptionOnly;
  284. $parameters['currentSubNetworksDisruptions'] = $currentSubNetworksDisruptions;
  285. $parameters['futureSubNetworksDisruptions'] = $futureSubNetworksDisruptions;
  286. }
  287. /**
  288. * @param array $subNetworks
  289. * @return int Number of disruptions on a subnetwork
  290. */
  291. protected function getDisruptionsCountForSubNetworkOrLine(array $subNetworks, string $status) {
  292. return array_reduce($subNetworks, function ($disruptionsCount, $subNetwork) use ($status) {
  293. if ($this->hasDisruptionsForSubnetworkOrLine($subNetwork, $status)) {
  294. return $disruptionsCount + 1;
  295. }
  296. return $disruptionsCount;
  297. }, 0);
  298. }
  299. /**
  300. * @param array $subNetworkData
  301. * @return bool true if the subnetwork or one of its lines has disruptions
  302. */
  303. protected function hasDisruptionsForSubnetworkOrLine(array $subNetworkData, string $status): bool
  304. {
  305. $hasSubnetworkDisruption = !empty($subNetworkData['disruptions'][$status]);
  306. $hasLineDisruption = !empty($subNetworkData['disruptions']['lines'][$status]);
  307. return $hasSubnetworkDisruption || $hasLineDisruption;
  308. }
  309. protected function generateMetas(array &$params)
  310. {
  311. $params['page_title'] = $this->metaService->getPageTitle($params);
  312. $params['enable_no_index'] = $this->metaService->enableNoIndex();
  313. $params['page_keywords'] = $this->metaService->getPageKeywords($params);
  314. $params['page_description'] = $this->metaService->getPageDescription($params);
  315. }
  316. }