src/CmsBundle/Controller/StorageController.php line 748

Open in your IDE?
  1. <?php
  2. namespace App\CmsBundle\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  5. use Symfony\Component\Console\Input\ArrayInput;
  6. use Symfony\Component\Console\Output\BufferedOutput;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  9. use GeoIp2\Database\Reader;
  10. use App\CmsBundle\Classes\Meta;
  11. // Injection
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. use App\CmsBundle\Util\Mailer;
  15. class StorageController extends AbstractController {
  16.     protected $em;
  17.     protected $breadcrumbs         null;
  18.     protected $languages           null;
  19.     protected $languages_available = [];
  20.     protected $siteToLang          = [];
  21.     protected $Settings            null;
  22.     protected $multisite           = [];
  23.     protected $multisite_other     = [];
  24.     protected $multisite_all       = [];
  25.     protected $tags                null;
  26.     protected $gravatar            '';
  27.     protected $modRoutes           = array();
  28.     protected $installed           = array();
  29.     protected $ipblocks            = array();
  30.     protected $language            null;
  31.     protected $translator          null;
  32.     protected $containerInterface      null;
  33.     protected $mailer               null;
  34.     protected $Meta                null
  35.     
  36.     protected $version             null;
  37.     protected $git_hash            null;
  38.     protected $git_hash_long       null;
  39.     protected $date                null;
  40.     protected $prev_version        null;
  41.     protected $host                '';
  42.     protected $uri                 '';
  43.     
  44.     protected $moderation          0;
  45.     
  46.     protected $webshop_enabled     false;
  47.     protected $webshop_quote_enabled false;
  48.     protected $new_reviews     false;
  49.     protected $Webshop             null;
  50.     protected $WebshopSettings     null;
  51.     protected $WebshopCustomer     null;
  52.     
  53.     public $bundleIcons            = [];
  54.     public $Timer null;
  55.     protected $cache_page          3600;
  56.     protected $cache_widget        3600;
  57.     protected $cache_bundle        3600;
  58.     public function __construct(TranslatorInterface $translatorContainerInterface $containerInterfaceMailer $mailer){
  59.         $this->translator $translator;
  60.         $this->containerInterface $containerInterface;
  61.         $this->mailer $mailer;
  62.     }
  63.     public function trans($key,  $params = [], $group ''$locale null){
  64.         /*
  65.          * Fallback for change in attributes in this function
  66.          * 
  67.          * It turns out that the symfony/translator extractor find our trans()
  68.          * function and assumes that the domein is defined in the third parameter.
  69.          * Which wasn't the case, switch the arguments of  our trans function
  70.          * around so the extractor can do it's magic.
  71.          */
  72.         if (!is_array($params)) {
  73.             $old_group $group;
  74.             $group $params;
  75.             $params $old_group;
  76.         }
  77.         // Get locale for admin
  78.         $adminLocale $this->get('session')->get('admin_custom_locale');
  79.         if (empty($adminLocale)){
  80.             $adminLocale $this->get('session')->get('admin_locale');
  81.         }
  82.         if(empty($adminLocale)){
  83.             // Fallback to default locale
  84.             $adminLocale $this->get('session')->get('_locale');
  85.         }
  86.         // Override by function
  87.         if(!empty($locale)){
  88.             $adminLocale $locale;
  89.         }
  90.         if (!is_array($params)) {
  91.             $params = [];
  92.         }
  93.         // check if token already exists
  94.         $token $this->em->getRepository('CmsBundle:LanguageToken')->findOneByToken($key);
  95.         if (empty($token)) {
  96.             $token = new \App\CmsBundle\Entity\LanguageToken();
  97.             $token->setToken($key);
  98.             $this->em->persist($token);
  99.             $this->em->flush();
  100.         }
  101.         $target_language $this->em->getRepository('CmsBundle:Language')->findOneBy(['locale' => $adminLocale]);
  102.         $trans $this->em->getRepository("CmsBundle:LanguageTranslation")->findOneby(['languageToken' => $token->getId(), 'language' => $target_language'catalogue' => $group]);
  103.         if (empty($trans)) {
  104.             $changes false;
  105.             foreach($this->languages as $L){
  106.                 $changes true;
  107.                 $trans = new \App\CmsBundle\Entity\LanguageTranslation();
  108.                 $trans->setLanguage($L);
  109.                 $trans->setCatalogue($group);
  110.                 $trans->setTranslation($key);
  111.                 $trans->setLanguageToken($token);
  112.                 $this->em->persist($trans);
  113.             }
  114.             if($changes){
  115.                 $this->em->flush();
  116.             }
  117.             unset($trans);
  118.         }
  119.         unset($token);
  120.         return $this->translator->trans($key$params$group$adminLocale);
  121.     }
  122.     private function generateRandomString($length 10) {
  123.         $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  124.         $charactersLength strlen($characters);
  125.         $randomString '';
  126.         for ($i 0$i $length$i++) {
  127.             $randomString .= $characters[rand(0$charactersLength 1)];
  128.         }
  129.         return $randomString;
  130.     }
  131.     public function test_permissions($request$User){
  132.         $permissions $User->listPermissions();
  133.         $isWebshop false;
  134.         if(strpos($request->get('_route'), 'admin_mod_webshop') !== false){
  135.             $isWebshop true;
  136.         }
  137.         if(!$isWebshop || !$User->checkPermissions('ALLOW_WEBSHOP')){
  138.             foreach($permissions as $k => $v){
  139.                 if(substr($k06) == 'ECOMM_'){
  140.                     unset($permissions[$k]);
  141.                 }
  142.             }
  143.         }
  144.         foreach($permissions as $perm => $path){
  145.             if(!empty($path)){
  146.                 $url $this->generateUrl($path);
  147.                 header('Location: ' $url);
  148.                 exit;
  149.             }
  150.         }
  151.     }
  152.     public function init($request null$translator null$containerInterface null$mailer null){
  153.         if(!empty($translator) && !empty($containerInterface) && !empty($mailer)){
  154.             $this->translator $translator;
  155.             $this->containerInterface $containerInterface;
  156.             $this->mailer $mailer;
  157.         }
  158.         if(preg_match('/(^admin_|^admin$)/'$request->get('_route')) && !preg_match('/setup2fa/'$request->get('_route')) && $this->getUser() != null){
  159.             // Logged in, in admin
  160.             if($this->getUser()->isTotpEnabled() && empty($this->getUser()->getTotpSecret())){
  161.                 // 2FA initialized, need to be setup
  162.                 header('Location: ' $this->generateUrl('admin_setup2fa')); exit;
  163.             }
  164.         }
  165.         // $GeoIPDB = new Reader('../src/CmsBundle/GeoLite2-City.mmdb');
  166.         $this->em $this->getDoctrine()->getManager();
  167.         if(empty($this->containerInterface)){
  168.             $this->containerInterface $this->container;
  169.         }
  170.         
  171.         if ($this->containerInterface->hasParameter('cache_max_age')) {
  172.             $this->cache_page   = (int)$this->containerInterface->getParameter('cache_max_age');
  173.         } else {
  174.             $this->cache_page   3600 24 7;
  175.         }
  176.         if ($this->containerInterface->hasParameter('widget_max_age')) {
  177.             $this->cache_widget = (int)$this->containerInterface->getParameter('widget_max_age');
  178.         } else {
  179.             $this->cache_widget 3600 24 7;
  180.         }
  181.         if ($this->containerInterface->hasParameter('bundle_max_age')) {
  182.             $this->cache_bundle = (int)$this->containerInterface->getParameter('bundle_max_age');
  183.         } else {
  184.             $this->cache_bundle 3600 24 7;
  185.         }
  186.         $this->Timer = new \App\CmsBundle\Classes\Timer($this->containerInterface->getParameter('kernel.environment') == 'dev');
  187.         $is_alias null;
  188.         $lookupHost preg_replace('/:\d+/'''$request->getHttpHost());
  189.         if(file_exists('../alias.json')){
  190.             $alias json_decode(file_get_contents('../alias.json'), true);
  191.             foreach($alias as $alias_parent => $aliasses){
  192.                 if(array_key_exists($lookupHost$aliasses) || in_array($lookupHost$aliasses)){ 
  193.                     $is_alias $lookupHost;
  194.                     $lookupHost $alias_parent;
  195.                 }
  196.             }
  197.         }
  198.         if(count($this->em->getRepository('CmsBundle:Settings')->findBy(['host' => str_replace('www.'''$lookupHost)])) == 0){
  199.             $ExistingSettings $this->em->getRepository('CmsBundle:Settings')->findOneBy([]);
  200.             $host str_replace('www.'''$lookupHost);
  201.             /* if(isset($_GET['link']) && $_GET['link'] == 'host'){
  202.                 // Assign host to settings directly
  203.                 $ExistingSettings->setHost($host);
  204.                 $this->em->persist($ExistingSettings);
  205.                 $this->em->flush();
  206.                 header('Location: /'); exit;
  207.             } */
  208.             $cleared $this->render('@Cms/no-host.html.twig', ['host' => $host'ExistingSettings' => $ExistingSettings])->getContent();
  209.             die($cleared);
  210.         }
  211.         /* *********************************
  212.             AUTOLOGIN BASED ON IP
  213.             CREATE FILE .ip WITH SYNTAX:
  214.             127.0.0.1:admin
  215.             217.158.75.1:username
  216.         ********************************* */
  217.         $isAdmin preg_match('/(^admin_|^admin$)/'$request->get('_route'));
  218.         if($this->getUser() == null){
  219.             if(!$isAdmin || $this->containerInterface->getParameter('kernel.environment') == 'dev'){
  220.                 $ip_whitelist_file '../.ip';
  221.                 if(file_exists($ip_whitelist_file) && !empty($_SERVER['REMOTE_ADDR'])){
  222.                     $ipdata file($ip_whitelist_file);
  223.                     foreach($ipdata as $ip_row){
  224.                         if(!preg_match('/\#/'$ip_row)){
  225.                             $ip_row explode(':'trim($ip_row));
  226.                             if($ip_row[0] == $_SERVER['REMOTE_ADDR']){
  227.                                 $AutoUser $this->getDoctrine()->getRepository('CmsBundle:User')->findOneByUsername($ip_row[1]);
  228.                                 if(!empty($AutoUser)){
  229.                                     $token = new UsernamePasswordToken($AutoUsernull'main'$AutoUser->getRoles());
  230.                                     $this->get('security.token_storage')->setToken($token);
  231.                                     $this->get('session')->set('_security_main'serialize($token));
  232.                                 }
  233.                             }
  234.                         }
  235.                     }
  236.                 }
  237.             }
  238.         }
  239.         $localeInRequest $request->getLocale();
  240.         $versionFile $this->containerInterface->get('kernel')->getProjectDir() . '/src/CmsBundle/VERSION';
  241.         if (file_exists($versionFile)) {
  242.             $versionEntries file($versionFile);
  243.             $this->version        trim($versionEntries[0]);
  244.             $this->git_hash       trim($versionEntries[1]);
  245.             $this->git_hash_long  trim($versionEntries[2]);
  246.             $this->date           trim($versionEntries[3]);
  247.             $this->prev_version   trim($versionEntries[4]);
  248.             /*foreach(file($versionFile) as $ln){
  249.                 $ln = trim($ln);
  250.                 dump($ln);
  251.             }*/
  252.         }
  253.         $isAdmin preg_match('/(^admin_|^adminjson|^_adminjson|^admin$)/'$request->get('_route'));
  254.         if($isAdmin){
  255.             // Only for admin panel
  256.             $this->ipblocks $this->em->getRepository('CmsBundle:Ipcheck')->findAll();
  257.             foreach($this->ipblocks as $index => $Ipcheck){
  258.                 if($Ipcheck->getLoginAttempts() < || $Ipcheck->getBlocked()){
  259.                     unset($this->ipblocks[$index]);
  260.                 }
  261.                 // Adding country code to existing
  262.                 /* if(empty($Ipcheck->getCountry())){
  263.                     if($Ipcheck->getIp() != '127.0.0.1'){
  264.                         try{
  265.                             $client_ip = $GeoIPDB->city($Ipcheck->getIp());
  266.                             $client_country = $client_ip->country->isoCode;
  267.                             $Ipcheck->setCountry($client_country);
  268.                             $this->em->persist($Ipcheck);
  269.                             $this->em->flush();
  270.                         }catch(\GeoIp2\Exception\AddressNotFoundException $e){}
  271.                     }
  272.                 } */
  273.             }
  274.             if($this->getUser() && !empty($this->getUser()->getLockinUri())){
  275.                 if(!preg_match('/^' str_replace('/''\\/'$this->getUser()->getLockinUri()) . '/'$request->getPathInfo())){
  276.                     header('Location:' preg_replace('/\/$/'''$this->generateUrl('homepage')) . $this->getUser()->getLockinUri());
  277.                     exit;
  278.                 }
  279.             }
  280.             // Check existing settings if site_key is filled
  281.             if($this->em->getRepository('CmsBundle:Settings')->countWithoutSiteKey()){
  282.                 $settings_sitekey $this->em->getRepository('CmsBundle:Settings')->findWithoutSiteKey();
  283.                 $languages_sitekey $this->em->getRepository('CmsBundle:Language')->findAll();
  284.                 $hasMoreForOneLanguage false;
  285.                 foreach($languages_sitekey as $k => $L){
  286.                     if($L->getSettings()->count() > 1){
  287.                         $hasMoreForOneLanguage true;
  288.                     }
  289.                 }
  290.                 if(!$hasMoreForOneLanguage){
  291.                     foreach($settings_sitekey as $k => $S){
  292.                         if(empty($S->getSiteKey())){
  293.                             $S->setSiteKey('default');
  294.                             $em $this->getDoctrine()->getManager();
  295.                             $em->persist($S);
  296.                             $em->flush();
  297.                             unset($settings_sitekey[$k]);
  298.                         }
  299.                     }
  300.                 }else{
  301.                     $host_done = [];
  302.                     $host_done_alt = [];
  303.                     // Remaining sites
  304.                     foreach($settings_sitekey as $k => $S){
  305.                         if(!empty($host_done_alt[$S->getLabel()])){
  306.                             $S->setSiteKey($host_done_alt[$S->getLabel()]);
  307.                             $em $this->getDoctrine()->getManager();
  308.                             $em->persist($S);
  309.                             $em->flush();
  310.                             unset($settings_sitekey[$k]);
  311.                         }elseif(!empty($host_done[$S->getHost()])){
  312.                             $S->setSiteKey($host_done[$S->getHost()]);
  313.                             $em $this->getDoctrine()->getManager();
  314.                             $em->persist($S);
  315.                             $em->flush();
  316.                             unset($settings_sitekey[$k]);
  317.                         }else{
  318.                             $newSitekey $this->generateRandomString();
  319.                             $S->setSiteKey($newSitekey);
  320.                             $em $this->getDoctrine()->getManager();
  321.                             $em->persist($S);
  322.                             $em->flush();
  323.                             unset($settings_sitekey[$k]);
  324.                             $host_done[$S->getHost()] = $newSitekey;
  325.                             $host_done_alt[$S->getLabel()] = $newSitekey;
  326.                         }
  327.                     }
  328.                 }
  329.             }
  330.         }
  331.         // Get locale for admin
  332.         $adminLocale $this->containerInterface->get('session')->get('admin_locale');
  333.         if(empty($adminLocale)){
  334.             // Fallback to default locale
  335.             $adminLocale $this->containerInterface->get('session')->get('_locale');
  336.         }
  337.         $this->languages       $this->em->getRepository('CmsBundle:Language')->findAll();
  338.         $this->multisite       $this->em->getRepository('CmsBundle:Settings')->findAll();
  339.         $this->multisite_other $this->em->getRepository('CmsBundle:Settings')->findAll();
  340.         $this->multisite_all   $this->em->getRepository('CmsBundle:Settings')->findAll();
  341.         /*foreach($this->multisite as $index => $Settings){
  342.             if($Settings->getLanguage() != $this->Language){
  343.                 unset($this->multisite[$index]);
  344.             }
  345.         }*/
  346.         $this->moderation $this->em->getRepository('CmsBundle:User')->countModeration();
  347.         // Multi-site switcher
  348.         $msite null;
  349.         if($isAdmin){
  350.             $msite $request->getSession()->get('admin_msite');
  351.             if(!empty($_GET['msite'])){ $msite = (int)$_GET['msite']; }
  352.             if($msite){
  353.                 $request->getSession()->set('admin_msite'$msite);
  354.             }else{
  355.                 // No 'msite', use first site based on locale
  356.                 $Language $this->em->getRepository('CmsBundle:Language')->findOneByLocale($adminLocale);
  357.                 // Find first by host as priority
  358.                 $msite_priority_Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'language' => $Language]);
  359.                 if(empty($msite_priority_Settings)){
  360.                     $msite_first_Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $Language], ['id' => 'asc']);
  361.                     if(!empty($msite_first_Settings)){
  362.                         $msite $msite_first_Settings->getId();
  363.                         $request->getSession()->set('admin_msite'$msite);
  364.                     }
  365.                 }else{
  366.                     $msite $msite_priority_Settings->getId();
  367.                     $request->getSession()->set('admin_msite'$msite);
  368.                 }
  369.             }
  370.         }
  371.         if (!empty($_GET['mlang']) && !empty($_GET['msite'])) {
  372.             $Settings $this->em->getRepository('CmsBundle:Settings')->find($_GET['msite']);
  373.             $this->Settings $Settings;
  374.             $Language $this->em->getRepository('CmsBundle:Language')->find($_GET['mlang']);
  375.             $this->language $Language;
  376.             $request->getSession()->set('admin_msite'$msite);
  377.             $request->getSession()->set('admin_locale'$Language->getLocale());
  378.         }
  379.         $Settings null;
  380.         $byBaseUri false;
  381.         if($msite){
  382.             $tmp_Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['id' => $msite], [], ['host' => 'null']);
  383.             if(empty($tmp_Settings) || $tmp_Settings->getLanguage() != $this->language){
  384.                 if(preg_match('/(\/[a-z]{2})(\/.*?)?$/'$request->getPathInfo(), $m)){
  385.                     $byBaseUri true;
  386.                     $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => $m[1]]);
  387.                     // dump($Settings);die();
  388.                 }else{
  389.                     $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => '']);
  390.                     if (empty($Settings)) {
  391.                         $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost)]);
  392.                     }
  393.                 }
  394.             }else{
  395.                 $Settings $tmp_Settings;
  396.             }
  397.         }else{
  398.             if(preg_match('/(\/[a-z]{2})(\/.*?)?$/'$request->getPathInfo(), $m)){
  399.                 $byBaseUri true;
  400.                 $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => $m[1]]);
  401.             }else{
  402.                 $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => '']);
  403.                 if (empty($Settings)) {
  404.                     $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost)]);
  405.                 }
  406.             }
  407.         }
  408.         $session_locale null;
  409.         if($isAdmin){
  410.             $session_locale $this->containerInterface->get('session')->get('admin_locale');
  411.         }else{
  412.             if(!$byBaseUri){
  413.                 $session_locale $this->containerInterface->get('session')->get('_locale');
  414.             }
  415.         }
  416.         // Check if settings is present, and if it matches the locale from session (if in session)
  417.         if(!empty($Settings) && ($session_locale == null || $Settings->getLanguage()->getLocale() == $session_locale)){
  418.             $this->Settings $Settings;
  419.             $this->language $Settings->getLanguage();
  420.             // dump('..');die();
  421.             // dump('..');die();
  422.         }else{
  423.             // Settings are not present or not valid for current locale
  424.             if($isAdmin){
  425.                 $locale $this->containerInterface->get('session')->get('admin_locale');
  426.             }else{
  427.                 $locale $this->containerInterface->get('session')->get('_locale');
  428.             }
  429.             if($locale){
  430.                 $this->language $this->em->getRepository('CmsBundle:Language')->findOneByLocale($locale);
  431.             }else{
  432.                 $this->language $this->languages[0];
  433.             }
  434.         }
  435.         // Set breadcrumbs
  436.         $this->Settings null;
  437.         if($msite){
  438.             $TempSettings $this->em->getRepository('CmsBundle:Settings')->find($msite);
  439.             if(!empty($TempSettings) && $TempSettings->getHost() != 'null' && $TempSettings->getLanguage() == $this->language){
  440.                 $this->Settings $TempSettings;
  441.             }else{
  442.                 if(preg_match('/(\/[a-z]{2})(\/.*?)?$/'$request->getPathInfo(), $m)){
  443.                     $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => $m[1]]);
  444.                 }else{
  445.                     $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => '']);
  446.                     if (empty($this->Settings)) {
  447.                         $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost)], ['id' => 'asc']);
  448.                     }
  449.                 }
  450.             }
  451.             /*if($this->Settings->getLanguage() != $this->language){
  452.                 $this->Settings = $this->em->getRepository('CmsBundle:Settings')->find($msite);
  453.             }*/
  454.             // dump($this->Settings->getLabel());die();
  455.         }else{
  456.             if(preg_match('/(\/[a-z]{2})(\/.*?)?$/'$request->getPathInfo(), $m)){
  457.                 $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => $m[1]]);
  458.             }else{
  459.                 $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost), 'base_uri' => '']);
  460.                 if (empty($this->Settings)) {
  461.                     $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['host' => str_replace('www.'''$lookupHost)], ['id' => 'asc']);
  462.                 }
  463.             }
  464.         }
  465.         if(empty($this->Settings) || preg_match('/(^admin_|^admin$)/'$request->get('_route'))){
  466.             if($msite){
  467.                 if(empty($Settings) || $Settings->getLanguage() != $this->language){
  468.                     $tmp_settings $this->em->getRepository('CmsBundle:Settings')->find($msite);
  469.                     if($tmp_settings->getLanguage() != $this->language){
  470.                         $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $this->language'host' => str_replace('www.'''$lookupHost)], ['id' => 'desc'], ['host' => 'null']);
  471.                         if(empty($this->Settings)){
  472.                             $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $this->language], ['id' => 'desc'], ['host' => 'null']);
  473.                         }
  474.                         if(empty($this->Settings)){
  475.                             $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy([], ['id' => 'asc']);
  476.                         }
  477.                     }else{
  478.                         $this->Settings $tmp_settings;
  479.                     }
  480.                 }else{
  481.                     $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $this->language'host' => str_replace('www.'''$lookupHost)], ['id' => 'desc'], ['host' => 'null']);
  482.                     if(empty($this->Settings)){
  483.                         $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $this->language], ['id' => 'desc'], ['host' => 'null']);
  484.                     }
  485.                     if(empty($this->Settings)){
  486.                         $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy([], ['id' => 'asc']);
  487.                     }
  488.                 }
  489.                 // Recheck
  490.                 if($this->Settings->getId() != $msite){
  491.                     $tmp_settings $this->em->getRepository('CmsBundle:Settings')->find($msite);
  492.                     $this->Settings $tmp_settings;
  493.                 }
  494.             }else{
  495.                 $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $this->language'host' => str_replace('www.'''$lookupHost)], ['id' => 'desc']);
  496.                 if(empty($this->Settings)){
  497.                     $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $this->language], ['id' => 'desc']);
  498.                 }
  499.                 if(empty($this->Settings)){
  500.                     $this->Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy([], ['id' => 'asc']);
  501.                 }
  502.             }
  503.         }
  504.         if($this->Settings->getLanguage() != $this->language && !$isAdmin){
  505.             $this->language $this->Settings->getLanguage();
  506.         }
  507.         // Find settings by language when settings language and backend language don't match
  508.         if($this->Settings->getLanguage() != $this->language){
  509.             // if($this->Settings->getLanguage()->getLocale() == 'nl'){
  510.                 // $searchSettings = $this->em->getRepository('CmsBundle:Settings')->findOneBy(['parent' => $this->Settings, 'language' => $this->language], ['id' => 'desc'], ['host' => 'null']);
  511.             // }else{
  512.                 $searchSettings $this->em->getRepository('CmsBundle:Settings')->findOneBy(['language' => $this->language], ['id' => 'desc']);
  513.             // }
  514.             if(empty($searchSettings)){
  515.                 // No settings found based on current language
  516.                 dump($this->language);
  517.                 dump($this->Settings);
  518.                 dump('....!!');die();
  519.                 $NewSettings = clone $this->Settings;
  520.                 $NewSettings->setLanguage($this->language);
  521.                 if($this->Settings->getLanguage()->getLocale() == 'nl'){
  522.                     $NewSettings->setParent($this->Settings);
  523.                 }else{
  524.                     $NewSettings->setParent($this->Settings->getParent());
  525.                 }
  526.                 $this->em->persist($NewSettings);
  527.                 $this->em->flush();
  528.                 $this->Settings $NewSettings;
  529.             }else{
  530.                 $this->Settings $searchSettings;
  531.             }
  532.         }
  533.         // Prefill required host
  534.         if(empty($this->Settings->getHost())){
  535.             $this->Settings->setHost($_SERVER['SERVER_NAME']);
  536.             $this->em->persist($this->Settings);
  537.             $this->em->flush();
  538.         }
  539.         $hasCustomAdminLocaleOverride false;
  540.         if ($this->getUser() && $isAdmin && !empty($this->getUser()->getAdminLocale())) {
  541.             $request->getSession()->set('admin_custom_locale'$this->getUser()->getAdminLocale());
  542.             // $request->getSession()->remove('admin_locale');
  543.             $request->setLocale($this->getUser()->getAdminLocale());
  544.             $hasCustomAdminLocaleOverride true;
  545.         }else{
  546.             if($this->language == null){
  547.                 // Might happen after changing locale for a language
  548.                 $this->language $this->languages[0];
  549.             }
  550.             if($isAdmin){
  551.                 $request->getSession()->set('admin_locale'$this->language->getLocale());
  552.             }else{
  553.                 $request->getSession()->set('_locale'$this->language->getLocale());
  554.             }
  555.             $request->setLocale($this->language->getLocale());
  556.             $request->getSession()->remove('admin_custom_locale');
  557.         }
  558.         $localeInRequest $request->getLocale();
  559.         if ($localeInRequest == 'en') {
  560.             $localeInRequest 'gb';
  561.         }
  562.         if($request->headers->get('Content-Type') == 'application/json'){
  563.             // JSON request
  564.         }else{
  565.             if ($this->containerInterface->hasParameter('trinity_disable_antibot') && ($this->containerInterface->getParameter('trinity_disable_antibot') || $this->containerInterface->getParameter('trinity_disable_antibot') == 'true')) {
  566.                 // Don't try to block bots
  567.             } else {
  568.                 $crawlerDetect = new \Jaybizzle\CrawlerDetect\CrawlerDetect;
  569.                 $isBot false;
  570.                 $botRedirect false;
  571.                 if ($crawlerDetect->isCrawler($request->headers->get('User-Agent')))
  572.                 {
  573.                     $isBot true;
  574.                     // List of allowed scraper useragent
  575.                     if(!preg_match('/beyonit-cricitalgen|pingdom|uptime-kuma|google|postmanruntime|chrome-lighthouse|adsbot|bingbot|slurp|linkedin|duckduckbot|baiduspider|yandexbot|spider|exabot|facebot|toolbot|facebook|ia_archiver|doorlinken|uptimerobot/'strtolower($request->headers->get('User-Agent')))){
  576.                         if (empty($_FILES) && empty($_POST)) {
  577.                             $botRedirect true;
  578.                         }
  579.                     }
  580.                 }
  581.                 $user_agent_log $this->containerInterface->hasParameter('trinity_useragent_log') && ($this->containerInterface->getParameter('trinity_useragent_log') || $this->containerInterface->getParameter('trinity_useragent_log') == 'true');
  582.                 if ($user_agent_log) {
  583.                     $logDate = new \DateTime();
  584.                     $logFile $this->containerInterface->get('kernel')->getProjectDir() . '/var/log/user-agents-' .$logDate->format('Y-m-d') . '.log';
  585.                     if ($isBot) {
  586.                         $logPrefix 'Bot ';
  587.                     } else {
  588.                         $logPrefix 'User';
  589.                     }
  590.                     if ($botRedirect) {
  591.                         $logPrefix .= ' (redirect):     ';
  592.                     } else {
  593.                         $logPrefix .= ' (no redirect):  ';
  594.                     }
  595.                     file_put_contents($logFile$logPrefix $request->headers->get('User-Agent') . PHP_EOLFILE_APPEND);
  596.                 }
  597.                 if ($botRedirect) {
  598.                     header('Location:' $request->getUri());exit;
  599.                 }
  600.             }
  601.         }
  602.         // Validate if current settings are linked to logged in user
  603.         if($isAdmin && $this->getUser()){
  604.             if($this->getUser()->getSites()->count() > 0){
  605.                 if(!$this->getUser()->getSites()->contains($this->Settings)){
  606.                     header('Location:' $this->generateUrl('admin_switch_language', ['locale' => $this->getUser()->getSites()->first()->getLanguage()->getLocale(), 'url' => urlencode($this->generateUrl($request->attributes->get('_route'), $request->attributes->get('_route_params')))]));
  607.                     exit;
  608.                 }
  609.             }
  610.         }
  611.         $thisIsAdmin false;
  612.         if(substr($request->get('_route'), 06) == 'admin_'){
  613.             $thisIsAdmin true;
  614.         }
  615.         $blocked false;
  616.         if($this->Settings && !empty($this->Settings->getRestrictAccessList())){
  617.             $accessList $this->Settings->getRestrictAccessList();
  618.             $denyList explode("\n"$this->Settings->getRestrictAccessDeny());
  619.             $type $this->Settings->getRestrictAccessType();
  620.             $ip $_SERVER['REMOTE_ADDR'];
  621.             if($type == 'admin_website' || ($type == 'admin' && $thisIsAdmin)){
  622.                 // Block admin and website
  623.                 $blocked true;
  624.                 if(in_array($ip$accessList)){
  625.                     $blocked false;
  626.                 }
  627.                 if(in_array($ip$denyList)){
  628.                     $blocked true;
  629.                 }
  630.             }
  631.         }
  632.         if($blocked){
  633.             die('Geen toegang.');
  634.         }
  635.         // Force HTTPS
  636.         if(substr($request->getHost(), -6) != '.local' && substr($request->getHost(), -4) != '.dev' && $this->Settings->getForceHttps() && !$request->isSecure()){
  637.             $this->Timer->mark('Force HTTPS');
  638.             $url $this->generateUrl($request->get('_route'), [], UrlGeneratorInterface::ABSOLUTE_URL);
  639.             $params $request->attributes->get('_route_params');
  640.             $urlParams = [];
  641.             foreach($params as $key => $param){
  642.                 if (substr($key05) == 'param' && !empty($param)) {
  643.                     $urlParams[] = $param;
  644.                 }
  645.             }
  646.             if(!empty($urlParams)){
  647.                 $url .= (preg_match('/.*?\/$/'$url) ? '' '/') . implode('/'$urlParams);
  648.             }
  649.             $q '';
  650.             if(!empty($_GET)){
  651.                 $q = [];
  652.                 foreach($_GET as $k => $v){
  653.                     if(is_array($v)){
  654.                         foreach($v as $k2 => $v2){
  655.                             $q[] = $k '[' $k2 ']=' $v2;
  656.                         }
  657.                     }else{
  658.                         $q[] = urlencode($k) . '=' urlencode($v);
  659.                     }
  660.                 }
  661.                 $q '?' implode('&'$q);
  662.             }
  663.             $url str_replace('http:''https:'$url $q);
  664.             header("Location: " $url);
  665.             exit;
  666.         }
  667.         if(is_null($this->Settings)) $this->Settings = new \App\CmsBundle\Entity\Settings();
  668.         // Validate access by IP-address, only allow override if 'development' mode is enabled
  669.         if(!is_null($request) && $this->containerInterface->getParameter('kernel.environment') != 'dev'){
  670.             $ra_type $this->Settings->getRestrictAccessType();
  671.             if(empty($ra_type)) $ra_type 'admin';
  672.             if(($ra_type == 'admin' && substr($request->get('_route'), 05) == 'admin') || ($ra_type == 'admin_website')){
  673.                 $access $this->Settings->hasAccess();
  674.                 if(!$access){
  675.                     throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException('No access.');
  676.                 }
  677.             }
  678.         }
  679.         $this->breadcrumbs $this->containerInterface->get("white_october_breadcrumbs");
  680.         $this->host '';
  681.         if($this->Settings->getHost()){
  682.             $www '';
  683.             if(preg_match('/www/'$lookupHost)){
  684.                 // Contains www
  685.                 $www 'www.';
  686.             }
  687.             if(!empty($is_alias)){
  688.                 $this->host 'http://' $www $is_alias;
  689.             }else{
  690.                 if($request->isSecure()){
  691.                     $this->host 'https://' $www $this->Settings->getHost();
  692.                 }else{
  693.                     $this->host 'http://' $www $this->Settings->getHost();
  694.                 }
  695.             }
  696.         }
  697.     if($this->breadcrumbs->count() == 0){
  698.             $this->breadcrumbs->addItem($this->Settings->getLabel(), $this->host $this->generateUrl('homepage') . substr($this->Settings->getBaseUri(),1));
  699.             if(!is_null($request)){
  700.                 $route $request->get('_route');
  701.                 if(preg_match('/admin/'$route)){
  702.                     $this->breadcrumbs->addRouteItem($this->trans('Admin', [], 'cms'), 'admin');
  703.                 }
  704.             }
  705.         }
  706.         if($this->language != $this->Settings->getLanguage()){
  707.             // Override language based on settings
  708.             $this->language $this->Settings->getLanguage();
  709.         }
  710.         $this->tags $this->getDoctrine()->getRepository('CmsBundle:Tag')->findAllNotEmpty();
  711.         foreach($this->tags as $i => $tag){
  712.             if($i 3) unset($this->tags[$i]);
  713.         }
  714.         /* *********************************
  715.             Fix default host folder for
  716.             media with locale attached.
  717.         ********************************* */
  718.         $this->Timer->mark('Prepare mediadir for current settings');
  719.         $Mediadir $this->getDoctrine()->getRepository('CmsBundle:Mediadir')->findOneBy(['label' => $this->Settings->getHost(), 'parent' => null]);
  720.         if ($Mediadir) {
  721.             // Found mediadir based on hostname without locale addition
  722.             if(!empty($this->languages) && count($this->languages) > 1){
  723.                 // Found multiple languages, now this folder need a locale suffix
  724.                 
  725.                 // Search for first language (probably NL)
  726.                 $Language $this->getDoctrine()->getRepository('CmsBundle:Language')->findOneBy([], ['id' => 'asc']);
  727.                 
  728.                 // Generate new label
  729.                 $newLabel $this->Settings->getHost() . ' (' strtoupper($Language->getLocale()) . ')';
  730.                 $Mediadir->setLabel($newLabel);
  731.                 // Save
  732.                 $this->em->persist($Mediadir);
  733.                 $this->em->flush();
  734.             }
  735.         }
  736.         $settingsWithSameSiteKey $this->getDoctrine()->getRepository('CmsBundle:Settings')->findBy(['site_key' => $this->Settings->getSiteKey()]);
  737.         foreach($settingsWithSameSiteKey as $S){
  738.             if(!empty($S->getLanguage()) && !in_array($S->getLanguage(), $this->languages_available)){
  739.                 $this->languages_available[] = $S->getLanguage();
  740.             }
  741.             $this->siteToLang[$S->getLanguage()->getId()] = $S->getId();
  742.         }
  743.         $parsedKeys = [];
  744.         foreach($this->multisite as $index => $S){
  745.             if($S->getLanguage() == $this->Settings->getLanguage()){
  746.                 $parsedKeys[] = $S->getSiteKey();
  747.             }
  748.         }
  749.         $multisite_filter = [];
  750.         foreach($this->multisite_other as $S){
  751.             if(!in_array($S->getSiteKey(), $parsedKeys)){
  752.                 if(!array_key_exists($S->getSiteKey(), $multisite_filter)){
  753.                     $multisite_filter[$S->getSiteKey()] = $S;
  754.                 }
  755.             }
  756.         }
  757.         $this->multisite_other $multisite_filter;
  758.         // Get routes by modules
  759.         $this->Timer->mark('Parse bundle info');
  760.         $this->parseBundleInfo();
  761.         $fb1 $this->parseCmsUrls($this->Settings->getFooterBlock1());
  762.         $this->Settings->setFooterBlock1($fb1);
  763.         $fb2 $this->parseCmsUrls($this->Settings->getFooterBlock2());
  764.         $this->Settings->setFooterBlock2($fb2);
  765.         $fb3 $this->parseCmsUrls($this->Settings->getFooterBlock3());
  766.         $this->Settings->setFooterBlock3($fb3);
  767.         $fb4 $this->parseCmsUrls($this->Settings->getFooterBlock4());
  768.         $this->Settings->setFooterBlock4($fb4);
  769.         $fb5 $this->parseCmsUrls($this->Settings->getFooterBlock5());
  770.         $this->Settings->setFooterBlock5($fb5);
  771.         $hbl $this->parseCmsUrls($this->Settings->getHeaderBarLeft());
  772.         $this->Settings->setHeaderBarLeft($hbl);
  773.         $hbr $this->parseCmsUrls($this->Settings->getHeaderBarRight());
  774.         $this->Settings->setHeaderBarRight($hbr);
  775.         $this->uri $request->getRequestUri();
  776.         // Get Gravatar
  777.         if($this->containerInterface->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
  778.             $this->gravatar '//www.gravatar.com/avatar/' md5(strtolower(trim($this->containerInterface->get('security.token_storage')->getToken()->getUser()->getEmail())));
  779.         }
  780.         $this->Timer->mark('Set webshop + settings defaults');
  781.         if(in_array('WebshopBundle'$this->installed)){
  782.             $this->webshop_enabled true;
  783.             $this->Webshop $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  784.             if($this->getUser()){
  785.                 $this->WebshopCustomer $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneBy(['user' => $this->getUser()]);
  786.             }
  787.             $this->WebshopSettings $this->Webshop->getSettings();
  788.             if ($this->WebshopSettings && method_exists($this->WebshopSettings'getQuoteEnabled')) {
  789.                 $this->webshop_quote_enabled $this->WebshopSettings->getQuoteEnabled();
  790.             }
  791.             $this->new_reviews $this->getDoctrine()->getRepository('TrinityWebshopBundle:Review')->countReviews(''false);
  792.         }
  793.         if(in_array('PelikanproductsBundle'$this->installed)){
  794.             $this->Webshop $this->getDoctrine()->getRepository('TrinityPelikanproductsBundle:Webshop')->getByLanguageAndSettings($this->language$this->Settings);
  795.             $this->WebshopSettings $this->Webshop->getSettings();
  796.         }
  797.         //Init Meta conversion API class
  798.         if(!empty($this->Settings->getMetaApiToken()) && !empty($this->Settings->getMetaPixelId())){
  799.             $this->Meta = new Meta($this->Settings);
  800.         }
  801.         $this->Timer->mark('Done loading storage init');
  802.         if(isset($_GET['timer']) && $_GET['timer'] === 1){
  803.             $this->Timer->show(true);
  804.         }
  805.     }
  806.     public function hasParameter(string $key): bool
  807.     {
  808.         try{
  809.             $param $this->getParameter($key);
  810.             if(!empty($param)){
  811.                 return true;
  812.             }
  813.         }catch(\Exception $e){
  814.             // Error
  815.         }
  816.         return false;
  817.     }
  818.     /**
  819.      * Parse text content and translate page:x notations to page url's.
  820.      *
  821.      * @param string $content Texts to replace
  822.      * @return string Update text
  823.      */
  824.     public function parseCmsUrls(?string $content) : ?string
  825.     {
  826.         if (preg_match_all('/\[page:([a-zA-Z0-9\-\_]+)(\#[a-zA-Z0-9\-].*?)?\]/'$content$matches))
  827.         {
  828.             $idToSlug = [];
  829.             $cacheFile preg_replace('/\/src.*/''/var/cache/prod/'__DIR__) . 'page_id_slug';
  830.             if (file_exists($cacheFile)) {
  831.                 $idToSlug json_decode(file_get_contents($cacheFile), true);
  832.             }
  833.             foreach ($matches[0] as $index => $tag) {
  834.                 $key $matches[1][$index];
  835.                 if (is_numeric($key)){
  836.                     if (array_key_exists($key$idToSlug)) {
  837.                         $key $idToSlug[$key];
  838.                     } else {
  839.                         $key 'homepage';
  840.                     }
  841.                         
  842.                 }
  843.                 $key str_replace('-''_'$key);
  844.                 $content str_replace('http://' $tag$this->generateUrl($key), $content);
  845.                 $content str_replace('https://' $tag$this->generateUrl($key), $content);
  846.                 $content str_replace($tag$this->generateUrl($key), $content);
  847.             }
  848.         }
  849.         return $content;
  850.     }
  851.     public function attributes($attributes = array()){
  852.         // $Version = new \App\CmsBundle\Model\Version();
  853.         $attr = array(
  854.             'new_reviews'         => $this->new_reviews,
  855.             'webshop_enabled'     => $this->webshop_enabled,
  856.             'webshop_quote_enabled' => $this->webshop_quote_enabled,
  857.             'Webshop'             => $this->Webshop,
  858.             'WebshopSettings'     => $this->WebshopSettings,
  859.             'WebshopCustomer'     => $this->WebshopCustomer,
  860.             'languages'           => $this->languages,
  861.             'languages_available' => $this->languages_available,
  862.             'siteToLang'          => $this->siteToLang,
  863.             'Settings'            => $this->Settings,
  864.             'multisite'           => $this->multisite,
  865.             'multisite_other'     => $this->multisite_other,
  866.             'multisite_all'       => $this->multisite_all,
  867.             'tags'                => $this->tags,
  868.             // 'version'          => $Version,
  869.             'modroutes'           => $this->modRoutes,
  870.             'installed'           => $this->installed,
  871.             'gravatar'            => $this->gravatar,
  872.             'language'            => $this->language,
  873.             'moderation'          => $this->moderation,
  874.             'version'             => $this->version,
  875.             'git_hash'            => $this->git_hash,
  876.             'git_hash_long'       => $this->git_hash_long,
  877.             'date'                => $this->date,
  878.             'host'                => $this->host,
  879.             'uri'                 => $this->uri,
  880.             'prev_version'        => $this->prev_version,
  881.             'bundleIcons'         => $this->bundleIcons,
  882.             'ipblocks'            => $this->ipblocks,
  883.             'translator'            => $this->translator,
  884.             // 'Timer'               => $this->Timer,
  885.             'cache_page'          => $this->cache_page,
  886.             'cache_page_min'      => ($this->cache_page 60),
  887.             'cache_widget'        => $this->cache_widget,
  888.             'cache_widget_min'    => ($this->cache_widget 60),
  889.             'cache_bundle'        => $this->cache_bundle,
  890.             'cache_bundle_min'    => ($this->cache_bundle 60),
  891.         );
  892.         foreach($attributes as $k => $v){
  893.             $attr[$k] = $v;
  894.         }
  895.         return $attr;
  896.     }
  897.     private function parseBundleInfo(){
  898.         $sort = [];
  899.         $srcdir '../src/';
  900.         foreach(scandir('../src/Trinity') as $bundleDir){
  901.             if(substr($bundleDir01) != '.'){
  902.                 $bundlePath '../src/Trinity/' $bundleDir '/';
  903.                 if(file_exists($bundlePath 'MODULE')){
  904.                     $bundleKey str_replace('bundle'''strtolower($bundleDir));
  905.                     $route 'admin_mod_' $bundleKey;
  906.                     $modcfg file($bundlePath 'MODULE');
  907.                     $conf = array('bundleName' => '''route' => $route'path' => $bundlePath);
  908.                     $bundleName str_replace(array($srcdir'/'), ''$conf['path']);
  909.                     $conf['bundleName'] = $bundleName;
  910.                     if(!in_array($bundleName$this->installed)){
  911.                         $this->installed[] = str_replace('Trinity'''$bundleName);
  912.                     }
  913.                     foreach($modcfg as $i => $cfg){
  914.                         if(preg_match('/^(.*?):\s+(.*?)$/'$cfg$m)){
  915.                             // Nav stuff
  916.                             if($m[1] == 'nav'){
  917.                                 $m[2] = json_decode($m[2], true);
  918.                                 foreach($m[2] as $route => $label){
  919.                                     $m[2][$route] = array('route' => trim($route), 'label' => trim($label));
  920.                                 }
  921.                             }
  922.                             if($m[1] == 'quickmenu'){
  923.                                 $m[2] = json_decode($m[2], true);
  924.                                 $c = array();
  925.                                 foreach($m[2]['add'] as $option){
  926.                                     // foreach($options as $option){
  927.                                         $c['add'][] = $option;
  928.                                     // }
  929.                                 }
  930.                                 $m[2] = $c;
  931.                             }
  932.                             if($m[1] == 'nav_icon'){
  933.                                 $m[2] = json_decode($m[2], true);
  934.                             }
  935.                             $conf[$m[1]] = $m[2];
  936.                         }
  937.                     }
  938.                     $this->bundleIcons[$conf['bundleName']] = $conf['icon'];
  939.                     $conf['name'] = str_replace("\r"''$conf['name']);
  940.                     $this->modRoutes[] = $conf;
  941.                 }
  942.             }
  943.         }
  944.         // SORT
  945.         $sort = [];
  946.         foreach($this->modRoutes as $r){
  947.             $sort[$r['name']] = $r;
  948.         }
  949.         ksort($sort);
  950.         $this->modRoutes $sort;
  951.     }
  952.     protected function bundleInstalled($bundleName){
  953.         $dir str_replace('CmsBundle/Controller''Trinity/'__DIR__);
  954.         foreach(scandir($dir) as $d){
  955.             if(strpos(strtolower($d), strtolower($bundleName)) !== false){
  956.                 return true;
  957.             }
  958.         }
  959.         return false;
  960.     }
  961.     /**
  962.      * Clear Symfony router cache
  963.      *
  964.      * @return Response
  965.      */
  966.     protected function clearRouterCache(){
  967.         $router $this->containerInterface->get('router');
  968.         $filesystem $this->containerInterface->get('filesystem');
  969.         $kernel $this->containerInterface->get('kernel');
  970.         $cacheDir $kernel->getCacheDir();
  971.         foreach (array('matcher_cache_class''generator_cache_class') as $option) {
  972.             try{
  973.                 $className $router->getOption($option);
  974.                 $cacheFile $cacheDir DIRECTORY_SEPARATOR $className '.php';
  975.                 $filesystem->remove($cacheFile);
  976.             }catch(\Exception $e){
  977.                 //
  978.             }
  979.         }
  980.         $router->warmUp($cacheDir);
  981.         return true;
  982.     }
  983.     private function htmlMinifier(string $content) : string
  984.     {
  985.         $search = [
  986.             '/(\n|^)(\x20+|\t)/',
  987.             '/(\n|^)\/\/(.*?)(\n|$)/',
  988.             '/\n/',
  989.             '/\<\!--.*?-->/',
  990.             '/(\x20+|\t)/',            # Delete multispace (Without \n)
  991.             '/\>\s+\</',            # strip whitespaces between tags
  992.             '/(\"|\')\s+\>/',        # strip whitespaces between quotation ("') and end tags
  993.             '/=\s+(\"|\')/'            # strip whitespaces between = "'
  994.         ];
  995.         $replace = [
  996.             "\n",
  997.             "\n",
  998.             " ",
  999.             "",
  1000.             " ",
  1001.             "><",
  1002.             "$1>",
  1003.             "=$1"
  1004.         ];
  1005.         return preg_replace($search$replace$content);
  1006.     }
  1007.     
  1008.     /**
  1009.      * Aanpassingen van de response html content
  1010.      *
  1011.      * @param Response $response Symfony Response object that needs to be optimized
  1012.      * @return Response Optimized Symfony Response object
  1013.      */
  1014.     protected function responseRewriteOutput(Response $response$minify false$defer true) : Response
  1015.     {
  1016. return $response;
  1017.         $old strlen($response->getContent());
  1018.         $content $this->htmlMinifier($response->getContent());
  1019.         $new strlen($content);
  1020.         $verschil $old $new;
  1021.         $percent = ($verschil $old) * 100;
  1022.         
  1023.         if ($this->containerInterface->getParameter('kernel.environment') == 'dev') {
  1024.             $content '<!-- old size: ' number_format($old0',''.') . ' new size: ' number_format($new0',''.') . ' improvement: ' round($percent2PHP_ROUND_HALF_DOWN) . '% -->' .  $content;
  1025.         }
  1026.         $response->setContent($content);
  1027.         // DOMDocument is disabled, it does weird things to the html layout. For example inserting </source> elements in <picture> which is not valid.
  1028.         return $response;
  1029.         //$response->setSharedMaxAge(3600);
  1030.         $dom = new \DOMDocument();
  1031.         $dom->validateOnParse true;
  1032.         $dom->resolveExternals true;
  1033.         libxml_use_internal_errors(true);
  1034.         $page mb_convert_encoding($response->getContent(), 'HTML-ENTITIES'"UTF-8");
  1035.         $dom->loadHTML($pageLIBXML_HTML_NOIMPLIED LIBXML_HTML_NODEFDTD LIBXML_NOENT);
  1036.         $xpath = new \DOMXpath($dom);
  1037.         if (0) {
  1038.             foreach (libxml_get_errors() as $error) {
  1039.                 // Do something with the error.
  1040.                 dump($error);
  1041.             }
  1042.             //die();
  1043.         }
  1044.         libxml_clear_errors();
  1045.         $defer false;
  1046.         $minify false;
  1047.         if ($defer) {
  1048.             foreach ($dom->getElementsByTagName('script') as $node)
  1049.             {
  1050.                 if ($node->getAttribute('type') == 'text/javascript' || $node->getAttribute('type') == '')
  1051.                 {
  1052.                     if ($node->getAttribute('type') == 'text/javascript' || $node->getAttribute('type') == '')
  1053.                     {
  1054.                         if ($node->getAttribute('src')) {
  1055.                             /*$aScript['handle'] = ($node->getAttribute('id'))?$node->getAttribute('id'):md5($node->nodeValue);
  1056.                             $aScript['handle'] =  md5($node->getAttribute('src'));
  1057.                             $aScript['src'] = $node->getAttribute('src');
  1058.                             $aScript['cleansrc'] =  remove_query_arg('ver',$node->getAttribute('src'));*/
  1059.                             
  1060.                             $node->setAttribute('defer','defer');
  1061.                         } else {
  1062.                             $node->setAttribute('src','data:text/javascript;base64,'.base64_encode($node->nodeValue));
  1063.                             $node->setAttribute('defer','defer');
  1064.                             $node->nodeValue='';
  1065.                         }
  1066.                     }
  1067.                 }
  1068.             }
  1069.         }
  1070.         if ($minify) {
  1071.             $dom $this->responseMinify($dom$xpath);
  1072.         }
  1073.         $dir $this->containerInterface->get('kernel')->getProjectDir() . '/var/cache/';
  1074.         file_put_contents($dir 'content_before.txt'$response->getContent());
  1075.         //dump('einde');die();
  1076.         $response->setContent($dom->saveHTML());
  1077.         file_put_contents($dir 'content_after.txt'$dom->saveHTML());
  1078.         //dump('hoi 1');die();
  1079.         return $response;
  1080.     }
  1081.     /**
  1082.      * Minify the html of a DOMDocument
  1083.      *
  1084.      * @param  \DOMDocument $dom DomDocumunt
  1085.      * @param  \DOMXPath $xpath DomXpath
  1086.      * @return \DOMDocument
  1087.      */
  1088.     private function responseMinify(\DOMDocument $dom\DOMXPath $xpath) : \DOMDocument
  1089.     {
  1090.         $dom->preserveWhiteSpace false;
  1091.         // remove comments
  1092.         foreach ($xpath->query('//comment()') as $comment) {
  1093.             $val$comment->nodeValue;
  1094.             if( strpos($val,'[')===false){
  1095.                 $comment->parentNode->removeChild($comment);
  1096.             }
  1097.         }
  1098.         $dom->normalizeDocument();
  1099.         $textnodes $xpath->query('//text()');
  1100.         $skip = ["style","pre","code","script","textarea"];
  1101.         foreach ($textnodes as $t) {
  1102.             $xp $t->getNodePath();
  1103.             $doskip false;
  1104.             foreach ($skip as $pattern) {
  1105.                 if (strpos($xp,"/$pattern")!==false) {
  1106.                     $doskip true;
  1107.                     break;
  1108.                 }
  1109.             }
  1110.             if ($doskip) {
  1111.                 continue;
  1112.             }
  1113.             $t->nodeValue preg_replace("/\s{2,}/"" "$t->nodeValue);
  1114.         }
  1115.         $dom->normalizeDocument();
  1116.         $divnodes $xpath->query('//div|//p|//nav|//footer|//article|//script|//hr|//br');
  1117.         foreach($divnodes as $d){
  1118.             $candidates = [];
  1119.             if(count($d->childNodes)){
  1120.                 $candidates[] = $d->firstChild;
  1121.                 $candidates[] = $d->lastChild;
  1122.                 $candidates[] = $d->previousSibling;
  1123.                 $candidates[] = $d->nextSibling;
  1124.             }
  1125.             foreach($candidates as $c){
  1126.                 if($c==null){
  1127.                     continue;
  1128.                 }
  1129.                 if($c->nodeType==3){
  1130.                     $c->nodeValue preg_replace('/\s{2,}/im'''$c->nodeValue);
  1131.                 }
  1132.             }
  1133.         }
  1134.         $dom->normalizeDocument();
  1135.         /*
  1136.         if($js){
  1137.             $scriptnodes = $xpath->query('//script');
  1138.             foreach($scriptnodes as $d){
  1139.                 $d->nodeValue = preg_replace(array('/<!--(.*)-->/Uis',"/[[:blank:]]+/",'/\/\*(.*)\*\//Uis',),array('',' ',''),str_replace(array("\n","\r","\t"),'',$d->nodeValue));
  1140.             }
  1141.         }
  1142.         if($css){
  1143.             $cssnodes = $xpath->query('//style');
  1144.             foreach($cssnodes as $d){
  1145.                 $d->nodeValue = preg_replace(array('/<!--(.*)-->/Uis',"/[[:blank:]]+/",'/\/\*(.*)\*\//Uis',),array('',' ',''),str_replace(array("\n","\r","\t"),'',$d->nodeValue));
  1146.             }
  1147.         }*/
  1148.         return $dom;
  1149.     }
  1150.     /**
  1151.      * Reset pageCache where a block contains a bundle
  1152.      *
  1153.      * @param string $string bundleName if string is null, then all pages of the website are reset.
  1154.      * @return void
  1155.      */
  1156.     protected function resetPageCacheThatContainedBundle(?string $string\App\CmsBundle\Entity\Settings $Settings) : void
  1157.     {
  1158.         // check if cache is enabled
  1159.         $allowCache false;
  1160.         if ($this->containerInterface->hasParameter('trinity_cache') && ($this->containerInterface->getParameter('trinity_cache') == 'true' || $this->containerInterface->getParameter('trinity_cache'))) {
  1161.             $allowCache true;
  1162.         }
  1163.         if (!$allowCache) {
  1164.             return;
  1165.         }
  1166.         if (empty($string)) {
  1167.             $pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(['settings' => $Settings]);
  1168.             if (!empty($pages))
  1169.             {
  1170.                 foreach($pages as $page)
  1171.                 {
  1172.                     if ($page->getEnabled() && $page->getCache()) {
  1173.                         $page->setCacheData(null);
  1174.                     }
  1175.                 }
  1176.             }
  1177.         } else {
  1178.             $pageBlocks $this->em->getRepository('CmsBundle:PageBlock')->findByData($string);
  1179.             if (!empty($pageBlocks)) {
  1180.                 foreach($pageBlocks as $block) {
  1181.                     $blockWrapper $block->getWrapper();
  1182.                     $page $blockWrapper->getPage();
  1183.                     if ($page->getSettings()->getId() == $Settings->getId()) {
  1184.                         // reset cache
  1185.                         $page->setCacheData(null);
  1186.                     }
  1187.                 }
  1188.             }
  1189.         }
  1190.         return;
  1191.     }
  1192. }