src/Controller/PageContentController.php line 152

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Admin\Entity\StdGeoMap;
  4. use App\Admin\Entity\StdPagesTag;
  5. use App\Admin\Entity\StdWebUsers;
  6. use App\Service\StdTrackingService;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpFoundation\JsonResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Knp\Component\Pager\PaginatorInterface;
  14. use App\Admin\Repository\StdPagesPagesRepository;
  15. use App\Admin\Repository\StdUsersRepository;
  16. use App\Admin\Repository\StdConfigRepository;
  17. use App\Admin\Entity\StdPages;
  18. use App\Admin\Entity\StdPagesPages;
  19. use App\Admin\Entity\StdPagesContent;
  20. use App\Admin\Entity\StdMenusFriendlyUrl;
  21. use App\Admin\Entity\StdFriendlyUrl;
  22. use App\Admin\Entity\StdBlocks;
  23. use App\Admin\Entity\StdDomains;
  24. use App\Admin\Entity\StdDomainsValues;
  25. use App\Admin\Enum\DomainValueType;
  26. use App\Admin\Entity\StdTemplatesBlocks;
  27. use App\Admin\Entity\StdContentTypes;
  28. use App\Admin\Entity\StdAttributesValues;
  29. use App\Admin\Entity\StdPagesAttributesValues;
  30. use App\Admin\Entity\StdLanguages;
  31. use App\Form\StdDynamicForm;
  32. use App\Entity\Forms;
  33. use App\Utils\Functions;
  34. use App\Admin\Entity\StdAttributes;
  35. use App\Admin\Entity\StdContentTypesAttributes;
  36. use App\Admin\Entity\StdNotifications;
  37. use App\Admin\Entity\StdRedirects;
  38. use ReCaptcha\ReCaptcha;
  39. use DateInterval;
  40. use DateTime;
  41. use DateTimeZone;
  42. use Symfony\Component\Security\Core\Security;
  43. use App\Admin\Controller\StdPagesController;
  44. use App\Admin\Entity\StdNotificationsScheduleSent;
  45. use App\Admin\Entity\StdNotificationsTypes;
  46. use App\Admin\Entity\StdSnippets;
  47. use App\Admin\Entity\StdSnippetsContent;
  48. use App\Admin\Entity\StdUsers;
  49. use App\Admin\Utils\AdminFunctions;
  50. use Symfony\Contracts\Translation\TranslatorInterface;
  51. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  52. use App\Event\StdFormsSubmitEvent;
  53. use Symfony\Component\HttpFoundation\Cookie;
  54. use App\Service\StdBlocksService;
  55. use App\Service\StudioService;
  56. use Doctrine\Persistence\ManagerRegistry;
  57. use Symfony\Component\Cache\Adapter\DoctrineDbalAdapter;
  58. use Symfony\Component\HttpKernel\KernelInterface;
  59. use Symfony\Component\Mailer\MailerInterface;
  60. use App\Admin\Entity\StdWebUsersAddresses;
  61. use App\Admin\Form\StdWebUsersAddressesForm;
  62. use App\Event\StdWebUsersActivatedEvent;
  63. use App\Event\StdWebUsersNewAddressEvent;
  64. use App\Event\StdWebUsersRegisteredEvent;
  65. use App\Event\StdWebUsersUpdateAddressEvent;
  66. use App\Exception\RedirectException;
  67. use App\Model\StdWebUsersChangePasswordFormModel;
  68. use App\Model\StdWebUsersEditFormModel;
  69. use App\Model\StdWebUsersRecoveryPasswordFormModel;
  70. use App\Model\StdWebUsersRegistrationFormModel;
  71. use Exception;
  72. use Symfony\Component\HttpFoundation\RedirectResponse;
  73. use App\Admin\Entity\StdWebRoles;
  74. use App\Form\StdWebUsersChangePasswordFormType;
  75. use App\Form\StdWebUsersEditFormType;
  76. use App\Form\StdWebUsersRecoveryPasswordFormType;
  77. use App\Form\StdWebUsersRegistrationFormType;
  78. use App\Repository\FormsRepository;
  79. use App\Service\StdSecurityService;
  80. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  81. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  82. use Symfony\Contracts\Cache\CacheInterface;
  83. use Symfony\Contracts\Cache\ItemInterface;
  84. class PageContentController extends AbstractController
  85. {
  86.     private $request;
  87.     private $isformhandled false;
  88.     private $usersrepository;
  89.     private $mailer;
  90.     private $paginator;
  91.     private $locale;
  92.     private $security;
  93.     private $passwordHasher;
  94.     private $masterRequestUri;
  95.     private $mainrequest;
  96.     private $translator;
  97.     private $dispatcher;
  98.     private $stdsecurity;
  99.     /**
  100.      * @var ManagerRegistry
  101.      */
  102.     private $registry;
  103.     private $entityManager;
  104.     private $redirectsCache;
  105.     private StudioService $stdService;
  106.     private StdTrackingService $stdTrackingService;
  107.     public function __construct(
  108.         RequestStack                $requestStack,
  109.         StdUsersRepository          $usersrepository,
  110.         MailerInterface             $mailer,
  111.         PaginatorInterface          $paginator,
  112.         Security                    $security,
  113.         TranslatorInterface         $translator,
  114.         EventDispatcherInterface    $dispatcher,
  115.         ManagerRegistry             $registry,
  116.         UserPasswordHasherInterface $passwordHasher,
  117.         private string              $formsDirectory,
  118.         CacheInterface              $redirectsCache,
  119.         StdSecurityService          $stdsecurity,
  120.         StudioService               $stdService,
  121.         StdTrackingService          $stdTrackingService
  122.     )
  123.     {
  124.         if ($requestStack->getCurrentRequest() == null) {
  125.             throw $this->createNotFoundException('Page not found');
  126.         }
  127.         $this->request $requestStack->getCurrentRequest();
  128.         $this->masterRequestUri $requestStack->getMainRequest()->getPathInfo();
  129.         $this->mainrequest $requestStack->getMainRequest();
  130.         $this->locale $this->request->getLocale();
  131.         $this->usersrepository $usersrepository;
  132.         $this->mailer $mailer;
  133.         $this->paginator $paginator;
  134.         $this->security $security;
  135.         $this->stdsecurity $stdsecurity;
  136.         $this->translator $translator;
  137.         $this->dispatcher $dispatcher;
  138.         $this->registry $registry;
  139.         $this->entityManager $registry->getManager();
  140.         $this->passwordHasher $passwordHasher;
  141.         $this->redirectsCache $redirectsCache;
  142.         $this->stdService $stdService;
  143.         $this->stdTrackingService $stdTrackingService;
  144.     }
  145.     #[Route(path'/'name'home')]
  146.     #[Route(path'/{locale}'name'home_locale'requirements: ['locale' => '[A-Za-z]{2}'])]
  147.     public function showHome(): Response
  148.     {
  149.         if ($this->entityManager->getRepository(StdLanguages::class)->findOneBy(['languageCode' => $this->locale'isPublic' => 1'isActive' => 1])) {
  150.             $rep $this->entityManager->getRepository(StdPagesContent::class);
  151.             $pageContent $rep->findOneBy(["url" => "home""languageCode" => $this->locale]);
  152.             if ($pageContent) {
  153.                 return $this->showContentById($pageContent->getPageId(), "default"true);
  154.             } else {
  155.                 $rep $this->entityManager->getRepository(StdPages::class);
  156.                 $page $rep->findOneById(1);
  157.                 return $this->showContentById($page"default"true);
  158.             }
  159.         } else {
  160.             $this->request->setLocale($this->request->getDefaultLocale());
  161.             $this->translator->setLocale($this->request->getDefaultLocale());
  162.             $this->translator->refreshCatalogue($this->request->getDefaultLocale());
  163.             throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  164.         }
  165.     }
  166.     #[Route(path'{_locale}/ajax_page_list/{skin}/{page}/{pagenumber}'name'ajax_page_list_render')]
  167.     public function renderAjaxPageList(StdPages $page$skin$pagenumber): Response
  168.     {
  169.         $rep $this->entityManager->getRepository(StdPagesContent::class);
  170.         $pagecontent $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $this->locale]);
  171.         if ($pagecontent) {
  172.             $variables $this->prepareVariables($pagecontent);
  173.         } else {
  174.             $variables = array();
  175.         }
  176.         $ajaxCall["isAjax"] = true;
  177.         $arrAttr = array();
  178.         // Verify filter
  179.         $dataForm $this->request->request->all();
  180.         $ajaxCall["operator"] = $this->request->request->get('attr_operator''or');
  181.         if ($dataForm) {
  182.             foreach ($dataForm as $search => $dataFilter) {
  183.                 if (strpos($search"ilter_")) {
  184.                     $dataExplode explode("filter_"$search);
  185.                     $attributeMachineName $dataExplode[1];
  186.                     $arrAttr[$attributeMachineName] = $dataFilter;
  187.                 }
  188.             }
  189.             if ($arrAttr) {
  190.                 $ajaxCall["arrAttr"] = $arrAttr;
  191.             }
  192.         }
  193.         // Format attributes
  194.         $contenttypeattributes $this->entityManager->getRepository(StdAttributes::class)->returnAttributesByContentType($page->getContentType()->getMachineName());
  195.         $attributesarr = [];
  196.         $arritem = [];
  197.         foreach ($contenttypeattributes as $entity) {
  198.             if ($entity instanceof StdAttributes) {
  199.                 $attributesarr[$entity->getMachineName()]["attribute"] = $entity;
  200.             }
  201.             if ($entity instanceof StdAttributesValues) {
  202.                 $attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["value"] = $entity;
  203.                 $attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["checked"] = false;
  204.                 if ($arrAttr && isset($arrAttr[$entity->getAttribute()->getMachineName()])) {
  205.                     if (is_array($arrAttr[$entity->getAttribute()->getMachineName()]) && array_search($entity->getValue(), $arrAttr[$entity->getAttribute()->getMachineName()]) !== FALSE) {
  206.                         $attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["checked"] = true;
  207.                     }
  208.                     if (!is_array($arrAttr[$entity->getAttribute()->getMachineName()]) && $arrAttr[$entity->getAttribute()->getMachineName()] == $entity->getValue()) {
  209.                         $attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["checked"] = true;
  210.                     }
  211.                 }
  212.             }
  213.         }
  214.         $content $this->renderPageContent($pagenumber$variables$page$pagecontentnulltrue$ajaxCall);
  215.         $payload array_merge([
  216.             "isajax" => true,
  217.             "allattributes" => $attributesarr,
  218.             "locale" => $this->locale,
  219.             "blockscontent" => $content["html"],
  220.             "blockscontentjs" => $content["js"],
  221.             'paginator' => array_key_exists("paginator"$content["payload"]) ? $content["payload"]["paginator"] : array()
  222.         ], $variables);
  223.         $result $this->render('ajax/' $skin '.html.twig'$payload);
  224.         if ($result) {
  225.             $data $result;
  226.         } else {
  227.             $data = new Response('{"success" => false}');
  228.         }
  229.         return $data;
  230.     }
  231.     #[Route(path'{_locale}/ajax_call/{skin}/{page}/{pagenumber}'name'ajax_call_render')]
  232.     public function renderAjaxCall(StdPages $page$skin$pagenumber): Response
  233.     {
  234.         $rep $this->entityManager->getRepository(StdPagesContent::class);
  235.         $pagecontent $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $this->locale]);
  236.         if ($pagecontent) {
  237.             $variables $this->prepareVariables($pagecontent);
  238.         } else {
  239.             $variables = array();
  240.         }
  241.         $ajaxCall["isAjax"] = true;
  242.         // Check for blockuniqueid to filter rendering to a specific block (for lazy loading)
  243.         $blockuniqueid $this->request->get("blockuniqueid") ?: $this->request->request->get("blockuniqueid");
  244.         if ($blockuniqueid) {
  245.             $ajaxCall["blockuniqueid"] = $blockuniqueid;
  246.         }
  247.         
  248.         // Check for blockskin to use a specific skin for the block
  249.         $blockskin $this->request->get("blockskin") ?: $this->request->request->get("blockskin");
  250.         if ($blockskin) {
  251.             $ajaxCall["blockskin"] = $blockskin;
  252.         }
  253.         $content $this->renderPageContent($pagenumber$variables$page$pagecontentnulltrue$ajaxCall);
  254.         $payload array_merge([
  255.             "isajax" => true,
  256.             "locale" => $this->locale,
  257.             "blockscontent" => $content["html"],
  258.             "blockscontentjs" => $content["js"],
  259.             'paginator' => $content["payload"]["paginator"] ?? []
  260.         ], $variables);
  261.         $result $this->render('ajax/' $skin '.html.twig'$payload);
  262.         if ($result) {
  263.             $data $result;
  264.         } else {
  265.             $data = new Response('{"success" => false}');
  266.         }
  267.         return $data;
  268.     }
  269.     #[Route(path'{_locale}/page/{page}'name'page_content')]
  270.     #[Route(path'{_locale}/page/{page}/{blockname}'name'page_content_blockname')]
  271.     public function previewPage(StdPages $page$blockname "")
  272.     {
  273.         return $this->showContentById($page'default'falsefalse, array(), $blockname);
  274.     }
  275.     public function showContentById($object$skin "default"$direct false$renderView false$relationTree = array(), $blockname ""$blockskin ""$renderblocks true$preview false)
  276.     {
  277.         $relationId null;
  278.         if ($object instanceof StdFriendlyUrl) {
  279.             $page $object->getPageId();
  280.             $relationId = !is_null($object->getRelationId()) ? $object->getRelationId()->getId() : null;
  281.             $this->stdTrackingService->trackVisitOnPage($page);
  282.         } elseif ($object instanceof StdPages) {
  283.             $page $object;
  284.             $this->stdTrackingService->trackVisitOnPage($page);
  285.         } elseif ($object['url']) {
  286.             $preview true;
  287.             $page $object['url']->getPageId();
  288.         } else {
  289.             throw new \Exception("Object is not a page neither a friendly url");
  290.         }
  291.         if (!$preview || !$object['dataForm']['new']) {
  292.             if (!$this->verifyPermission($page)) {
  293.                 $loginpage Functions::getPageInfo($this->localeFunctions::getConfig('login_page'''$this->entityManager), $this->entityManager);
  294.                 throw new RedirectException(new RedirectResponse($loginpage['url']));
  295.             }
  296.         }
  297.         $pageskin "";
  298.         if ($this->request->isXmlHttpRequest()) {
  299.             if (!$blockname) {
  300.                 $blockname $this->request->get("block");
  301.             }
  302.             if (!$blockname) {
  303.                 $blockname $this->request->request->get("block");
  304.             }
  305.             if (!$blockskin)
  306.                 $blockskin $this->request->get("blockskin");
  307.             if (!$blockskin)
  308.                 $blockskin $this->request->request->get("blockskin");
  309.             if (!$pageskin)
  310.                 $pageskin $this->request->get("pageskin");
  311.             if (!$pageskin)
  312.                 $pageskin $this->request->request->get("pageskin");
  313.         }
  314.         /*
  315.         Quando um formulário ÃƒÆ’ƒÂ© submetido não pode fazer redirect senão perde o request (POST)
  316.         */
  317.         $formTestRedirect $this->createForm(StdDynamicForm::class);
  318.         $formTestRedirect->handleRequest($this->request);
  319.         if ($formTestRedirect->isSubmitted() && $formTestRedirect->isValid()) {
  320.             $direct true;
  321.         }
  322.         $breadCrumbs = [];
  323.         if ($relationTree) {
  324.             if (!$preview || !$object['dataForm']['new']) {
  325.                 $breadCrumbs $this->findBreadCrumbs($page$relationTree$this->entityManager);
  326.             } else {
  327.                 $breadCrumbs $this->findBreadCrumbs($object$relationTree$this->entityManager);
  328.             }
  329.         } else {
  330.             if (!$preview || !$object['dataForm']['new']) {
  331.                 $breadCrumbs $this->findBreadCrumbs($pagenull$this->entityManager);
  332.             } else {
  333.                 $breadCrumbs $this->findBreadCrumbs($objectnull$this->entityManager);
  334.             }
  335.         }
  336.         $headercontent = [];
  337.         $publishDate null;
  338.         $expireDate null;
  339.         if ($page->getPublishDate())
  340.             $publishDate = new DateTime($page->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  341.         if ($page->getExpireDate())
  342.             $expireDate = new DateTime($page->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  343.         $rulesAndMessages["messages"] = "";
  344.         $rulesAndMessages["rules"] = "";
  345.         $useReCaptcha true;
  346.         if ($preview || Functions::isPagePublished($page)) {
  347.             if (!$direct) {
  348.                 $verify $this->entityManager->getRepository(StdFriendlyUrl::class)->findOneBy(["pageId" => $page->getId(), "isCanonical" => 1"languageCode" => $this->locale]);
  349.                 if ($verify) {
  350.                     return $this->redirect($verify->getUrl());
  351.                 }
  352.             }
  353.             $rep $this->entityManager->getRepository(StdPagesContent::class);
  354.             // BEGIN SEO URL
  355.             $alternateUrls = [];
  356.             $defaultUrl null;
  357.             $canonicalUrl null;
  358.             if (!$preview) {
  359.                 if ($canonical $this->entityManager->getRepository(StdFriendlyUrl::class)->findOneBy(["pageId" => $page->getId(), "isCanonical" => 1"languageCode" => $this->locale])) {
  360.                     $canonicalUrl $canonical->getUrl() . (($_SERVER['QUERY_STRING'] ?? '') != '' '?' $_SERVER['QUERY_STRING'] : '');
  361.                 }
  362.                 //returns all the active and public languages, also returns the page url if it exists
  363.                 $tempLanguages $rep->searchLanguagesAndUrl($page->getId(), $relationId);
  364.                 foreach ($tempLanguages as $tempLanguage) {
  365.                     // Commented to allow full URL to be set when /home is the route to match hreflang and canonical
  366.                     // if ($this->request->get('_route') == 'home' || $this->request->get('_route') == 'home_locale')
  367.                     // {
  368.                     //     $tempLanguage['url'] = '/' . $tempLanguage['language_code'];
  369.                     // }
  370.                     $tempLanguage['url'] .= ($_SERVER['QUERY_STRING'] ?? '') != '' '?' $_SERVER['QUERY_STRING'] : '';
  371.                     $alternateUrls[] = $tempLanguage;
  372.                     if ($tempLanguage['is_default']) {
  373.                         $defaultUrl $tempLanguage['url'];
  374.                     }
  375.                     if (is_null($canonicalUrl) && $tempLanguage['language_code'] == $this->locale) {
  376.                         $canonicalUrl $tempLanguage['url'];
  377.                     }
  378.                 }
  379.                 if (!is_null($defaultUrl) && ($this->request->get('_route') == 'home' || $this->request->get('_route') == 'home_locale')) {
  380.                     $defaultUrl '';
  381.                 }
  382.             }
  383.             // END SEO URL
  384.             if (!$preview) {
  385.                 $pagecontent $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $this->locale]);
  386.             } else {
  387.                 $pagecontent $object["pageContent"];
  388.                 $pagecontent->setTitle("Preview - " $pagecontent->getTitle());
  389.                 $languageCode $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $this->locale]);
  390.                 $pagecontent->setLanguageCode($languageCode);
  391.             }
  392.             if ($pagecontent) {
  393.                 if ($preview) {
  394.                     $variables $this->prepareVariables($pagecontent$object);
  395.                 } else {
  396.                     $variables $this->prepareVariables($pagecontent);
  397.                 }
  398.                 if ($page->getContentType()->getMachineName() == "forms") {
  399.                     $formData $this->entityManager->getRepository(Forms::class)->findOneById($this->request->query->get("id"));
  400.                     if ($formData && $this->request->query->get("edit")) {
  401.                         $variables["formdata"] = $formData->getContent();
  402.                     }
  403.                 }
  404.                 if ($breadCrumbs)
  405.                     $variables array_merge($variables, array("breadCrumbs" => $breadCrumbs));
  406.                 $variables["preview"] = 0;
  407.                 if ($preview) {
  408.                     $variables["preview"] = 1;
  409.                 }
  410.             } else {
  411.                 throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  412.             }
  413.             if ($renderblocks) {
  414.                 $content $this->renderPageContent($this->request->query->getInt('pag'1), $variables$page$pagecontent$blockskintrue, array(), $blockname);
  415.             } else {
  416.                 $content["html"] = "";
  417.                 $content["js"] = "";
  418.                 $content["cookies"] = [];
  419.             }
  420.             $response = new Response();
  421.             if ($page->getIncludeSitemap() == 0) {
  422.                 $response->headers->set('X-Robots-Tag''noindex, nofollow');
  423.             }
  424.             isset($content['cookies']) && $this->addCookiesToResponse($response$content['cookies']);
  425.             if ($this->request->isXmlHttpRequest()) {
  426.                 if ($pageskin) {
  427.                     $payload array_merge([
  428.                         "locale" => $this->locale,
  429.                         "blockscontent" => $content["html"],
  430.                         "blockscontentjs" => $content["js"],
  431.                         'alternateUrls' => $alternateUrls,
  432.                         'defaultUrl' => $defaultUrl,
  433.                         'canonicalUrl' => $canonicalUrl
  434.                     ], $variables);
  435.                     $layouttemplate 'layouts/' $page->getContentType()->getMachineName() . '/' $page->getContentType()->getMachineName() . '.' $pageskin '.html.twig';
  436.                     if ($this->container->get('twig')->getLoader()->exists($layouttemplate)) {
  437.                         return $this->renderView($layouttemplate$payload);
  438.                     } else {
  439.                         return $this->renderView('layouts/base.html.twig'$payload);
  440.                     }
  441.                 }
  442.                 $response->setContent($content["html"]);
  443.                 return $response;
  444.             } else {
  445.                 if ($pagecontent)
  446.                     $fields $pagecontent->getContent();
  447.                 else
  448.                     $fields = [];
  449.                 $redirect "";
  450.                 if (isset($fields["form_redirect"]))
  451.                     $redirect $fields["form_redirect"];
  452.                 $isPage false;
  453.                 $rulesAndMessages = array("messages" => """rules" => "");
  454.                 if (isset($fields["fields"])) {
  455.                     $rulesAndMessages $this->getRulesAndMessagesForm($fields["fields"]);
  456.                     foreach ($fields["fields"] as $field)
  457.                         if (isset($field["isPage"]) && $field["isPage"] == 1)
  458.                             $isPage true;
  459.                 }
  460.                 $form $this->createForm(StdDynamicForm::class);
  461.                 $form->handleRequest($this->request);
  462.                 if ($form->isSubmitted() && $form->isValid() && !$this->isformhandled) {
  463.                     $this->isformhandled true;
  464.                     $newForm = new Forms();
  465.                     $user $this->usersrepository->findOneById(0);
  466.                     $dataForm $this->request->request->all();
  467.                     $recaptchaToken $dataForm["recaptchatoken"];
  468.                     if ($recaptchaToken != 0) {
  469.                         $recaptcha = new ReCaptcha(Functions::getConfig("GOOGLE_RECAPTCHA_SECRET"""$this->entityManager), new \ReCaptcha\RequestMethod\CurlPost());
  470.                         $recaptchaRes $recaptcha
  471.                             ->setScoreThreshold(Functions::getConfig("GOOGLE_RECAPTCHA_SCORE_THRESHOLD"""$this->entityManager) ?? "0.5")
  472.                             ->verify($recaptchaToken);
  473.                         if (!$recaptchaRes->isSuccess()) {
  474.                             return new Response("Recaptcha Error");
  475.                         }
  476.                     } else {
  477.                         return new Response("Recaptcha Error");
  478.                     }
  479.                     $trataForm false;
  480.                     //Editing a form
  481.                     if ($this->request->query->get("id") && $this->request->query->get("edit")) {
  482.                         $trataForm true;
  483.                         $newForm $this->entityManager->getRepository(StdForms::class)->findOneBy(["id" => $this->request->query->get("id")]);
  484.                     }
  485.                     if (isset($dataForm["form_id"])) {
  486.                         if (is_array($fields["fields"])) {
  487.                             foreach ($fields["fields"] as $field) {
  488.                                 if (isset($field["components"]["input_combo_pages"]) && $dataForm["form_id"] == $field["components"]["input_combo_pages"]) {
  489.                                     $trataForm true;
  490.                                 }
  491.                             }
  492.                         };
  493.                         if ($trataForm) {
  494.                             unset($dataForm["std_dynamic_form"]);
  495.                             $filesArray $this->request->files->all();
  496.                             $folderName Functions::cleanString($dataForm["form_name"]);
  497.                             $attach $attachEmail = [];
  498.                             $i 0;
  499.                             if (isset($dataForm["insert_new_message"]) && $dataForm["insert_new_message"] != "") {
  500.                                 $webUser $this->security->getUser();
  501.                                 $newMessageTemp $dataForm[$dataForm["insert_new_message"]];
  502.                                 $dataForm[$dataForm["insert_new_message"]] = [];
  503.                                 $nowDate = new DateTime();
  504.                                 $nowDateFormated $nowDate->format('Y-m-d H:i:s');
  505.                                 if ($webUser && $webUser instanceof StdWebUsers) {
  506.                                     $dataForm[$dataForm["insert_new_message"]][] =
  507.                                         array(
  508.                                             "createdBy" => $webUser->getId()
  509.                                         , "createdByName" => $webUser->getName()
  510.                                         , "createdAt" => $nowDateFormated
  511.                                         "message" => $newMessageTemp
  512.                                         );
  513.                                 } else {
  514.                                     $dataForm[$dataForm["insert_new_message"]][] = \json_encode(
  515.                                         array(
  516.                                             "createdBy" => ""
  517.                                         "createdByName" => ""
  518.                                         "createdAt" => $nowDateFormated
  519.                                         "message" => $newMessageTemp
  520.                                         ));
  521.                                 }
  522.                             }
  523.                             foreach ($filesArray as $file_key => $files) {
  524.                                 foreach ($files as $file) {
  525.                                     $i++;
  526.                                     $originalName $file->getClientOriginalName();
  527.                                     $mimeType $file->getClientMimeType();
  528.                                     $fileName Functions::generateUniqueFileName() . '.' $file->guessExtension();
  529.                                     try {
  530.                                         $file->move(
  531.                                             $this->formsDirectory '/' $folderName '/',
  532.                                             $fileName
  533.                                         );
  534.                                     } catch (\Exception $e) {
  535.                                     }
  536.                                     $dataForm[$file_key][] = ["name" => $file->getClientOriginalName(), "file_name" => $fileName"type" => "file"];
  537.                                     // $attachEmail[] = $file;
  538.                                     $attachEmail[$i]["path"] = $this->formsDirectory '/' $folderName '/' $fileName;
  539.                                     $attachEmail[$i]["originalName"] = $originalName;
  540.                                     $attachEmail[$i]["mimeType"] = $mimeType;
  541.                                 }
  542.                             }
  543.                             $newForm->setFormName($dataForm["form_name"]);
  544.                             $newForm->setFormType($dataForm["form_type"]);
  545.                             $newForm->setContent($dataForm);
  546.                             $newForm->setCreatedDate(new \DateTime());
  547.                             $newForm->setUpdatedDate(new \DateTime());
  548.                             $newForm->setCreatedBy($user);
  549.                             $newForm->setUpdatedBy($user);
  550.                             $sendEmail false;
  551.                             $formInput "";
  552.                             if ($isPage) {
  553.                                 if (isset($dataForm["form_id"])) {
  554.                                     $formPage $rep->findOneBy(["pageId" => $dataForm["form_id"], "languageCode" => $this->locale]);
  555.                                 }
  556.                                 if (isset($formPage)) {
  557.                                     $pageFields $formPage->getContent();
  558.                                     if (isset($pageFields["form_email_sender"]) && $pageFields["form_email_sender"] == 1)
  559.                                         $sendEmail true;
  560.                                     $renderedform $this->renderFormContent($dataForm$pageFields);
  561.                                     $repNotifications $this->entityManager->getRepository(StdNotifications::class);
  562.                                     if ($sendEmail && $dataForm[$pageFields["form_input_email_to_send"]] != "") {
  563.                                         $userNotification $repNotifications->findOneBy(["id" => $pageFields["form_notification_user"]]);
  564.                                         $emailContent $userNotification $userNotification->getEmailBody() : "";
  565.                                         $subject $userNotification $userNotification->getEmailSubject() : "";
  566.                                         $twig $this->container->get('twig');
  567.                                         $template Functions::twig_template_from_string($twig'{% extends "admin/emails/base.html.twig" %}{% block content %} ' $emailContent ' {% endblock %}');
  568.                                         $body $template->render(array_merge($dataForm, array("rendered_form" => $renderedform"locale" => $this->locale)));
  569.                                         $template Functions::twig_template_from_string($twightml_entity_decode($subjectENT_QUOTES ENT_XML1'UTF-8'));
  570.                                         $subject $template->render($dataForm);
  571.                                         $ccEmails str_replace(' '''$pageFields["form_notification_user_cc"]);
  572.                                         $cc array_filter(explode(";"$ccEmails));
  573.                                         $bccEmails str_replace(' '''$pageFields["form_notification_user_bcc"]);
  574.                                         $bcc array_filter(explode(";"$bccEmails));
  575.                                         $to "";
  576.                                         if (isset($pageFields["form_input_email_to_send"])) {
  577.                                             if (strpos($pageFields["form_input_email_to_send"], ',') !== false) {
  578.                                                 $pageFields["form_input_email_to_send"] = explode(','str_replace([' '], [''], $pageFields["form_input_email_to_send"]));
  579.                                                 $to = array();
  580.                                                 foreach ($pageFields["form_input_email_to_send"] as $tosend) {
  581.                                                     if (isset($dataForm[$tosend])) {
  582.                                                         $tosend_emails explode(';'preg_replace('/[\s,]+/'';'$dataForm[$tosend]));
  583.                                                         $tosend_emails array_filter($tosend_emails'strlen');
  584.                                                         $to array_merge($tosend_emails$to);
  585.                                                     }
  586.                                                 }
  587.                                             } else {
  588.                                                 if (isset($dataForm[$pageFields["form_input_email_to_send"]])) {
  589.                                                     $toEmails str_replace(' '''$dataForm[$pageFields["form_input_email_to_send"]]);
  590.                                                     $to array_filter(explode(";"$toEmails));
  591.                                                 }
  592.                                             }
  593.                                             if ($to != "") {
  594.                                                 Functions::sendEmail($this->mailer$pageFields["form_email_from"], $pageFields["form_email_from_name"], $to$cc$bcc$subject$bodynull$this->entityManager);
  595.                                             }
  596.                                         }
  597.                                     }
  598.                                     // Send to admin
  599.                                     if ($pageFields["form_notification_admin"] && $pageFields["form_email_to"] != "") {
  600.                                         $adminNotification $repNotifications->findOneBy(["id" => $pageFields["form_notification_admin"]]);
  601.                                         $emailContent $adminNotification $adminNotification->getEmailBody() : "";
  602.                                         $subject $adminNotification $adminNotification->getEmailSubject() : "";
  603.                                         $twig $this->container->get('twig');
  604.                                         $template Functions::twig_template_from_string($twig'{% extends "admin/emails/base.html.twig" %}{% block content %} ' $emailContent ' {% endblock %}');
  605.                                         $body $template->render(array_merge($dataForm, array("rendered_form" => $renderedform"locale" => $this->request->getDefaultLocale())));
  606.                                         $template Functions::twig_template_from_string($twightml_entity_decode($subjectENT_QUOTES ENT_XML1'UTF-8'));
  607.                                         $subject $template->render($dataForm);
  608.                                         $toEmails str_replace(' '''$pageFields["form_email_to"]);
  609.                                         $to explode(";"$toEmails);
  610.                                         $ccEmails str_replace(' '''$pageFields["form_email_admin_cc"]);
  611.                                         $cc array_filter(explode(";"$ccEmails));
  612.                                         $bccEmails str_replace(' '''$pageFields["form_email_admin_bcc"]);
  613.                                         $bcc array_filter(explode(";"$bccEmails));
  614.                                         Functions::sendEmail($this->mailer$pageFields["form_email_from"], $pageFields["form_email_from_name"], $to$cc$bcc$subject$body$attachEmail$this->entityManager);
  615.                                     }
  616.                                 }
  617.                             }
  618.                             $this->entityManager->persist($newForm);
  619.                             $this->entityManager->flush();
  620.                             if ($redirect != "") {
  621.                                 return $this->redirect($this->request->getScheme() . $redirect);
  622.                             }
  623.                         }
  624.                     }
  625.                 }
  626.                 $headercontent = [
  627.                     "publishdate" => ($publishDate != null $publishDate->format('Y-m-d H:i:s') : null),
  628.                     "expiredate" => ($expireDate != null $expireDate->format('Y-m-d H:i:s') : null),
  629.                     "lastupdate" => ($page->getUpdatedDate() != null $page->getUpdatedDate()->format('Y-m-d H:i:s') : null),
  630.                     "createdby" => $page->getCreatedBy()->getName(),
  631.                     "order" => $page->getOrderValue()
  632.                 ];
  633.                 // global $studio;
  634.                 $payload array_merge([
  635.                     "page" => $page,
  636.                     "headercontent" => $headercontent,
  637.                     "locale" => $this->locale,
  638.                     "blockscontent" => $content["html"],
  639.                     "blockscontentjs" => $content["js"],
  640.                     'useReCaptcha' => false,
  641.                     'form' => $form->createView(),
  642.                     'messages' => $rulesAndMessages["messages"],
  643.                     'rules' => $rulesAndMessages["rules"],
  644.                     'alternateUrls' => $alternateUrls,
  645.                     'defaultUrl' => $defaultUrl,
  646.                     'canonicalUrl' => $canonicalUrl,
  647.                     // 'studio' => $studio,
  648.                     'preview' => $preview,
  649.                     'editBlocksInfo' => $content["variables"]["editBlocksInfo"] ?? []
  650.                 ], $variables);
  651.                 if ($this->container->get('twig')->getLoader()->exists('layouts/global/' $page->getLayout() . '.html.twig')) {
  652.                     if ($renderView)
  653.                         return $this->renderView('layouts/global/' $page->getLayout() . '.html.twig'$payload);
  654.                     else
  655.                         return $this->render('layouts/global/' $page->getLayout() . '.html.twig'$payload$response);
  656.                 } else {
  657.                     if ($this->container->get('twig')->getLoader()->exists('layouts/' $page->getContentType()->getMachineName() . '/' $page->getContentType()->getMachineName() . '.' $skin '.html.twig')) {
  658.                         if ($renderView)
  659.                             return $this->renderView('layouts/' $page->getContentType()->getMachineName() . '/' $page->getContentType()->getMachineName() . '.' $skin '.html.twig'$payload);
  660.                         else
  661.                             return $this->render('layouts/' $page->getContentType()->getMachineName() . '/' $page->getContentType()->getMachineName() . '.' $skin '.html.twig'$payload$response);
  662.                     } else {
  663.                         if ($renderView)
  664.                             return $this->renderView('layouts/base.html.twig'$payload);
  665.                         else
  666.                             return $this->render('layouts/base.html.twig'$payload$response);
  667.                     }
  668.                 }
  669.             }
  670.         } else {
  671.             if ($renderView) {
  672.                 return $this->renderView('layouts/blank.html.twig', []);
  673.             } else
  674.                 throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  675.         }
  676.     }
  677.     private function renderFormContent($values$formcontent)
  678.     {
  679.         $blocksservice = new StdBlocksService($this->stdTrackingService$this->entityManager);
  680.         $formname $values["form_name"];
  681.         $folderName Functions::cleanString($formname);
  682.         $content $formcontent["fields"];
  683.         $result "";
  684.         foreach ($content as $block) {
  685.             $block = (array)$block;
  686.             $component = (array)$block["components"];
  687.             $blockName = (string)$block["block"];
  688.             $domainvalues = [];
  689.             $stdblock $this->entityManager->getRepository(StdBlocks::class)->findOneBy(['machineName' => $blockName]);
  690.             if ($stdblock) {
  691.                 $stdsettings $stdblock->getSettings();
  692.                 if (isset($stdsettings["isFormDomain"]) && $stdsettings["isFormDomain"]) {
  693.                     //get the domain values for the selected domain
  694.                     if ($component["form_select_domain"]) {
  695.                         $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $component["form_select_domain"]]);
  696.                     }
  697.                 } else if (isset($stdsettings["isFormStatus"]) && $stdsettings["isFormStatus"]) {
  698.                     //get the domain values for the selected domain
  699.                     $domainobj $this->entityManager->getRepository(StdDomains::class)->findOneBy(["machineName" => "form_status"]);
  700.                     if ($domainobj) {
  701.                         $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id")]);
  702.                     }
  703.                 }
  704.             }
  705.             if (isset($component["form_input_name"]) && !Functions::startsWith($blockName'form_file')) {
  706.                 $name $component["form_input_name"];
  707.                 if (isset($values[$name])) {
  708.                     $payload = [];
  709.                     $payload array_merge([
  710.                         'value' => isset($values[$name]) ? $values[$name] : [],
  711.                         'settings' => $block["settings"],
  712.                         'fields' => $block["components"],
  713.                         'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  714.                         'values' => $domainvalues
  715.                     ]);
  716.                 }
  717.             } else if (isset($component["form_input_name"]) && Functions::startsWith($blockName'form_file')) {
  718.                 $name $component["form_input_name"];
  719.                 $payload = [];
  720.                 $attachments = [];
  721.                 $i 0;
  722.                 if (isset($values["foto"])) {
  723.                     foreach ($values["foto"] as $attach) {
  724.                         $href '/forms/' $folderName '/' $attach["file_name"];
  725.                         $attachments[$i]["href"] = $href;
  726.                         $attachments[$i]["name"] = $attach["name"];
  727.                         $i++;
  728.                     }
  729.                 }
  730.                 $payload array_merge([
  731.                     'anexos' => $attachments,
  732.                     'settings' => $block["settings"],
  733.                     'fields' => $block["components"],
  734.                     'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  735.                 ]);
  736.             } else {
  737.                 continue;
  738.             }
  739.             $skin "default";
  740.             if ($block["skin"] != "")
  741.                 $skin $block["skin"];
  742.             if ($this->container->get('twig')->getLoader()->exists("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".email.twig"))
  743.                 $result .= $this->renderView("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".email.twig"$payload);
  744.         }
  745.         return $result;
  746.     }
  747.     #[Route(path'{_locale}/show/{url}'name'page_content_url')]
  748.     public function showContentByURL(StdPagesContent $pageContent): Response
  749.     {
  750.         // $rep = $this->entityManager->getRepository(StdPages::class);
  751.         // $page = $rep->findOneById($pageContent->getPageId());
  752.         return $this->render('layouts/base.html.twig', [
  753.             'controller_name' => 'PageContentController',
  754.             'content' => $pageContent->getContent(),
  755.             "locale" => $this->request->getLocale()
  756.         ]);
  757.     }
  758.     function RenderMenu(Request $requestStdPagesPagesRepository $pagesReposStdConfigRepository $stdConfig): Response
  759.     {
  760.         $menuSkin $request->query->get('skin');
  761.         $menu $request->query->get('menu');
  762.         $usecache $request->query->get('use_cache'true);
  763.         $lang $request->getLocale();
  764.         $menuId $stdConfig->findOneBy(['machineName' => $menu'languageCode' => $lang]);
  765.         if ($menuId && (int)$menuId->getValue() > 0) {
  766.             $cache = new DoctrineDbalAdapter($this->registry->getConnection());
  767.             $cachekey Functions::cleanString('menu' $menuId->getValue() . '-' $menu $lang $menuSkin $this->generateUserCacheKey($this->security));
  768.             $cacheitem $cache->getItem($cachekey);
  769.             if (!$cacheitem->isHit() || !$usecache) {
  770.                 $cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
  771.                 $relationId $menuId->getValue();
  772.                 $numOfLevels $request->query->get('numOfLevels');
  773.                 if ($numOfLevels) {
  774.                     $numOfLevels++;
  775.                 } else {
  776.                     $numOfLevels 99999;
  777.                 }
  778.                 if ($menuSkin) {
  779.                     $skin $menuSkin;
  780.                 } else {
  781.                     $skinid $stdConfig->findOneBy(['machineName' => $menu "_skin"'languageCode' => $lang]);
  782.                     $skin $skinid->getValue();
  783.                 }
  784.                 $results $this->RenderCategories($relationId$numOfLevels$pagesRepos0$skin$lang, [
  785.                     'masterRequestUri' => $this->masterRequestUri
  786.                 ]);
  787.                 if ($this->container->get('twig')->getLoader()->exists('content-types/menus/' $skin '/' $skin '.default.html.twig'))
  788.                     $item $this->render('content-types/menus/' $skin '/' $skin '.default.html.twig', [
  789.                         'results' => $results,
  790.                         'masterRequestUri' => $this->masterRequestUri
  791.                     ]);
  792.                 else
  793.                     $item $this->render('content-types/menus/menus.default.html.twig', [
  794.                         'results' => $results,
  795.                         'masterRequestUri' => $this->masterRequestUri
  796.                     ]);
  797.                 $cache->save($cacheitem->set($item));
  798.                 return $item;
  799.             } else {
  800.                 return $cacheitem->get();
  801.             }
  802.         } else {
  803.             return new Response();
  804.         }
  805.     }
  806.     function RenderMenuBloco(Request $requestStdPagesPagesRepository $pagesRepos): Response
  807.     {
  808.         $menuId $request->query->get('menu');
  809.         $menuSkin $request->query->get('skin');
  810.         if ($menuId) {
  811.             $cache = new DoctrineDbalAdapter($this->registry->getConnection());
  812.             $lang $request->getLocale();
  813.             $cachekey Functions::cleanString($lang $menuSkin $menuId $this->generateUserCacheKey($this->security));
  814.             $cacheitem $cache->getItem($cachekey);
  815.             if (!$cacheitem->isHit()) {
  816.                 $cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
  817.                 $relationId $menuId;
  818.                 $numOfLevels 0;
  819.                 if ($numOfLevels) {
  820.                     $numOfLevels++;
  821.                 } else {
  822.                     $numOfLevels 99999;
  823.                 }
  824.                 if ($menuSkin) {
  825.                     $skin $menuSkin;
  826.                 } else {
  827.                     $skin "";
  828.                 }
  829.                 $results $this->RenderCategories($relationId$numOfLevels$pagesRepos0$skin$lang);
  830.                 if ($skin != "" && $this->container->get('twig')->getLoader()->exists('content-types/menus/' $skin '/' $skin '.default.html.twig'))
  831.                     $item $this->render('content-types/menus/' $skin '/' $skin '.default.html.twig', [
  832.                         'results' => $results
  833.                     ]);
  834.                 else
  835.                     $item $this->render('content-types/menus/menus.default.html.twig', [
  836.                         'results' => $results
  837.                     ]);
  838.                 $cache->save($cacheitem->set($item));
  839.                 return $item;
  840.             } else {
  841.                 return $cacheitem->get();
  842.             }
  843.         } else {
  844.             return new Response();
  845.         }
  846.     }
  847.     function RenderCategories($relationId$numOfLevels$pagesRepos$lvl$skin$lang$extraVariables = array())
  848.     {
  849.         $results $pagesRepos->getPagesRelations($relationId);
  850.         $numOfLevels--;
  851.         $result "";
  852.         $lvl++;
  853.         $user $this->security->getUser();
  854.         foreach ($results as $relation) {
  855.             $page $relation->getPageId();
  856.             $rep $this->entityManager->getRepository(StdPagesContent::class);
  857.             $pagecontent $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $lang]);
  858.             $hasPermissions false;
  859.             if (!is_null($user) && $user instanceof StdUsers) {
  860.                 $hasPermissions true// Is a backoffice user, so can he can see all items
  861.             } elseif (isset($pagecontent) && isset($pagecontent->getContent()['id'])) {
  862.                 if ($originalPage $this->entityManager->getRepository(StdPages::class)->find($pagecontent->getContent()['id'])) {
  863.                     $roles $originalPage->getRoles();
  864.                     if (sizeof($roles) > 0) {
  865.                         if ($user && sizeof($user->getRoles()) && sizeof($originalPage->getRolesByNames($user->getRoles()))) {
  866.                             $hasPermissions true// User and page have coincident roles
  867.                         }
  868.                     } else {
  869.                         $hasPermissions true// Page has no roles associated, so everyone can see it
  870.                     }
  871.                 }
  872.             } else {
  873.                 $roles $page->getRoles();
  874.                 if (sizeof($roles) > 0) {
  875.                     if ($user && sizeof($user->getRoles()) && sizeof($page->getRolesByNames($user->getRoles()))) {
  876.                         $hasPermissions true// User and page have coincident roles
  877.                     }
  878.                 } else {
  879.                     $hasPermissions true// Page has no roles associated, so everyone can see it
  880.                 }
  881.             }
  882.             if ($hasPermissions) {
  883.                 if ($pagecontent) {
  884.                     $variables $this->prepareVariables($pagecontent);
  885.                 } else {
  886.                     $variables = array();
  887.                 }
  888.                 $relationId $relation->getId();
  889.                 if ($skin != "") {
  890.                     if ($this->container->get('twig')->getLoader()->exists('content-types/menus/' $skin '/' $skin '.' $lvl '.html.twig'))
  891.                         $skinPage 'content-types/menus/' $skin '/' $skin '.' $lvl '.html.twig';
  892.                     else
  893.                         $skinPage 'content-types/menus/' $skin '/' $skin '.n.html.twig';
  894.                 } else {
  895.                     if ($this->container->get('twig')->getLoader()->exists('content-types/menus/menus.' $lvl '.html.twig'))
  896.                         $skinPage 'content-types/menus/menus.' $lvl '.html.twig';
  897.                     else
  898.                         $skinPage 'content-types/menus/menus.n.html.twig';
  899.                 }
  900.                 if ($numOfLevels 0) {
  901.                     $res $this->RenderCategories($relationId$numOfLevels$pagesRepos$lvl$skin$lang);
  902.                     $variables["results"] = $res;
  903.                     $content $this->renderPageContent(1$variables$page$pagecontent$skinPagefalse, array(), ".");
  904.                     $payload array_merge([
  905.                         "locale" => $this->locale,
  906.                         "blockscontent" => $content["html"],
  907.                         "blockscontentjs" => $content["js"],
  908.                         "level" => $lvl
  909.                     ], $variables$extraVariables);
  910.                     if (isset($payload["id"]) && $payload["id"] != "") {
  911.                         $originPageContent $rep->findOneBy(["pageId" => $payload["id"], "languageCode" => $this->locale]);
  912.                         $menuUrlRep $this->entityManager->getRepository(StdMenusFriendlyUrl::class);
  913.                         $menuUrl $menuUrlRep->getUrl($relation->getId());
  914.                         if ($originPageContent) {
  915.                             $originVariables $this->prepareVariables($originPageContent);
  916.                             $origin = [];
  917.                             foreach ($originVariables as $key => $value)
  918.                                 $origin["origin_" $key] = $value;
  919.                             $payload array_merge($payload$origin);
  920.                         }
  921.                         $payload array_merge([
  922.                             "friendly_url" => $menuUrl["url"] ?? "",
  923.                         ], $payload);
  924.                     }
  925.                     $result .= $this->renderView($skinPage$payload);
  926.                 }
  927.             }
  928.         }
  929.         return $result;
  930.     }
  931.     private function renderPageContent(int $pagenumber, array $variables, ?StdPages $pageStdPagesContent|StdSnippetsContent|null $pageContent, ?string $pageskinparam$renderlistblocks true$ajaxCall = array(), $blockmachinename ""): array
  932.     {
  933.         $blocksservice = new StdBlocksService($this->stdTrackingService$this->entityManager);
  934.         $content = array();
  935.         if ($pageContent) {
  936.             $cont $pageContent->getContent();
  937.             if (isset($cont["fields"]))
  938.                 $content $cont["fields"];
  939.         }
  940.         $result "";
  941.         $resultjs "";
  942.         $payload = [];
  943.         $headercontent = [];
  944.         $publishDatePage null;
  945.         $expireDatePage null;
  946.         $blockSequence 0;
  947.         $now = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
  948.         $publishDateIni $now;
  949.         $dateFim = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
  950.         $dateFim->add(new DateInterval('P10D'));
  951.         $expireDateIni $dateFim;
  952.         // global $studio;
  953.         // $variables['studio'] = $studio;
  954.         $variables["editBlocksInfo"] = [];
  955.         // Add page to variables so it's available in all blocks, including those rendered via snippets
  956.         if ($page !== null) {
  957.             $variables["page"] = $page;
  958.         }
  959.         $cookieLocationId $this->request->cookies->get('CloseToYou-Location');
  960.         $sessionLocations $this->request->getSession()->get('close_location_ids');
  961.         $effectiveLocations = [];
  962.         if ($cookieLocationId) {
  963.             $cookieLocation $this->entityManager->getRepository(StdDomainsValues::class)->findOneBy(['id' => (int)$cookieLocationId]);
  964.             if ($cookieLocation) {
  965.                 if (is_array($sessionLocations) && ($pos array_search((int)$cookieLocationId$sessionLocationstrue)) !== false) {
  966.                     $effectiveLocations[] = (int)$cookieLocationId;
  967.                     $offset 1;
  968.                     $count count($sessionLocations);
  969.                     while (($pos $offset) >= || ($pos $offset) < $count) {
  970.                         if (($pos $offset) >= 0) {
  971.                             $idLeft $sessionLocations[$pos $offset];
  972.                             if (!in_array($idLeft$effectiveLocationstrue)) {
  973.                                 $effectiveLocations[] = $idLeft;
  974.                             }
  975.                         }
  976.                         if (($pos $offset) < $count) {
  977.                             $idRight $sessionLocations[$pos $offset];
  978.                             if (!in_array($idRight$effectiveLocationstrue)) {
  979.                                 $effectiveLocations[] = $idRight;
  980.                             }
  981.                         }
  982.                         $offset++;
  983.                     }
  984.                 } else {
  985.                     $effectiveLocations[] = (int)$cookieLocationId;
  986.                     if (is_array($sessionLocations)) {
  987.                         foreach ($sessionLocations as $locId) {
  988.                             if ($locId != $cookieLocationId && !in_array($locId$effectiveLocationstrue)) {
  989.                                 $effectiveLocations[] = $locId;
  990.                             }
  991.                         }
  992.                     }
  993.                 }
  994.                 $this->request->getSession()->set('close_location_ids'$effectiveLocations);
  995.                 $variables['userDistrict'] = $cookieLocation->getGeoMap()->getDistrictName();
  996.                 $variables['userMunicipality'] = $cookieLocation->getGeoMap()->getMunicipalityName();
  997.             }
  998.         } elseif (!empty($sessionLocations)) {
  999.             $effectiveLocations $sessionLocations;
  1000.             $locationDomainValue $this->entityManager->getRepository(StdDomainsValues::class)
  1001.                 ->findOneBy(['id' => $sessionLocations[0]]);
  1002.             if ($locationDomainValue) {
  1003.                 $variables['userDistrict'] = $locationDomainValue->getGeoMap()->getDistrictName();
  1004.                 $variables['userMunicipality'] = $locationDomainValue->getGeoMap()->getMunicipalityName();
  1005.             }
  1006.         } else {
  1007.             $variables['userDistrict'] = null;
  1008.             $variables['userMunicipality'] = null;
  1009.         }
  1010.         $cookies = [];
  1011.         $block_groups = [];
  1012.         foreach ($content as $block) {
  1013.             $publishDate $publishDateIni;
  1014.             $expireDate $expireDateIni;
  1015.             if (array_key_exists("settings"$block) && $block["settings"]) {
  1016.                 if (array_key_exists("disabled_block"$block["settings"]) && $block["settings"]["disabled_block"]) {
  1017.                     continue;
  1018.                 }
  1019.                 if (array_key_exists("publish_date"$block["settings"]) && $block["settings"]["publish_date"]) {
  1020.                     $dateIni date_create_from_format("d/m/Y h:i A"$block["settings"]["publish_date"]);
  1021.                     $publishDate = new DateTime($dateIni->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  1022.                 }
  1023.                 if (array_key_exists("expire_date"$block["settings"]) && $block["settings"]["expire_date"]) {
  1024.                     $dateFim date_create_from_format("d/m/Y h:i A"$block["settings"]["expire_date"]);
  1025.                     $expireDate = new DateTime($dateFim->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  1026.                 }
  1027.             }
  1028.             if ($publishDate <= $now && $expireDate $now) {
  1029.                 $pageskin "";
  1030.                 if ($pageskinparam) {
  1031.                     $pageskin "blocks/" $block["block"] . "/" $block["block"] . "." $pageskinparam ".html.twig";
  1032.                 }
  1033.                 $iscacheable true;
  1034.                 $blockSequence++;
  1035.                 if (is_a($pageContentStdSnippetsContent::class)) {
  1036.                     $objectId $pageContent->getSnippetId()->getId();
  1037.                     $editpagelink $this->generateUrl('admin_snippets_edit', array('id' => $objectId'language_code' => $this->locale));
  1038.                 } else {
  1039.                     $objectId $page->getId();
  1040.                     $editpagelink $this->generateUrl('admin_pages_edit', array('page_id' => $objectId'content_type' => $page->getContentType()->getMachineName(), 'language_code' => $this->locale));
  1041.                 }
  1042.                 $variables["blockSequence"] = $block["block"] . "_" $objectId "_" $blockSequence;
  1043.                 // Set blockuniqueid in variables so ALL payloads (via array_merge) have it for lazy loading
  1044.                 $variables["blockuniqueid"] = $block["blockuniqueid"] ?? "";
  1045.                 if (array_key_exists("blockuniqueid"$block)) {
  1046.                     $variables["editBlocksInfo"][$block["blockuniqueid"]] = [
  1047.                         "blockuniqueid" => $block["blockuniqueid"] ?? '',
  1048.                         "blockmachinename" => $block["block"] ?? '',
  1049.                         "blockname" => $block["blockname"] ?? '',
  1050.                         "skin" => $block["skin"] ?? '',
  1051.                         "editpagelink" => $editpagelink ?? ''
  1052.                     ];
  1053.                 }
  1054.                 // Filter by blockuniqueid for lazy loading - skip blocks that don't match
  1055.                 if (isset($ajaxCall["blockuniqueid"]) && $ajaxCall["blockuniqueid"
  1056.                     && (!isset($block["blockuniqueid"]) || $block["blockuniqueid"] !== $ajaxCall["blockuniqueid"])) {
  1057.                     continue;
  1058.                 }
  1059.                 if ($blockmachinename && $block["block"] != $blockmachinename && $variables["blockSequence"] != $blockmachinename) {
  1060.                     continue;
  1061.                 }
  1062.                 $payload = [];
  1063.                 $stdblock $this->entityManager->getRepository(StdBlocks::class)->findOneBy(['machineName' => $block["block"]]);
  1064.                 if ($stdblock) {
  1065.                     $stdsettings $stdblock->getSettings();
  1066.                     if (isset($stdsettings['isCacheable']) && !$stdsettings['isCacheable']) {
  1067.                         $iscacheable false;
  1068.                     }
  1069.                     isset($stdsettings['webpackEntries']) && $this->mainrequest->attributes->set("webpackEntries"array_merge($this->mainrequest->attributes->get('webpackEntries'), array_combine($stdsettings['webpackEntries'], $stdsettings['webpackEntries'])));
  1070.                     if (isset($block["templatesBlocksId"]) && $block["templatesBlocksId"] && isset($block["isMaster"]) && $block["isMaster"]) {
  1071.                         $stdtemplate $page->getTemplateId();
  1072.                         if ($stdtemplate->getId()) {
  1073.                             $stdtemplateblock $this->entityManager->getRepository(StdTemplatesBlocks::class)->findOneById($block["templatesBlocksId"]);
  1074.                             if ($stdtemplateblock) {
  1075.                                 $blockcontent $stdtemplateblock->getContent();
  1076.                                 $block["settings"] = $blockcontent["settings"];
  1077.                                 $block["components"] = $blockcontent["components"];
  1078.                                 $block["skin"] = $blockcontent["skin"];
  1079.                                 $block["repeatable"] = ($blockcontent["repeatable"] ? $blocksservice->filterPublishedRepeatables($blockcontent["repeatable"]) : array());
  1080.                             }
  1081.                         }
  1082.                     }
  1083.                     
  1084.                     // Check if lazy loading is enabled - skip list processing and render lazy skeleton instead
  1085.                     $isLazyLoadingEnabled $block["block"] === "block_list" 
  1086.                         && isset($block["settings"]["lazy_loading_enabled"]) 
  1087.                         && $block["settings"]["lazy_loading_enabled"
  1088.                         && (!$ajaxCall || !array_key_exists("isAjax"$ajaxCall));
  1089.                     
  1090.                     // DEBUG: Log lazy loading check for block_list (main renderPageContent)
  1091.                     if ($block["block"] === "block_list") {
  1092.                         file_put_contents('/tmp/lazy_debug.log'date('Y-m-d H:i:s') . " MAIN FUNC LAZY CHECK - isLazyLoadingEnabled: " . ($isLazyLoadingEnabled "TRUE" "FALSE") . " | isList: " . (isset($stdsettings["isList"]) && $stdsettings["isList"] ? "TRUE" "FALSE") . " | blockuniqueid: " . ($block["blockuniqueid"] ?? "NOT SET") . " | lazy_enabled_setting: " . (isset($block["settings"]["lazy_loading_enabled"]) ? ($block["settings"]["lazy_loading_enabled"] ? "TRUE" "FALSE") : "NOT SET") . "\n"FILE_APPEND);
  1093.                     }
  1094.                     
  1095.                     if (isset($stdsettings["isList"]) && $stdsettings["isList"] && $renderlistblocks && !$isLazyLoadingEnabled) {
  1096.                         //it's a list
  1097.                         //get the content_type, template and the category from block components
  1098.                         //get x category childs and render with selected skin
  1099.                         $iscacheable false;
  1100.                         // Use content_type_list instead of the old content_type field
  1101.                         $contentType null;
  1102.                         if (isset($block["components"]["content_type_list"]) && !empty($block["components"]["content_type_list"])) {
  1103.                             // For multiple content types, use the first one for compatibility
  1104.                             $contentTypeId is_array($block["components"]["content_type_list"])
  1105.                                 ? $block["components"]["content_type_list"][0]
  1106.                                 : $block["components"]["content_type_list"];
  1107.                             $contentType $this->entityManager->getRepository(StdContentTypes::class)->findOneById($contentTypeId);
  1108.                         }
  1109.                         $levels = (isset($block["components"]["levels"]) ? $block["components"]["levels"] : 1);
  1110.                         $contentTypeList = (isset($block["components"]["content_type_list"]) ? $block["components"]["content_type_list"] : array());
  1111.                         $block["components"]['categoryContent'] = null;
  1112.                         ($categoryPagePage $this->entityManager->getRepository(StdPagesPages::class)->find($block["components"]["category"]))
  1113.                         && ($categoryContent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(['pageId' => $categoryPagePage->getPageId(), 'languageCode' => $this->locale]))
  1114.                         && $block["components"]['categoryContent'] = $categoryContent;
  1115.                         $queryCategoriesRaw $this->request->query->all('category');
  1116.                         $queryCategories is_array($queryCategoriesRaw) ? array_values(array_filter(array_map('intval'$queryCategoriesRaw))) : [];
  1117.                         if (!is_array($queryCategoriesRaw) && $queryCategoriesRaw !== null && $queryCategoriesRaw !== '') {
  1118.                             $queryCategories = [(int)$queryCategoriesRaw];
  1119.                         }
  1120.                         if (!empty($queryCategories)) {
  1121.                             $relationIds = [];
  1122.                             foreach ($queryCategories as $pageId) {
  1123.                                 $pagesRelations $this->entityManager->getRepository(StdPagesPages::class)->findBy([
  1124.                                     'pageId' => $pageId
  1125.                                 ]);
  1126.                                 foreach ($pagesRelations as $pagesRelation) {
  1127.                                     $relationIds[] = $pagesRelation->getId();
  1128.                                 }
  1129.                             }
  1130.                             $queryCategories = !empty($relationIds) ? $relationIds $queryCategories;
  1131.                         }
  1132.                         $filterCurrentPage false;
  1133.                         if ($block["components"]["category"] == "-1") {
  1134.                             $canurl $this->entityManager->getRepository(StdFriendlyUrl::class)->findBy(["pageId" => $page->getId(), "url" => $this->request->getPathInfo(), "languageCode" => $this->locale]);
  1135.                             if (!$canurl) {
  1136.                                 $canurl $this->entityManager->getRepository(StdFriendlyUrl::class)->findBy(["pageId" => $page->getId(), "isCanonical" => 1"languageCode" => $this->locale]);
  1137.                             }
  1138.                             if ($canurl) {
  1139.                                 $relationid $canurl[0]->getRelationId() ?? -1;
  1140.                             } else {
  1141.                                 $relationid = -1;
  1142.                             }
  1143.                         } else if($block["components"]["category"] == "-2") {
  1144.                             $rootCategory "Temas";
  1145.                             $rootCategoryPage $this->entityManager->getRepository(StdPages::class)->findOneBy(['machineName' => strtolower($rootCategory)]);
  1146.                             if (!$rootCategoryPage) {
  1147.                                 $rootCategoryContent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(['title' => $rootCategory'languageCode' => $this->locale]);
  1148.                                 if ($rootCategoryContent) {
  1149.                                     $rootCategoryPage $rootCategoryContent->getPageId();
  1150.                                 }
  1151.                             }
  1152.                             $filteredCategoriesUnderTemas = [];
  1153.                             if ($rootCategoryPage) {
  1154.                                 $rootRelation $this->entityManager->getRepository(StdPagesPages::class)->findOneBy([
  1155.                                     'pageId' => $rootCategoryPage->getId(),
  1156.                                     'relationId' => 0
  1157.                                 ]);
  1158.                                 if ($rootRelation) {
  1159.                                     $currentPageCategories $this->entityManager->getRepository(StdPagesPages::class)->findBy(['pageId' => $page->getId()]);
  1160.                                     foreach($currentPageCategories as $category) {
  1161.                                         $catRelation $this->entityManager->getRepository(StdPagesPages::class)->find($category->getRelationId());
  1162.                                         if ($catRelation) {
  1163.                                             $currentRelation $catRelation;
  1164.                                             $isUnderTemas false;
  1165.                                             while ($currentRelation) {
  1166.                                                 if ($currentRelation->getPageId()->getId() == $rootCategoryPage->getId()) {
  1167.                                                     $isUnderTemas true;
  1168.                                                     break;
  1169.                                                 }
  1170.                                                 if ($currentRelation->getRelationId() == 0) {
  1171.                                                     break;
  1172.                                                 }
  1173.                                                 $currentRelation $this->entityManager->getRepository(StdPagesPages::class)->find($currentRelation->getRelationId());
  1174.                                             }
  1175.                                             if ($isUnderTemas) {
  1176.                                                 $filteredCategoriesUnderTemas[] = $category;
  1177.                                             }
  1178.                                         }
  1179.                                     }
  1180.                                 }
  1181.                             }
  1182.                             if (!empty($filteredCategoriesUnderTemas)) {
  1183.                                 $relationid $filteredCategoriesUnderTemas[0]->getRelationId();
  1184.                             } else {
  1185.                                 $relationid = -1;
  1186.                             }
  1187.                             $filterCurrentPage true;
  1188.                         } else {
  1189.                             $relationid $block["components"]["category"];
  1190.                         }
  1191.                         // Build locationTags: cookie (if present) takes precedence and is placed first
  1192.                         $locationTags = [];
  1193.                         $cookieLocationId $this->request->cookies->get('CloseToYou-Location');
  1194.                         $sessionLocations $this->request->getSession()->get('close_location_ids');
  1195.                         if ($cookieLocationId) {
  1196.                             $locationTags[] = (int)$cookieLocationId;
  1197.                             if (is_array($sessionLocations)) {
  1198.                                 foreach ($sessionLocations as $locId) {
  1199.                                     if ($locId != $cookieLocationId) {
  1200.                                         $locationTags[] = $locId;
  1201.                                     }
  1202.                                 }
  1203.                             }
  1204.                         } elseif (!empty($sessionLocations)) {
  1205.                             $locationTags $sessionLocations;
  1206.                         }
  1207.                         $effectiveRelationId = !empty($queryCategories) ? $queryCategories $relationid;
  1208.                         $relations $this->entityManager->getRepository(StdPagesPages::class)->getNChildsOfRelation([
  1209.                             "filterCurrentPage" => $filterCurrentPage $page null,
  1210.                             "relation_id" => $effectiveRelationId,
  1211.                             "start_item" => isset($block["components"]["start_item"]) ? $block["components"]["start_item"] : null,
  1212.                             "limit" => $block["components"]["limit"],
  1213.                             "template" => $block["components"]["template"],
  1214.                             "order" => $block["components"]["order"],
  1215.                             "order_by" => $block["components"]["order_by"] ?? '',
  1216.                             "levels" => $levels,
  1217.                             "paginate" => $block["components"]["paginate"],
  1218.                             "content_type_list" => $contentTypeList,
  1219.                             "ajaxFilter" => $ajaxCall,
  1220.                             "tags" => ($block["components"]["tags"] ?? ""),
  1221.                             "page" => $pagenumber,
  1222.                             "paginator" => $this->paginator,
  1223.                             "language_code" => $this->locale,
  1224.                             "roles" => ($this->security->getUser() instanceof StdWebUsers $this->security->getUser()->getRoles() : null),
  1225.                             "locationTags" => $locationTags
  1226.                         ]);
  1227.                         $resultlist "";
  1228.                         $resultlistjs "";
  1229.                         $total count($relations);
  1230.                         $index 0;
  1231.                         if (!isset($locationValues)) {
  1232.                             try {
  1233.                                 $locationValues $this->entityManager->getRepository(StdDomainsValues::class)
  1234.                                     ->createQueryBuilder('dv')
  1235.                                     ->leftJoin('dv.geoMap''gm')
  1236.                                     ->andWhere('dv.isActive = 1')
  1237.                                     ->andWhere('gm.type IN (:locTypes)')
  1238.                                     ->setParameter('locTypes', ['municipality''district'])
  1239.                                     ->addOrderBy('dv.description''ASC')
  1240.                                     ->getQuery()
  1241.                                     ->getResult();
  1242.                             } catch (\Throwable $e) {
  1243.                                 $locationValues = [];
  1244.                             }
  1245.                         }
  1246.                         $top10IdsPages = [];
  1247.                         $hasProgramsContentType false;
  1248.                         if (!empty($contentTypeList) && is_array($contentTypeList)) {
  1249.                             $programsContentType $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['machineName' => 'programs']);
  1250.                             if ($programsContentType) {
  1251.                                 $hasProgramsContentType in_array($programsContentType->getId(), $contentTypeList);
  1252.                             }
  1253.                         }
  1254.                         if ($hasProgramsContentType) {
  1255.                             $top10IdsPages $blocksservice->fetchProgramsTop10Ids(
  1256.                                 $this->entityManager
  1257.                             );
  1258.                         }
  1259.                         foreach ($relations as $stdpagespages) {
  1260.                             $relationcontent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $stdpagespages["page_id"], "languageCode" => $this->locale]);
  1261.                             //render
  1262.                             $friendlyUrl "";
  1263.                             if ($relationcontent) {
  1264.                                 $fields $this->prepareVariables($relationcontent);
  1265.                                 // Check if this specific item has 'programs' content type and is in a block that includes programs
  1266.                                 if ($hasProgramsContentType && $relationcontent->getPageId() && $relationcontent->getPageId()->getContentType() && $relationcontent->getPageId()->getContentType()->getMachineName() === 'programs') {
  1267.                                     // verifica se o page_id atual está na lista de Top10 fixada no bloco
  1268.                                     $fields["isTop10"] = in_array(
  1269.                                         (int)$relationcontent->getPageId()->getId(),
  1270.                                         $top10IdsPages,
  1271.                                         true
  1272.                                     );
  1273.                                 }
  1274.                                 // get friendly Url
  1275.                                 $friendlyUrlObj $this->findFriendlyUrlByPageId($relationcontent->getPageId()->getId(), $this->entityManager$this->locale);
  1276.                                 $friendlyUrl $friendlyUrlObj $friendlyUrlObj->getUrl() : "";
  1277.                                 $relationPageId $relationcontent->getPageId();
  1278.                                 if ($relationPageId->getPublishDate())
  1279.                                     $publishDatePage = new DateTime($relationPageId->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  1280.                                 if ($relationPageId->getExpireDate())
  1281.                                     $expireDatePage = new DateTime($relationPageId->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  1282.                             } else {
  1283.                                 $fields = array();
  1284.                             }
  1285.                             // Get the actual content type of this specific item
  1286.                             $itemContentType null;
  1287.                             if ($relationcontent && $relationcontent->getPageId()) {
  1288.                                 $itemContentType $relationcontent->getPageId()->getContentType();
  1289.                             }
  1290.                             // Handle skin selection based on the item's content type
  1291.                             $selectedSkin 'default';
  1292.                             $skinMapping = []; // Map content type machine names to skins
  1293.                             if (array_key_exists("skin"$block["components"]) && $block["components"]["skin"]) {
  1294.                                 $skinValue $block["components"]["skin"];
  1295.                                 if (is_array($skinValue) && !empty($skinValue)) {
  1296.                                     // Multiple skins - need to map to content types
  1297.                                     // For now, we'll use a simple mapping: first skin for first content type, etc.
  1298.                                     $contentTypeList $block["components"]["content_type_list"] ?? [];
  1299.                                     if (is_array($contentTypeList) && !empty($contentTypeList)) {
  1300.                                         for ($i 0$i min(count($contentTypeList), count($skinValue)); $i++) {
  1301.                                             $ctId $contentTypeList[$i];
  1302.                                             $skin $skinValue[$i];
  1303.                                             $ct $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['id' => $ctId]);
  1304.                                             if ($ct) {
  1305.                                                 $skinMapping[$ct->getMachineName()] = $skin;
  1306.                                             }
  1307.                                         }
  1308.                                     }
  1309.                                     // Use mapped skin or fallback to first skin
  1310.                                     if ($itemContentType && isset($skinMapping[$itemContentType->getMachineName()])) {
  1311.                                         $selectedSkin $skinMapping[$itemContentType->getMachineName()];
  1312.                                     } else {
  1313.                                         $selectedSkin reset($skinValue); // Fallback to first skin
  1314.                                     }
  1315.                                 } elseif (is_string($skinValue)) {
  1316.                                     $selectedSkin $skinValue;
  1317.                                 }
  1318.                             }
  1319.                             // Template selection logic with fallbacks
  1320.                             if (!empty($itemContentType)) {
  1321.                                 // 1st priority: Specific skin template for this content type
  1322.                                 if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.' $selectedSkin '.html.twig')) {
  1323.                                     $skinparam 'content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.' $selectedSkin '.html.twig';
  1324.                                 }
  1325.                                 // 2nd priority: Content type default template
  1326.                                 elseif ($this->container->get('twig')->getLoader()->exists('content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.default.html.twig')) {
  1327.                                     $skinparam 'content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.default.html.twig';
  1328.                                 }
  1329.                                 // 3rd priority: Global fallback template
  1330.                                 else {
  1331.                                     $skinparam 'content-types/default/content_type.default.html.twig';
  1332.                                 }
  1333.                             }
  1334.                             // Handle JS skin template with same fallback logic
  1335.                             if (!empty($itemContentType)) {
  1336.                                 // 1st priority: Specific skin JS template
  1337.                                 if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.' $selectedSkin '.js.twig')) {
  1338.                                     $skinjsparam 'content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.' $selectedSkin '.js.twig';
  1339.                                 }
  1340.                                 // 2nd priority: Content type default JS template
  1341.                                 elseif ($this->container->get('twig')->getLoader()->exists('content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.default.js.twig')) {
  1342.                                     $skinjsparam 'content-types/' $itemContentType->getMachineName() . '/' $itemContentType->getMachineName() . '.default.js.twig';
  1343.                                 }
  1344.                                 // 3rd priority: Global fallback JS template
  1345.                                 else {
  1346.                                     $skinjsparam 'content-types/default/content_type.default.js.twig';
  1347.                                 }
  1348.                             } else {
  1349.                                 $skinjsparam 'content-types/default/content_type.default.js.twig';
  1350.                             }
  1351.                             $content = [];
  1352.                             if (isset($stdsettings["renderPageBlocks"]) && $stdsettings["renderPageBlocks"]) {
  1353.                                 $renderblocks false;
  1354.                                 if (isset($stdsettings["renderListBlocks"]) && $stdsettings["renderListBlocks"]) {
  1355.                                     $renderblocks true;
  1356.                                 }
  1357.                                 $content $this->renderPageContent($pagenumber$fields$relationcontent->getPageId(), $relationcontentnull$renderblocks);
  1358.                             } else {
  1359.                                 $content["html"] = "";
  1360.                                 $content["js"] = "";
  1361.                             }
  1362.                             $headercontent = [
  1363.                                 "publishdate" => ($publishDatePage != null $publishDatePage->format('Y-m-d H:i:s') : null),
  1364.                                 "expiredate" => ($expireDatePage != null $expireDatePage->format('Y-m-d H:i:s') : null),
  1365.                                 "lastupdate" => ($page->getUpdatedDate() != null $page->getUpdatedDate()->format('Y-m-d H:i:s') : null),
  1366.                                 "createdby" => $page->getCreatedBy()->getName(),
  1367.                                 "order" => $page->getOrderValue()
  1368.                             ];
  1369.                             $payload array_merge([
  1370.                                 "headercontent" => $headercontent,
  1371.                                 "id" => ($relationcontent $relationcontent->getPageId()->getId() : null),
  1372.                                 "page" => $relationcontent $relationcontent->getPageId() : null,
  1373.                                 "relationid" => $stdpagespages["relation_id"],
  1374.                                 "total" => $total,
  1375.                                 "index" => $index,
  1376.                                 "settings" => $block["settings"],
  1377.                                 "locale" => $this->locale,
  1378.                                 "blockscontent" => $content["html"],
  1379.                                 "blockscontentjs" => $content["js"],
  1380.                                 "pagination" => $relations,
  1381.                                 'friendlyUrl' => $friendlyUrl
  1382.                             ], $fields);
  1383.                             if ($this->container->get('twig')->getLoader()->exists($skinparam))
  1384.                                 $resultlist .= $this->renderView($skinparam$payload);
  1385.                             if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
  1386.                                 $resultlistjs .= $this->renderView($skinjsparam$payload);
  1387.                             $index++;
  1388.                         }
  1389.                         $payload array_merge($variables, [
  1390.                             'settings' => $block["settings"],
  1391.                             'fields' => $block["components"],
  1392.                             'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  1393.                             'blockscontent' => $resultlist,
  1394.                             'blockscontentjs' => $resultlistjs,
  1395.                             'paginator' => $relations,
  1396.                             'location_values' => $locationValues ?? [],
  1397.                             'blockuniqueid' => $block["blockuniqueid"] ?? ""
  1398.                         ]);
  1399.                     } elseif (isset($stdsettings["isFormList"]) && $stdsettings["isFormList"]) {
  1400.                         $forms = array();
  1401.                         // if user is logged get his submitted forms
  1402.                         if (isset($block["components"]) && isset($block["components"]["form_types"]) && $this->getUser() != null) {
  1403.                             // if form_type is empty get all
  1404.                             if ($block["components"]["form_types"] != '') {
  1405.                                 $forms $this->entityManager->getRepository(Forms::class)->findBy(array("formType" => $block["components"]["form_types"], "netuserId" => $this->getUser()->getId()));
  1406.                             } else {
  1407.                                 $forms $this->entityManager->getRepository(Forms::class)->findBy(array("netuserId" => $this->getUser()->getId()));
  1408.                             }
  1409.                         }
  1410.                         $payload array_merge($variables, [
  1411.                             'domain' => 'private-area',
  1412.                             'fields' => $block["components"],
  1413.                             'locale' => $this->locale,
  1414.                             'settings' => $block["settings"],
  1415.                             'formedit' => isset($block["components"]["form_edit"]) ? $block["components"]["form_edit"] : '0',
  1416.                             'forms' => $forms]);
  1417.                     } elseif (isset($block["isPage"]) && $block["isPage"]) {
  1418.                         $contentType $this->entityManager->getRepository(StdContentTypes::class)->findOneById($block["components"]["input_type_content_type"]);
  1419.                         $subpageContent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $block["components"]["input_combo_pages"], "languageCode" => $this->locale]);
  1420.                         $fields = array();
  1421.                         if ($subpageContent) {
  1422.                             $fields $this->prepareVariables($subpageContent);
  1423.                             $inputSkin = isset($block["components"]["input_combo_skin"]) && $block["components"]["input_combo_skin"] != "" $block["components"]["input_combo_skin"] : "default";
  1424.                             if ($this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.html.twig')) {
  1425.                                 $skinparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.html.twig';
  1426.                             } else {
  1427.                                 $skinparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.html.twig';
  1428.                             }
  1429.                             if ($this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.js.twig')) {
  1430.                                 $skinjsparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.js.twig';
  1431.                             } else {
  1432.                                 $skinjsparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.js.twig';
  1433.                             }
  1434.                             if ($contentType->getMachineName() == "forms" && $this->request->query->get("id")) {
  1435.                                 $formData $this->entityManager->getRepository(Forms::class)->findOneById($this->request->query->get("id"));
  1436.                                 if ($formData) {
  1437.                                     $fields["formdata"] = $formData->getContent();
  1438.                                 }
  1439.                             }
  1440.                             $content $this->renderPageContent($pagenumber$fields$subpageContent->getPageId(), $subpageContentnull);
  1441.                             // isset($content['webpackEntries']) && $webpackEntries = array_merge($webpackEntries, $content['webpackEntries']);
  1442.                             isset($content['cookies']) && $cookies array_merge($cookies$content['cookies']);
  1443.                             if ($contentType->getMachineName() == "forms") {
  1444.                                 /** edit parameter
  1445.                                  * 1-edit
  1446.                                  * 0-resubmit
  1447.                                  */
  1448.                                 // If id and edit parameters exist get the form from id parameter and current logged user
  1449.                                 if ($this->request->query->get("id") !== null && $this->request->query->get("edit") !== null) {
  1450.                                     $form $this->entityManager->getRepository(Forms::class)->findOneBy(array("netuserId" => $this->security->getUser(), "id" => $this->request->query->get("id")));
  1451.                                     // if the form doesnt belong to the current user throw error
  1452.                                     if ($form === null) {
  1453.                                         throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  1454.                                     } else {
  1455.                                         $formContent $form->getContent();
  1456.                                         // if form_id is setted find form based on that id
  1457.                                         if ($formContent && isset($formContent["form_id"])) {
  1458.                                             $formPage $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $formContent["form_id"], "languageCode" => $this->locale]);
  1459.                                             if ($formPage) {
  1460.                                                 $formPageContent $formPage->getContent();
  1461.                                                 if ($formPageContent && isset($formPageContent["form_allow_edit"]) && isset($formPageContent["form_allow_resubmit"])) {
  1462.                                                     //if the edit parameter is 1 and form doesnt allow edition throw error
  1463.                                                     if ($this->request->query->get("edit") == && $formPageContent["form_allow_edit"] == 0) {
  1464.                                                         throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  1465.                                                     }
  1466.                                                     //if the edit parameter is 0 and form doesnt allow submission throw error
  1467.                                                     if ($this->request->query->get("edit") == && $formPageContent["form_allow_resubmit"] == 0) {
  1468.                                                         throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  1469.                                                     }
  1470.                                                 } else {
  1471.                                                     throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  1472.                                                 }
  1473.                                             } else {
  1474.                                                 throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  1475.                                             }
  1476.                                         } else {
  1477.                                             throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  1478.                                         }
  1479.                                     }
  1480.                                 }
  1481.                                 $form $this->createForm(StdDynamicForm::class);
  1482.                                 $fieldsvariables array_merge($variables$this->prepareVariables($subpageContent));
  1483.                                 $rulesAndMessages $this->getRulesAndMessagesForm($form_content["fields"]);
  1484.                                 $payload array_merge([
  1485.                                     'settings' => $block["settings"],
  1486.                                     'fields' => $block["components"],
  1487.                                     'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  1488.                                     'blockscontent' => $content["html"],
  1489.                                     'blockscontentjs' => $content["js"],
  1490.                                     'form' => $form->createView(),
  1491.                                     'messages' => $rulesAndMessages["messages"],
  1492.                                     'rules' => $rulesAndMessages["rules"],
  1493.                                     // need this original page id (not the form id as pageid) to save as form content, so block submited forms can have the access to original page url
  1494.                                     'originalpageid' => $page->getId()
  1495.                                 ], $fieldsvariables);
  1496.                             } else {
  1497.                                 $payload array_merge([
  1498.                                     'settings' => $block["settings"],
  1499.                                     'fields' => $block["components"],
  1500.                                     'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  1501.                                     'blockscontent' => $content["html"],
  1502.                                     'blockscontentjs' => $content["js"],
  1503.                                     // need this original page id (not the form id as pageid) to save as form content, so block submited forms can have the access to original page url
  1504.                                     'originalpageid' => $page->getId()
  1505.                                 ], $fields);
  1506.                             }
  1507.                             if ($this->container->get('twig')->getLoader()->exists($skinparam))
  1508.                                 $result .= $this->renderView($skinparam$payload);
  1509.                             if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
  1510.                                 $resultjs .= $this->renderView($skinjsparam$payload);
  1511.                         }
  1512.                     } elseif (isset($stdsettings["isWebUsersResetPassword"]) && $stdsettings["isWebUsersResetPassword"]) {
  1513.                         $recovery $this->request->get("_recoverykey");
  1514.                         $payload array_merge($variables, [
  1515.                             'settings' => $block["settings"],
  1516.                             'fields' => $block["components"]
  1517.                         ]);
  1518.                         if ($recovery && ($netuser $this->entityManager->getRepository(StdWebUsers::class)->findOneBy(["passwordrecovery" => $recovery]))) {
  1519.                             $recoverymodel = new StdWebUsersRecoveryPasswordFormModel();
  1520.                             $form $this->createForm(StdWebUsersRecoveryPasswordFormType::class, $recoverymodel);
  1521.                             $errors $form->handleRequest($this->request);
  1522.                             if ($form->isSubmitted() && $form->isValid()) {
  1523.                                 try {
  1524.                                     $password $form->get('plainPassword')->getData();
  1525.                                     $netuser->setPasswordrecovery("");
  1526.                                     $dispatchStdWebUsersActivatedEvent = !$netuser->getIsActive();
  1527.                                     $netuser->setIsActive(1);
  1528.                                     $netuser->setPassword($this->passwordHasher->hashPassword(
  1529.                                         $netuser,
  1530.                                         $password
  1531.                                     ));
  1532.                                     $this->entityManager->persist($netuser);
  1533.                                     $this->entityManager->flush();
  1534.                                     if ($dispatchStdWebUsersActivatedEvent) {
  1535.                                         $event = new StdWebUsersActivatedEvent($netuser);
  1536.                                         $this->dispatcher->dispatch($eventStdWebUsersActivatedEvent::NAME);
  1537.                                     }
  1538.                                     $this->addFlash('success'$this->translator->trans("passwordchangedsuccess", [], 'webusers'));
  1539.                                 } catch (Exception $e) {
  1540.                                     $this->addFlash('error'$this->translator->trans("passwordchangederror", [], 'webusers'));
  1541.                                     $payload array_merge($payload, [
  1542.                                         'formelement' => $form->createView(),
  1543.                                         'webuser' => $netuser
  1544.                                     ]);
  1545.                                 }
  1546.                             } else {
  1547.                                 $payload array_merge($payload, [
  1548.                                     'formelement' => $form->createView(),
  1549.                                     'webuser' => $netuser
  1550.                                 ]);
  1551.                             }
  1552.                         } else {
  1553.                             $this->addFlash('error'$this->translator->trans("passwordchangedlinkexpired", [], 'webusers'));
  1554.                         }
  1555.                     } elseif (isset($stdsettings["isWebUsersRegistration"]) && $stdsettings["isWebUsersRegistration"]) {
  1556.                         $activation $this->request->get("_activationkey");
  1557.                         if ($activation) {
  1558.                             if (!$this->request->isMethod("GET") && !$this->request->isMethod("POST"))
  1559.                                 throw $this->createNotFoundException('The page does not exist');
  1560.                             $netuser $this->entityManager->getRepository(StdWebUsers::class)->findOneBy(["activationkey" => $activation]);
  1561.                             if ($netuser) {
  1562.                                 $netuser->setActivationKey('');
  1563.                                 $netuser->setIsActive(1);
  1564.                                 $this->entityManager->persist($netuser);
  1565.                                 $event = new StdWebUsersActivatedEvent($netuser);
  1566.                                 $this->dispatcher->dispatch($eventStdWebUsersActivatedEvent::NAME);
  1567.                                 $this->entityManager->flush();
  1568.                                 //send welcome email
  1569.                                 $repNotifications $this->entityManager->getRepository(StdNotifications::class);
  1570.                                 $userNotification $repNotifications->findOneBy(["machineName" => "webuserwelcome""languageCode" => $this->locale]);
  1571.                                 $emailContent $userNotification $userNotification->getEmailBody() : "";
  1572.                                 $subject $userNotification $userNotification->getEmailSubject() : "";
  1573.                                 $twig $this->container->get('twig');
  1574.                                 $template Functions::twig_template_from_string($twig'{% extends "admin/emails/base.html.twig" %}{% block content %} ' $emailContent ' {% endblock %}');
  1575.                                 $body $template->render(["webuser" => $netuser"locale" => $this->locale]);
  1576.                                 $template Functions::twig_template_from_string($twightml_entity_decode($subjectENT_QUOTES ENT_XML1'UTF-8'));
  1577.                                 $subject $template->render(["webuser" => $netuser]);
  1578.                                 if (!Functions::sendEmail($this->mailer"""", [$netuser->getEmail()], [], [], $subject$bodynull$this->entityManager)) {
  1579.                                     $this->addFlash('error'$this->translator->trans("erroroccurred", [], 'studio'));
  1580.                                 } else {
  1581.                                     $this->addFlash('success'$this->translator->trans("registeractivated", [], 'register'));
  1582.                                 }
  1583.                             } else {
  1584.                                 throw $this->createNotFoundException('The page does not exist');
  1585.                             }
  1586.                             $payload array_merge($variables, [
  1587.                                 'settings' => $block["settings"],
  1588.                                 'fields' => $block["components"],
  1589.                                 'activation' => true
  1590.                             ]);
  1591.                         } else {
  1592.                             $netuser = new StdWebUsersRegistrationFormModel();
  1593.                             $formNetuser $this->createForm(StdWebUsersRegistrationFormType::class, $netuser, ["locale" => $this->locale"entitymanager" => $this->entityManager"translator" => $this->translator"address1" => $block["components"]["address1"], "address2" => $block["components"]["address2"]]);
  1594.                             $formNetuser->handleRequest($this->request);
  1595.                             if ($formNetuser->isSubmitted() && $formNetuser->isValid()) {
  1596.                                 $dataform $this->request->request->all();
  1597.                                 $recaptchaToken $dataform["recaptchatoken"];
  1598.                                 $erroroccurred false;
  1599.                                 if ($recaptchaToken != 0) {
  1600.                                     $recaptcha = new ReCaptcha(Functions::getConfig("GOOGLE_RECAPTCHA_SECRET"""$this->entityManager), new \ReCaptcha\RequestMethod\CurlPost());
  1601.                                     $recaptchaRes $recaptcha
  1602.                                         ->setScoreThreshold(Functions::getConfig("GOOGLE_RECAPTCHA_SCORE_THRESHOLD"""$this->entityManager) ?? "0.5")
  1603.                                         ->verify($recaptchaToken);
  1604.                                     if (!$recaptchaRes->isSuccess()) {
  1605.                                         $erroroccurred true;
  1606.                                         $this->addFlash('error'$this->translator->trans("recaptchaerror", [], 'studio'));
  1607.                                     }
  1608.                                 } else {
  1609.                                     $erroroccurred true;
  1610.                                     $this->addFlash('error'$this->translator->trans("recaptchaerror", [], 'studio'));
  1611.                                 }
  1612.                                 if (!$erroroccurred) {
  1613.                                     $netuserRegistration $formNetuser->getData();
  1614.                                     $olduser $this->entityManager->getRepository(StdWebUsers::class)->findOneBy(["email" => $netuserRegistration->email"isActive" => 0]);
  1615.                                     if ($olduser) {
  1616.                                         $this->entityManager->remove($olduser);
  1617.                                         $oldaddresses $this->entityManager->getRepository(StdWebUsersAddresses::class)->findBy(["webuser" => $olduser]);
  1618.                                         foreach ($oldaddresses as $oldaddress) {
  1619.                                             $this->entityManager->remove($oldaddress);
  1620.                                         }
  1621.                                         $this->entityManager->flush();
  1622.                                     }
  1623.                                     $date = new DateTime();
  1624.                                     $activationkey md5($netuserRegistration->email $date->format('Y-m-d H:i:s'));
  1625.                                     $netuser = new StdWebUsers();
  1626.                                     $netuser->setName($netuserRegistration->name);
  1627.                                     $netuser->setInfo($this->request->request->get("info"));
  1628.                                     $netuser->setEmail($netuserRegistration->email);
  1629.                                     $netuser->setUsername($netuserRegistration->email);
  1630.                                     $netuser->setPhone($netuserRegistration->phone);
  1631.                                     $netuser->setMobile($netuserRegistration->mobile);
  1632.                                     $netuser->setVat($netuserRegistration->vat);
  1633.                                     $netuser->setTermsAcceptedAt(new DateTime());
  1634.                                     $defaultroles $this->entityManager->getRepository(StdWebRoles::class)->findBy(["isDefault" => true"isActive" => true]);
  1635.                                     $netuser->setRoles($defaultroles);
  1636.                                     if ($netuserRegistration->facebookId != "") {
  1637.                                         $netuser->setFacebookId($netuserRegistration->facebookId);
  1638.                                         $netuser->setFacebookIntegration(true);
  1639.                                         $netuser->setPassword($this->passwordHasher->hashPassword(
  1640.                                             $netuser,
  1641.                                             Functions::generateString(16)
  1642.                                         ));
  1643.                                     } else {
  1644.                                         $netuser->setPassword($this->passwordHasher->hashPassword(
  1645.                                             $netuser,
  1646.                                             $netuserRegistration->plainPassword
  1647.                                         ));
  1648.                                     }
  1649.                                     if ($block["components"]["activation"]) {
  1650.                                         $netuser->setActivationkey($activationkey);
  1651.                                         $netuser->setIsActive(0);
  1652.                                         $event = new StdWebUsersRegisteredEvent($netuser);
  1653.                                         $this->dispatcher->dispatch($eventStdWebUsersRegisteredEvent::NAME);
  1654.                                     } else {
  1655.                                         $netuser->setIsActive(1);
  1656.                                         $event = new StdWebUsersRegisteredEvent($netuser);
  1657.                                         $this->dispatcher->dispatch($eventStdWebUsersRegisteredEvent::NAME);
  1658.                                         $event = new StdWebUsersActivatedEvent($netuser);
  1659.                                         $this->dispatcher->dispatch($eventStdWebUsersActivatedEvent::NAME);
  1660.                                     }
  1661.                                     $this->entityManager->persist($netuser);
  1662.                                     $this->entityManager->flush();
  1663.                                     if ($block["components"]["address1"]) {
  1664.                                         $address1 = new StdWebUsersAddresses();
  1665.                                         $address1->setName($netuserRegistration->address1Name);
  1666.                                         $address1->setAddressLine1($netuserRegistration->address1AddressLine1);
  1667.                                         $address1->setZipCode1($netuserRegistration->address1ZipCode1);
  1668.                                         // $address1->setZipCode2($netuserRegistration->address1ZipCode2);
  1669.                                         $address1->setPhone($netuserRegistration->address1Phone);
  1670.                                         $address1->setMobile($netuserRegistration->address1Mobile);
  1671.                                         $address1->setCity($netuserRegistration->address1City);
  1672.                                         $address1->setCountry($netuserRegistration->address1Country->getMachineName());
  1673.                                         $address1->setIsBilling(1);
  1674.                                         $address1->setIsDefault(1);
  1675.                                         $address1->setWebuser($netuser);
  1676.                                         $this->entityManager->persist($address1);
  1677.                                         $this->entityManager->flush();
  1678.                                     }
  1679.                                     if ($block["components"]["address2"]) {
  1680.                                         $address2 = new StdWebUsersAddresses();
  1681.                                         $address2->setName($netuserRegistration->address2Name);
  1682.                                         $address2->setAddressLine1($netuserRegistration->address2AddressLine1);
  1683.                                         $address2->setZipCode1($netuserRegistration->address2ZipCode1);
  1684.                                         // $address2->setZipCode2($netuserRegistration->address2ZipCode2);
  1685.                                         $address2->setPhone($netuserRegistration->address2Phone);
  1686.                                         $address2->setMobile($netuserRegistration->address2Mobile);
  1687.                                         $address2->setCity($netuserRegistration->address2City);
  1688.                                         $address2->setCountry($netuserRegistration->address2Country->getMachineName());
  1689.                                         $address2->setIsBilling(0);
  1690.                                         $address2->setIsDefault(0);
  1691.                                         $address2->setWebuser($netuser);
  1692.                                         $this->entityManager->persist($address2);
  1693.                                         $this->entityManager->flush();
  1694.                                     }
  1695.                                     $repNotifications $this->entityManager->getRepository(StdNotifications::class);
  1696.                                     if ($block["components"]["activation"]) {
  1697.                                         $activationlink $this->request->getUri();
  1698.                                         if (strpos($activationlink'?') === false) {
  1699.                                             $activationlink .= '?_activationkey=' $activationkey;
  1700.                                         } else {
  1701.                                             $activationlink .= '&_activationkey=' $activationkey;
  1702.                                         }
  1703.                                         $dataform["activationlink"] = $activationlink;
  1704.                                         $userNotification $repNotifications->findOneBy(["machineName" => "webuseractivation""languageCode" => $this->locale]);
  1705.                                     } else {
  1706.                                         $userNotification $repNotifications->findOneBy(["machineName" => "webuserwelcome""languageCode" => $this->locale]);
  1707.                                     }
  1708.                                     $emailContent $userNotification $userNotification->getEmailBody() : "";
  1709.                                     $subject $userNotification $userNotification->getEmailSubject() : "";
  1710.                                     $twig $this->container->get('twig');
  1711.                                     $template Functions::twig_template_from_string($twig'{% extends "admin/emails/base.html.twig" %}{% block content %} ' $emailContent ' {% endblock %}');
  1712.                                     $body $template->render(array_merge($dataform, ["webuser" => $netuser"locale" => $this->locale]));
  1713.                                     $template Functions::twig_template_from_string($twightml_entity_decode($subjectENT_QUOTES ENT_XML1'UTF-8'));
  1714.                                     $subject $template->render(array_merge($dataform, ["webuser" => $netuser]));
  1715.                                     if (!Functions::sendEmail($this->mailer"""", [$netuser->getEmail()], [], [], $subject$bodynull$this->entityManager)) {
  1716.                                         if ($block["components"]["address1"]) {
  1717.                                             $this->entityManager->remove($address1);
  1718.                                         }
  1719.                                         if ($block["components"]["address2"]) {
  1720.                                             $this->entityManager->remove($address2);
  1721.                                         }
  1722.                                         $this->entityManager->remove($netuser);
  1723.                                         $this->entityManager->flush();
  1724.                                         $this->addFlash('error'$this->translator->trans("erroroccurred", [], 'studio'));
  1725.                                     } else {
  1726.                                         $this->addFlash('success'$this->translator->trans("registersuccess", [], 'register'));
  1727.                                         if ($block["components"]["redirectto"]) {
  1728.                                             throw new RedirectException(new RedirectResponse('/' trim($block['components']['redirectto'], '/')));
  1729.                                         }
  1730.                                         //clean form fields after submission
  1731.                                         unset($netuser);
  1732.                                         unset($formNetuser);
  1733.                                         $netuser = new StdWebUsersRegistrationFormModel();
  1734.                                         $formNetuser $this->createForm(StdWebUsersRegistrationFormType::class, $netuser, ["locale" => $this->locale"entitymanager" => $this->entityManager"translator" => $this->translator"address1" => $block["components"]["address1"], "address2" => $block["components"]["address2"]]);
  1735.                                     }
  1736.                                 }
  1737.                             }
  1738.                             $payload array_merge($variables, [
  1739.                                 'settings' => $block["settings"],
  1740.                                 'fields' => $block["components"],
  1741.                                 'activation' => false,
  1742.                                 'formelement' => $formNetuser->createView()
  1743.                             ]);
  1744.                         }
  1745.                     } elseif (isset($stdsettings["isWebUsersLogin"]) && $stdsettings["isWebUsersLogin"]) {
  1746.                         $payload array_merge($variables, [
  1747.                             'settings' => $block["settings"],
  1748.                             'fields' => $block["components"],
  1749.                         ]);
  1750.                         if (($webUser $this->security->getUser()) && ($webUser instanceof StdWebUsers) && $block['components']['force_redirect_when_logged']) {
  1751.                             throw new RedirectException(new RedirectResponse('/' trim($block['components']['redirectto'], '/')));
  1752.                         }
  1753.                     } elseif (isset($stdsettings["isWebUserPass"]) && $stdsettings["isWebUserPass"]) {
  1754.                         $payload array_merge($variables, [
  1755.                             'settings' => $block["settings"],
  1756.                             'fields' => $block["components"],
  1757.                         ]);
  1758.                         if (($webUser $this->security->getUser()) && ($webUser instanceof StdWebUsers)) {
  1759.                             $form $this->createForm(StdWebUsersChangePasswordFormType::class, (new StdWebUsersChangePasswordFormModel()), [
  1760.                                 //'action'=>'/pt/xixinha'
  1761.                             ]);
  1762.                             $form->handleRequest($this->request);
  1763.                             if ($form->isSubmitted()) {
  1764.                                 if ($form->isValid()) {
  1765.                                     $formData $form->getData();
  1766.                                     $webUser->setPassword($this->passwordHasher->hashPassword($webUser$formData->password));
  1767.                                     $this->entityManager->persist($webUser);
  1768.                                     $this->entityManager->flush();
  1769.                                     $userNotification $this->entityManager->getRepository(StdNotifications::class)->findOneBy(["machineName" => "webuserpasschanged""languageCode" => $this->locale]);
  1770.                                     $emailContent $userNotification $userNotification->getEmailBody() : "";
  1771.                                     $subject $userNotification $userNotification->getEmailSubject() : "";
  1772.                                     $twig $this->container->get('twig');
  1773.                                     $template Functions::twig_template_from_string($twig'{% extends "admin/emails/base.html.twig" %}{% block content %} ' $emailContent ' {% endblock %}');
  1774.                                     $body $template->render(["webuser" => $webUser"locale" => $this->locale]);
  1775.                                     $template Functions::twig_template_from_string($twightml_entity_decode($subjectENT_QUOTES ENT_XML1'UTF-8'));
  1776.                                     $subject $template->render(["webuser" => $webUser]);
  1777.                                     if (!Functions::sendEmail($this->mailer"""", [$webUser->getEmail()], [], [], $subject$bodynull$this->entityManager)) {
  1778.                                         $this->addFlash('error'$this->translator->trans("changepass.error", [], 'webusers'));
  1779.                                     } else {
  1780.                                         $this->addFlash('success'$this->translator->trans("changepass.success", [], 'webusers'));
  1781.                                     }
  1782.                                 } else {
  1783.                                     $this->addFlash('error'$this->translator->trans("changepass.invaliddata", [], 'webusers'));
  1784.                                 }
  1785.                             }
  1786.                             $payload['webUser'] = $webUser;
  1787.                             $payload['form'] = $form->createView();
  1788.                         }
  1789.                     } elseif (isset($stdsettings["isWebUserDetail"]) && $stdsettings["isWebUserDetail"]) {
  1790.                         $payload array_merge($variables, [
  1791.                             'settings' => $block["settings"],
  1792.                             'fields' => $block["components"],
  1793.                         ]);
  1794.                         if (($webUser $this->security->getUser()) && ($webUser instanceof StdWebUsers)) {
  1795.                             $formFields = [];
  1796.                             isset($block['components']['show_erp_code']) && $block['components']['show_erp_code'] && $formFields[] = ['name' => 'erpcode''required' => false'type' => 'text''disabled' => true];
  1797.                             isset($block['components']['show_name']) && $block['components']['show_name'] && $formFields[] = ['name' => 'name''required' => $block['components']['required_name'], 'type' => 'text''disabled' => !$block['components']['editable']];
  1798.                             isset($block['components']['show_username']) && $block['components']['show_username'] && $formFields[] = ['name' => 'username''required' => $block['components']['required_username'], 'type' => 'text''disabled' => !$block['components']['editable']];
  1799.                             isset($block['components']['show_email']) && $block['components']['show_email'] && $formFields[] = ['name' => 'email''required' => $block['components']['required_email'], 'type' => 'email''disabled' => !$block['components']['editable']];
  1800.                             isset($block['components']['show_phone']) && $block['components']['show_phone'] && $formFields[] = ['name' => 'phone''required' => $block['components']['required_phone'], 'type' => 'text''disabled' => !$block['components']['editable']];
  1801.                             isset($block['components']['show_mobile']) && $block['components']['show_mobile'] && $formFields[] = ['name' => 'mobile''required' => $block['components']['required_mobile'], 'type' => 'text''disabled' => !$block['components']['editable']];
  1802.                             isset($block['components']['show_vat']) && $block['components']['show_vat'] && $formFields[] = ['name' => 'vat''required' => $block['components']['required_vat'], 'type' => 'text''disabled' => !$block['components']['editable']];
  1803.                             if (isset($block['repeatable']) && is_array($block['repeatable']) && !empty($block['repeatable'])) {
  1804.                                 $infoFields = [];
  1805.                                 foreach ($block['repeatable'] as $field) {
  1806.                                     $infoFields[] = ['name' => $field['info_name'], 'required' => $field['info_required'], 'type' => $field['info_type'], 'disabled' => !$block['components']['editable']];
  1807.                                 }
  1808.                                 $formFields[] = ['name' => 'info''type' => 'form''fields' => $infoFields];
  1809.                             }
  1810.                             isset($block['components']['editable']) && $block['components']['editable'] && $formFields[] = ['name' => 'save''required' => true'type' => 'submit'];
  1811.                             $form $this->createForm(StdWebUsersEditFormType::class, ($webUserModel = new StdWebUsersEditFormModel($webUser$formFields)));
  1812.                             $form->handleRequest($this->request);
  1813.                             if ($form->isSubmitted() && $form->isValid()) {
  1814.                                 if (!$this->entityManager->getRepository(StdWebUsers::class)->emailExistsInOtherUser($webUserModel->email$webUser->getId())) {
  1815.                                     $this->entityManager->persist($webUserModel->getUpdatedWebUser());
  1816.                                     $this->entityManager->flush();
  1817.                                     $this->addFlash('success'$this->translator->trans("web_users_detail.saved_successfully", [], 'webusers'));
  1818.                                 } else {
  1819.                                     $this->addFlash('error'$this->translator->trans("web_users_detail.email_exists", [], 'webusers'));
  1820.                                 }
  1821.                             }
  1822.                             //$defaultAddress = $this->entityManager->getRepository(StdWebUsersAddresses::class)->findOneBy(['webuser'=>$webUser->getid(),'isActive'=>1, 'isDefault'=>1]);
  1823.                             $payload['form'] = $form->createView();
  1824.                             $payload['webUser'] = $webUser;
  1825.                             //$payload['defaultAddress'] = $defaultAddress;
  1826.                         }
  1827.                     } elseif (isset($stdsettings['isWebUsersNotifications']) && $stdsettings['isWebUsersNotifications']) {
  1828.                         if (($webuser $this->security->getUser()) && ($webuser instanceof StdWebUsers)) {
  1829.                             $payload['webuser'] = $webuser;
  1830.                         }
  1831.                         $notificationsReceived $this->entityManager->getRepository(StdNotificationsScheduleSent::class)->findBy(['webUser' => $webuser->getId(), 'isViewed' => 0], ['createdDate' => 'DESC']);
  1832.                         $notifications = [];
  1833.                         foreach ($notificationsReceived as $notification) {
  1834.                             $name $notification->getNotification()->getName();
  1835.                             $description $notification->getNotification()->getDescription();
  1836.                             if ($notification->getNotification()->getNotification()) {
  1837.                                 $name $notification->getNotification()->getNotification()->getName();
  1838.                                 $description $notification->getNotification()->getNotification()->getShortDescription();
  1839.                             }
  1840.                             $date $notification->getCreatedDate()->format("Y-m-d H:i:s");
  1841.                             $timestamp strtotime($date);
  1842.                             $secDiffence time() - $timestamp;
  1843.                             $minutes floor($secDiffence 60);
  1844.                             $hours floor($secDiffence 3600);
  1845.                             $days floor($secDiffence 86400);
  1846.                             if ($minutes == 0) {
  1847.                                 $time $this->translator->trans("now", [], 'notifications');
  1848.                             } else if ($minutes 60) {
  1849.                                 if ($minutes 2) {
  1850.                                     $time sprintf("%d " $this->translator->trans("minute", [], 'notifications'), $minutes);
  1851.                                 } else {
  1852.                                     $time sprintf("%d " $this->translator->trans("minutes", [], 'notifications'), $minutes);
  1853.                                 }
  1854.                             } elseif ($hours 24) {
  1855.                                 if ($hours 2) {
  1856.                                     $time sprintf("%d " $this->translator->trans("hour", [], 'notifications'), $hours);
  1857.                                 } else {
  1858.                                     $time sprintf("%d " $this->translator->trans("hours", [], 'notifications'), $hours);
  1859.                                 }
  1860.                             } else {
  1861.                                 if ($days 2) {
  1862.                                     $time sprintf("%d " $this->translator->trans("day", [], 'notifications'), $days);
  1863.                                 } else {
  1864.                                     $time sprintf("%d " $this->translator->trans("days", [], 'notifications'), $days);
  1865.                                 }
  1866.                             }
  1867.                             $type $notification->getType() ? $notification->getType()->getMachineName() : "push_notification";
  1868.                             $type $this->translator->trans($type, [], 'notifications');
  1869.                             $notifications[] = array("id" => $notification->getId(), 'type' => $type'title' => $name'description' => $description'date' => $time);
  1870.                         }
  1871.                         $payload array_merge($variables, [
  1872.                             'settings' => $block["settings"],
  1873.                             'fields' => $block["components"],
  1874.                             'notifications' => $notifications
  1875.                         ], $payload);
  1876.                     } elseif (isset($stdsettings["isWebUsersAddresses"]) && $stdsettings["isWebUsersAddresses"]) {
  1877.                         if (($webuser $this->security->getUser()) && ($webuser instanceof StdWebUsers)) {
  1878.                             $payload['webuser'] = $webuser;
  1879.                         }
  1880.                         $action "";
  1881.                         if ($this->request->isMethod('post')) {
  1882.                             $action $this->request->request->get("_action");
  1883.                             if ($this->request->request->get("std_web_users_addresses_form") !== null) {
  1884.                                 $idaddress $this->request->request->get("std_web_users_addresses_form")["id"];
  1885.                             } else {
  1886.                                 $idaddress $this->request->request->get("id");
  1887.                             }
  1888.                             $address $this->entityManager->getRepository(StdWebUsersAddresses::class)->findOneBy(["id" => $idaddress"webuser" => $webuser]);
  1889.                         }
  1890.                         if ($block["components"]["addnew"] || $action == "edit" || $action == "save") {
  1891.                             //create form to create new address
  1892.                             //check form submission
  1893.                             if (!isset($address)) {
  1894.                                 $address = new StdWebUsersAddresses();
  1895.                             }
  1896.                             $formAddress $this->createForm(StdWebUsersAddressesForm::class, $address, ["locale" => $this->locale"entitymanager" => $this->entityManager"translator" => $this->translator]);
  1897.                             $formAddress->handleRequest($this->request);
  1898.                             if ($formAddress->isSubmitted() && $formAddress->isValid()) {
  1899.                                 $dataform $this->request->request->all();
  1900.                                 $address $formAddress->getData();
  1901.                                 $address->setCountry($dataform["std_web_users_addresses_form"]["countrychoice"]);
  1902.                                 //save address
  1903.                                 $address->setWebuser($webuser);
  1904.                                 $this->entityManager->persist($address);
  1905.                                 if (!$address->getId()) {
  1906.                                     $event = new StdWebUsersNewAddressEvent($address);
  1907.                                     $this->dispatcher->dispatch($eventStdWebUsersNewAddressEvent::NAME);
  1908.                                 } else {
  1909.                                     $event = new StdWebUsersUpdateAddressEvent($address);
  1910.                                     $this->dispatcher->dispatch($eventStdWebUsersUpdateAddressEvent::NAME);
  1911.                                 }
  1912.                                 $this->entityManager->flush();
  1913.                                 $address = new StdWebUsersAddresses();
  1914.                                 $formAddress $this->createForm(StdWebUsersAddressesForm::class, $address, ["locale" => $this->locale"entitymanager" => $this->entityManager"translator" => $this->translator]);
  1915.                             }
  1916.                             $variables["form"] = $formAddress->createView();
  1917.                         }
  1918.                         if ($action == "setdefault" && isset($address)) {
  1919.                             $currentDefault $this->entityManager->getRepository(StdWebUsersAddresses::class)->findOneBy(["isDefault" => 1"webuser" => $webuser]);
  1920.                             if ($currentDefault) {
  1921.                                 $currentDefault->setIsDefault(0);
  1922.                                 $this->entityManager->persist($currentDefault);
  1923.                             }
  1924.                             $address->setIsDefault(1);
  1925.                             $this->entityManager->persist($address);
  1926.                             $this->entityManager->flush();
  1927.                         }
  1928.                         if ($action == "delete" && isset($address)) {
  1929.                             $this->entityManager->remove($address);
  1930.                             $this->entityManager->flush();
  1931.                         }
  1932.                         $payload array_merge($variables, [
  1933.                             'settings' => $block["settings"],
  1934.                             'fields' => $block["components"],
  1935.                         ], $payload);
  1936.                     } elseif (isset($stdsettings["isFormDomain"]) && $stdsettings["isFormDomain"]) {
  1937.                         if ($block["components"]["form_parent"]) {
  1938.                             $parentId $this->request->get("parentId""");
  1939.                             if ($parentId) {
  1940.                                 $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $block["components"]["form_select_domain"], "parentDomainValue" => $parentId]);
  1941.                             } else {
  1942.                                 $domainvalues = [];
  1943.                             }
  1944.                         } else {
  1945.                             $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $block["components"]["form_select_domain"]]);
  1946.                         }
  1947.                         $payload array_merge($variables, [
  1948.                             'settings' => $block["settings"],
  1949.                             'fields' => $block["components"],
  1950.                             'values' => $domainvalues
  1951.                         ]);
  1952.                     } elseif (isset($stdsettings["isFormStatus"]) && $stdsettings["isFormStatus"]) {
  1953.                         //get the domain values for the selected domain
  1954.                         $domainvalues = [];
  1955.                         $domainobj $this->entityManager->getRepository(StdDomains::class)->findOneBy(["machineName" => "form_status"]);
  1956.                         if ($domainobj) {
  1957.                             if ($block["components"]["form_select_default"] != "") {
  1958.                                 $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id"), "machineName" => $block["components"]["form_select_default"]]);
  1959.                             } else {
  1960.                                 $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id")]);
  1961.                             }
  1962.                         }
  1963.                         $payload array_merge($variables, [
  1964.                             'settings' => $block["settings"],
  1965.                             'fields' => $block["components"],
  1966.                             'values' => $domainvalues
  1967.                         ]);
  1968.                     } elseif (isset($stdsettings["isResultsBlock"]) && $stdsettings["isResultsBlock"]) {
  1969.                         $pagesSearchData = [];
  1970.                         $hasGeneralSearch false;
  1971.                         $searchQuery = (string)$this->request->query->get('p''');
  1972.                         $requestedType strtolower((string)$this->request->query->get('type''all'));
  1973.                         $order strtolower((string)$this->request->query->get('order''relevance'));
  1974.                         if ($order === 'recent') {
  1975.                             $order 'newest';
  1976.                         }
  1977.                         if ($order === 'oldest') {
  1978.                             $order 'popular';
  1979.                         }
  1980.                         $page = (int)$this->request->query->get('page'1);
  1981.                         $pageSize = (int)$this->request->query->get('pageSize'15);
  1982.                         $page $page $page 1;
  1983.                         if ($pageSize <= || $pageSize 60) {
  1984.                             $pageSize 15;
  1985.                         }
  1986.                         $validTypes = ['news''news_reports''programs''event''all'];
  1987.                         if (!in_array($requestedType$validTypestrue)) {
  1988.                             $requestedType 'news';
  1989.                         }
  1990.                         $facetTagsRaw $this->request->query->all('tags');
  1991.                         $facetThemesRaw $this->request->query->all('themes');
  1992.                         $facetSubThemesRaw $this->request->query->all('subthemes');
  1993.                         $facetContentTypesRaw $this->request->query->all('content_type');
  1994.                         if (empty($facetContentTypesRaw)) {
  1995.                             $facetContentTypesRaw = ['news''news_reports''programs''event'];
  1996.                         }
  1997.                         $facetTags is_array($facetTagsRaw) ? array_values(array_filter(array_map('strval'$facetTagsRaw))) : [];
  1998.                         $facetThemes is_array($facetThemesRaw) ? array_values(array_filter(array_map('strval'$facetThemesRaw))) : [];
  1999.                         $facetSubThemes is_array($facetSubThemesRaw) ? array_values(array_filter(array_map('strval'$facetSubThemesRaw))) : [];
  2000.                         $facetContentTypes is_array($facetContentTypesRaw) ? array_values(array_filter(array_map('strval'$facetContentTypesRaw))) : [];
  2001.                         $shouldSearchAll = ($searchQuery === '');
  2002.                         if ($searchQuery !== '' || $shouldSearchAll || (isset($block['components']['show_empty_search']) && $block['components']['show_empty_search'])) {
  2003.                             $hasGeneralSearch true;
  2004.                             $arrayContentTypes = !empty($block['components']['search_content_types']) ? $block['components']['search_content_types'] : null;
  2005.                             // Override content types if specified in URL parameters
  2006.                             if (!empty($facetContentTypes)) {
  2007.                                 $contentTypeMapping = [
  2008.                                     'news' => 'news',
  2009.                                     'programs' => 'programs',
  2010.                                     'news_reports' => 'news_reports',
  2011.                                     'event' => 'event'
  2012.                                 ];
  2013.                                 $mappedContentTypes = [];
  2014.                                 foreach ($facetContentTypes as $ctName) {
  2015.                                     if (isset($contentTypeMapping[$ctName])) {
  2016.                                         $contentType $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['machineName' => $contentTypeMapping[$ctName]]);
  2017.                                         if ($contentType) {
  2018.                                             $mappedContentTypes[] = $contentType->getId();
  2019.                                         }
  2020.                                     }
  2021.                                 }
  2022.                                 if (!empty($mappedContentTypes)) {
  2023.                                     $arrayContentTypes $mappedContentTypes;
  2024.                                 }
  2025.                             }
  2026.                             $arrayCategories = !empty($block['components']['search_categories']) ? $block['components']['search_categories'] : null;
  2027.                             $pagesSearchData $this->entityManager->getRepository(StdPages::class)->searchPages([
  2028.                                 'searchQuery' => $searchQuery,
  2029.                                 'paginate' => isset($block['components']['paginate']) ? $block['components']['paginate'] : false,
  2030.                                 'limit' => isset($block['components']['limit']) ? $block['components']['limit'] : false,
  2031.                                 'page' => $pagenumber,
  2032.                                 'paginator' => $this->paginator,
  2033.                                 'language_code' => $this->locale,
  2034.                                 'component_types' => $arrayContentTypes,
  2035.                                 'categories' => $arrayCategories,
  2036.                                 'roles' => ($this->security->getUser() instanceof StdWebUsers $this->security->getUser()->getRoles() : null)
  2037.                             ]);
  2038.                         }
  2039.                         $pagesSearchData array_values(array_filter($pagesSearchData, function($item) {
  2040.                             if ($item instanceof StdPagesContent) {
  2041.                                 $page $item->getPageId();
  2042.                             } elseif ($item instanceof StdPages) {
  2043.                                 $page $item;
  2044.                             } else {
  2045.                                 return false;
  2046.                             }
  2047.                             return $page && Functions::isPagePublished($page);
  2048.                         }));
  2049.                         $activeTags $facetTags;
  2050.                         $activeThemes array_merge($facetThemes$facetSubThemes);
  2051.                         if (!is_array($activeTags)) {
  2052.                             $activeTags = [];
  2053.                         }
  2054.                         if (!is_array($activeThemes)) {
  2055.                             $activeThemes = [];
  2056.                         }
  2057.                         $activeTags array_values(array_unique(array_filter(array_map(fn($v) => trim((string)$v), $activeTags))));
  2058.                         $activeThemes array_values(array_unique(array_filter(array_map(fn($v) => trim((string)$v), $activeThemes))));
  2059.                         $requestedTagEntity null;
  2060.                         if (count($activeTags) === 1) {
  2061.                             $tagValue $activeTags[0];
  2062.                             if (is_numeric($tagValue)) {
  2063.                                 $requestedTagEntity $this->entityManager->getRepository(StdDomainsValues::class)->find((int)$tagValue);
  2064.                             }
  2065.                             if (!$requestedTagEntity) {
  2066.                                 $requestedTagEntity $this->entityManager->getRepository(StdDomainsValues::class)
  2067.                                     ->findOneBy(['machineName' => $tagValue]);
  2068.                             }
  2069.                             if (!$requestedTagEntity) {
  2070.                                 $requestedTagEntity $this->entityManager->getRepository(StdDomainsValues::class)
  2071.                                     ->findOneBy(['description' => $tagValue]);
  2072.                             }
  2073.                         }
  2074.                         $extractTagMachines = function ($item) {
  2075.                             $col = [];
  2076.                             if ($item instanceof StdPagesContent) {
  2077.                                 $page $item->getPageId();
  2078.                                 if (!empty($page)) {
  2079.                                     foreach ($page->getTags() as $tagLink) {
  2080.                                         if ($tagLink instanceof StdPagesTag) {
  2081.                                             $dv $tagLink->getDomainValue();
  2082.                                             if ($dv) {
  2083.                                                 $col[] = (string)$dv->getId();
  2084.                                                 $m $dv->getMachineName() ?? $dv->getDescription();
  2085.                                                 if ($m) {
  2086.                                                     $col[] = strtolower(trim($m));
  2087.                                                 }
  2088.                                             }
  2089.                                         }
  2090.                                     }
  2091.                                 }
  2092.                             }
  2093.                             return array_values(array_unique($col));
  2094.                         };
  2095.                         $extractThemeLabels = function ($item) {
  2096.                             $col = [];
  2097.                             if (is_array($item)) {
  2098.                                 if (isset($item['theme']) && $item['theme'] !== '') {
  2099.                                     $col[] = trim((string)$item['theme']);
  2100.                                 }
  2101.                                 if (isset($item['categories']) && is_iterable($item['categories'])) {
  2102.                                     foreach ($item['categories'] as $c) {
  2103.                                         $label is_array($c) ? ($c['label'] ?? ($c['name'] ?? ($c['title'] ?? null))) : (string)$c;
  2104.                                         if ($label) {
  2105.                                             $col[] = trim((string)$label);
  2106.                                         }
  2107.                                     }
  2108.                                 }
  2109.                             }
  2110.                             if ($item instanceof StdPagesContent) {
  2111.                                 $page $item->getPageId();
  2112.                                 if (!empty($page)) {
  2113.                                     $conn $this->entityManager->getConnection();
  2114.                                     $sql "SELECT DISTINCT pp_parent.page_id as category_page_id
  2115.                                             FROM std_pages_pages pp_child
  2116.                                             JOIN std_pages_pages pp_parent ON pp_parent.id = pp_child.relation_id
  2117.                                             JOIN std_pages p_cat ON p_cat.id = pp_parent.page_id
  2118.                                             JOIN std_content_types ct ON ct.id = p_cat.content_type
  2119.                                             WHERE pp_child.page_id = :page_id
  2120.                                             AND ct.machine_name = 'pages_categories'
  2121.                                             AND p_cat.is_active = 1";
  2122.                                     try {
  2123.                                         $stmt $conn->prepare($sql);
  2124.                                         $result $stmt->executeQuery(['page_id' => $page->getId()]);
  2125.                                         $categoryIds $result->fetchAllAssociative();
  2126.                                         foreach ($categoryIds as $catRow) {
  2127.                                             $categoryPageId $catRow['category_page_id'];
  2128.                                             // Add the page ID for matching
  2129.                                             $col[] = (string)$categoryPageId;
  2130.                                             $categoryPage $this->entityManager->getRepository(StdPages::class)->find($categoryPageId);
  2131.                                             if ($categoryPage) {
  2132.                                                 $name $categoryPage->getName();
  2133.                                                 if ($name) {
  2134.                                                     $col[] = trim((string)$name);
  2135.                                                 }
  2136.                                                 // Also add machine name if available
  2137.                                                 $machineName $categoryPage->getMachineName();
  2138.                                                 if ($machineName) {
  2139.                                                     $col[] = trim((string)$machineName);
  2140.                                                 }
  2141.                                             }
  2142.                                         }
  2143.                                     } catch (\Exception $e) {
  2144.                                         // Silently handle database errors
  2145.                                     }
  2146.                                     foreach ($page->getTags() as $tagLink) {
  2147.                                         if ($tagLink instanceof StdPagesTag) {
  2148.                                             $dv $tagLink->getDomainValue();
  2149.                                             if ($dv) {
  2150.                                                 $domainName $dv->getDomain() ? $dv->getDomain()->getMachineName() : '';
  2151.                                                 if (in_array($domainName, ['themes''subthemes''categorias''subcategorias'])) {
  2152.                                                     // Include both ID and machine name/description for matching
  2153.                                                     $col[] = (string)$dv->getId();
  2154.                                                     $themeValue $dv->getMachineName() ?? $dv->getDescription();
  2155.                                                     if ($themeValue) {
  2156.                                                         $col[] = trim((string)$themeValue);
  2157.                                                     }
  2158.                                                 }
  2159.                                             }
  2160.                                         }
  2161.                                     }
  2162.                                 }
  2163.                             }
  2164.                             return array_values(array_unique($col));
  2165.                         };
  2166.                         if ($activeTags || $activeThemes) {
  2167.                             $pagesSearchData array_values(array_filter($pagesSearchData, function ($r) use ($activeTags$activeThemes$extractTagMachines$extractThemeLabels) {
  2168.                                 $itemTags $extractTagMachines($r);
  2169.                                 $itemThemes $extractThemeLabels($r);
  2170.                                 foreach ($activeTags as $t) {
  2171.                                     $tNorm strtolower(trim($t));
  2172.                                     if (!in_array($tNorm$itemTagstrue)) {
  2173.                                         return false;
  2174.                                     }
  2175.                                 }
  2176.                                 if ($activeThemes) {
  2177.                                     $any false;
  2178.                                     $normalizedItemThemes array_map(fn($v) => mb_strtolower(trim($v)), $itemThemes);
  2179.                                     foreach ($activeThemes as $th) {
  2180.                                         $thNorm mb_strtolower(trim($th));
  2181.                                         if (in_array($thNorm$normalizedItemThemestrue)) {
  2182.                                             $any true;
  2183.                                             break;
  2184.                                         }
  2185.                                     }
  2186.                                     if (!$any) {
  2187.                                         return false;
  2188.                                     }
  2189.                                 }
  2190.                                 return true;
  2191.                             }));
  2192.                         }
  2193.                         $allattributes = [];
  2194.                         foreach ($pagesSearchData as $pagecontent) {
  2195.                             if (!is_object($pagecontent) || !method_exists($pagecontent'getPageId')) {
  2196.                                 continue;
  2197.                             }
  2198.                             $pageIdObj $pagecontent->getPageId();
  2199.                             if (!is_object($pageIdObj) || !method_exists($pageIdObj'getId')) {
  2200.                                 continue;
  2201.                             }
  2202.                             $allPagesAttributesValues $this->entityManager->getRepository(StdPagesAttributesValues::class)->getPageAttributes($pageIdObj);
  2203.                             $attributesarr = [];
  2204.                             foreach ($allPagesAttributesValues as $entity) {
  2205.                                 if ($entity instanceof StdAttributes) {
  2206.                                     $attributesarr[$entity->getMachineName()]["attribute"] = $entity;
  2207.                                 }
  2208.                                 if ($entity instanceof StdAttributesValues) {
  2209.                                     $attributesarr[$entity->getAttribute()->getMachineName()]["values"]["{$entity->getValue()}"] = $entity;
  2210.                                 }
  2211.                             }
  2212.                             $allattributes[$pageIdObj->getId()] = $attributesarr;
  2213.                         }
  2214.                         $extractType = function ($item) {
  2215.                             $raw '';
  2216.                             if ($item instanceof StdPagesContent) {
  2217.                                 $raw $item->getPageId()?->getContentType()?->getMachineName();
  2218.                             } elseif ($item instanceof StdPages) {
  2219.                                 $raw $item->getContentType()?->getMachineName();
  2220.                             } elseif (is_array($item)) {
  2221.                                 $raw $item['content_type'] ?? ($item['type'] ?? ($item['content']['type'] ?? ''));
  2222.                             }
  2223.                             if (!in_array($raw, ['programs''news_reports''event''news'], true)) {
  2224.                                 return 'news';
  2225.                             }
  2226.                             return $raw;
  2227.                         };
  2228.                         $counts = ['news' => 0'news_reports' => 0'programs' => 0'event' => 0'all' => 0];
  2229.                         foreach ($pagesSearchData as $r) {
  2230.                             $k $extractType($r);
  2231.                             if (isset($counts[$k])) {
  2232.                                 $counts[$k]++;
  2233.                             }
  2234.                             $counts['all']++; // Count all items for the 'all' tab
  2235.                         }
  2236.                         // Filter by content type, unless 'all' is requested
  2237.                         if ($requestedType === 'all') {
  2238.                             $filtered $pagesSearchData// Show all content types
  2239.                         } else {
  2240.                             $filtered array_filter($pagesSearchData, function ($r) use ($extractType$requestedType) {
  2241.                                 return $extractType($r) === $requestedType;
  2242.                             });
  2243.                         }
  2244.                         $getPublishTimestamp = function ($item): int {
  2245.                             $dt null;
  2246.                             if ($item instanceof StdPagesContent) {
  2247.                                 $dt $item->getPageId()?->getPublishDate();
  2248.                             } elseif ($item instanceof StdPages) {
  2249.                                 $dt $item->getPublishDate();
  2250.                             } elseif (is_array($item)) {
  2251.                                 $raw $item['publish_date'] ?? ($item['content']['publish_date'] ?? ($item['content']['date'] ?? ($item['date'] ?? null)));
  2252.                                 if (is_string($raw)) {
  2253.                                     return strtotime($raw) ?: 0;
  2254.                                 }
  2255.                                 if ($raw instanceof \DateTimeInterface) {
  2256.                                     return $raw->getTimestamp();
  2257.                                 }
  2258.                                 return 0;
  2259.                             }
  2260.                             if (is_string($dt)) {
  2261.                                 return strtotime($dt) ?: 0;
  2262.                             }
  2263.                             if ($dt instanceof \DateTimeInterface) {
  2264.                                 return $dt->getTimestamp();
  2265.                             }
  2266.                             return 0;
  2267.                         };
  2268.                         if ($order === 'newest') {
  2269.                             usort($filtered, function ($a$b) use ($getPublishTimestamp) {
  2270.                                 $ta $getPublishTimestamp($a);
  2271.                                 $tb $getPublishTimestamp($b);
  2272.                                 if ($ta === $tb) return 0;
  2273.                                 return $ta $tb ? -1;
  2274.                             });
  2275.                         } elseif ($order === 'popular') {
  2276.                             $pageIds = [];
  2277.                             foreach ($filtered as $it) {
  2278.                                 if ($it instanceof StdPagesContent) {
  2279.                                     $pid $it->getPageId()?->getId();
  2280.                                 } elseif ($it instanceof StdPages) {
  2281.                                     $pid $it->getId();
  2282.                                 } elseif (is_array($it)) {
  2283.                                     $pid $it['id'] ?? null;
  2284.                                 } else {
  2285.                                     $pid null;
  2286.                                 }
  2287.                                 if ($pid) {
  2288.                                     $pageIds[] = $pid;
  2289.                                 }
  2290.                             }
  2291.                             $pageIds array_values(array_unique($pageIds));
  2292.                             $popularCounts = [];
  2293.                             if ($pageIds) {
  2294.                                 $q $this->entityManager->createQuery('SELECT p.id as pid, COUNT(t.id) as cnt FROM App\\Entity\\StdPagesTracking t JOIN t.page p WHERE p.id IN (:ids) GROUP BY p.id');
  2295.                                 $q->setParameter('ids'$pageIds);
  2296.                                 foreach ($q->getResult() as $row) {
  2297.                                     $popularCounts[(int)$row['pid']] = (int)$row['cnt'];
  2298.                                 }
  2299.                             }
  2300.                             usort($filtered, function ($a$b) use ($popularCounts$getPublishTimestamp) {
  2301.                                 $getPid = function ($x) {
  2302.                                     if ($x instanceof StdPagesContent) return $x->getPageId()?->getId();
  2303.                                     if ($x instanceof StdPages) return $x->getId();
  2304.                                     if (is_array($x)) return $x['id'] ?? null;
  2305.                                     return null;
  2306.                                 };
  2307.                                 $pa $getPid($a);
  2308.                                 $pb $getPid($b);
  2309.                                 $ca $pa && isset($popularCounts[$pa]) ? $popularCounts[$pa] : 0;
  2310.                                 $cb $pb && isset($popularCounts[$pb]) ? $popularCounts[$pb] : 0;
  2311.                                 if ($ca === $cb) {
  2312.                                     $ta $getPublishTimestamp($a);
  2313.                                     $tb $getPublishTimestamp($b);
  2314.                                     if ($ta === $tb) return 0;
  2315.                                     return $ta $tb ? -1;
  2316.                                 }
  2317.                                 return $ca $cb ? -1;
  2318.                             });
  2319.                         } else {
  2320.                             $locationTags = [];
  2321.                             $cookieLocationId $this->request->cookies->get('CloseToYou-Location');
  2322.                             $sessionLocations $this->request->getSession()->get('close_location_ids');
  2323.                             if ($cookieLocationId) {
  2324.                                 $locationTags[] = (int)$cookieLocationId;
  2325.                                 if (is_array($sessionLocations)) {
  2326.                                     foreach ($sessionLocations as $locId) {
  2327.                                         if ($locId != $cookieLocationId) {
  2328.                                             $locationTags[] = (int)$locId;
  2329.                                         }
  2330.                                     }
  2331.                                 }
  2332.                             } elseif (!empty($sessionLocations)) {
  2333.                                 $locationTags array_map('intval'$sessionLocations);
  2334.                             }
  2335.                             if (!empty($locationTags)) {
  2336.                                 // Location-based ordering (like 'location' order_by in repository)
  2337.                                 usort($filtered, function ($a$b) use ($locationTags$getPublishTimestamp) {
  2338.                                     $getLocationScore = function ($item) use ($locationTags) {
  2339.                                         $bestScore 999999// Start with high value (farthest)
  2340.                                         if ($item instanceof StdPagesContent) {
  2341.                                             $page $item->getPageId();
  2342.                                             if ($page) {
  2343.                                                 foreach ($page->getTags() as $tagLink) {
  2344.                                                     if ($tagLink instanceof StdPagesTag) {
  2345.                                                         $dv $tagLink->getDomainValue();
  2346.                                                         if ($dv) {
  2347.                                                             $tagIndex array_search($dv->getId(), $locationTags);
  2348.                                                             if ($tagIndex !== false && $tagIndex $bestScore) {
  2349.                                                                 $bestScore $tagIndex// Lower index = closer = better
  2350.                                                             }
  2351.                                                         }
  2352.                                                     }
  2353.                                                 }
  2354.                                             }
  2355.                                         } elseif ($item instanceof StdPages) {
  2356.                                             foreach ($item->getTags() as $tagLink) {
  2357.                                                 if ($tagLink instanceof StdPagesTag) {
  2358.                                                     $dv $tagLink->getDomainValue();
  2359.                                                     if ($dv) {
  2360.                                                         $tagIndex array_search($dv->getId(), $locationTags);
  2361.                                                         if ($tagIndex !== false && $tagIndex $bestScore) {
  2362.                                                             $bestScore $tagIndex// Lower index = closer = better
  2363.                                                         }
  2364.                                                     }
  2365.                                                 }
  2366.                                             }
  2367.                                         }
  2368.                                         return $bestScore;
  2369.                                     };
  2370.                                     $scoreA $getLocationScore($a);
  2371.                                     $scoreB $getLocationScore($b);
  2372.                                     // Lower score (closer location) comes first
  2373.                                     if ($scoreA !== $scoreB) {
  2374.                                         return $scoreA $scoreB;
  2375.                                     }
  2376.                                     // If same location score, sort by publish date (newest first)
  2377.                                     $ta $getPublishTimestamp($a);
  2378.                                     $tb $getPublishTimestamp($b);
  2379.                                     if ($ta === $tb) return 0;
  2380.                                     return $ta $tb ? -1;
  2381.                                 });
  2382.                             } else {
  2383.                                 // Historic ordering (like 'historic' order_by in repository)
  2384.                                 $recommended = [];
  2385.                                 try {
  2386.                                     $recommended $this->stdTrackingService->getRecommendedPagesForUser();
  2387.                                 } catch (\Throwable $e) {
  2388.                                     $recommended = [];
  2389.                                 }
  2390.                                 $recommendedPageIds = [];
  2391.                                 foreach ($recommended as $rec) {
  2392.                                     if ($rec instanceof StdPagesContent) {
  2393.                                         $pid $rec->getPageId()?->getId();
  2394.                                     } elseif ($rec instanceof StdPages) {
  2395.                                         $pid $rec->getId();
  2396.                                     } elseif (is_array($rec)) {
  2397.                                         $pid $rec['id'] ?? null;
  2398.                                     } else {
  2399.                                         $pid null;
  2400.                                     }
  2401.                                     if ($pid) {
  2402.                                         $recommendedPageIds[] = $pid;
  2403.                                     }
  2404.                                 }
  2405.                                 if (!empty($recommendedPageIds)) {
  2406.                                     // Get existing page IDs from filtered results
  2407.                                     $existingPageIds = [];
  2408.                                     foreach ($filtered as $item) {
  2409.                                         if ($item instanceof StdPagesContent) {
  2410.                                             $pid $item->getPageId()?->getId();
  2411.                                         } elseif ($item instanceof StdPages) {
  2412.                                             $pid $item->getId();
  2413.                                         } elseif (is_array($item)) {
  2414.                                             $pid $item['id'] ?? null;
  2415.                                         } else {
  2416.                                             $pid null;
  2417.                                         }
  2418.                                         if ($pid) {
  2419.                                             $existingPageIds[] = $pid;
  2420.                                         }
  2421.                                     }
  2422.                                     // Find recommended pages that are NOT in current filtered results
  2423.                                     $missingRecommendedIds array_diff($recommendedPageIds$existingPageIds);
  2424.                                     if (!empty($missingRecommendedIds)) {
  2425.                                         // Fetch missing recommended pages that match current filters
  2426.                                         $qb $this->entityManager->createQueryBuilder();
  2427.                                         $qb->select('pc, p')
  2428.                                             ->from('App\Admin\Entity\StdPagesContent''pc')
  2429.                                             ->join('pc.pageId''p')
  2430.                                             ->where('p.id IN (:recommendedIds)')
  2431.                                             ->andWhere('p.isActive = 1')
  2432.                                             ->andWhere('(p.publishDate IS NULL OR p.publishDate <= :now)')
  2433.                                             ->andWhere('(p.expireDate IS NULL OR p.expireDate > :now)')
  2434.                                             ->andWhere('pc.languageCode = :language')
  2435.                                             ->setParameter('recommendedIds'$missingRecommendedIds)
  2436.                                             ->setParameter('now', new \DateTime())
  2437.                                             ->setParameter('language'$this->locale);
  2438.                                         // Apply same search query filter if exists
  2439.                                         if (!empty($searchQuery)) {
  2440.                                             $qb->andWhere('(pc.title LIKE :search OR JSON_SEARCH(LOWER(pc.content), \'all\', :search) IS NOT NULL)')
  2441.                                                ->setParameter('search''%' strtolower($searchQuery) . '%');
  2442.                                         }
  2443.                                         // Apply same content type filter if exists
  2444.                                         if (!empty($arrayContentTypes)) {
  2445.                                             $qb->andWhere('p.contentType IN (:contentTypes)')
  2446.                                                 ->setParameter('contentTypes'$arrayContentTypes);
  2447.                                         }
  2448.                                         // Apply same category filter if exists
  2449.                                         if (!empty($arrayCategories)) {
  2450.                                             $qb->join('p.tags''pt')
  2451.                                                 ->join('pt.domainValue''dv')
  2452.                                                 ->andWhere('dv.id IN (:categories)')
  2453.                                                 ->setParameter('categories'$arrayCategories);
  2454.                                         }
  2455.                                         $missingRecommended $qb->getQuery()->getResult();
  2456.                                         if ($activeTags || $activeThemes) {
  2457.                                             $missingRecommended array_values(array_filter($missingRecommended, function ($r) use ($activeTags$activeThemes$extractTagMachines$extractThemeLabels) {
  2458.                                                 $itemTags $extractTagMachines($r);
  2459.                                                 $itemThemes $extractThemeLabels($r);
  2460.                                                 foreach ($activeTags as $t) {
  2461.                                                     $tNorm strtolower(trim($t));
  2462.                                                     if (!in_array($tNorm$itemTagstrue)) {
  2463.                                                         return false;
  2464.                                                     }
  2465.                                                 }
  2466.                                                 if ($activeThemes) {
  2467.                                                     $any false;
  2468.                                                     $normalizedItemThemes array_map(fn($v) => mb_strtolower(trim($v)), $itemThemes);
  2469.                                                     foreach ($activeThemes as $th) {
  2470.                                                         $thNorm mb_strtolower(trim($th));
  2471.                                                         if (in_array($thNorm$normalizedItemThemestrue)) {
  2472.                                                             $any true;
  2473.                                                             break;
  2474.                                                         }
  2475.                                                     }
  2476.                                                     if (!$any) {
  2477.                                                         return false;
  2478.                                                     }
  2479.                                                 }
  2480.                                                 return true;
  2481.                                             }));
  2482.                                         }
  2483.                                         // Merge with existing filtered results
  2484.                                         $filtered array_merge($missingRecommended$filtered);
  2485.                                     }
  2486.                                     usort($filtered, function ($a$b) use ($recommendedPageIds$getPublishTimestamp) {
  2487.                                         $getPid = function ($x) {
  2488.                                             if ($x instanceof StdPagesContent) return $x->getPageId()?->getId();
  2489.                                             if ($x instanceof StdPages) return $x->getId();
  2490.                                             if (is_array($x)) return $x['id'] ?? null;
  2491.                                             return null;
  2492.                                         };
  2493.                                         $getTagCount = function ($x) {
  2494.                                             if ($x instanceof StdPagesContent) {
  2495.                                                 $page $x->getPageId();
  2496.                                                 return $page count($page->getTags()) : 0;
  2497.                                             } elseif ($x instanceof StdPages) {
  2498.                                                 return count($x->getTags());
  2499.                                             }
  2500.                                             return 0;
  2501.                                         };
  2502.                                         $pa $getPid($a);
  2503.                                         $pb $getPid($b);
  2504.                                         $aRec $pa !== null && in_array($pa$recommendedPageIds);
  2505.                                         $bRec $pb !== null && in_array($pb$recommendedPageIds);
  2506.                                         // 1. Recommended pages come first
  2507.                                         if ($aRec && !$bRec) {
  2508.                                             return -1;
  2509.                                         } elseif (!$aRec && $bRec) {
  2510.                                             return 1;
  2511.                                         }
  2512.                                         // 2. If both have same recommendation status, sort by tag count (DESC)
  2513.                                         $tagCountA $getTagCount($a);
  2514.                                         $tagCountB $getTagCount($b);
  2515.                                         if ($tagCountA !== $tagCountB) {
  2516.                                             return $tagCountA $tagCountB ? -1;
  2517.                                         }
  2518.                                         // 3. Finally sort by publish date (DESC)
  2519.                                         $ta $getPublishTimestamp($a);
  2520.                                         $tb $getPublishTimestamp($b);
  2521.                                         if ($ta === $tb) return 0;
  2522.                                         return $ta $tb ? -1;
  2523.                                     });
  2524.                                 } else {
  2525.                                     // No recommended pages - just sort by publish date (DESC)
  2526.                                     usort($filtered, function ($a$b) use ($getPublishTimestamp) {
  2527.                                         $ta $getPublishTimestamp($a);
  2528.                                         $tb $getPublishTimestamp($b);
  2529.                                         if ($ta === $tb) return 0;
  2530.                                         return $ta $tb ? -1;
  2531.                                     });
  2532.                                 }
  2533.                             }
  2534.                         }
  2535.                         $totalFiltered count($filtered);
  2536.                         $pageCount $totalFiltered ? (int)ceil($totalFiltered $pageSize) : 1;
  2537.                         if ($page $pageCount) {
  2538.                             $page $pageCount;
  2539.                         }
  2540.                         $offset = ($page 1) * $pageSize;
  2541.                         $pageItems array_slice(array_values($filtered), $offset$pageSize);
  2542.                         $nextPage $page $pageCount $page 0;
  2543.                         $resultsMeta = [
  2544.                             'query' => $searchQuery,
  2545.                             'currentType' => $requestedType,
  2546.                             'order' => $order,
  2547.                             'page' => $page,
  2548.                             'pageSize' => $pageSize,
  2549.                             'pageCount' => $pageCount,
  2550.                             'nextPage' => $nextPage,
  2551.                             'counts' => $counts,
  2552.                             'total' => $totalFiltered,
  2553.                             'totalAll' => count($pagesSearchData),
  2554.                             'items' => $pageItems,
  2555.                             'hasSearch' => $hasGeneralSearch,
  2556.                         ];
  2557.                         $payload array_merge($variables, [
  2558.                             'settings' => $block['settings'],
  2559.                             'fields' => $block['components'],
  2560.                             'values' => $pagesSearchData,
  2561.                             'results' => $resultsMeta,
  2562.                             'attributes' => $allattributes,
  2563.                             'paginator' => $pagesSearchData,
  2564.                             'total' => $totalFiltered,
  2565.                             'total_all_types' => count($pagesSearchData),
  2566.                             'hasGeneralSearch' => $hasGeneralSearch,
  2567.                             'requestedTag' => $requestedTagEntity,
  2568.                         ]);
  2569.                     } elseif (isset($stdsettings["isContentSnippet"]) && $stdsettings["isContentSnippet"]) {
  2570.                         if ($snippetContent $this->entityManager->getRepository(StdSnippetsContent::class)->findOneBy(["snippetId" => $block["components"]["combo_content_snippet"], "languageCode" => $this->locale])) {
  2571.                             if ($snippetContent) {
  2572.                                 $renderedcontent $this->renderPageContent($pagenumber$variables$page$snippetContentnull);
  2573.                                 // isset($renderedcontent['webpackEntries']) && $webpackEntries = array_merge($webpackEntries, $renderedcontent['webpackEntries']);
  2574.                                 isset($renderedcontent['cookies']) && $cookies array_merge($cookies$renderedcontent['cookies']);
  2575.                                 if (array_key_exists('editBlocksInfo'$renderedcontent["variables"]) && count($renderedcontent["variables"]["editBlocksInfo"]) > 0) {
  2576.                                     $variables["editBlocksInfo"] = array_merge(
  2577.                                         $renderedcontent["variables"]["editBlocksInfo"], $variables["editBlocksInfo"]
  2578.                                     );
  2579.                                 }
  2580.                                 $payload array_merge([
  2581.                                     'settings' => $block["settings"],
  2582.                                     'fields' => $block["components"],
  2583.                                     'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2584.                                     'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  2585.                                     'blockscontent' => $renderedcontent["html"],
  2586.                                     'blockscontentjs' => $renderedcontent["js"],
  2587.                                 ], $variables);
  2588.                             } else {
  2589.                                 $payload array_merge($variables, [
  2590.                                     'settings' => $block["settings"],
  2591.                                     'fields' => $block["components"],
  2592.                                     'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2593.                                     'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array())
  2594.                                 ]);
  2595.                             }
  2596.                         }
  2597.                     } elseif (isset($stdsettings["isFormSequential"]) && $stdsettings["isFormSequential"]) {
  2598.                         $form_sequential_pad_number = isset($block["components"]["form_sequential_pad_number"]) ? $block["components"]["form_sequential_pad_number"] : 0;
  2599.                         $sequential $this->entityManager->getRepository(Forms::class)->findNextFormSequentialByFormName($page->getMachineName(), $form_sequential_pad_number);
  2600.                         $block["components"]["form_sequential"] = $sequential;
  2601.                         $payload array_merge($variables, [
  2602.                             'settings' => $block["settings"],
  2603.                             'fields' => $block["components"],
  2604.                         ]);
  2605.                     } elseif (isset($stdsettings["isListForYou"]) && $stdsettings["isListForYou"]) {
  2606.                         $limit = (int)($block['settings']['limit'] ?? 10);
  2607.                         $queryPage $this->request->query->getInt('page'0);
  2608.                         $pageNum $queryPage $queryPage : ($pagenumber ?? 1);
  2609.                         $locationTags = [];
  2610.                         $cookieLocationId $this->request->cookies->get('CloseToYou-Location');
  2611.                         $sessionLocations $this->request->getSession()->get('close_location_ids');
  2612.                         if ($cookieLocationId) {
  2613.                             $locationTags[] = (int)$cookieLocationId;
  2614.                             if (is_array($sessionLocations)) {
  2615.                                 foreach ($sessionLocations as $locId) {
  2616.                                     if ($locId != $cookieLocationId) {
  2617.                                         $locationTags[] = $locId;
  2618.                                     }
  2619.                                 }
  2620.                             }
  2621.                         } elseif (!empty($sessionLocations)) {
  2622.                             $locationTags $sessionLocations;
  2623.                         }
  2624.                         $block['settings']['locationTags'] = $locationTags;
  2625.                         $newsData $blocksservice->fetchNewsList(
  2626.                             $this->locale,
  2627.                             $this->entityManager,
  2628.                             $block['settings'],
  2629.                             $block['components'],
  2630.                             $pageNum,
  2631.                             $limit,
  2632.                             $this->paginator
  2633.                         );
  2634.                         if (!isset($locationValues)) {
  2635.                             try {
  2636.                                 $locationValues $this->entityManager->getRepository(StdDomainsValues::class)
  2637.                                     ->createQueryBuilder('dv')
  2638.                                     ->andWhere('dv.isActive = 1')
  2639.                                     ->andWhere('dv.type = :locType')
  2640.                                     ->setParameter('locType'DomainValueType::Location->value)
  2641.                                     ->addOrderBy('dv.description''ASC')
  2642.                                     ->getQuery()->getResult();
  2643.                             } catch (\Throwable $e) {
  2644.                                 $locationValues = [];
  2645.                             }
  2646.                         }
  2647.                         $payload array_merge($variables, [
  2648.                             'settings' => $block['settings'],
  2649.                             'fields' => $block['components'],
  2650.                             'items' => $newsData['items'],
  2651.                             'paginator' => $newsData['paginator'] ?? null,
  2652.                             'isajax' => $ajaxCall && array_key_exists('isAjax'$ajaxCall) ? true false,
  2653.                             'location_values' => $locationValues ?? []
  2654.                         ]);
  2655.                     } elseif (isset($stdsettings['isListNews']) && $stdsettings['isListNews']) {
  2656.                         $limit = (int)($block['settings']['limit'] ?? 10);
  2657.                         $queryPage $this->request->query->getInt('page'0);
  2658.                         $pageNum $queryPage $queryPage : ($pagenumber ?? 1);
  2659.                         $locationTags = [];
  2660.                         $cookieLocationId $this->request->cookies->get('CloseToYou-Location');
  2661.                         $sessionLocations $this->request->getSession()->get('close_location_ids');
  2662.                         if ($cookieLocationId) {
  2663.                             $locationTags[] = (int)$cookieLocationId;
  2664.                             if (is_array($sessionLocations)) {
  2665.                                 foreach ($sessionLocations as $locId) {
  2666.                                     if ($locId != $cookieLocationId) {
  2667.                                         $locationTags[] = $locId;
  2668.                                     }
  2669.                                 }
  2670.                             }
  2671.                         } elseif (!empty($sessionLocations)) {
  2672.                             $locationTags $sessionLocations;
  2673.                         }
  2674.                         $block['settings']['locationTags'] = $locationTags;
  2675.                         $newsData $blocksservice->fetchNewsList(
  2676.                             $this->locale,
  2677.                             $this->entityManager,
  2678.                             $block['settings'],
  2679.                             $block['components'],
  2680.                             $pageNum,
  2681.                             $limit,
  2682.                             $this->paginator
  2683.                         );
  2684.                         if (!isset($locationValues)) {
  2685.                             try {
  2686.                                 $locationValues $this->entityManager->getRepository(StdDomainsValues::class)
  2687.                                     ->createQueryBuilder('dv')
  2688.                                     ->andWhere('dv.isActive = 1')
  2689.                                     ->andWhere('dv.type = :locType')
  2690.                                     ->setParameter('locType'DomainValueType::Location->value)
  2691.                                     ->addOrderBy('dv.description''ASC')
  2692.                                     ->getQuery()->getResult();
  2693.                             } catch (\Throwable $e) {
  2694.                                 $locationValues = [];
  2695.                             }
  2696.                         }
  2697.                         $payload array_merge($variables, [
  2698.                             'settings' => $block['settings'],
  2699.                             'fields' => $block['components'],
  2700.                             'items' => $newsData['items'],
  2701.                             'paginator' => $newsData['paginator'] ?? null,
  2702.                             'isajax' => $ajaxCall && array_key_exists('isAjax'$ajaxCall) ? true false,
  2703.                             'location_values' => $locationValues ?? []
  2704.                         ]);
  2705.                     } elseif (isset($stdsettings['isListseetv']) && $stdsettings['isListseetv']) {
  2706.                         // Limite
  2707.                         $limit = (int)($block['settings']['limit'] ?? 30);
  2708.                         //  categoria
  2709.                         $categoryId = isset($block['components']['category'])
  2710.                             ? (int)$block['components']['category']
  2711.                             : null;
  2712.                         // Pega os itens do content type "see_tv".
  2713.                         // Requisito: todos com video_youtubeid são tratados como LIVE;
  2714.                         // ordenação: mais recente primeiro (start_date desc)
  2715.                         $channels $blocksservice->fetchSeeTvForList(
  2716.                             $this->locale,
  2717.                             $this->entityManager,
  2718.                             $limit,
  2719.                             0,
  2720.                             'pt',
  2721.                             $categoryId
  2722.                         );
  2723.                         $payload array_merge($variables, [
  2724.                             'settings' => $block['settings'],
  2725.                             'fields' => $block['components'],
  2726.                             'channels' => $channels
  2727.                         ]);
  2728.                     } elseif (isset($stdsettings['isTop10']) && $stdsettings['isTop10']) {
  2729.                         // 1) Pega os componentes do bloco (program_1..program_10)
  2730.                         $components $block['components'] ?? [];
  2731.                         $items $blocksservice->fetchProgramsTop10(
  2732.                             $this->locale,
  2733.                             $this->entityManager,
  2734.                             $components,
  2735.                             10 // limit
  2736.                         );
  2737.                         // 4) Payload padrão para o Twig
  2738.                         $payload array_merge($variables, [
  2739.                             'settings' => $block['settings'] ?? [],
  2740.                             'fields' => $block['components'] ?? [],
  2741.                             'items' => $items,
  2742.                             'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2743.                         ]);
  2744.                     } elseif (isset($stdsettings['isLike']) && $stdsettings['isLike']) {
  2745.                         $limit  = (int)($block['settings']['limit'] ?? 30);
  2746.                         $pageId $variables['page']['id'] ?? null;
  2747.                         $items $blocksservice->fetchProgramsLike(
  2748.                             $this->locale,
  2749.                             $this->entityManager,
  2750.                             $pageId,
  2751.                             $limit
  2752.                         );
  2753.                         $payload array_merge($variables, [
  2754.                             'settings' => $block['settings']   ?? [],
  2755.                             'fields'   => $block['components'] ?? [],
  2756.                             'items'    => $items,
  2757.                             'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2758.                         ]);
  2759.                     } elseif (isset($stdsettings['isConta5MinBlock']) && $stdsettings['isConta5MinBlock']) {
  2760.                         $limit = (int)($block['settings']['limit'] ?? 30);
  2761.                         $relationId = (int)($block['components']['category'] ?? -1);
  2762.                         // Handle category filter from query params (same logic as list blocks)
  2763.                         $queryCategoriesRaw $this->request->query->all('category');
  2764.                         $queryCategories is_array($queryCategoriesRaw) ? array_values(array_filter(array_map('intval'$queryCategoriesRaw))) : [];
  2765.                         if (!is_array($queryCategoriesRaw) && $queryCategoriesRaw !== null && $queryCategoriesRaw !== '') {
  2766.                             $queryCategories = [(int)$queryCategoriesRaw];
  2767.                         }
  2768.                         if (!empty($queryCategories)) {
  2769.                             $relationIds = [];
  2770.                             foreach ($queryCategories as $pageId) {
  2771.                                 $pagesRelations $this->entityManager->getRepository(StdPagesPages::class)->findBy([
  2772.                                     'pageId' => $pageId
  2773.                                 ]);
  2774.                                 foreach ($pagesRelations as $pagesRelation) {
  2775.                                     $relationIds[] = $pagesRelation->getId();
  2776.                                 }
  2777.                             }
  2778.                             $relationId = !empty($relationIds) ? $relationIds $queryCategories;
  2779.                         }
  2780.                         $items $blocksservice->fetchConta5Min(
  2781.                             $this->locale,
  2782.                             $this->entityManager,
  2783.                             $limit,
  2784.                             $relationId
  2785.                         );
  2786.                         $payload array_merge($variables, [
  2787.                             'settings' => $block['settings'] ?? [],
  2788.                             'fields'   => $block['components'] ?? [],
  2789.                             'items'    => $items,
  2790.                             'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2791.                         ]);
  2792.                     } elseif (isset($stdsettings['isCurtasBlock']) && $stdsettings['isCurtasBlock']) {
  2793.                         $limit = (int)($block['settings']['limit'] ?? 30);
  2794.                         $relationId = (int)($block['components']['category'] ?? -1);
  2795.                         $items $blocksservice->fetchCurtas(
  2796.                             $this->locale,
  2797.                             $this->entityManager,
  2798.                             $limit,
  2799.                             $relationId
  2800.                         );
  2801.                         $payload array_merge($variables, [
  2802.                             'settings' => $block['settings'] ?? [],
  2803.                             'fields'   => $block['components'] ?? [],
  2804.                             'items'    => $items,
  2805.                             'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2806.                         ]);
  2807.                     } else {
  2808.                         $payload array_merge($variables, [
  2809.                             'settings' => $block["settings"],
  2810.                             'fields' => $block["components"],
  2811.                             'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2812.                             'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array())
  2813.                         ]);
  2814.                     }
  2815.                     $cache = new DoctrineDbalAdapter($this->registry->getConnection());
  2816.                     if ($ajaxCall && array_key_exists("isAjax"$ajaxCall))
  2817.                         $payload array_merge($payload, ["isajax" => true]);
  2818.                     
  2819.                     // DEBUG: Log pageskin value for block_list blocks
  2820.                     if ($block["block"] === "block_list") {
  2821.                         file_put_contents('/tmp/lazy_debug.log'date('Y-m-d H:i:s') . " PAGESKIN CHECK - pageskin: '" $pageskin "' | block: " $block["block"] . " | blockuniqueid: " . ($block["blockuniqueid"] ?? "NOT SET") . "\n"FILE_APPEND);
  2822.                     }
  2823.                     
  2824.                     $skin "default";
  2825.                     if ($pageskin != "") {
  2826.                         $skin $pageskin;
  2827.                         if ($this->container->get('twig')->getLoader()->exists($skin)) {
  2828.                             $cachekey Functions::cleanString($this->locale $variables["blockSequence"] . "-" $skin "-" $pagenumber);
  2829.                             $cacheitem $cache->getItem($cachekey);
  2830.                             $updated false;
  2831.                             if (is_array($cacheitem->get()) && strtotime($cacheitem->get()["updated"]) < strtotime($pageContent->getUpdatedDate()->format("Y-m-d H:i:s"))) {
  2832.                                 $updated true;
  2833.                             }
  2834.                             if ($updated || !$cacheitem->isHit() || !$iscacheable || (getenv("APP_ENV") == "dev" && !getenv("CACHE_FORCE"))) {
  2835.                                 $item = array("updated" => date("Y-m-d H:i:s"), "data" => $this->renderView($skin$payload));
  2836.                                 if ($iscacheable) {
  2837.                                     $cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
  2838.                                     $cache->save($cacheitem->set($item));
  2839.                                 }
  2840.                                 $result .= $item["data"];
  2841.                             } else {
  2842.                                 $result .= $cacheitem->get()["data"];
  2843.                             }
  2844.                         }
  2845.                     } else {
  2846.                         if ($block["skin"] != "")
  2847.                             $skin $block["skin"];
  2848.                         
  2849.                         // DEBUG: Log ALL block_list blocks to see what's happening
  2850.                         if ($block["block"] === "block_list") {
  2851.                             file_put_contents('/tmp/lazy_debug.log'date('Y-m-d H:i:s') . " BLOCK_LIST DEBUG - skin: " $skin " | blockuniqueid: " . ($block["blockuniqueid"] ?? "NOT SET") . " | lazy_enabled: " . (isset($block["settings"]["lazy_loading_enabled"]) ? ($block["settings"]["lazy_loading_enabled"] ? "TRUE" "FALSE") : "NOT SET") . " | ajaxCall: " json_encode($ajaxCall) . "\n"FILE_APPEND);
  2852.                         }
  2853.                         
  2854.                         // For AJAX lazy loading requests, use the blockskin passed from the lazy loader
  2855.                         if ($ajaxCall && array_key_exists("isAjax"$ajaxCall) && isset($ajaxCall["blockskin"]) && !empty($ajaxCall["blockskin"])) {
  2856.                             $skin $ajaxCall["blockskin"];
  2857.                         }
  2858.                         // Check if lazy loading is enabled for this block (only for block_list and non-AJAX requests)
  2859.                         elseif ($block["block"] === "block_list" 
  2860.                             && isset($block["settings"]["lazy_loading_enabled"]) 
  2861.                             && $block["settings"]["lazy_loading_enabled"
  2862.                             && (!$ajaxCall || !array_key_exists("isAjax"$ajaxCall))) {
  2863.                             // Store the original block skin so the lazy template knows what to load via AJAX
  2864.                             // Use lazy_loading_skin if set, otherwise fall back to the block's main skin
  2865.                             $targetSkin = !empty($block["settings"]["lazy_loading_skin"]) 
  2866.                                 ? $block["settings"]["lazy_loading_skin"
  2867.                                 : $skin;
  2868.                             // DEBUG: Log blockuniqueid value
  2869.                             file_put_contents('/tmp/lazy_debug.log'date('Y-m-d H:i:s') . " LAZY LOADING BRANCH - blockuniqueid: " . ($block["blockuniqueid"] ?? "NOT SET") . " | skin: " $targetSkin " | block keys: " implode(', 'array_keys($block)) . "\n"FILE_APPEND);
  2870.                             // Build proper payload for lazy template
  2871.                             $payload array_merge($variables, [
  2872.                                 'settings' => $block["settings"],
  2873.                                 'fields' => $block["components"],
  2874.                                 'blockuniqueid' => $block["blockuniqueid"] ?? "",
  2875.                                 'lazy_loading_skin' => $targetSkin
  2876.                             ]);
  2877.                             $skin "lazy";
  2878.                         }
  2879.                         
  2880.                         if ($this->container->get('twig')->getLoader()->exists("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".html.twig")) {
  2881.                             $cachekey Functions::cleanString($this->locale $variables["blockSequence"] . "-" "blocks/" $block["block"] . "/" $block["block"] . "." $skin ".html.twig" "-" $pagenumber);
  2882.                             $cacheitem $cache->getItem($cachekey);
  2883.                             $updated false;
  2884.                             if (isset($variables["preview"]) && $variables["preview"] || is_array($cacheitem->get()) && strtotime($cacheitem->get()["updated"]) < strtotime($pageContent->getUpdatedDate()->format("Y-m-d H:i:s"))) {
  2885.                                 $updated true;
  2886.                             }
  2887.                             if ($updated || !$cacheitem->isHit() || !$iscacheable || (getenv("APP_ENV") == "dev" && !getenv("CACHE_FORCE"))) {
  2888.                                 $item = array("updated" => date("Y-m-d H:i:s"), "data" => $this->renderView("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".html.twig"$payload));
  2889.                                 /* BLOCK GROUP */
  2890.                                 if ($block["block"] == "block_group") {
  2891.                                     if (array_key_exists("group_children"$block["components"]) && $block["components"]["group_children"] != "") {
  2892.                                         $block_group_children json_decode($block["components"]["group_children"]);
  2893.                                         $group_last_children end($block_group_children);
  2894.                                         $block_groups[$group_last_children->block_uniqueid] = array();
  2895.                                     }
  2896.                                     $group_data explode('<!-- @START GROUP CONTENT -->'$item['data']);
  2897.                                     if (count($group_data) > 0) {
  2898.                                         $item["data"] = $group_data[0];
  2899.                                         $block_groups[$group_last_children->block_uniqueid]["end_html"] = $group_data[1];
  2900.                                     } else {
  2901.                                         $block_groups[$group_last_children->block_uniqueid]["end_html"] = "";
  2902.                                     }
  2903.                                 }
  2904.                                 /* @END BLOCK GROUP */
  2905.                                 if ($iscacheable && (!isset($variables["preview"]) || !$variables["preview"])) {
  2906.                                     $cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
  2907.                                     $cache->save($cacheitem->set($item));
  2908.                                 }
  2909.                                 $result .= $item["data"];
  2910.                             } else {
  2911.                                 $result .= $cacheitem->get()["data"];
  2912.                             }
  2913.                         }
  2914.                         if ($this->container->get('twig')->getLoader()->exists("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".js.twig")) {
  2915.                             $cachekey Functions::cleanString($this->locale $variables["blockSequence"] . "-" "blocks/" $block["block"] . "/" $block["block"] . "." $skin ".js.twig" "-" $pagenumber);
  2916.                             $cacheitem $cache->getItem($cachekey);
  2917.                             $updated false;
  2918.                             if (is_array($cacheitem->get()) && strtotime($cacheitem->get()["updated"]) < strtotime($pageContent->getUpdatedDate()->format("Y-m-d H:i:s"))) {
  2919.                                 $updated true;
  2920.                             }
  2921.                             if ($updated || !$cacheitem->isHit() || !$iscacheable || (getenv("APP_ENV") == "dev" && !getenv("CACHE_FORCE"))) {
  2922.                                 $item = array("updated" => date("Y-m-d H:i:s"), "data" => $this->renderView("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".js.twig"$payload));
  2923.                                 if ($iscacheable) {
  2924.                                     $cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
  2925.                                     $cache->save($cacheitem->set($item));
  2926.                                 }
  2927.                                 $resultjs .= $item["data"];
  2928.                             } else {
  2929.                                 $resultjs .= $cacheitem->get()["data"];
  2930.                             }
  2931.                         }
  2932.                     }
  2933.                 }
  2934.             }
  2935.             /* BLOCK GROUP */
  2936.             if (isset($block["blockuniqueid"]) && isset($block_groups[$block["blockuniqueid"]])) {
  2937.                 if (array_key_exists("end_html"$block_groups[$block["blockuniqueid"]])) {
  2938.                     $result .= $block_groups[$block["blockuniqueid"]]["end_html"];
  2939.                 }
  2940.             }
  2941.             /* @END BLOCK GROUP */
  2942.         }
  2943.         $this->mainrequest->attributes->set('webpackEntries'array_map(function ($value) {
  2944.             return str_replace('%locale%'$this->locale$value);
  2945.         }, $this->mainrequest->attributes->get('webpackEntries')));
  2946.         if ($ajaxCall && array_key_exists("isAjax"$ajaxCall)) {
  2947.             if ($payload) {
  2948.                 return array("html" => $result"js" => $resultjs"payload" => $payload"variables" => $variables'cookies' => $cookies);
  2949.             } else {
  2950.                 return array("html" => $result"js" => $resultjs"payload" => array(), "variables" => $variables'cookies' => $cookies);
  2951.             }
  2952.         } else {
  2953.             return array("html" => $result"js" => $resultjs"variables" => $variables'cookies' => $cookies'block_groups' => $block_groups);
  2954.         }
  2955.     }
  2956.     private function findFriendlyUrlByPageId($pageId$entityManager$language)
  2957.     {
  2958.         $friendlyUrlRepo $entityManager->getRepository(StdFriendlyUrl::class)->getRowByPageAndRelationTreeNotNull($pageId$language);
  2959.         if (!$friendlyUrlRepo) {
  2960.             $friendlyUrlRepo $entityManager->getRepository(StdFriendlyUrl::class)->getOneRowByPage($pageId$language);
  2961.         }
  2962.         return $friendlyUrlRepo;
  2963.     }
  2964.     private function renderPreviewPageContent($fields, array $variables = []): array
  2965.     {
  2966.         $blocksservice = new StdBlocksService($this->stdTrackingService$this->entityManager);
  2967.         $renderlistblocks true;
  2968.         $pagenumber 1;
  2969.         $cont $fields;
  2970.         if (isset($cont["fields"]))
  2971.             $content $cont["fields"];
  2972.         else
  2973.             $content = array();
  2974.         $result "";
  2975.         $resultjs "";
  2976.         $payload = [];
  2977.         $headercontent = [];
  2978.         $publishDatePage null;
  2979.         $expireDatePage null;
  2980.         $blockSequence 0;
  2981.         $now = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
  2982.         $publishDateIni $now;
  2983.         $dateFim = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
  2984.         $dateFim->add(new DateInterval('P10D'));
  2985.         $expireDateIni $dateFim;
  2986.         $blockmachinename "";
  2987.         foreach ($content as $block) {
  2988.             $publishDate $publishDateIni;
  2989.             $expireDate $expireDateIni;
  2990.             if (array_key_exists("settings"$block) && $block["settings"]) {
  2991.                 if (array_key_exists("publish_date"$block["settings"]) && $block["settings"]["publish_date"]) {
  2992.                     $dateIni date_create_from_format("d/m/Y h:i A"$block["settings"]["publish_date"]);
  2993.                     $publishDate = new DateTime($dateIni->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  2994.                 }
  2995.                 if (array_key_exists("expire_date"$block["settings"]) && $block["settings"]["expire_date"]) {
  2996.                     $dateFim date_create_from_format("d/m/Y h:i A"$block["settings"]["expire_date"]);
  2997.                     $expireDate = new DateTime($dateFim->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  2998.                 }
  2999.             }
  3000.             if ($publishDate <= $now && $expireDate $now) {
  3001.                 if (!empty($pageskin)) {
  3002.                     $pageskin "blocks/" $block["block"] . "/" $block["block"] . "." $pageskin ".html.twig";
  3003.                 }
  3004.                 $iscacheable true;
  3005.                 $blockSequence++;
  3006.                 $variables["blockSequence"] = $block["block"] . "_1_" $blockSequence;
  3007.                 if (!empty($blockmachinename) && $block["block"] != $blockmachinename && $variables["blockSequence"] != $blockmachinename) {
  3008.                     continue;
  3009.                 }
  3010.                 $payload = [];
  3011.                 $stdblock $this->entityManager->getRepository(StdBlocks::class)->findOneBy(['machineName' => $block["block"]]);
  3012.                 if ($stdblock) {
  3013.                     $stdsettings $stdblock->getSettings();
  3014.                     if (isset($block["templatesBlocksId"]) && $block["templatesBlocksId"] && isset($block["isMaster"]) && $block["isMaster"]) {
  3015.                         $stdtemplate $page->getTemplateId();
  3016.                         if ($stdtemplate->getId()) {
  3017.                             $stdtemplateblock $this->entityManager->getRepository(StdTemplatesBlocks::class)->findOneById($block["templatesBlocksId"]);
  3018.                             if ($stdtemplateblock) {
  3019.                                 $blockcontent $stdtemplateblock->getContent();
  3020.                                 $block["settings"] = $blockcontent["settings"];
  3021.                                 $block["components"] = $blockcontent["components"];
  3022.                                 $block["skin"] = $blockcontent["skin"];
  3023.                                 $block["repeatable"] = ($blockcontent["repeatable"] ? $blocksservice->filterPublishedRepeatables($blockcontent["repeatable"]) : array());
  3024.                             }
  3025.                         }
  3026.                     }
  3027.                     
  3028.                     // Check if lazy loading is enabled - skip list processing and render lazy skeleton instead
  3029.                     $isLazyLoadingEnabled $block["block"] === "block_list" 
  3030.                         && isset($block["settings"]["lazy_loading_enabled"]) 
  3031.                         && $block["settings"]["lazy_loading_enabled"
  3032.                         && (!$ajaxCall || !array_key_exists("isAjax"$ajaxCall));
  3033.                     
  3034.                     if (isset($stdsettings["isList"]) && $stdsettings["isList"] && $renderlistblocks && !$isLazyLoadingEnabled) {
  3035.                         //it's a list
  3036.                         //get the content_type, template and the category from block components
  3037.                         //get x category childs and render with selected skin
  3038.                         $iscacheable false;
  3039.                         // Use content_type_list instead of the old content_type field
  3040.                         $contentType null;
  3041.                         if (isset($block["components"]["content_type_list"]) && !empty($block["components"]["content_type_list"])) {
  3042.                             // For multiple content types, use the first one for compatibility
  3043.                             $contentTypeId is_array($block["components"]["content_type_list"])
  3044.                                 ? $block["components"]["content_type_list"][0]
  3045.                                 : $block["components"]["content_type_list"];
  3046.                             $contentType $this->entityManager->getRepository(StdContentTypes::class)->findOneById($contentTypeId);
  3047.                         }
  3048.                         $levels = (isset($block["components"]["levels"]) ? $block["components"]["levels"] : 1);
  3049.                         $contentTypeList = (isset($block["components"]["content_type_list"]) ? $block["components"]["content_type_list"] : array());
  3050.                         $locationTags = [];
  3051.                         if (!empty($this->request->getSession()->get('close_location_ids'))) {
  3052.                             $locationTags $this->request->getSession()->get('close_location_ids');
  3053.                         }
  3054.                         $relations $this->entityManager->getRepository(StdPagesPages::class)->getNChildsOfRelation(["relation_id" => $block["components"]["category"], "limit" => $block["components"]["limit"], "template" => $block["components"]["template"], "order" => $block["components"]["order"], "levels" => $levels"paginate" => $block["components"]["paginate"], "content_type_list" => $contentTypeList"ajaxFilter" => [], "page" => $pagenumber"paginator" => $this->paginator"language_code" => $this->locale'locationTags' => $locationTags]);
  3055.                         $resultlist "";
  3056.                         $resultlistjs "";
  3057.                         $total count($relations);
  3058.                         $index 0;
  3059.                         foreach ($relations as $stdpagespages) {
  3060.                             $relationcontent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $stdpagespages["page_id"], "languageCode" => $this->locale]);
  3061.                             //render
  3062.                             $friendlyUrl "";
  3063.                             if ($relationcontent) {
  3064.                                 $friendlyUrlObj $this->findFriendlyUrlByPageId($relationcontent->getPageId()->getId(), $this->entityManager$this->locale);
  3065.                                 $friendlyUrl $friendlyUrlObj $friendlyUrlObj->getUrl() : "";
  3066.                                 $fields $this->prepareVariables($relationcontent);
  3067.                                 $relationPageId $relationcontent->getPageId();
  3068.                                 $fields['isTop10'] = false;
  3069.                                 if ($relationPageId->getPublishDate())
  3070.                                     $publishDatePage = new DateTime($relationPageId->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  3071.                                 if ($relationPageId->getExpireDate())
  3072.                                     $expireDatePage = new DateTime($relationPageId->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  3073.                             } else {
  3074.                                 $fields = array();
  3075.                             }
  3076.                             // Handle skin selection with fallback logic
  3077.                             $selectedSkin 'default';
  3078.                             $skinparam 'content-types/default/content_type.default.html.twig'// Default fallback
  3079.                             $skinjsparam 'content-types/default/content_type.default.js.twig'// Default JS fallback
  3080.                             if (array_key_exists("skin"$block["components"]) && $block["components"]["skin"]) {
  3081.                                 $skinValue $block["components"]["skin"];
  3082.                                 // If skin is an array (multiple selection), use the first one
  3083.                                 if (is_array($skinValue) && !empty($skinValue)) {
  3084.                                     $selectedSkin reset($skinValue);
  3085.                                 } elseif (is_string($skinValue)) {
  3086.                                     $selectedSkin $skinValue;
  3087.                                 }
  3088.                             }
  3089.                             // Template selection with cascading fallbacks
  3090.                             if (!empty($contentType)) {
  3091.                                 // 1st priority: Specific skin template
  3092.                                 if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $selectedSkin '.html.twig')) {
  3093.                                     $skinparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $selectedSkin '.html.twig';
  3094.                                 }
  3095.                                 // 2nd priority: Content type default template
  3096.                                 elseif ($this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.html.twig')) {
  3097.                                     $skinparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.html.twig';
  3098.                                 }
  3099.                                 // JS template with same fallback logic
  3100.                                 if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $selectedSkin '.js.twig')) {
  3101.                                     $skinjsparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $selectedSkin '.js.twig';
  3102.                                 }
  3103.                                 elseif ($this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.js.twig')) {
  3104.                                     $skinjsparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.js.twig';
  3105.                                 }
  3106.                             }
  3107.                             if (isset($stdsettings["renderPageBlocks"]) && $stdsettings["renderPageBlocks"]) {
  3108.                                 $content $this->renderPageContent($pagenumber$fields$relationcontent->getPageId(), $relationcontentnullfalse);
  3109.                             } else {
  3110.                                 $content["html"] = "";
  3111.                                 $content["js"] = "";
  3112.                             }
  3113.                             $headercontent = [
  3114.                                 "publishdate" => ($publishDatePage != null $publishDatePage->format('Y-m-d H:i:s') : null),
  3115.                                 "expiredate" => ($expireDatePage != null $expireDatePage->format('Y-m-d H:i:s') : null),
  3116.                                 "lastupdate" => "",//($page->getUpdatedDate() != null ? $page->getUpdatedDate()->format('Y-m-d H:i:s') : null),
  3117.                                 "createdby" => "",//$page->getCreatedBy()->getName(),
  3118.                                 "order" => 0,//$page->getOrderValue()
  3119.                             ];
  3120.                             $payload array_merge([
  3121.                                 "headercontent" => $headercontent,
  3122.                                 "id" => $relationcontent->getPageId()->getId(),
  3123.                                 "relationid" => $stdpagespages["relation_id"],
  3124.                                 "currentrelationid" => $stdpagespages["id"],
  3125.                                 "total" => $total,
  3126.                                 "index" => $index,
  3127.                                 "settings" => $block["settings"],
  3128.                                 "locale" => $this->locale,
  3129.                                 "blockscontent" => $content["html"],
  3130.                                 "blockscontentjs" => $content["js"],
  3131.                                 "pagination" => $relations,
  3132.                                 'friendlyUrl' => $friendlyUrl
  3133.                             ], $fields);
  3134.                             if ($this->container->get('twig')->getLoader()->exists($skinparam))
  3135.                                 $resultlist .= $this->renderView($skinparam$payload);
  3136.                             if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
  3137.                                 $resultlistjs .= $this->renderView($skinjsparam$payload);
  3138.                             $index++;
  3139.                         }
  3140.                         $payload array_merge($variables, [
  3141.                             'settings' => $block["settings"],
  3142.                             'fields' => $block["components"],
  3143.                             'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  3144.                             'blockscontent' => $resultlist,
  3145.                             'blockscontentjs' => $resultlistjs,
  3146.                             'paginator' => $relations
  3147.                         ]);
  3148.                     } elseif (isset($block["isPage"]) && $block["isPage"]) {
  3149.                         $contentType $this->entityManager->getRepository(StdContentTypes::class)->findOneById($block["components"]["input_type_content_type"]);
  3150.                         $pageContent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $block["components"]["input_combo_pages"], "languageCode" => $this->locale]);
  3151.                         if ($pageContent)
  3152.                             $fields $this->prepareVariables($pageContent);
  3153.                         $inputSkin = isset($block["components"]["input_combo_skin"]) && $block["components"]["input_combo_skin"] != "" $block["components"]["input_combo_skin"] : "default";
  3154.                         if ($this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.html.twig'))
  3155.                             $skinparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.html.twig';
  3156.                         else
  3157.                             $skinparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.html.twig';
  3158.                         if ($this->container->get('twig')->getLoader()->exists('content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.js.twig'))
  3159.                             $skinjsparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.' $inputSkin '.js.twig';
  3160.                         else
  3161.                             $skinjsparam 'content-types/' $contentType->getMachineName() . '/' $contentType->getMachineName() . '.default.js.twig';
  3162.                         $content $this->renderPageContent($pagenumber$fields$pageContent->getPageId(), $pageContentnull);
  3163.                         if ($contentType->getMachineName() == "forms") {
  3164.                             $form $this->createForm(StdDynamicForm::class);
  3165.                             $fields $pageContent->getContent();
  3166.                             $fieldsvariables $this->prepareVariables($pageContent);
  3167.                             $rulesAndMessages $this->getRulesAndMessagesForm($fields["fields"]);
  3168.                             $payload array_merge([
  3169.                                 'settings' => $block["settings"],
  3170.                                 'fields' => $block["components"],
  3171.                                 'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  3172.                                 'blockscontent' => $content["html"],
  3173.                                 'blockscontentjs' => $content["js"],
  3174.                                 'form' => $form->createView(),
  3175.                                 'messages' => $rulesAndMessages["messages"],
  3176.                                 'rules' => $rulesAndMessages["rules"],
  3177.                             ], $fieldsvariables);
  3178.                         } else {
  3179.                             $payload array_merge([
  3180.                                 'settings' => $block["settings"],
  3181.                                 'fields' => $block["components"],
  3182.                                 'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
  3183.                                 'blockscontent' => $content["html"],
  3184.                                 'blockscontentjs' => $content["js"],
  3185.                             ], $fields);
  3186.                         }
  3187.                         if ($this->container->get('twig')->getLoader()->exists($skinparam))
  3188.                             $result .= $this->renderView($skinparam$payload);
  3189.                         if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
  3190.                             $resultjs .= $this->renderView($skinjsparam$payload);
  3191.                     } elseif (isset($stdsettings["isFormDomain"]) && $stdsettings["isFormDomain"]) {
  3192.                         //get the domain values for the selected domain
  3193.                         if ($block["components"]["form_select_domain"]) {
  3194.                             $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $block["components"]["form_select_domain"]]);
  3195.                         }
  3196.                         $payload array_merge($variables, [
  3197.                             'settings' => $block["settings"],
  3198.                             'fields' => $block["components"],
  3199.                             'values' => $domainvalues
  3200.                         ]);
  3201.                     } elseif (isset($stdsettings["isFormStatus"]) && $stdsettings["isFormStatus"]) {
  3202.                         //get the domain values for the selected domain
  3203.                         $domainvalues = [];
  3204.                         $domainobj $this->entityManager->getRepository(StdDomains::class)->findOneBy(["machineName" => "form_status"]);
  3205.                         if ($domainobj) {
  3206.                             if ($block["components"]["form_select_default"] != "") {
  3207.                                 $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id"), "machineName" => $block["components"]["form_select_default"]]);
  3208.                             } else {
  3209.                                 $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id")]);
  3210.                             }
  3211.                         }
  3212.                         $payload array_merge($variables, [
  3213.                             'settings' => $block["settings"],
  3214.                             'fields' => $block["components"],
  3215.                             'values' => $domainvalues
  3216.                         ]);
  3217.                     } else {
  3218.                         $payload array_merge($variables, [
  3219.                             'settings' => $block["settings"],
  3220.                             'fields' => $block["components"],
  3221.                             'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array())
  3222.                         ]);
  3223.                     }
  3224.                     if (!empty($ajaxCall) && array_key_exists("isAjax"false))
  3225.                         $payload array_merge($payload, ["isajax" => true]);
  3226.                     $skin "default";
  3227.                     if (!empty($pageskin)) {
  3228.                         $skin $pageskin;
  3229.                         if ($this->container->get('twig')->getLoader()->exists($skin)) {
  3230.                             $result .= $this->renderView($skin$payload);
  3231.                         }
  3232.                     } else {
  3233.                         if ($block["skin"] != "")
  3234.                             $skin $block["skin"];
  3235.                         if ($this->container->get('twig')->getLoader()->exists("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".html.twig")) {
  3236.                             $result .= $this->renderView("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".html.twig"$payload);
  3237.                         }
  3238.                         if ($this->container->get('twig')->getLoader()->exists("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".js.twig")) {
  3239.                             $resultjs .= $this->renderView("blocks/" $block["block"] . "/" $block["block"] . "." $skin ".js.twig"$payload);
  3240.                         }
  3241.                     }
  3242.                 }
  3243.             }
  3244.         }
  3245.         if (!empty($ajaxCall) && array_key_exists("isAjax"false)) {
  3246.             if ($payload) {
  3247.                 return array("html" => $result"js" => $resultjs"payload" => $payload"variables" => $variables);
  3248.             } else {
  3249.                 return array("html" => $result"js" => $resultjs"payload" => array(), "variables" => $variables);
  3250.             }
  3251.         } else {
  3252.             return array("html" => $result"js" => $resultjs"variables" => $variables);
  3253.         }
  3254.     }
  3255.     private function prepareVariables(StdPagesContent $pageContent$preview = array()): array
  3256.     {
  3257.         $variables $pageContent->getContent();
  3258.         unset($variables["fields"]);
  3259.         $variables["title"] = $pageContent->getTitle();
  3260.         $variables["pageid"] = $pageContent->getPageId()->getId();
  3261.         $variables["contenttype"] = $pageContent->getPageId()->getContentType()->getMachineName();
  3262.         $variables["url"] = $pageContent->getUrl();
  3263.         $variables["metatitle"] = $pageContent->getMetaTitle();
  3264.         $variables["metakeywords"] = $pageContent->getMetaKeywords();
  3265.         $variables["metadescription"] = $pageContent->getMetaDescription();
  3266.         $variables["languagecode"] = $pageContent->getLanguageCode();
  3267.         $variables["ogtitle"] = $pageContent->getOgTitle();
  3268.         $variables["ogimage"] = $pageContent->getOgImage();
  3269.         $variables["ogdescription"] = $pageContent->getOgDescription();
  3270.         $variables["ogurl"] = $pageContent->getOgUrl();
  3271.         $variables["scriptshead"] = $pageContent->getScriptsHead();
  3272.         $variables["scriptsbody"] = $pageContent->getScriptsBody();
  3273.         $variables["scriptsfooter"] = $pageContent->getScriptsFooter();
  3274.         $variables["page"] = $pageContent->getPageId();
  3275.         if ($this->stdTrackingService->isPreciseTrackingEnabled()) {
  3276.             $allowedPreciseLocation $this->stdTrackingService
  3277.                 ->getRecentPreciseLocationOfIp($this->request->getClientIp(), false);
  3278.             $addTrackingPreciseJs false;
  3279.             $useGeoMapTracking $this->stdTrackingService->isUseGeoMapForTracking();
  3280.             $useApiTracking $this->stdTrackingService->isUseApiForTracking();
  3281.             if ($allowedPreciseLocation === null) {
  3282.                 $addTrackingPreciseJs true;
  3283.             }
  3284.             $variables["scripts_tracking_precise"] = $addTrackingPreciseJs;
  3285.             $variables["use_geo_map_tracking"] = $useGeoMapTracking;
  3286.             $variables["use_api_tracking"] = $useApiTracking;
  3287.         }
  3288.         //get page attributes
  3289.         if (empty($preview)) {
  3290.             $allPagesAttributesValues $this->entityManager->getRepository(StdPagesAttributesValues::class)->getPageAttributes($pageContent->getPageId());
  3291.         } elseif (isset($preview['dataForm']['pages_attributes'])) {
  3292.             foreach ($preview['dataForm']['pages_attributes'] as $key => $pagesattributes) {
  3293.                 $parts explode('|||'$key);
  3294.                 $allPagesAttributesValues[] = $this->entityManager->getRepository(StdAttributes::class)->findOneBy(['machineName' => $parts[1]]);;
  3295.                 $allPagesAttributesValues[] = $this->entityManager->getRepository(StdAttributesValues::class)->findOneBy(['attributeMachineName' => $parts[1]]);
  3296.             }
  3297.         } else {
  3298.             $allPagesAttributesValues = [];
  3299.         }
  3300.         $attributesarr = [];
  3301.         foreach ($allPagesAttributesValues as $entity) {
  3302.             if ($entity instanceof StdAttributes) {
  3303.                 $attributesarr[$entity->getMachineName()]["attribute"] = $entity;
  3304.             }
  3305.             if ($entity instanceof StdAttributesValues) {
  3306.                 $attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()] = $entity;
  3307.             }
  3308.         }
  3309.         $variables["pageattributes"] = $attributesarr;
  3310.         $variables["isTop10"] = false;
  3311.         return $variables;
  3312.     }
  3313.     private function getRulesAndMessagesForm(array $fields)
  3314.     {
  3315.         $messages = [];
  3316.         $rules = [];
  3317.         foreach ($fields as $field) {
  3318.             $name "";
  3319.             if (isset($field["components"]["form_input_name"])) {
  3320.                 $name $field["components"]["form_input_name"];
  3321.             }
  3322.             if ($name == "") {
  3323.                 continue;
  3324.             }
  3325.             if ($field["block"] == "form_checkbox" && isset($field["repeatable"]) && count($field["repeatable"]) > 1) {
  3326.                 $name .= "[]";
  3327.             }
  3328.             foreach ($field["settings"] as $key => $value) {
  3329.                 if (Functions::startsWith($key"setting") || Functions::startsWith($key"separator")) {
  3330.                     continue;
  3331.                 }
  3332.                 $keyArray explode("_"$key);
  3333.                 $rule $keyArray[1];
  3334.                 if ($value === "1") {
  3335.                     $value true;
  3336.                 } else if ($value === "0" || $value === "" || !$value) {
  3337.                     $value false;
  3338.                 }
  3339.                 $message "";
  3340.                 if (isset($field["components"]["form_input_" $keyArray[1] . "_label"]))
  3341.                     $message $field["components"]["form_input_" $keyArray[1] . "_label"];
  3342.                 if ($field["block"] == "form_checkbox" && $rule == "required") {
  3343.                     $rules[$name]["required"] = $value;
  3344.                 } else {
  3345.                     $rules[$name][$rule] = $value;
  3346.                 }
  3347.                 if ($message != "") {
  3348.                     $messages[$name][$rule] = $message;
  3349.                 }
  3350.             }
  3351.         }
  3352.         return array("rules" => $rules"messages" => $messages);
  3353.     }
  3354.     #[Route(path'{_locale}/listPagesJson/{contentTypeToList}'name'list_pages_json')]
  3355.     public function listPagesJson($contentTypeToList): Response
  3356.     {
  3357.         //TO DO
  3358.         //receber o order (opcional)
  3359.         //receber o relation_id /categoria (opcional)
  3360.         //receber o paginate (opcional), se vier preenchido deve vir paginate=1
  3361.         //receber o page (obrigatório se vier o paginate)
  3362.         //receber o limit (obrigatório se vier o paginate)
  3363.         //Acrescentar mais campos na resposta json?
  3364.         $now = new \DateTime();
  3365.         $contentType $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(["machineName" => $contentTypeToList]);
  3366.         if ($contentType) {
  3367.             //categoria associada ao content type
  3368.             $category $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['machineName' => $contentType->getMachineNameCategories()]);
  3369.             $pageController = new StdPagesController($this->translator$this->entityManager$this->dispatcher);
  3370.             $arrAttr = array();
  3371.             // Verify filter
  3372.             $dataForm $this->request->request->all();
  3373.             if ($dataForm) {
  3374.                 foreach ($dataForm as $search => $dataFilter) {
  3375.                     if (strpos($search"ilter_")) {
  3376.                         $dataExplode explode("filter_"$search);
  3377.                         $attributeMachineName $dataExplode[1];
  3378.                         $arrAttr[$attributeMachineName] = $dataFilter;
  3379.                     }
  3380.                 }
  3381.             }
  3382.             // Format attributes
  3383.             $attributesReturn = [];
  3384.             $contentTypesAttr $this->entityManager->getRepository(StdContentTypesAttributes::class)->findBy(["contentTypeMachineName" => $contentType->getMachineName()]);
  3385.             foreach ($contentTypesAttr as $ctt) {
  3386.                 $attributes $this->entityManager->getRepository(StdAttributes::class)->findBy(["machineName" => $ctt->getAttributeMachineName()]);
  3387.                 foreach ($attributes as $attr) {
  3388.                     $attrValues $this->entityManager->getRepository(StdAttributesValues::class)->findBy(["attributeMachineName" => $attr->getMachineName()]);
  3389.                     foreach ($attrValues as $val) {
  3390.                         $attributesReturn[] = array(
  3391.                             "attributeMachineName" => $val->getAttributeMachineName(),
  3392.                             "label" => $val->getLabel(),
  3393.                             "value" => $val->getValue(),
  3394.                             "image" => $val->getImage(),
  3395.                             "order" => $val->getOrderValue()
  3396.                         );
  3397.                     }
  3398.                 }
  3399.             }
  3400.             usort($attributesReturn, function ($a$b) {
  3401.                 return $a['order'] <=> $b['order'];
  3402.             });
  3403.             $pages $this->entityManager->getRepository(StdPages::class)->searchContent(array(
  3404.                 "search" => (isset($dataForm["search"]) ? $dataForm["search"] : "")
  3405.             , "contentType" => $contentType->getId()
  3406.             , "ajaxFilter" => sizeof($arrAttr) > ? array("arrAttr" => $arrAttr) : []
  3407.             ));
  3408.             $returnArr = [];
  3409.             $categories = [];
  3410.             $total $pages["total"];
  3411.             $index 0;
  3412.             foreach ($pages["stdPages"] as $page) {
  3413.                 $pageContent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $page["id"], "languageCode" => $this->locale]);
  3414.                 $attrValues = [];
  3415.                 if ($pageContent) {
  3416.                     $pageAttributes $this->entityManager->getRepository(StdPagesAttributesValues::class)->findBy(["pageId" => $page["id"]]);
  3417.                     if ($pageAttributes) {
  3418.                         foreach ($pageAttributes as $pa) {
  3419.                             $attrValues[] = $this->entityManager->getRepository(StdAttributesValues::class)->findOneBy([
  3420.                                 "attributeMachineName" => $pa->getAttributeMachineName()
  3421.                                 , "value" => $pa->getValue()]);
  3422.                         }
  3423.                     }
  3424.                     $pageObj $pageContent->getPageId();
  3425.                     $publishDate null;
  3426.                     $expireDate null;
  3427.                     if ($pageObj->getPublishDate())
  3428.                         $publishDate = new DateTime($pageObj->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  3429.                     if ($pageObj->getExpireDate())
  3430.                         $expireDate = new DateTime($pageObj->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
  3431.                     if ($pageObj->getIsActive() && ((is_null($pageObj->getPublishDate()) || $now >= $publishDate) && (is_null($pageObj->getExpireDate()) || $now <= $expireDate))) {
  3432.                         $pageArray = array(
  3433.                             "id" => $pageContent->getPageId()->getId()
  3434.                         , "title" => $pageContent->getPageId()->getName()
  3435.                         );
  3436.                         $contentArray = [];
  3437.                         foreach ($pageContent->getContent() as $key => $content) {
  3438.                             $contentArray[$key] = $content;
  3439.                         }
  3440.                         //ir buscar categorias associadas ao conteudo
  3441.                         $categoriesOfPage = [];
  3442.                         if ($category) {
  3443.                             $pagesRelations $pageController->getRelations($category->getMachineName(), $this->entityManager$pageObjtrue);
  3444.                             //estas são as categorias associadas ao content type
  3445.                             if ($pagesRelations && count($categories) == 0) {
  3446.                                 foreach ($pagesRelations["content"] as $pr) {
  3447.                                     $categories[] = array("id" => $pr["value"], "title" => $pr["title"]);
  3448.                                 }
  3449.                             }
  3450.                             if ($pagesRelations["values"] != "") {
  3451.                                 $relationscats explode(","$pagesRelations["values"]);
  3452.                                 foreach ($relationscats as $relcats) {
  3453.                                     $pagepage $this->entityManager->getRepository(StdPagesPages::class)->findOneBy(array("id" => $relcats));
  3454.                                     if ($pagepage && $pagepage->getContentType()->getId() == $category->getId()) {
  3455.                                         $categoriesOfPage[] = array("id" => $pagepage->getPageId()->getId(), "title" => $pagepage->getPageId()->getName());
  3456.                                     }
  3457.                                 }
  3458.                             }
  3459.                         }
  3460.                         $returnArr[] = array(
  3461.                             "canonicalUrl" => $pageContent->getCanonicalUrl()
  3462.                         , "url" => $pageContent->getUrl()
  3463.                         , "title" => $pageContent->getTitle()
  3464.                         , "pageId" => $pageArray
  3465.                         "content" => $contentArray
  3466.                         "pageAttributes" => $attrValues
  3467.                         "categories" => $categoriesOfPage
  3468.                         "publishDate" => ($pageObj->getPublishDate() ? $pageObj->getPublishDate()->format('Y-m-d H:i:s') : null)
  3469.                         );
  3470.                     }
  3471.                 }
  3472.             }
  3473.             $returArray = [];
  3474.             $returArray["pages"] = $returnArr;
  3475.             $returArray["attributes"] = $attributesReturn;
  3476.             // $returArray["categories"]=array_unique($categories,SORT_REGULAR);
  3477.             $returArray["categories"] = $categories;
  3478.             return new Response(\json_encode($returArray));
  3479.         }
  3480.         return new Response(\json_encode(["sucess" => false]));
  3481.     }
  3482.     #[Route(path'/subscribe-egoi'name'subscribe-egoi')]
  3483.     public function subscribeEgoi(): JsonResponse
  3484.     {
  3485.         //falta a lista e api key no config
  3486.         if ($this->request->isXmlHttpRequest()) {
  3487.             $emailsubscribed "";
  3488.             $egoilist "";
  3489.             $egoiapikey "";
  3490.             if ($this->request->request->get('email') && $this->request->request->get('email') != "") {
  3491.                 $emailsubscribed $this->request->request->get('email');
  3492.             } elseif ($this->request->request->get('EMAIL') && $this->request->request->get('EMAIL') != "") {
  3493.                 $emailsubscribed $this->request->request->get('EMAIL');
  3494.             }
  3495.             if ($this->request->request->get('egoilist') && $this->request->request->get('egoilist') != "") {
  3496.                 $egoilist $this->request->request->get('egoilist');
  3497.             } else {
  3498.                 $egoilist getenv("EGOI_LIST_ID");
  3499.             }
  3500.             $egoiapikey Functions::getConfig("egoiapikey"""$this->entityManager);
  3501.             if ($egoiapikey == "") {
  3502.                 $egoiapikey getenv("EGOI_API_KEY");
  3503.             }
  3504.             if ($emailsubscribed != "" && $egoilist != "" && $egoiapikey != "") {
  3505.                 try {
  3506.                     $client = new \GuzzleHttp\Client(['base_uri' => 'https://api.egoiapp.com/']);
  3507.                     $response $client->request(
  3508.                         'POST'
  3509.                         '/lists/' $egoilist '/contacts'
  3510.                         , [
  3511.                             'body' => \GuzzleHttp\Utils::jsonEncode(["base" => ["email" => $emailsubscribed"language" => $this->locale]])
  3512.                             , 'headers' => [
  3513.                                 "Apikey: " $egoiapikey,
  3514.                                 "Content-Type: application/json"
  3515.                             ]
  3516.                         ]
  3517.                     );
  3518.                     $code $response->getStatusCode();
  3519.                     if ($code == 201) {
  3520.                         return new JsonResponse(["success" => true]);
  3521.                     } else {
  3522.                         return new JsonResponse(["success" => false"errorMsg" => "Erro ao subscrever"]);
  3523.                     }
  3524.                 } catch (\GuzzleHttp\Exception\RequestException $e) {
  3525.                     $guzzleResult $e->getResponse();
  3526.                     return new JsonResponse(["success" => false"errorMsg" => "Erro ao subscrever: " $guzzleResult->getReasonPhrase()]);
  3527.                 }
  3528.             } else {
  3529.                 return new JsonResponse(["success" => false"errorMsg" => "Erro ao subscrever"]);
  3530.             }
  3531.         } else {
  3532.             throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  3533.         }
  3534.     }
  3535.     #[Route(path'{path}'name'friendly_url'requirements: ['path' => '.+'], priority: -100)]
  3536.     public function showByFriendlyUrl(string $pathstring $skin "default"$thrownotfound true): Response
  3537.     {
  3538.         $repLang $this->entityManager->getRepository(StdLanguages::class);
  3539.         if (!$repLang->findOneBy(['languageCode' => $this->request->getLocale(), 'isActive' => true'isPublic' => true])) {
  3540.             throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  3541.         }
  3542.         //search redirect rules
  3543.         $rule $this->redirectsCache->get("std_redirects_" md5($path), function (ItemInterface $item) use ($path) {
  3544.             $testRule $this->entityManager->getRepository(StdRedirects::class)->getOneRule($path);
  3545.             return $testRule;
  3546.         }, $_ENV["STD_REDIRECTS_CACHE_BETA"]);
  3547.         if ($rule) {
  3548.             return $this->redirect(preg_replace("#" $rule->getUrlOrigin() . "#"$rule->getUrlDestination(), $path), $rule->getCode());
  3549.         }
  3550.         //search pages
  3551.         $rep $this->entityManager->getRepository(StdFriendlyUrl::class);
  3552.         $url $rep->findOneByUrl("/" $path);
  3553.         if ($url) {
  3554.             $relationTree $url->getRelationTree();
  3555.             if (!$relationTree) {
  3556.                 $url2 $rep->getRowByPageAndRelationTreeNotNull($url->getPageId()->getId(), $this->locale);
  3557.                 if ($url2)
  3558.                     $relationTree $url2->getRelationTree();
  3559.             }
  3560.             if ($url->getPageId()) {
  3561.                 return $this->showContentById($url$skintruefalse$relationTree);
  3562.             }
  3563.         } else {
  3564.             if ($thrownotfound)
  3565.                 throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  3566.             else
  3567.                 return new Response("");
  3568.         }
  3569.     }
  3570.     private function verifyPermission($page)
  3571.     {
  3572.         if (!$page) return;
  3573.         //check if page contenttype is forms and validate the form permissions
  3574.         if ($page->getContentType()->getMachineName() == "forms") {
  3575.             $lang $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $this->request->getLocale(), "isActive" => true]);
  3576.             $form_content $page->getLocalizedContents($lang)->getContent();
  3577.             $form_permissions Functions::checkFormPermissions($this->security$this->entityManager$form_content);
  3578.             if ($this->request->query->get("edit") && (!$form_permissions["u"] || $form_content["form_allow_edit"] != 1)) {
  3579.                 throw $this->createAccessDeniedException('ACCESS DENIED!');
  3580.             }
  3581.         }
  3582.         if (!count(($pageRoles $page->getRoles()))) return true// the page has no roles associated, so everyone can access
  3583.         if (!($user $this->security->getUser())) {
  3584.             return false;
  3585.         }
  3586.         //if user is impersonating check with the original user
  3587.         $token $this->security->getToken();
  3588.         if ($token instanceof SwitchUserToken) {
  3589.             $user $token->getOriginalToken()->getUser();
  3590.         }
  3591.         $roles = [];
  3592.         foreach ($pageRoles as $role) {
  3593.             $roles[] = $role->getName();
  3594.         }
  3595.         if (!$this->stdsecurity->userIsGranted($user$roles)) {
  3596.             return false;
  3597.         }
  3598.         return true;
  3599.     }
  3600.     public function RenderPages($pages$skin$renderblocks false): Response
  3601.     {
  3602.         $strContent "";
  3603.         if (is_array($pages) && sizeof($pages) > 0) {
  3604.             foreach ($pages as $pageId) {
  3605.                 $strContent .= $this->RenderPage((int)$pageId$skin$renderblocks);
  3606.             }
  3607.             return new Response($strContent);
  3608.         }
  3609.         return new Response();
  3610.     }
  3611.     #[Route(path'{_locale}/preview/{contentType}/{id}'name'preview_page_content_type')]
  3612.     public function previewContentType(
  3613.         string           $contentType,
  3614.         int              $id,
  3615.         string           $_locale,
  3616.         StdBlocksService $stdBlocksService,
  3617.         Request          $request
  3618.     ): Response
  3619.     {
  3620.         $contentTypeEntity $this->entityManager
  3621.             ->getRepository(StdContentTypes::class)
  3622.             ->findOneBy(['machineName' => $contentType]);
  3623.         if (!$contentTypeEntity) {
  3624.             throw $this->createNotFoundException("Content type '$contentType' not found.");
  3625.         }
  3626.         $page $this->entityManager
  3627.             ->getRepository(StdPages::class)
  3628.             ->find($id);
  3629.         if (!$page || $page->getContentType()?->getId() !== $contentTypeEntity->getId()) {
  3630.             throw $this->createNotFoundException("Page with ID $id not found for content type '$contentType'.");
  3631.         }
  3632.         $friendlyUrl $this->entityManager
  3633.             ->getRepository(StdFriendlyUrl::class)
  3634.             ->findOneBy([
  3635.                 'pageId' => $page,
  3636.                 'languageCode' => $_locale,
  3637.                 'isCanonical' => true,
  3638.             ]);
  3639.         if (!$friendlyUrl) {
  3640.             throw $this->createNotFoundException("No canonical URL found for page ID $id in locale $_locale.");
  3641.         }
  3642.         $contentRepo $this->entityManager->getRepository(StdPagesContent::class);
  3643.         $pageContent $contentRepo->findOneBy([
  3644.             'pageId' => $page,
  3645.             'languageCode' => $_locale,
  3646.         ]);
  3647.         if (!$pageContent) {
  3648.             throw $this->createNotFoundException("Content not found for page ID $id in locale $_locale.");
  3649.         }
  3650.         $fields $stdBlocksService->formatArrayFields($request$pageContent->getContent());
  3651.         $content = [
  3652.             'url' => $friendlyUrl,
  3653.             'pageContent' => $pageContent,
  3654.             'fields' => $fields,
  3655.             'dataForm' => [
  3656.                 'new' => 0
  3657.             ]
  3658.         ];
  3659.         $relationTree $friendlyUrl->getRelationTree() ?? [];
  3660.         return $this->showContentById($content'default'truefalse$relationTree""""truetrue);
  3661.     }
  3662.     #[Route(path'{_locale}/preview'name'preview_page_content')]
  3663.     public function preview(Request $requestStdBlocksService $stdBlocksService$skin 'default'): \Symfony\Component\HttpFoundation\Response
  3664.     {
  3665.         $dataForm $request->request->all();
  3666.         $dataForm AdminFunctions::processSubmittedBlockData($dataForm);
  3667.         $arrFinal["page-content"] = array();
  3668.         $var "";
  3669.         if (isset($dataForm["std_pages_form"]) && $dataForm["std_pages_form"]) {
  3670.             $dynamicContent $dataForm["std_pages_form"];
  3671.             foreach ($dynamicContent as $k => $value) {
  3672.                 if (strpos($k"age-content-")) {
  3673.                     if ($value) {
  3674.                         $var $var $var "," '{ "page-content": [';
  3675.                         $dataExplode explode("-_-"$k);
  3676.                         $valueN json_encode($value);
  3677.                         $var .= '{"' str_replace('-_-''": {"'str_replace(array("ajax-page-content-_-""page-content-_-"), ""$k)) . '" : ' $valueN;
  3678.                         for ($i 1$i count($dataExplode); $i++) {
  3679.                             $var .= "}";
  3680.                         }
  3681.                     }
  3682.                 }
  3683.             }
  3684.             if ($var) {
  3685.                 $var .= "]}";
  3686.                 $arrFinal json_decode(str_replace(array("\r""\n"), ""$var), true);
  3687.             }
  3688.         } else {
  3689.             throw $this->createNotFoundException('Preview not found, please reopen preview.');
  3690.         }
  3691.         // Format array fields for preview
  3692.         $stdPages = new StdPages();
  3693.         $arr $stdBlocksService->formatArrayFields($request$arrFinal["page-content"]);
  3694.         $fields $arr;
  3695.         //search pages
  3696.         $rep $this->entityManager->getRepository(StdFriendlyUrl::class);
  3697.         $url $rep->findOneByUrl($dataForm['std_pages_form']['canonical_url']);
  3698.         $dataForm['new'] = 0;
  3699.         if (!$url) {
  3700.             $dataForm['new'] = 1;
  3701.         }
  3702.         if (!$dataForm['new']) {
  3703.             $this->locale $this->locale;
  3704.             $relationTree $url->getRelationTree();
  3705.             if (!$relationTree) {
  3706.                 $url2 $rep->getRowByPageAndRelationTreeNotNull($url->getPageId()->getId(), $this->locale);
  3707.                 if ($url2)
  3708.                     $relationTree $url2->getRelationTree();
  3709.             }
  3710.         } else {
  3711.             $stdPage $dataForm['std_pages_form'];
  3712.             $url = new StdFriendlyUrl;
  3713.             $url->setUrl($stdPage['canonical_url']);
  3714.             $url->setLanguageCode($stdPage['languageCode']);
  3715.             $url->setIsCanonical(true);
  3716.             $pageId = new StdPages;
  3717.             if ($stdPage['template_id'])
  3718.                 $pageId->setTemplateId($stdPage['template_id']);
  3719.             if ($stdPage['layout'])
  3720.                 $pageId->setLayout($stdPage['layout']);
  3721.             $pageId->setName($stdPage['title']);
  3722.             $pageId->setContentType($this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['id' => 6]));
  3723.             $pageId->setcreatedBy($this->getUser());
  3724.             if (array_key_exists("postdaterange"$dataForm))
  3725.                 $postdaterange preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#''$3-$2-$1 $4'$dataForm['postdaterange']);
  3726.             else
  3727.                 $postdaterange null;
  3728.             if (array_key_exists("expiredaterange"$dataForm))
  3729.                 $expiredaterange preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#''$3-$2-$1 $4'$dataForm['expiredaterange']);
  3730.             else
  3731.                 $expiredaterange null;
  3732.             $pageId->setCreatedDate(new \DateTime());
  3733.             $pageId->setUpdatedBy($this->getUser());
  3734.             $pageId->setUpdatedDate(new \DateTime());
  3735.             $pageId->setPublishDate($postdaterange ? new \DateTime(date('Y-m-d H:i:s'strtotime($postdaterange))) : new \DateTime());
  3736.             $pageId->setExpireDate($expiredaterange ? (new \DateTime(date('Y-m-d H:i:s'strtotime($expiredaterange)))) : null);
  3737.             $url->setPageId($pageId);
  3738.             $relationTree = [];
  3739.         }
  3740.         $content['url'] = $url;
  3741.         $content['dataForm'] = $dataForm;
  3742.         $content['fields'] = $fields;
  3743.         $dataForm $content["dataForm"]["std_pages_form"];
  3744.         $pagecontent = new stdPagesContent;
  3745.         $pagecontent->setPageId($content["url"]->getPageId());
  3746.         $pagecontent->setTitle($dataForm["title"]);
  3747.         $pagecontent->setUrl($dataForm["url"]);
  3748.         $pagecontent->setMetaKeywords($dataForm["meta_keywords"]);
  3749.         $pagecontent->setMetaTitle($dataForm["meta_title"]);
  3750.         $pagecontent->setMetaDescription($dataForm["meta_description"]);
  3751.         $pagecontent->setOgTitle($dataForm["og_title"]);
  3752.         $pagecontent->setOgImage($dataForm["og_image"]);
  3753.         $pagecontent->setOgDescription($dataForm["og_description"]);
  3754.         $pagecontent->setOgUrl($dataForm["og_url"]);
  3755.         $pagecontent->setCanonicalUrl($dataForm["canonical_url"]);
  3756.         $pagecontent->setScriptsHead($dataForm["script_head"]);
  3757.         $pagecontent->setScriptsBody($dataForm["script_body"]);
  3758.         $pagecontent->setScriptsFooter($dataForm["script_footer"]);
  3759.         $pagecontent->setContent($content["fields"]);
  3760.         $pagecontent->setUpdatedDate(new \DateTime());
  3761.         $content["pageContent"] = $pagecontent;
  3762.         return $this->showContentById($content$skintruefalse$relationTree);
  3763.     }
  3764.     private function findBreadCrumbs($actual$relationTree$entityManager$arr = array())
  3765.     {
  3766.         $preview['new'] = 0;
  3767.         if ($actual && !($actual instanceof stdPages)) {
  3768.             $preview['new'] = 1;
  3769.             $preview['data'] = $actual;
  3770.             $actual $actual['url']->getPageId();
  3771.         }
  3772.         $rep $entityManager->getRepository(StdFriendlyUrl::class);
  3773.         $repPageContent $entityManager->getRepository(StdPagesContent::class);
  3774.         if ($relationTree && $relationTree["relation_id"]) {
  3775.             $page $rep->findOneBy(["relationId" => $relationTree["relation_id"], "languageCode" => $this->locale]);
  3776.             if (!$page) {
  3777.                 $page $rep->findOneBy(["url" => "/" $this->locale $relationTree["url"]]);
  3778.                 if (!$page) {
  3779.                     return [];
  3780.                 }
  3781.             }
  3782.             $pageContent $repPageContent->findOneBy(["pageId" => $page->getPageId()->getId(), "languageCode" => $this->locale]);
  3783.             $arrRound = array();
  3784.             $arrRound["url"] = $relationTree["url"];
  3785.             $arrRound["friendlyUrlId"] = $page->getId();
  3786.             $arrRound["friendlyUrl"] = $page->getUrl();
  3787.             $arrRound["pageId"] = $page->getPageId()->getId();
  3788.             $arrRound["title"] = $pageContent->getTitle();
  3789.             $arrRound["active"] = " ";
  3790.             if (sizeof($pageContent->getContent()) == 0) {
  3791.                 $arrRound["dontshow"] = true;
  3792.             } else {
  3793.                 $arrRound["dontshow"] = true;
  3794.                 foreach ($pageContent->getContent() as $k => $content) {
  3795.                     if ($content != "") {
  3796.                         $arrRound["dontshow"] = false;
  3797.                         break;
  3798.                     }
  3799.                 }
  3800.             }
  3801.             array_push($arr$arrRound);
  3802.             if (array_key_exists("children"$relationTree)) {
  3803.                 $arr $this->findBreadCrumbs(false$relationTree["children"], $entityManager$arr);
  3804.             }
  3805.         }
  3806.         if ($actual) {
  3807.             if (!$preview['new']) {
  3808.                 $pageContent $repPageContent->findOneBy(["pageId" => $actual->getId(), "languageCode" => $this->locale]);
  3809.                 $arrFinal["title"] = $pageContent->getTitle();
  3810.             } else {
  3811.                 $pageContent $preview['data'];
  3812.                 $arrFinal["title"] = $pageContent['dataForm']['std_pages_form']['title'];
  3813.             }
  3814.             $arrFinal["url"] = "#";
  3815.             $arrFinal["friendlyUrlId"] = null;
  3816.             $arrFinal["friendlyUrl"] = "#";
  3817.             $arrFinal["pageId"] = null;
  3818.             $arrFinal["active"] = "active";
  3819.             if (!$preview['new'] && sizeof($pageContent->getContent()) == 0)
  3820.                 $arrFinal["dontshow"] = true;
  3821.             elseif ($preview['new'] && sizeof($pageContent['pageContent']->getContent()) == 0) {
  3822.             } else
  3823.                 $arrFinal["dontshow"] = false;
  3824.             array_push($arr$arrFinal);
  3825.         }
  3826.         return $arr;
  3827.     }
  3828.     #[Route(path'{_locale}/ics/generate'name'ics_generate'methods: ['GET'])]
  3829.     public function icsGenerate(): \Symfony\Component\HttpFoundation\Response
  3830.     {
  3831.         $data $this->request->query->all();
  3832.         if (isset($data["id"]) && $data["id"] != '' && isset($data["description"]) && $data["description"] != "" && isset($data["startdate"]) && $data["startdate"] != "" && isset($data["enddate"]) && $data["enddate"] != "" && isset($data["name"]) && $data["name"] != "") {
  3833.             $startDate date('Y-m-d h:i'strtotime($data["startdate"]));
  3834.             $endDate date('Y-m-d h:i'strtotime($data["enddate"]));
  3835.             $provider = new \BOMO\IcalBundle\Provider\IcsProvider();
  3836.             $tz $provider->createTimezone();
  3837.             $tz
  3838.                 ->setTzid('Europe/London')
  3839.                 ->setXProp('X-LIC-LOCATION'$tz->getTzid());
  3840.             $cal $provider->createCalendar($tz);
  3841.             $event $cal->newEvent();
  3842.             $event
  3843.                 ->setStartDate(new \DateTime($startDate))
  3844.                 ->setEndDate(new \DateTime($endDate))
  3845.                 ->setName($data["name"])
  3846.                 ->setDescription($data["description"]);
  3847.             $calStr $cal->returnCalendar();
  3848.             return new Response(
  3849.                 $calStr,
  3850.                 \Symfony\Component\HttpFoundation\Response::HTTP_OK,
  3851.                 array(
  3852.                     'Content-Type' => 'text/calendar; charset=utf-8',
  3853.                     'Content-Disposition' => 'attachment; filename="calendar.ics"',
  3854.                 )
  3855.             );
  3856.         }
  3857.         throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
  3858.     }
  3859.     #[Route(path'{_locale}/handle-form/'name'ajax_handle_form'methods: ['POST'])]
  3860.     public function ajaxHandleForm(EventDispatcherInterface $dispatcher): JsonResponse
  3861.     {
  3862.         $event = new StdFormsSubmitEvent($this->request$this->formsDirectory);
  3863.         $dispatcher->dispatch($eventStdFormsSubmitEvent::NAME);
  3864.         return new JsonResponse($event->toArray());
  3865.     }
  3866.     private function addCookiesToResponse(Response $response$cookies)
  3867.     {
  3868.         if (is_array($cookies)) {
  3869.             foreach ($cookies as $cookie) {
  3870.                 ($cookie instanceof Cookie) && $response->headers->setCookie($cookie);
  3871.             }
  3872.         }
  3873.     }
  3874.     private function generateUserCacheKey(Security $security): string
  3875.     {
  3876.         if (!is_null($security->getUser())
  3877.             && $security->getUser() instanceof StdWebUsers
  3878.             && is_array($security->getUser()->getRoles())
  3879.             && !empty(is_array($security->getUser()->getRoles()))) {
  3880.             $cachekey str_replace('ROLE_'''implode("-"$security->getUser()->getRoles()));
  3881.             $cachekey md5($cachekey);
  3882.             return '-' $cachekey;
  3883.         }
  3884.         return '';
  3885.     }
  3886.     #[Route(path'{_locale}/forms/list/datatable'name'ajax_form_list_datatable'methods: ['GET'])]
  3887.     public function ajaxFormListDatatable(Request $request$_locale): JsonResponse
  3888.     {
  3889.         if (!$request->isXmlHttpRequest()) {
  3890.             throw $this->createNotFoundException('The page does not exist');
  3891.         }
  3892.         $dataForm $request->query->all();
  3893.         if ($dataForm) {
  3894.             $lang $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $_locale"isActive" => true]);
  3895.             //Columns that will appear on Datatable
  3896.             if (array_key_exists("table_fields"$dataForm) && $dataForm["table_fields"] != "") {
  3897.                 $dataForm["table_fields"] = json_decode($dataForm["table_fields"]);
  3898.                 $columns $dataForm["table_fields"];
  3899.             }
  3900.             //Search
  3901.             $search $dataForm["search"]["value"] ?? "";
  3902.             //Order
  3903.             $order $dataForm["order"] ?? [];
  3904.             $orderby = [];
  3905.             if (count($order) > 0) {
  3906.                 foreach ($order as $ord) {
  3907.                     if ($ord["column"] != "")
  3908.                         $orderby[] = ["column" => $columns[$ord["column"]], "order" => $ord["dir"]];
  3909.                 }
  3910.             }
  3911.             //Apply Start/Limits to results
  3912.             $start $dataForm["start"];
  3913.             $limit $dataForm["length"];
  3914.             //Machine name of the Form
  3915.             $formPageMachineName null;
  3916.             if (array_key_exists("form_name"$dataForm)) {
  3917.                 $formPageMachineName $dataForm["form_name"];
  3918.             }
  3919.             $user null;
  3920.             if ($dataForm["form_only_user"] === "1") {
  3921.                 $webUser $this->security->getUser();
  3922.                 if ($webUser && $webUser instanceof StdWebUsers) {
  3923.                     $user $webUser->getId();
  3924.                 }
  3925.             }
  3926.             //Get all forms submitted by machinename or user
  3927.             $forms $this->entityManager->getRepository(Forms::class)->findContentBySearchQuery($columns$_locale$orderby$formPageMachineName$user$search$start$limit);
  3928.             //Rows
  3929.             $list $rows = [];
  3930.             $page "";
  3931.             $form_page "";
  3932.             $page_url "";
  3933.             $formDomainBlocks = [];
  3934.             $permissions = ["c" => true"r" => true"u" => true"d" => true];
  3935.             foreach ($forms["results"] as $k => $form) {
  3936.                 if (!$form_page) {
  3937.                     $form_page $this->entityManager->getRepository(StdPages::class)->findOneBy(["machineName" => $form["form"]->getFormName()]);
  3938.                     if ($form_page) {
  3939.                         $form_localized $form_page->getLocalizedContents($lang);
  3940.                         $form_content $form_localized->getContent();
  3941.                         //"Check if the Form contains form_domain blocks. If it does, we need to retrieve the Domain Value for each one."
  3942.                         if (array_key_exists("fields"$form_content)) {
  3943.                             foreach ($form_content["fields"] as $field) {
  3944.                                 if ($field['block'] === 'form_domain' && $field["components"]["form_select_domain"] != "") {
  3945.                                     $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $field["components"]["form_select_domain"]]);
  3946.                                     $domainsarr = [];
  3947.                                     foreach ($domainvalues as $domain) {
  3948.                                         $domainsarr[$domain->getMachineName()] = $domain->getDescription();
  3949.                                     }
  3950.                                     $formDomainBlocks[$field["components"]["form_input_name"]] = $domainsarr;
  3951.                                 }
  3952.                             }
  3953.                         }
  3954.                         $permissions Functions::checkFormPermissions($this->security$this->entityManager$form_content);
  3955.                         $page_url $form_localized->getCanonicalUrl();
  3956.                     }
  3957.                 }
  3958.                 if (!$page) {
  3959.                     $page $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $form["form_page_id"], "languageCode" => $_locale]);
  3960.                     if ($page) {
  3961.                         $page_url $page->getCanonicalUrl();
  3962.                     }
  3963.                 }
  3964.                 $rows[$k] = array_intersect_key($formarray_flip($columns));
  3965.                 if (count($formDomainBlocks)) {
  3966.                     foreach ($formDomainBlocks as $domain => $domainBlock) {
  3967.                         if (array_key_exists($domain$rows[$k])) {
  3968.                             $rows[$k][$domain] = $formDomainBlocks[$domain][$rows[$k][$domain]];
  3969.                         }
  3970.                     }
  3971.                 }
  3972.                 //If datatable has form sequential column, will merge the prefix and sufix with the sequential value
  3973.                 if (array_key_exists("form_sequential"$rows[$k])) {
  3974.                     $formdata $form["form"]->getContent();
  3975.                     $form_seq_prefix $form_seq_sufix "";
  3976.                     if (array_key_exists("form_sequential_prefix"$formdata)) {
  3977.                         $form_seq_prefix $formdata["form_sequential_prefix"];
  3978.                     }
  3979.                     if (array_key_exists("form_sequential_sufix"$formdata)) {
  3980.                         $form_seq_sufix $formdata["form_sequential_sufix"];
  3981.                     }
  3982.                     $rows[$k]["form_sequential"] = $form_seq_prefix "" $rows[$k]["form_sequential"] . "" $form_seq_sufix;
  3983.                 }
  3984.                 $actions_view $this->renderView('blocks/submitted_forms_list/submitted_forms_list.actions.html.twig',
  3985.                     array(
  3986.                         'locale' => $_locale,
  3987.                         'form' => $form,
  3988.                         'form_content' => $form_content,
  3989.                         'page_url' => $page_url,
  3990.                         'permissions' => $permissions
  3991.                     )
  3992.                 );
  3993.                 $rows[$k] = array_merge($rows[$k], ['actions' => $actions_view]);
  3994.             }
  3995.             //Total
  3996.             $list["total"] = $forms["total"];
  3997.         }
  3998.         //Results
  3999.         $result = array(
  4000.             'draw' => $dataForm["draw"],
  4001.             'recordsTotal' => $list["total"],
  4002.             'recordsFiltered' => $list["total"],
  4003.             'permissions' => $permissions,
  4004.             'data' => $rows
  4005.         );
  4006.         return new JsonResponse($result);
  4007.     }
  4008.     #[Route(path'{_locale}/forms/view/{id}'name'form_generate_view')]
  4009.     public function formGenerateView(Request $request$id$_locale): JsonResponse
  4010.     {
  4011.         $lang $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $_locale"isActive" => true]);
  4012.         $form $this->entityManager->getRepository(Forms::class)->findOneBy(["id" => $id]);
  4013.         if ($form) {
  4014.             $formdata $form->getContent();
  4015.             $page $this->entityManager->getRepository(StdPages::class)->findOneBy(["machineName" => $form->getFormName()]);
  4016.             $content $page->getLocalizedContents($lang)->getContent();
  4017.             //Check if the Form contains  form_domain blocks. If it does, we need to retrieve the Domain Value for each one.
  4018.             if (array_key_exists("fields"$content)) {
  4019.                 foreach ($content["fields"] as $field) {
  4020.                     if ($field['block'] === 'form_domain' && $field["components"]["form_select_domain"] != "") {
  4021.                         $domainvalues $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $field["components"]["form_select_domain"]]);
  4022.                         $domainsarr = [];
  4023.                         foreach ($domainvalues as $domain) {
  4024.                             $domainsarr[$domain->getMachineName()] = $domain->getDescription();
  4025.                         }
  4026.                         $formDomainBlocks[$field["components"]["form_input_name"]] = $domainsarr;
  4027.                     }
  4028.                 }
  4029.             }
  4030.             if (count($formDomainBlocks)) {
  4031.                 foreach ($formDomainBlocks as $domain => $domainBlock) {
  4032.                     if (array_key_exists($domain$formdata) && $formdata[$domain] != "") {
  4033.                         $formdata[$domain] = $formDomainBlocks[$domain][$formdata[$domain]];
  4034.                     }
  4035.                 }
  4036.             }
  4037.             if ($content) {
  4038.                 $form_permissions Functions::checkFormPermissions($this->security$this->entityManager$content);
  4039.                 if ($form_permissions) {
  4040.                     if (!$form_permissions["r"]) {
  4041.                         throw $this->createNotFoundException('The page does not exist');
  4042.                     } else {
  4043.                         $html $this->renderView('blocks/submitted_forms_list/form.view.html.twig', [
  4044.                             'content' => $content,
  4045.                             'formdata' => $formdata,
  4046.                             'request' => $request->request->all(),
  4047.                             'query' => $request->query->all(),
  4048.                         ]);
  4049.                         return new JsonResponse($html);
  4050.                     }
  4051.                 }
  4052.             }
  4053.         }
  4054.         throw $this->createNotFoundException('The page does not exist');
  4055.     }
  4056.     #[Route(path'/{_locale}/forms/delete/{id}'name'form_delete')]
  4057.     public function formDelete(int $id$_locale): Response
  4058.     {
  4059.         $lang $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $_locale"isActive" => true]);
  4060.         $form $this->entityManager->getRepository(Forms::class)->findOneBy(["id" => $id]);
  4061.         if ($form) {
  4062.             $page $this->entityManager->getRepository(StdPages::class)->findOneBy(["machineName" => $form->getFormName()]);
  4063.             $page_localized $page->getLocalizedContents($lang);
  4064.             $content $page_localized->getContent();
  4065.             if ($content) {
  4066.                 $form_permissions Functions::checkFormPermissions($this->security$this->entityManager$content);
  4067.                 if ($form_permissions) {
  4068.                     if ($form_permissions["d"]) {
  4069.                         $this->entityManager->remove($form);
  4070.                         $this->entityManager->flush();
  4071.                         // $this->addFlash('success',  $this->translator->trans('deleted_successfully', [], 'studio'));
  4072.                         return $this->redirect($_SERVER["HTTP_REFERER"]);
  4073.                     } else {
  4074.                         throw $this->createAccessDeniedException('ACCESS DENIED!');
  4075.                     }
  4076.                 }
  4077.             }
  4078.         }
  4079.     }
  4080.     /**
  4081.      * Refactored from RenderPages to allow a single page to be rendered without the fuss of walking through an array and concatenating the results
  4082.      * @param int $pageId Page Id (field id from DB)
  4083.      * @param skin $page
  4084.      */
  4085.     public function RenderPage(int|StdPages $pageId$skin$renderblocks falsebool $returnResponse false): string|Response
  4086.     {
  4087.         $strContent "";
  4088.         $page $pageId instanceof StdPages ?
  4089.             $pageId :
  4090.             $this->entityManager->getRepository(StdPages::class)->findOneBy(["id" => $pageId]);
  4091.         if ($page) {
  4092.             $pagecontent $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $pageId"languageCode" => $this->locale]);
  4093.             if ($pagecontent) {
  4094.                 $response $this->showContentById($page$skintruetrue, array(), """"$renderblocks);
  4095.                 if ($response instanceof Response) {
  4096.                     $strContent $response->getContent();
  4097.                 } else {
  4098.                     $strContent $response;
  4099.                 }
  4100.             }
  4101.         }
  4102.         return $returnResponse ? new Response($strContent) : $strContent;
  4103.     }
  4104.     function renderSnippet(?StdSnippets $stdSnippets null$pageId null): Response
  4105.     {
  4106.         $strContent "";
  4107.         if ($stdSnippets) {
  4108.             $language $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $this->locale]);
  4109.             $stdSnippetsContent $stdSnippets->getLocalizedContents($language);
  4110.             if ($stdSnippetsContent) {
  4111.                 if($pageId != null) {
  4112.                     $pageId $this->entityManager->getRepository(StdPages::class)->findOneBy(["id" => $pageId]);
  4113.                 }
  4114.                 $response $this->renderPageContent(0, [], $pageId$stdSnippetsContentnull);
  4115.                 if ($response instanceof Response) {
  4116.                     $strContent $response->getContent();
  4117.                 } else {
  4118.                     $strContent $response;
  4119.                 }
  4120.             }
  4121.         }
  4122.         return new Response(isset($strContent["html"]) ? $strContent["html"] : $strContent);
  4123.     }
  4124. }