<?php
namespace App\Controller;
use App\Admin\Entity\StdGeoMap;
use App\Admin\Entity\StdPagesTag;
use App\Admin\Entity\StdWebUsers;
use App\Service\StdTrackingService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Knp\Component\Pager\PaginatorInterface;
use App\Admin\Repository\StdPagesPagesRepository;
use App\Admin\Repository\StdUsersRepository;
use App\Admin\Repository\StdConfigRepository;
use App\Admin\Entity\StdPages;
use App\Admin\Entity\StdPagesPages;
use App\Admin\Entity\StdPagesContent;
use App\Admin\Entity\StdMenusFriendlyUrl;
use App\Admin\Entity\StdFriendlyUrl;
use App\Admin\Entity\StdBlocks;
use App\Admin\Entity\StdDomains;
use App\Admin\Entity\StdDomainsValues;
use App\Admin\Enum\DomainValueType;
use App\Admin\Entity\StdTemplatesBlocks;
use App\Admin\Entity\StdContentTypes;
use App\Admin\Entity\StdAttributesValues;
use App\Admin\Entity\StdPagesAttributesValues;
use App\Admin\Entity\StdLanguages;
use App\Form\StdDynamicForm;
use App\Entity\Forms;
use App\Utils\Functions;
use App\Admin\Entity\StdAttributes;
use App\Admin\Entity\StdContentTypesAttributes;
use App\Admin\Entity\StdNotifications;
use App\Admin\Entity\StdRedirects;
use ReCaptcha\ReCaptcha;
use DateInterval;
use DateTime;
use DateTimeZone;
use Symfony\Component\Security\Core\Security;
use App\Admin\Controller\StdPagesController;
use App\Admin\Entity\StdNotificationsScheduleSent;
use App\Admin\Entity\StdNotificationsTypes;
use App\Admin\Entity\StdSnippets;
use App\Admin\Entity\StdSnippetsContent;
use App\Admin\Entity\StdUsers;
use App\Admin\Utils\AdminFunctions;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use App\Event\StdFormsSubmitEvent;
use Symfony\Component\HttpFoundation\Cookie;
use App\Service\StdBlocksService;
use App\Service\StudioService;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Cache\Adapter\DoctrineDbalAdapter;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mailer\MailerInterface;
use App\Admin\Entity\StdWebUsersAddresses;
use App\Admin\Form\StdWebUsersAddressesForm;
use App\Event\StdWebUsersActivatedEvent;
use App\Event\StdWebUsersNewAddressEvent;
use App\Event\StdWebUsersRegisteredEvent;
use App\Event\StdWebUsersUpdateAddressEvent;
use App\Exception\RedirectException;
use App\Model\StdWebUsersChangePasswordFormModel;
use App\Model\StdWebUsersEditFormModel;
use App\Model\StdWebUsersRecoveryPasswordFormModel;
use App\Model\StdWebUsersRegistrationFormModel;
use Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\Admin\Entity\StdWebRoles;
use App\Form\StdWebUsersChangePasswordFormType;
use App\Form\StdWebUsersEditFormType;
use App\Form\StdWebUsersRecoveryPasswordFormType;
use App\Form\StdWebUsersRegistrationFormType;
use App\Repository\FormsRepository;
use App\Service\StdSecurityService;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
class PageContentController extends AbstractController
{
private $request;
private $isformhandled = false;
private $usersrepository;
private $mailer;
private $paginator;
private $locale;
private $security;
private $passwordHasher;
private $masterRequestUri;
private $mainrequest;
private $translator;
private $dispatcher;
private $stdsecurity;
/**
* @var ManagerRegistry
*/
private $registry;
private $entityManager;
private $redirectsCache;
private StudioService $stdService;
private StdTrackingService $stdTrackingService;
public function __construct(
RequestStack $requestStack,
StdUsersRepository $usersrepository,
MailerInterface $mailer,
PaginatorInterface $paginator,
Security $security,
TranslatorInterface $translator,
EventDispatcherInterface $dispatcher,
ManagerRegistry $registry,
UserPasswordHasherInterface $passwordHasher,
private string $formsDirectory,
CacheInterface $redirectsCache,
StdSecurityService $stdsecurity,
StudioService $stdService,
StdTrackingService $stdTrackingService
)
{
if ($requestStack->getCurrentRequest() == null) {
throw $this->createNotFoundException('Page not found');
}
$this->request = $requestStack->getCurrentRequest();
$this->masterRequestUri = $requestStack->getMainRequest()->getPathInfo();
$this->mainrequest = $requestStack->getMainRequest();
$this->locale = $this->request->getLocale();
$this->usersrepository = $usersrepository;
$this->mailer = $mailer;
$this->paginator = $paginator;
$this->security = $security;
$this->stdsecurity = $stdsecurity;
$this->translator = $translator;
$this->dispatcher = $dispatcher;
$this->registry = $registry;
$this->entityManager = $registry->getManager();
$this->passwordHasher = $passwordHasher;
$this->redirectsCache = $redirectsCache;
$this->stdService = $stdService;
$this->stdTrackingService = $stdTrackingService;
}
#[Route(path: '/', name: 'home')]
#[Route(path: '/{locale}', name: 'home_locale', requirements: ['locale' => '[A-Za-z]{2}'])]
public function showHome(): Response
{
if ($this->entityManager->getRepository(StdLanguages::class)->findOneBy(['languageCode' => $this->locale, 'isPublic' => 1, 'isActive' => 1])) {
$rep = $this->entityManager->getRepository(StdPagesContent::class);
$pageContent = $rep->findOneBy(["url" => "home", "languageCode" => $this->locale]);
if ($pageContent) {
return $this->showContentById($pageContent->getPageId(), "default", true);
} else {
$rep = $this->entityManager->getRepository(StdPages::class);
$page = $rep->findOneById(1);
return $this->showContentById($page, "default", true);
}
} else {
$this->request->setLocale($this->request->getDefaultLocale());
$this->translator->setLocale($this->request->getDefaultLocale());
$this->translator->refreshCatalogue($this->request->getDefaultLocale());
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
}
#[Route(path: '{_locale}/ajax_page_list/{skin}/{page}/{pagenumber}', name: 'ajax_page_list_render')]
public function renderAjaxPageList(StdPages $page, $skin, $pagenumber): Response
{
$rep = $this->entityManager->getRepository(StdPagesContent::class);
$pagecontent = $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $this->locale]);
if ($pagecontent) {
$variables = $this->prepareVariables($pagecontent);
} else {
$variables = array();
}
$ajaxCall["isAjax"] = true;
$arrAttr = array();
// Verify filter
$dataForm = $this->request->request->all();
$ajaxCall["operator"] = $this->request->request->get('attr_operator', 'or');
if ($dataForm) {
foreach ($dataForm as $search => $dataFilter) {
if (strpos($search, "ilter_")) {
$dataExplode = explode("filter_", $search);
$attributeMachineName = $dataExplode[1];
$arrAttr[$attributeMachineName] = $dataFilter;
}
}
if ($arrAttr) {
$ajaxCall["arrAttr"] = $arrAttr;
}
}
// Format attributes
$contenttypeattributes = $this->entityManager->getRepository(StdAttributes::class)->returnAttributesByContentType($page->getContentType()->getMachineName());
$attributesarr = [];
$arritem = [];
foreach ($contenttypeattributes as $entity) {
if ($entity instanceof StdAttributes) {
$attributesarr[$entity->getMachineName()]["attribute"] = $entity;
}
if ($entity instanceof StdAttributesValues) {
$attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["value"] = $entity;
$attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["checked"] = false;
if ($arrAttr && isset($arrAttr[$entity->getAttribute()->getMachineName()])) {
if (is_array($arrAttr[$entity->getAttribute()->getMachineName()]) && array_search($entity->getValue(), $arrAttr[$entity->getAttribute()->getMachineName()]) !== FALSE) {
$attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["checked"] = true;
}
if (!is_array($arrAttr[$entity->getAttribute()->getMachineName()]) && $arrAttr[$entity->getAttribute()->getMachineName()] == $entity->getValue()) {
$attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()]["checked"] = true;
}
}
}
}
$content = $this->renderPageContent($pagenumber, $variables, $page, $pagecontent, null, true, $ajaxCall);
$payload = array_merge([
"isajax" => true,
"allattributes" => $attributesarr,
"locale" => $this->locale,
"blockscontent" => $content["html"],
"blockscontentjs" => $content["js"],
'paginator' => array_key_exists("paginator", $content["payload"]) ? $content["payload"]["paginator"] : array()
], $variables);
$result = $this->render('ajax/' . $skin . '.html.twig', $payload);
if ($result) {
$data = $result;
} else {
$data = new Response('{"success" => false}');
}
return $data;
}
#[Route(path: '{_locale}/ajax_call/{skin}/{page}/{pagenumber}', name: 'ajax_call_render')]
public function renderAjaxCall(StdPages $page, $skin, $pagenumber): Response
{
$rep = $this->entityManager->getRepository(StdPagesContent::class);
$pagecontent = $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $this->locale]);
if ($pagecontent) {
$variables = $this->prepareVariables($pagecontent);
} else {
$variables = array();
}
$ajaxCall["isAjax"] = true;
// Check for blockuniqueid to filter rendering to a specific block (for lazy loading)
$blockuniqueid = $this->request->get("blockuniqueid") ?: $this->request->request->get("blockuniqueid");
if ($blockuniqueid) {
$ajaxCall["blockuniqueid"] = $blockuniqueid;
}
// Check for blockskin to use a specific skin for the block
$blockskin = $this->request->get("blockskin") ?: $this->request->request->get("blockskin");
if ($blockskin) {
$ajaxCall["blockskin"] = $blockskin;
}
$content = $this->renderPageContent($pagenumber, $variables, $page, $pagecontent, null, true, $ajaxCall);
$payload = array_merge([
"isajax" => true,
"locale" => $this->locale,
"blockscontent" => $content["html"],
"blockscontentjs" => $content["js"],
'paginator' => $content["payload"]["paginator"] ?? []
], $variables);
$result = $this->render('ajax/' . $skin . '.html.twig', $payload);
if ($result) {
$data = $result;
} else {
$data = new Response('{"success" => false}');
}
return $data;
}
#[Route(path: '{_locale}/page/{page}', name: 'page_content')]
#[Route(path: '{_locale}/page/{page}/{blockname}', name: 'page_content_blockname')]
public function previewPage(StdPages $page, $blockname = "")
{
return $this->showContentById($page, 'default', false, false, array(), $blockname);
}
public function showContentById($object, $skin = "default", $direct = false, $renderView = false, $relationTree = array(), $blockname = "", $blockskin = "", $renderblocks = true, $preview = false)
{
$relationId = null;
if ($object instanceof StdFriendlyUrl) {
$page = $object->getPageId();
$relationId = !is_null($object->getRelationId()) ? $object->getRelationId()->getId() : null;
$this->stdTrackingService->trackVisitOnPage($page);
} elseif ($object instanceof StdPages) {
$page = $object;
$this->stdTrackingService->trackVisitOnPage($page);
} elseif ($object['url']) {
$preview = true;
$page = $object['url']->getPageId();
} else {
throw new \Exception("Object is not a page neither a friendly url");
}
if (!$preview || !$object['dataForm']['new']) {
if (!$this->verifyPermission($page)) {
$loginpage = Functions::getPageInfo($this->locale, Functions::getConfig('login_page', '', $this->entityManager), $this->entityManager);
throw new RedirectException(new RedirectResponse($loginpage['url']));
}
}
$pageskin = "";
if ($this->request->isXmlHttpRequest()) {
if (!$blockname) {
$blockname = $this->request->get("block");
}
if (!$blockname) {
$blockname = $this->request->request->get("block");
}
if (!$blockskin)
$blockskin = $this->request->get("blockskin");
if (!$blockskin)
$blockskin = $this->request->request->get("blockskin");
if (!$pageskin)
$pageskin = $this->request->get("pageskin");
if (!$pageskin)
$pageskin = $this->request->request->get("pageskin");
}
/*
Quando um formulário é submetido não pode fazer redirect senão perde o request (POST)
*/
$formTestRedirect = $this->createForm(StdDynamicForm::class);
$formTestRedirect->handleRequest($this->request);
if ($formTestRedirect->isSubmitted() && $formTestRedirect->isValid()) {
$direct = true;
}
$breadCrumbs = [];
if ($relationTree) {
if (!$preview || !$object['dataForm']['new']) {
$breadCrumbs = $this->findBreadCrumbs($page, $relationTree, $this->entityManager);
} else {
$breadCrumbs = $this->findBreadCrumbs($object, $relationTree, $this->entityManager);
}
} else {
if (!$preview || !$object['dataForm']['new']) {
$breadCrumbs = $this->findBreadCrumbs($page, null, $this->entityManager);
} else {
$breadCrumbs = $this->findBreadCrumbs($object, null, $this->entityManager);
}
}
$headercontent = [];
$publishDate = null;
$expireDate = null;
if ($page->getPublishDate())
$publishDate = new DateTime($page->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
if ($page->getExpireDate())
$expireDate = new DateTime($page->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
$rulesAndMessages["messages"] = "";
$rulesAndMessages["rules"] = "";
$useReCaptcha = true;
if ($preview || Functions::isPagePublished($page)) {
if (!$direct) {
$verify = $this->entityManager->getRepository(StdFriendlyUrl::class)->findOneBy(["pageId" => $page->getId(), "isCanonical" => 1, "languageCode" => $this->locale]);
if ($verify) {
return $this->redirect($verify->getUrl());
}
}
$rep = $this->entityManager->getRepository(StdPagesContent::class);
// BEGIN SEO URL
$alternateUrls = [];
$defaultUrl = null;
$canonicalUrl = null;
if (!$preview) {
if ($canonical = $this->entityManager->getRepository(StdFriendlyUrl::class)->findOneBy(["pageId" => $page->getId(), "isCanonical" => 1, "languageCode" => $this->locale])) {
$canonicalUrl = $canonical->getUrl() . (($_SERVER['QUERY_STRING'] ?? '') != '' ? '?' . $_SERVER['QUERY_STRING'] : '');
}
//returns all the active and public languages, also returns the page url if it exists
$tempLanguages = $rep->searchLanguagesAndUrl($page->getId(), $relationId);
foreach ($tempLanguages as $tempLanguage) {
// Commented to allow full URL to be set when /home is the route to match hreflang and canonical
// if ($this->request->get('_route') == 'home' || $this->request->get('_route') == 'home_locale')
// {
// $tempLanguage['url'] = '/' . $tempLanguage['language_code'];
// }
$tempLanguage['url'] .= ($_SERVER['QUERY_STRING'] ?? '') != '' ? '?' . $_SERVER['QUERY_STRING'] : '';
$alternateUrls[] = $tempLanguage;
if ($tempLanguage['is_default']) {
$defaultUrl = $tempLanguage['url'];
}
if (is_null($canonicalUrl) && $tempLanguage['language_code'] == $this->locale) {
$canonicalUrl = $tempLanguage['url'];
}
}
if (!is_null($defaultUrl) && ($this->request->get('_route') == 'home' || $this->request->get('_route') == 'home_locale')) {
$defaultUrl = '';
}
}
// END SEO URL
if (!$preview) {
$pagecontent = $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $this->locale]);
} else {
$pagecontent = $object["pageContent"];
$pagecontent->setTitle("Preview - " . $pagecontent->getTitle());
$languageCode = $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $this->locale]);
$pagecontent->setLanguageCode($languageCode);
}
if ($pagecontent) {
if ($preview) {
$variables = $this->prepareVariables($pagecontent, $object);
} else {
$variables = $this->prepareVariables($pagecontent);
}
if ($page->getContentType()->getMachineName() == "forms") {
$formData = $this->entityManager->getRepository(Forms::class)->findOneById($this->request->query->get("id"));
if ($formData && $this->request->query->get("edit")) {
$variables["formdata"] = $formData->getContent();
}
}
if ($breadCrumbs)
$variables = array_merge($variables, array("breadCrumbs" => $breadCrumbs));
$variables["preview"] = 0;
if ($preview) {
$variables["preview"] = 1;
}
} else {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
if ($renderblocks) {
$content = $this->renderPageContent($this->request->query->getInt('pag', 1), $variables, $page, $pagecontent, $blockskin, true, array(), $blockname);
} else {
$content["html"] = "";
$content["js"] = "";
$content["cookies"] = [];
}
$response = new Response();
if ($page->getIncludeSitemap() == 0) {
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
}
isset($content['cookies']) && $this->addCookiesToResponse($response, $content['cookies']);
if ($this->request->isXmlHttpRequest()) {
if ($pageskin) {
$payload = array_merge([
"locale" => $this->locale,
"blockscontent" => $content["html"],
"blockscontentjs" => $content["js"],
'alternateUrls' => $alternateUrls,
'defaultUrl' => $defaultUrl,
'canonicalUrl' => $canonicalUrl
], $variables);
$layouttemplate = 'layouts/' . $page->getContentType()->getMachineName() . '/' . $page->getContentType()->getMachineName() . '.' . $pageskin . '.html.twig';
if ($this->container->get('twig')->getLoader()->exists($layouttemplate)) {
return $this->renderView($layouttemplate, $payload);
} else {
return $this->renderView('layouts/base.html.twig', $payload);
}
}
$response->setContent($content["html"]);
return $response;
} else {
if ($pagecontent)
$fields = $pagecontent->getContent();
else
$fields = [];
$redirect = "";
if (isset($fields["form_redirect"]))
$redirect = $fields["form_redirect"];
$isPage = false;
$rulesAndMessages = array("messages" => "", "rules" => "");
if (isset($fields["fields"])) {
$rulesAndMessages = $this->getRulesAndMessagesForm($fields["fields"]);
foreach ($fields["fields"] as $field)
if (isset($field["isPage"]) && $field["isPage"] == 1)
$isPage = true;
}
$form = $this->createForm(StdDynamicForm::class);
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid() && !$this->isformhandled) {
$this->isformhandled = true;
$newForm = new Forms();
$user = $this->usersrepository->findOneById(0);
$dataForm = $this->request->request->all();
$recaptchaToken = $dataForm["recaptchatoken"];
if ($recaptchaToken != 0) {
$recaptcha = new ReCaptcha(Functions::getConfig("GOOGLE_RECAPTCHA_SECRET", "", $this->entityManager), new \ReCaptcha\RequestMethod\CurlPost());
$recaptchaRes = $recaptcha
->setScoreThreshold(Functions::getConfig("GOOGLE_RECAPTCHA_SCORE_THRESHOLD", "", $this->entityManager) ?? "0.5")
->verify($recaptchaToken);
if (!$recaptchaRes->isSuccess()) {
return new Response("Recaptcha Error");
}
} else {
return new Response("Recaptcha Error");
}
$trataForm = false;
//Editing a form
if ($this->request->query->get("id") && $this->request->query->get("edit")) {
$trataForm = true;
$newForm = $this->entityManager->getRepository(StdForms::class)->findOneBy(["id" => $this->request->query->get("id")]);
}
if (isset($dataForm["form_id"])) {
if (is_array($fields["fields"])) {
foreach ($fields["fields"] as $field) {
if (isset($field["components"]["input_combo_pages"]) && $dataForm["form_id"] == $field["components"]["input_combo_pages"]) {
$trataForm = true;
}
}
};
if ($trataForm) {
unset($dataForm["std_dynamic_form"]);
$filesArray = $this->request->files->all();
$folderName = Functions::cleanString($dataForm["form_name"]);
$attach = $attachEmail = [];
$i = 0;
if (isset($dataForm["insert_new_message"]) && $dataForm["insert_new_message"] != "") {
$webUser = $this->security->getUser();
$newMessageTemp = $dataForm[$dataForm["insert_new_message"]];
$dataForm[$dataForm["insert_new_message"]] = [];
$nowDate = new DateTime();
$nowDateFormated = $nowDate->format('Y-m-d H:i:s');
if ($webUser && $webUser instanceof StdWebUsers) {
$dataForm[$dataForm["insert_new_message"]][] =
array(
"createdBy" => $webUser->getId()
, "createdByName" => $webUser->getName()
, "createdAt" => $nowDateFormated
, "message" => $newMessageTemp
);
} else {
$dataForm[$dataForm["insert_new_message"]][] = \json_encode(
array(
"createdBy" => ""
, "createdByName" => ""
, "createdAt" => $nowDateFormated
, "message" => $newMessageTemp
));
}
}
foreach ($filesArray as $file_key => $files) {
foreach ($files as $file) {
$i++;
$originalName = $file->getClientOriginalName();
$mimeType = $file->getClientMimeType();
$fileName = Functions::generateUniqueFileName() . '.' . $file->guessExtension();
try {
$file->move(
$this->formsDirectory . '/' . $folderName . '/',
$fileName
);
} catch (\Exception $e) {
}
$dataForm[$file_key][] = ["name" => $file->getClientOriginalName(), "file_name" => $fileName, "type" => "file"];
// $attachEmail[] = $file;
$attachEmail[$i]["path"] = $this->formsDirectory . '/' . $folderName . '/' . $fileName;
$attachEmail[$i]["originalName"] = $originalName;
$attachEmail[$i]["mimeType"] = $mimeType;
}
}
$newForm->setFormName($dataForm["form_name"]);
$newForm->setFormType($dataForm["form_type"]);
$newForm->setContent($dataForm);
$newForm->setCreatedDate(new \DateTime());
$newForm->setUpdatedDate(new \DateTime());
$newForm->setCreatedBy($user);
$newForm->setUpdatedBy($user);
$sendEmail = false;
$formInput = "";
if ($isPage) {
if (isset($dataForm["form_id"])) {
$formPage = $rep->findOneBy(["pageId" => $dataForm["form_id"], "languageCode" => $this->locale]);
}
if (isset($formPage)) {
$pageFields = $formPage->getContent();
if (isset($pageFields["form_email_sender"]) && $pageFields["form_email_sender"] == 1)
$sendEmail = true;
$renderedform = $this->renderFormContent($dataForm, $pageFields);
$repNotifications = $this->entityManager->getRepository(StdNotifications::class);
if ($sendEmail && $dataForm[$pageFields["form_input_email_to_send"]] != "") {
$userNotification = $repNotifications->findOneBy(["id" => $pageFields["form_notification_user"]]);
$emailContent = $userNotification ? $userNotification->getEmailBody() : "";
$subject = $userNotification ? $userNotification->getEmailSubject() : "";
$twig = $this->container->get('twig');
$template = Functions::twig_template_from_string($twig, '{% extends "admin/emails/base.html.twig" %}{% block content %} ' . $emailContent . ' {% endblock %}');
$body = $template->render(array_merge($dataForm, array("rendered_form" => $renderedform, "locale" => $this->locale)));
$template = Functions::twig_template_from_string($twig, html_entity_decode($subject, ENT_QUOTES | ENT_XML1, 'UTF-8'));
$subject = $template->render($dataForm);
$ccEmails = str_replace(' ', '', $pageFields["form_notification_user_cc"]);
$cc = array_filter(explode(";", $ccEmails));
$bccEmails = str_replace(' ', '', $pageFields["form_notification_user_bcc"]);
$bcc = array_filter(explode(";", $bccEmails));
$to = "";
if (isset($pageFields["form_input_email_to_send"])) {
if (strpos($pageFields["form_input_email_to_send"], ',') !== false) {
$pageFields["form_input_email_to_send"] = explode(',', str_replace([' '], [''], $pageFields["form_input_email_to_send"]));
$to = array();
foreach ($pageFields["form_input_email_to_send"] as $tosend) {
if (isset($dataForm[$tosend])) {
$tosend_emails = explode(';', preg_replace('/[\s,]+/', ';', $dataForm[$tosend]));
$tosend_emails = array_filter($tosend_emails, 'strlen');
$to = array_merge($tosend_emails, $to);
}
}
} else {
if (isset($dataForm[$pageFields["form_input_email_to_send"]])) {
$toEmails = str_replace(' ', '', $dataForm[$pageFields["form_input_email_to_send"]]);
$to = array_filter(explode(";", $toEmails));
}
}
if ($to != "") {
Functions::sendEmail($this->mailer, $pageFields["form_email_from"], $pageFields["form_email_from_name"], $to, $cc, $bcc, $subject, $body, null, $this->entityManager);
}
}
}
// Send to admin
if ($pageFields["form_notification_admin"] && $pageFields["form_email_to"] != "") {
$adminNotification = $repNotifications->findOneBy(["id" => $pageFields["form_notification_admin"]]);
$emailContent = $adminNotification ? $adminNotification->getEmailBody() : "";
$subject = $adminNotification ? $adminNotification->getEmailSubject() : "";
$twig = $this->container->get('twig');
$template = Functions::twig_template_from_string($twig, '{% extends "admin/emails/base.html.twig" %}{% block content %} ' . $emailContent . ' {% endblock %}');
$body = $template->render(array_merge($dataForm, array("rendered_form" => $renderedform, "locale" => $this->request->getDefaultLocale())));
$template = Functions::twig_template_from_string($twig, html_entity_decode($subject, ENT_QUOTES | ENT_XML1, 'UTF-8'));
$subject = $template->render($dataForm);
$toEmails = str_replace(' ', '', $pageFields["form_email_to"]);
$to = explode(";", $toEmails);
$ccEmails = str_replace(' ', '', $pageFields["form_email_admin_cc"]);
$cc = array_filter(explode(";", $ccEmails));
$bccEmails = str_replace(' ', '', $pageFields["form_email_admin_bcc"]);
$bcc = array_filter(explode(";", $bccEmails));
Functions::sendEmail($this->mailer, $pageFields["form_email_from"], $pageFields["form_email_from_name"], $to, $cc, $bcc, $subject, $body, $attachEmail, $this->entityManager);
}
}
}
$this->entityManager->persist($newForm);
$this->entityManager->flush();
if ($redirect != "") {
return $this->redirect($this->request->getScheme() . $redirect);
}
}
}
}
$headercontent = [
"publishdate" => ($publishDate != null ? $publishDate->format('Y-m-d H:i:s') : null),
"expiredate" => ($expireDate != null ? $expireDate->format('Y-m-d H:i:s') : null),
"lastupdate" => ($page->getUpdatedDate() != null ? $page->getUpdatedDate()->format('Y-m-d H:i:s') : null),
"createdby" => $page->getCreatedBy()->getName(),
"order" => $page->getOrderValue()
];
// global $studio;
$payload = array_merge([
"page" => $page,
"headercontent" => $headercontent,
"locale" => $this->locale,
"blockscontent" => $content["html"],
"blockscontentjs" => $content["js"],
'useReCaptcha' => false,
'form' => $form->createView(),
'messages' => $rulesAndMessages["messages"],
'rules' => $rulesAndMessages["rules"],
'alternateUrls' => $alternateUrls,
'defaultUrl' => $defaultUrl,
'canonicalUrl' => $canonicalUrl,
// 'studio' => $studio,
'preview' => $preview,
'editBlocksInfo' => $content["variables"]["editBlocksInfo"] ?? []
], $variables);
if ($this->container->get('twig')->getLoader()->exists('layouts/global/' . $page->getLayout() . '.html.twig')) {
if ($renderView)
return $this->renderView('layouts/global/' . $page->getLayout() . '.html.twig', $payload);
else
return $this->render('layouts/global/' . $page->getLayout() . '.html.twig', $payload, $response);
} else {
if ($this->container->get('twig')->getLoader()->exists('layouts/' . $page->getContentType()->getMachineName() . '/' . $page->getContentType()->getMachineName() . '.' . $skin . '.html.twig')) {
if ($renderView)
return $this->renderView('layouts/' . $page->getContentType()->getMachineName() . '/' . $page->getContentType()->getMachineName() . '.' . $skin . '.html.twig', $payload);
else
return $this->render('layouts/' . $page->getContentType()->getMachineName() . '/' . $page->getContentType()->getMachineName() . '.' . $skin . '.html.twig', $payload, $response);
} else {
if ($renderView)
return $this->renderView('layouts/base.html.twig', $payload);
else
return $this->render('layouts/base.html.twig', $payload, $response);
}
}
}
} else {
if ($renderView) {
return $this->renderView('layouts/blank.html.twig', []);
} else
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
}
private function renderFormContent($values, $formcontent)
{
$blocksservice = new StdBlocksService($this->stdTrackingService, $this->entityManager);
$formname = $values["form_name"];
$folderName = Functions::cleanString($formname);
$content = $formcontent["fields"];
$result = "";
foreach ($content as $block) {
$block = (array)$block;
$component = (array)$block["components"];
$blockName = (string)$block["block"];
$domainvalues = [];
$stdblock = $this->entityManager->getRepository(StdBlocks::class)->findOneBy(['machineName' => $blockName]);
if ($stdblock) {
$stdsettings = $stdblock->getSettings();
if (isset($stdsettings["isFormDomain"]) && $stdsettings["isFormDomain"]) {
//get the domain values for the selected domain
if ($component["form_select_domain"]) {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $component["form_select_domain"]]);
}
} else if (isset($stdsettings["isFormStatus"]) && $stdsettings["isFormStatus"]) {
//get the domain values for the selected domain
$domainobj = $this->entityManager->getRepository(StdDomains::class)->findOneBy(["machineName" => "form_status"]);
if ($domainobj) {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id")]);
}
}
}
if (isset($component["form_input_name"]) && !Functions::startsWith($blockName, 'form_file')) {
$name = $component["form_input_name"];
if (isset($values[$name])) {
$payload = [];
$payload = array_merge([
'value' => isset($values[$name]) ? $values[$name] : [],
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'values' => $domainvalues
]);
}
} else if (isset($component["form_input_name"]) && Functions::startsWith($blockName, 'form_file')) {
$name = $component["form_input_name"];
$payload = [];
$attachments = [];
$i = 0;
if (isset($values["foto"])) {
foreach ($values["foto"] as $attach) {
$href = '/forms/' . $folderName . '/' . $attach["file_name"];
$attachments[$i]["href"] = $href;
$attachments[$i]["name"] = $attach["name"];
$i++;
}
}
$payload = array_merge([
'anexos' => $attachments,
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
]);
} else {
continue;
}
$skin = "default";
if ($block["skin"] != "")
$skin = $block["skin"];
if ($this->container->get('twig')->getLoader()->exists("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".email.twig"))
$result .= $this->renderView("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".email.twig", $payload);
}
return $result;
}
#[Route(path: '{_locale}/show/{url}', name: 'page_content_url')]
public function showContentByURL(StdPagesContent $pageContent): Response
{
// $rep = $this->entityManager->getRepository(StdPages::class);
// $page = $rep->findOneById($pageContent->getPageId());
return $this->render('layouts/base.html.twig', [
'controller_name' => 'PageContentController',
'content' => $pageContent->getContent(),
"locale" => $this->request->getLocale()
]);
}
function RenderMenu(Request $request, StdPagesPagesRepository $pagesRepos, StdConfigRepository $stdConfig): Response
{
$menuSkin = $request->query->get('skin');
$menu = $request->query->get('menu');
$usecache = $request->query->get('use_cache', true);
$lang = $request->getLocale();
$menuId = $stdConfig->findOneBy(['machineName' => $menu, 'languageCode' => $lang]);
if ($menuId && (int)$menuId->getValue() > 0) {
$cache = new DoctrineDbalAdapter($this->registry->getConnection());
$cachekey = Functions::cleanString('menu' . $menuId->getValue() . '-' . $menu . $lang . $menuSkin . $this->generateUserCacheKey($this->security));
$cacheitem = $cache->getItem($cachekey);
if (!$cacheitem->isHit() || !$usecache) {
$cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
$relationId = $menuId->getValue();
$numOfLevels = $request->query->get('numOfLevels');
if ($numOfLevels) {
$numOfLevels++;
} else {
$numOfLevels = 99999;
}
if ($menuSkin) {
$skin = $menuSkin;
} else {
$skinid = $stdConfig->findOneBy(['machineName' => $menu . "_skin", 'languageCode' => $lang]);
$skin = $skinid->getValue();
}
$results = $this->RenderCategories($relationId, $numOfLevels, $pagesRepos, 0, $skin, $lang, [
'masterRequestUri' => $this->masterRequestUri
]);
if ($this->container->get('twig')->getLoader()->exists('content-types/menus/' . $skin . '/' . $skin . '.default.html.twig'))
$item = $this->render('content-types/menus/' . $skin . '/' . $skin . '.default.html.twig', [
'results' => $results,
'masterRequestUri' => $this->masterRequestUri
]);
else
$item = $this->render('content-types/menus/menus.default.html.twig', [
'results' => $results,
'masterRequestUri' => $this->masterRequestUri
]);
$cache->save($cacheitem->set($item));
return $item;
} else {
return $cacheitem->get();
}
} else {
return new Response();
}
}
function RenderMenuBloco(Request $request, StdPagesPagesRepository $pagesRepos): Response
{
$menuId = $request->query->get('menu');
$menuSkin = $request->query->get('skin');
if ($menuId) {
$cache = new DoctrineDbalAdapter($this->registry->getConnection());
$lang = $request->getLocale();
$cachekey = Functions::cleanString($lang . $menuSkin . $menuId . $this->generateUserCacheKey($this->security));
$cacheitem = $cache->getItem($cachekey);
if (!$cacheitem->isHit()) {
$cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
$relationId = $menuId;
$numOfLevels = 0;
if ($numOfLevels) {
$numOfLevels++;
} else {
$numOfLevels = 99999;
}
if ($menuSkin) {
$skin = $menuSkin;
} else {
$skin = "";
}
$results = $this->RenderCategories($relationId, $numOfLevels, $pagesRepos, 0, $skin, $lang);
if ($skin != "" && $this->container->get('twig')->getLoader()->exists('content-types/menus/' . $skin . '/' . $skin . '.default.html.twig'))
$item = $this->render('content-types/menus/' . $skin . '/' . $skin . '.default.html.twig', [
'results' => $results
]);
else
$item = $this->render('content-types/menus/menus.default.html.twig', [
'results' => $results
]);
$cache->save($cacheitem->set($item));
return $item;
} else {
return $cacheitem->get();
}
} else {
return new Response();
}
}
function RenderCategories($relationId, $numOfLevels, $pagesRepos, $lvl, $skin, $lang, $extraVariables = array())
{
$results = $pagesRepos->getPagesRelations($relationId);
$numOfLevels--;
$result = "";
$lvl++;
$user = $this->security->getUser();
foreach ($results as $relation) {
$page = $relation->getPageId();
$rep = $this->entityManager->getRepository(StdPagesContent::class);
$pagecontent = $rep->findOneBy(["pageId" => $page->getId(), "languageCode" => $lang]);
$hasPermissions = false;
if (!is_null($user) && $user instanceof StdUsers) {
$hasPermissions = true; // Is a backoffice user, so can he can see all items
} elseif (isset($pagecontent) && isset($pagecontent->getContent()['id'])) {
if ($originalPage = $this->entityManager->getRepository(StdPages::class)->find($pagecontent->getContent()['id'])) {
$roles = $originalPage->getRoles();
if (sizeof($roles) > 0) {
if ($user && sizeof($user->getRoles()) && sizeof($originalPage->getRolesByNames($user->getRoles()))) {
$hasPermissions = true; // User and page have coincident roles
}
} else {
$hasPermissions = true; // Page has no roles associated, so everyone can see it
}
}
} else {
$roles = $page->getRoles();
if (sizeof($roles) > 0) {
if ($user && sizeof($user->getRoles()) && sizeof($page->getRolesByNames($user->getRoles()))) {
$hasPermissions = true; // User and page have coincident roles
}
} else {
$hasPermissions = true; // Page has no roles associated, so everyone can see it
}
}
if ($hasPermissions) {
if ($pagecontent) {
$variables = $this->prepareVariables($pagecontent);
} else {
$variables = array();
}
$relationId = $relation->getId();
if ($skin != "") {
if ($this->container->get('twig')->getLoader()->exists('content-types/menus/' . $skin . '/' . $skin . '.' . $lvl . '.html.twig'))
$skinPage = 'content-types/menus/' . $skin . '/' . $skin . '.' . $lvl . '.html.twig';
else
$skinPage = 'content-types/menus/' . $skin . '/' . $skin . '.n.html.twig';
} else {
if ($this->container->get('twig')->getLoader()->exists('content-types/menus/menus.' . $lvl . '.html.twig'))
$skinPage = 'content-types/menus/menus.' . $lvl . '.html.twig';
else
$skinPage = 'content-types/menus/menus.n.html.twig';
}
if ($numOfLevels > 0) {
$res = $this->RenderCategories($relationId, $numOfLevels, $pagesRepos, $lvl, $skin, $lang);
$variables["results"] = $res;
$content = $this->renderPageContent(1, $variables, $page, $pagecontent, $skinPage, false, array(), ".");
$payload = array_merge([
"locale" => $this->locale,
"blockscontent" => $content["html"],
"blockscontentjs" => $content["js"],
"level" => $lvl
], $variables, $extraVariables);
if (isset($payload["id"]) && $payload["id"] != "") {
$originPageContent = $rep->findOneBy(["pageId" => $payload["id"], "languageCode" => $this->locale]);
$menuUrlRep = $this->entityManager->getRepository(StdMenusFriendlyUrl::class);
$menuUrl = $menuUrlRep->getUrl($relation->getId());
if ($originPageContent) {
$originVariables = $this->prepareVariables($originPageContent);
$origin = [];
foreach ($originVariables as $key => $value)
$origin["origin_" . $key] = $value;
$payload = array_merge($payload, $origin);
}
$payload = array_merge([
"friendly_url" => $menuUrl["url"] ?? "",
], $payload);
}
$result .= $this->renderView($skinPage, $payload);
}
}
}
return $result;
}
private function renderPageContent(int $pagenumber, array $variables, ?StdPages $page, StdPagesContent|StdSnippetsContent|null $pageContent, ?string $pageskinparam, $renderlistblocks = true, $ajaxCall = array(), $blockmachinename = ""): array
{
$blocksservice = new StdBlocksService($this->stdTrackingService, $this->entityManager);
$content = array();
if ($pageContent) {
$cont = $pageContent->getContent();
if (isset($cont["fields"]))
$content = $cont["fields"];
}
$result = "";
$resultjs = "";
$payload = [];
$headercontent = [];
$publishDatePage = null;
$expireDatePage = null;
$blockSequence = 0;
$now = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
$publishDateIni = $now;
$dateFim = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
$dateFim->add(new DateInterval('P10D'));
$expireDateIni = $dateFim;
// global $studio;
// $variables['studio'] = $studio;
$variables["editBlocksInfo"] = [];
// Add page to variables so it's available in all blocks, including those rendered via snippets
if ($page !== null) {
$variables["page"] = $page;
}
$cookieLocationId = $this->request->cookies->get('CloseToYou-Location');
$sessionLocations = $this->request->getSession()->get('close_location_ids');
$effectiveLocations = [];
if ($cookieLocationId) {
$cookieLocation = $this->entityManager->getRepository(StdDomainsValues::class)->findOneBy(['id' => (int)$cookieLocationId]);
if ($cookieLocation) {
if (is_array($sessionLocations) && ($pos = array_search((int)$cookieLocationId, $sessionLocations, true)) !== false) {
$effectiveLocations[] = (int)$cookieLocationId;
$offset = 1;
$count = count($sessionLocations);
while (($pos - $offset) >= 0 || ($pos + $offset) < $count) {
if (($pos - $offset) >= 0) {
$idLeft = $sessionLocations[$pos - $offset];
if (!in_array($idLeft, $effectiveLocations, true)) {
$effectiveLocations[] = $idLeft;
}
}
if (($pos + $offset) < $count) {
$idRight = $sessionLocations[$pos + $offset];
if (!in_array($idRight, $effectiveLocations, true)) {
$effectiveLocations[] = $idRight;
}
}
$offset++;
}
} else {
$effectiveLocations[] = (int)$cookieLocationId;
if (is_array($sessionLocations)) {
foreach ($sessionLocations as $locId) {
if ($locId != $cookieLocationId && !in_array($locId, $effectiveLocations, true)) {
$effectiveLocations[] = $locId;
}
}
}
}
$this->request->getSession()->set('close_location_ids', $effectiveLocations);
$variables['userDistrict'] = $cookieLocation->getGeoMap()->getDistrictName();
$variables['userMunicipality'] = $cookieLocation->getGeoMap()->getMunicipalityName();
}
} elseif (!empty($sessionLocations)) {
$effectiveLocations = $sessionLocations;
$locationDomainValue = $this->entityManager->getRepository(StdDomainsValues::class)
->findOneBy(['id' => $sessionLocations[0]]);
if ($locationDomainValue) {
$variables['userDistrict'] = $locationDomainValue->getGeoMap()->getDistrictName();
$variables['userMunicipality'] = $locationDomainValue->getGeoMap()->getMunicipalityName();
}
} else {
$variables['userDistrict'] = null;
$variables['userMunicipality'] = null;
}
$cookies = [];
$block_groups = [];
foreach ($content as $block) {
$publishDate = $publishDateIni;
$expireDate = $expireDateIni;
if (array_key_exists("settings", $block) && $block["settings"]) {
if (array_key_exists("disabled_block", $block["settings"]) && $block["settings"]["disabled_block"]) {
continue;
}
if (array_key_exists("publish_date", $block["settings"]) && $block["settings"]["publish_date"]) {
$dateIni = date_create_from_format("d/m/Y h:i A", $block["settings"]["publish_date"]);
$publishDate = new DateTime($dateIni->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
}
if (array_key_exists("expire_date", $block["settings"]) && $block["settings"]["expire_date"]) {
$dateFim = date_create_from_format("d/m/Y h:i A", $block["settings"]["expire_date"]);
$expireDate = new DateTime($dateFim->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
}
}
if ($publishDate <= $now && $expireDate > $now) {
$pageskin = "";
if ($pageskinparam) {
$pageskin = "blocks/" . $block["block"] . "/" . $block["block"] . "." . $pageskinparam . ".html.twig";
}
$iscacheable = true;
$blockSequence++;
if (is_a($pageContent, StdSnippetsContent::class)) {
$objectId = $pageContent->getSnippetId()->getId();
$editpagelink = $this->generateUrl('admin_snippets_edit', array('id' => $objectId, 'language_code' => $this->locale));
} else {
$objectId = $page->getId();
$editpagelink = $this->generateUrl('admin_pages_edit', array('page_id' => $objectId, 'content_type' => $page->getContentType()->getMachineName(), 'language_code' => $this->locale));
}
$variables["blockSequence"] = $block["block"] . "_" . $objectId . "_" . $blockSequence;
// Set blockuniqueid in variables so ALL payloads (via array_merge) have it for lazy loading
$variables["blockuniqueid"] = $block["blockuniqueid"] ?? "";
if (array_key_exists("blockuniqueid", $block)) {
$variables["editBlocksInfo"][$block["blockuniqueid"]] = [
"blockuniqueid" => $block["blockuniqueid"] ?? '',
"blockmachinename" => $block["block"] ?? '',
"blockname" => $block["blockname"] ?? '',
"skin" => $block["skin"] ?? '',
"editpagelink" => $editpagelink ?? ''
];
}
// Filter by blockuniqueid for lazy loading - skip blocks that don't match
if (isset($ajaxCall["blockuniqueid"]) && $ajaxCall["blockuniqueid"]
&& (!isset($block["blockuniqueid"]) || $block["blockuniqueid"] !== $ajaxCall["blockuniqueid"])) {
continue;
}
if ($blockmachinename && $block["block"] != $blockmachinename && $variables["blockSequence"] != $blockmachinename) {
continue;
}
$payload = [];
$stdblock = $this->entityManager->getRepository(StdBlocks::class)->findOneBy(['machineName' => $block["block"]]);
if ($stdblock) {
$stdsettings = $stdblock->getSettings();
if (isset($stdsettings['isCacheable']) && !$stdsettings['isCacheable']) {
$iscacheable = false;
}
isset($stdsettings['webpackEntries']) && $this->mainrequest->attributes->set("webpackEntries", array_merge($this->mainrequest->attributes->get('webpackEntries'), array_combine($stdsettings['webpackEntries'], $stdsettings['webpackEntries'])));
if (isset($block["templatesBlocksId"]) && $block["templatesBlocksId"] && isset($block["isMaster"]) && $block["isMaster"]) {
$stdtemplate = $page->getTemplateId();
if ($stdtemplate->getId()) {
$stdtemplateblock = $this->entityManager->getRepository(StdTemplatesBlocks::class)->findOneById($block["templatesBlocksId"]);
if ($stdtemplateblock) {
$blockcontent = $stdtemplateblock->getContent();
$block["settings"] = $blockcontent["settings"];
$block["components"] = $blockcontent["components"];
$block["skin"] = $blockcontent["skin"];
$block["repeatable"] = ($blockcontent["repeatable"] ? $blocksservice->filterPublishedRepeatables($blockcontent["repeatable"]) : array());
}
}
}
// Check if lazy loading is enabled - skip list processing and render lazy skeleton instead
$isLazyLoadingEnabled = $block["block"] === "block_list"
&& isset($block["settings"]["lazy_loading_enabled"])
&& $block["settings"]["lazy_loading_enabled"]
&& (!$ajaxCall || !array_key_exists("isAjax", $ajaxCall));
// DEBUG: Log lazy loading check for block_list (main renderPageContent)
if ($block["block"] === "block_list") {
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);
}
if (isset($stdsettings["isList"]) && $stdsettings["isList"] && $renderlistblocks && !$isLazyLoadingEnabled) {
//it's a list
//get the content_type, template and the category from block components
//get x category childs and render with selected skin
$iscacheable = false;
// Use content_type_list instead of the old content_type field
$contentType = null;
if (isset($block["components"]["content_type_list"]) && !empty($block["components"]["content_type_list"])) {
// For multiple content types, use the first one for compatibility
$contentTypeId = is_array($block["components"]["content_type_list"])
? $block["components"]["content_type_list"][0]
: $block["components"]["content_type_list"];
$contentType = $this->entityManager->getRepository(StdContentTypes::class)->findOneById($contentTypeId);
}
$levels = (isset($block["components"]["levels"]) ? $block["components"]["levels"] : 1);
$contentTypeList = (isset($block["components"]["content_type_list"]) ? $block["components"]["content_type_list"] : array());
$block["components"]['categoryContent'] = null;
($categoryPagePage = $this->entityManager->getRepository(StdPagesPages::class)->find($block["components"]["category"]))
&& ($categoryContent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(['pageId' => $categoryPagePage->getPageId(), 'languageCode' => $this->locale]))
&& $block["components"]['categoryContent'] = $categoryContent;
$queryCategoriesRaw = $this->request->query->all('category');
$queryCategories = is_array($queryCategoriesRaw) ? array_values(array_filter(array_map('intval', $queryCategoriesRaw))) : [];
if (!is_array($queryCategoriesRaw) && $queryCategoriesRaw !== null && $queryCategoriesRaw !== '') {
$queryCategories = [(int)$queryCategoriesRaw];
}
if (!empty($queryCategories)) {
$relationIds = [];
foreach ($queryCategories as $pageId) {
$pagesRelations = $this->entityManager->getRepository(StdPagesPages::class)->findBy([
'pageId' => $pageId
]);
foreach ($pagesRelations as $pagesRelation) {
$relationIds[] = $pagesRelation->getId();
}
}
$queryCategories = !empty($relationIds) ? $relationIds : $queryCategories;
}
$filterCurrentPage = false;
if ($block["components"]["category"] == "-1") {
$canurl = $this->entityManager->getRepository(StdFriendlyUrl::class)->findBy(["pageId" => $page->getId(), "url" => $this->request->getPathInfo(), "languageCode" => $this->locale]);
if (!$canurl) {
$canurl = $this->entityManager->getRepository(StdFriendlyUrl::class)->findBy(["pageId" => $page->getId(), "isCanonical" => 1, "languageCode" => $this->locale]);
}
if ($canurl) {
$relationid = $canurl[0]->getRelationId() ?? -1;
} else {
$relationid = -1;
}
} else if($block["components"]["category"] == "-2") {
$rootCategory = "Temas";
$rootCategoryPage = $this->entityManager->getRepository(StdPages::class)->findOneBy(['machineName' => strtolower($rootCategory)]);
if (!$rootCategoryPage) {
$rootCategoryContent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(['title' => $rootCategory, 'languageCode' => $this->locale]);
if ($rootCategoryContent) {
$rootCategoryPage = $rootCategoryContent->getPageId();
}
}
$filteredCategoriesUnderTemas = [];
if ($rootCategoryPage) {
$rootRelation = $this->entityManager->getRepository(StdPagesPages::class)->findOneBy([
'pageId' => $rootCategoryPage->getId(),
'relationId' => 0
]);
if ($rootRelation) {
$currentPageCategories = $this->entityManager->getRepository(StdPagesPages::class)->findBy(['pageId' => $page->getId()]);
foreach($currentPageCategories as $category) {
$catRelation = $this->entityManager->getRepository(StdPagesPages::class)->find($category->getRelationId());
if ($catRelation) {
$currentRelation = $catRelation;
$isUnderTemas = false;
while ($currentRelation) {
if ($currentRelation->getPageId()->getId() == $rootCategoryPage->getId()) {
$isUnderTemas = true;
break;
}
if ($currentRelation->getRelationId() == 0) {
break;
}
$currentRelation = $this->entityManager->getRepository(StdPagesPages::class)->find($currentRelation->getRelationId());
}
if ($isUnderTemas) {
$filteredCategoriesUnderTemas[] = $category;
}
}
}
}
}
if (!empty($filteredCategoriesUnderTemas)) {
$relationid = $filteredCategoriesUnderTemas[0]->getRelationId();
} else {
$relationid = -1;
}
$filterCurrentPage = true;
} else {
$relationid = $block["components"]["category"];
}
// Build locationTags: cookie (if present) takes precedence and is placed first
$locationTags = [];
$cookieLocationId = $this->request->cookies->get('CloseToYou-Location');
$sessionLocations = $this->request->getSession()->get('close_location_ids');
if ($cookieLocationId) {
$locationTags[] = (int)$cookieLocationId;
if (is_array($sessionLocations)) {
foreach ($sessionLocations as $locId) {
if ($locId != $cookieLocationId) {
$locationTags[] = $locId;
}
}
}
} elseif (!empty($sessionLocations)) {
$locationTags = $sessionLocations;
}
$effectiveRelationId = !empty($queryCategories) ? $queryCategories : $relationid;
$relations = $this->entityManager->getRepository(StdPagesPages::class)->getNChildsOfRelation([
"filterCurrentPage" => $filterCurrentPage ? $page : null,
"relation_id" => $effectiveRelationId,
"start_item" => isset($block["components"]["start_item"]) ? $block["components"]["start_item"] : null,
"limit" => $block["components"]["limit"],
"template" => $block["components"]["template"],
"order" => $block["components"]["order"],
"order_by" => $block["components"]["order_by"] ?? '',
"levels" => $levels,
"paginate" => $block["components"]["paginate"],
"content_type_list" => $contentTypeList,
"ajaxFilter" => $ajaxCall,
"tags" => ($block["components"]["tags"] ?? ""),
"page" => $pagenumber,
"paginator" => $this->paginator,
"language_code" => $this->locale,
"roles" => ($this->security->getUser() instanceof StdWebUsers ? $this->security->getUser()->getRoles() : null),
"locationTags" => $locationTags
]);
$resultlist = "";
$resultlistjs = "";
$total = count($relations);
$index = 0;
if (!isset($locationValues)) {
try {
$locationValues = $this->entityManager->getRepository(StdDomainsValues::class)
->createQueryBuilder('dv')
->leftJoin('dv.geoMap', 'gm')
->andWhere('dv.isActive = 1')
->andWhere('gm.type IN (:locTypes)')
->setParameter('locTypes', ['municipality', 'district'])
->addOrderBy('dv.description', 'ASC')
->getQuery()
->getResult();
} catch (\Throwable $e) {
$locationValues = [];
}
}
$top10IdsPages = [];
$hasProgramsContentType = false;
if (!empty($contentTypeList) && is_array($contentTypeList)) {
$programsContentType = $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['machineName' => 'programs']);
if ($programsContentType) {
$hasProgramsContentType = in_array($programsContentType->getId(), $contentTypeList);
}
}
if ($hasProgramsContentType) {
$top10IdsPages = $blocksservice->fetchProgramsTop10Ids(
$this->entityManager
);
}
foreach ($relations as $stdpagespages) {
$relationcontent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $stdpagespages["page_id"], "languageCode" => $this->locale]);
//render
$friendlyUrl = "";
if ($relationcontent) {
$fields = $this->prepareVariables($relationcontent);
// Check if this specific item has 'programs' content type and is in a block that includes programs
if ($hasProgramsContentType && $relationcontent->getPageId() && $relationcontent->getPageId()->getContentType() && $relationcontent->getPageId()->getContentType()->getMachineName() === 'programs') {
// verifica se o page_id atual está na lista de Top10 fixada no bloco
$fields["isTop10"] = in_array(
(int)$relationcontent->getPageId()->getId(),
$top10IdsPages,
true
);
}
// get friendly Url
$friendlyUrlObj = $this->findFriendlyUrlByPageId($relationcontent->getPageId()->getId(), $this->entityManager, $this->locale);
$friendlyUrl = $friendlyUrlObj ? $friendlyUrlObj->getUrl() : "";
$relationPageId = $relationcontent->getPageId();
if ($relationPageId->getPublishDate())
$publishDatePage = new DateTime($relationPageId->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
if ($relationPageId->getExpireDate())
$expireDatePage = new DateTime($relationPageId->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
} else {
$fields = array();
}
// Get the actual content type of this specific item
$itemContentType = null;
if ($relationcontent && $relationcontent->getPageId()) {
$itemContentType = $relationcontent->getPageId()->getContentType();
}
// Handle skin selection based on the item's content type
$selectedSkin = 'default';
$skinMapping = []; // Map content type machine names to skins
if (array_key_exists("skin", $block["components"]) && $block["components"]["skin"]) {
$skinValue = $block["components"]["skin"];
if (is_array($skinValue) && !empty($skinValue)) {
// Multiple skins - need to map to content types
// For now, we'll use a simple mapping: first skin for first content type, etc.
$contentTypeList = $block["components"]["content_type_list"] ?? [];
if (is_array($contentTypeList) && !empty($contentTypeList)) {
for ($i = 0; $i < min(count($contentTypeList), count($skinValue)); $i++) {
$ctId = $contentTypeList[$i];
$skin = $skinValue[$i];
$ct = $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['id' => $ctId]);
if ($ct) {
$skinMapping[$ct->getMachineName()] = $skin;
}
}
}
// Use mapped skin or fallback to first skin
if ($itemContentType && isset($skinMapping[$itemContentType->getMachineName()])) {
$selectedSkin = $skinMapping[$itemContentType->getMachineName()];
} else {
$selectedSkin = reset($skinValue); // Fallback to first skin
}
} elseif (is_string($skinValue)) {
$selectedSkin = $skinValue;
}
}
// Template selection logic with fallbacks
if (!empty($itemContentType)) {
// 1st priority: Specific skin template for this content type
if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.' . $selectedSkin . '.html.twig')) {
$skinparam = 'content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.' . $selectedSkin . '.html.twig';
}
// 2nd priority: Content type default template
elseif ($this->container->get('twig')->getLoader()->exists('content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.default.html.twig')) {
$skinparam = 'content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.default.html.twig';
}
// 3rd priority: Global fallback template
else {
$skinparam = 'content-types/default/content_type.default.html.twig';
}
}
// Handle JS skin template with same fallback logic
if (!empty($itemContentType)) {
// 1st priority: Specific skin JS template
if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.' . $selectedSkin . '.js.twig')) {
$skinjsparam = 'content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.' . $selectedSkin . '.js.twig';
}
// 2nd priority: Content type default JS template
elseif ($this->container->get('twig')->getLoader()->exists('content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.default.js.twig')) {
$skinjsparam = 'content-types/' . $itemContentType->getMachineName() . '/' . $itemContentType->getMachineName() . '.default.js.twig';
}
// 3rd priority: Global fallback JS template
else {
$skinjsparam = 'content-types/default/content_type.default.js.twig';
}
} else {
$skinjsparam = 'content-types/default/content_type.default.js.twig';
}
$content = [];
if (isset($stdsettings["renderPageBlocks"]) && $stdsettings["renderPageBlocks"]) {
$renderblocks = false;
if (isset($stdsettings["renderListBlocks"]) && $stdsettings["renderListBlocks"]) {
$renderblocks = true;
}
$content = $this->renderPageContent($pagenumber, $fields, $relationcontent->getPageId(), $relationcontent, null, $renderblocks);
} else {
$content["html"] = "";
$content["js"] = "";
}
$headercontent = [
"publishdate" => ($publishDatePage != null ? $publishDatePage->format('Y-m-d H:i:s') : null),
"expiredate" => ($expireDatePage != null ? $expireDatePage->format('Y-m-d H:i:s') : null),
"lastupdate" => ($page->getUpdatedDate() != null ? $page->getUpdatedDate()->format('Y-m-d H:i:s') : null),
"createdby" => $page->getCreatedBy()->getName(),
"order" => $page->getOrderValue()
];
$payload = array_merge([
"headercontent" => $headercontent,
"id" => ($relationcontent ? $relationcontent->getPageId()->getId() : null),
"page" => $relationcontent ? $relationcontent->getPageId() : null,
"relationid" => $stdpagespages["relation_id"],
"total" => $total,
"index" => $index,
"settings" => $block["settings"],
"locale" => $this->locale,
"blockscontent" => $content["html"],
"blockscontentjs" => $content["js"],
"pagination" => $relations,
'friendlyUrl' => $friendlyUrl
], $fields);
if ($this->container->get('twig')->getLoader()->exists($skinparam))
$resultlist .= $this->renderView($skinparam, $payload);
if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
$resultlistjs .= $this->renderView($skinjsparam, $payload);
$index++;
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'blockscontent' => $resultlist,
'blockscontentjs' => $resultlistjs,
'paginator' => $relations,
'location_values' => $locationValues ?? [],
'blockuniqueid' => $block["blockuniqueid"] ?? ""
]);
} elseif (isset($stdsettings["isFormList"]) && $stdsettings["isFormList"]) {
$forms = array();
// if user is logged get his submitted forms
if (isset($block["components"]) && isset($block["components"]["form_types"]) && $this->getUser() != null) {
// if form_type is empty get all
if ($block["components"]["form_types"] != '') {
$forms = $this->entityManager->getRepository(Forms::class)->findBy(array("formType" => $block["components"]["form_types"], "netuserId" => $this->getUser()->getId()));
} else {
$forms = $this->entityManager->getRepository(Forms::class)->findBy(array("netuserId" => $this->getUser()->getId()));
}
}
$payload = array_merge($variables, [
'domain' => 'private-area',
'fields' => $block["components"],
'locale' => $this->locale,
'settings' => $block["settings"],
'formedit' => isset($block["components"]["form_edit"]) ? $block["components"]["form_edit"] : '0',
'forms' => $forms]);
} elseif (isset($block["isPage"]) && $block["isPage"]) {
$contentType = $this->entityManager->getRepository(StdContentTypes::class)->findOneById($block["components"]["input_type_content_type"]);
$subpageContent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $block["components"]["input_combo_pages"], "languageCode" => $this->locale]);
$fields = array();
if ($subpageContent) {
$fields = $this->prepareVariables($subpageContent);
$inputSkin = isset($block["components"]["input_combo_skin"]) && $block["components"]["input_combo_skin"] != "" ? $block["components"]["input_combo_skin"] : "default";
if ($this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.html.twig')) {
$skinparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.html.twig';
} else {
$skinparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.html.twig';
}
if ($this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.js.twig')) {
$skinjsparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.js.twig';
} else {
$skinjsparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.js.twig';
}
if ($contentType->getMachineName() == "forms" && $this->request->query->get("id")) {
$formData = $this->entityManager->getRepository(Forms::class)->findOneById($this->request->query->get("id"));
if ($formData) {
$fields["formdata"] = $formData->getContent();
}
}
$content = $this->renderPageContent($pagenumber, $fields, $subpageContent->getPageId(), $subpageContent, null);
// isset($content['webpackEntries']) && $webpackEntries = array_merge($webpackEntries, $content['webpackEntries']);
isset($content['cookies']) && $cookies = array_merge($cookies, $content['cookies']);
if ($contentType->getMachineName() == "forms") {
/** edit parameter
* 1-edit
* 0-resubmit
*/
// If id and edit parameters exist get the form from id parameter and current logged user
if ($this->request->query->get("id") !== null && $this->request->query->get("edit") !== null) {
$form = $this->entityManager->getRepository(Forms::class)->findOneBy(array("netuserId" => $this->security->getUser(), "id" => $this->request->query->get("id")));
// if the form doesnt belong to the current user throw error
if ($form === null) {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
} else {
$formContent = $form->getContent();
// if form_id is setted find form based on that id
if ($formContent && isset($formContent["form_id"])) {
$formPage = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $formContent["form_id"], "languageCode" => $this->locale]);
if ($formPage) {
$formPageContent = $formPage->getContent();
if ($formPageContent && isset($formPageContent["form_allow_edit"]) && isset($formPageContent["form_allow_resubmit"])) {
//if the edit parameter is 1 and form doesnt allow edition throw error
if ($this->request->query->get("edit") == 1 && $formPageContent["form_allow_edit"] == 0) {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
//if the edit parameter is 0 and form doesnt allow submission throw error
if ($this->request->query->get("edit") == 0 && $formPageContent["form_allow_resubmit"] == 0) {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
} else {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
} else {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
} else {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
}
}
$form = $this->createForm(StdDynamicForm::class);
$fieldsvariables = array_merge($variables, $this->prepareVariables($subpageContent));
$rulesAndMessages = $this->getRulesAndMessagesForm($form_content["fields"]);
$payload = array_merge([
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'blockscontent' => $content["html"],
'blockscontentjs' => $content["js"],
'form' => $form->createView(),
'messages' => $rulesAndMessages["messages"],
'rules' => $rulesAndMessages["rules"],
// 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
'originalpageid' => $page->getId()
], $fieldsvariables);
} else {
$payload = array_merge([
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'blockscontent' => $content["html"],
'blockscontentjs' => $content["js"],
// 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
'originalpageid' => $page->getId()
], $fields);
}
if ($this->container->get('twig')->getLoader()->exists($skinparam))
$result .= $this->renderView($skinparam, $payload);
if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
$resultjs .= $this->renderView($skinjsparam, $payload);
}
} elseif (isset($stdsettings["isWebUsersResetPassword"]) && $stdsettings["isWebUsersResetPassword"]) {
$recovery = $this->request->get("_recoverykey");
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"]
]);
if ($recovery && ($netuser = $this->entityManager->getRepository(StdWebUsers::class)->findOneBy(["passwordrecovery" => $recovery]))) {
$recoverymodel = new StdWebUsersRecoveryPasswordFormModel();
$form = $this->createForm(StdWebUsersRecoveryPasswordFormType::class, $recoverymodel);
$errors = $form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$password = $form->get('plainPassword')->getData();
$netuser->setPasswordrecovery("");
$dispatchStdWebUsersActivatedEvent = !$netuser->getIsActive();
$netuser->setIsActive(1);
$netuser->setPassword($this->passwordHasher->hashPassword(
$netuser,
$password
));
$this->entityManager->persist($netuser);
$this->entityManager->flush();
if ($dispatchStdWebUsersActivatedEvent) {
$event = new StdWebUsersActivatedEvent($netuser);
$this->dispatcher->dispatch($event, StdWebUsersActivatedEvent::NAME);
}
$this->addFlash('success', $this->translator->trans("passwordchangedsuccess", [], 'webusers'));
} catch (Exception $e) {
$this->addFlash('error', $this->translator->trans("passwordchangederror", [], 'webusers'));
$payload = array_merge($payload, [
'formelement' => $form->createView(),
'webuser' => $netuser
]);
}
} else {
$payload = array_merge($payload, [
'formelement' => $form->createView(),
'webuser' => $netuser
]);
}
} else {
$this->addFlash('error', $this->translator->trans("passwordchangedlinkexpired", [], 'webusers'));
}
} elseif (isset($stdsettings["isWebUsersRegistration"]) && $stdsettings["isWebUsersRegistration"]) {
$activation = $this->request->get("_activationkey");
if ($activation) {
if (!$this->request->isMethod("GET") && !$this->request->isMethod("POST"))
throw $this->createNotFoundException('The page does not exist');
$netuser = $this->entityManager->getRepository(StdWebUsers::class)->findOneBy(["activationkey" => $activation]);
if ($netuser) {
$netuser->setActivationKey('');
$netuser->setIsActive(1);
$this->entityManager->persist($netuser);
$event = new StdWebUsersActivatedEvent($netuser);
$this->dispatcher->dispatch($event, StdWebUsersActivatedEvent::NAME);
$this->entityManager->flush();
//send welcome email
$repNotifications = $this->entityManager->getRepository(StdNotifications::class);
$userNotification = $repNotifications->findOneBy(["machineName" => "webuserwelcome", "languageCode" => $this->locale]);
$emailContent = $userNotification ? $userNotification->getEmailBody() : "";
$subject = $userNotification ? $userNotification->getEmailSubject() : "";
$twig = $this->container->get('twig');
$template = Functions::twig_template_from_string($twig, '{% extends "admin/emails/base.html.twig" %}{% block content %} ' . $emailContent . ' {% endblock %}');
$body = $template->render(["webuser" => $netuser, "locale" => $this->locale]);
$template = Functions::twig_template_from_string($twig, html_entity_decode($subject, ENT_QUOTES | ENT_XML1, 'UTF-8'));
$subject = $template->render(["webuser" => $netuser]);
if (!Functions::sendEmail($this->mailer, "", "", [$netuser->getEmail()], [], [], $subject, $body, null, $this->entityManager)) {
$this->addFlash('error', $this->translator->trans("erroroccurred", [], 'studio'));
} else {
$this->addFlash('success', $this->translator->trans("registeractivated", [], 'register'));
}
} else {
throw $this->createNotFoundException('The page does not exist');
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'activation' => true
]);
} else {
$netuser = new StdWebUsersRegistrationFormModel();
$formNetuser = $this->createForm(StdWebUsersRegistrationFormType::class, $netuser, ["locale" => $this->locale, "entitymanager" => $this->entityManager, "translator" => $this->translator, "address1" => $block["components"]["address1"], "address2" => $block["components"]["address2"]]);
$formNetuser->handleRequest($this->request);
if ($formNetuser->isSubmitted() && $formNetuser->isValid()) {
$dataform = $this->request->request->all();
$recaptchaToken = $dataform["recaptchatoken"];
$erroroccurred = false;
if ($recaptchaToken != 0) {
$recaptcha = new ReCaptcha(Functions::getConfig("GOOGLE_RECAPTCHA_SECRET", "", $this->entityManager), new \ReCaptcha\RequestMethod\CurlPost());
$recaptchaRes = $recaptcha
->setScoreThreshold(Functions::getConfig("GOOGLE_RECAPTCHA_SCORE_THRESHOLD", "", $this->entityManager) ?? "0.5")
->verify($recaptchaToken);
if (!$recaptchaRes->isSuccess()) {
$erroroccurred = true;
$this->addFlash('error', $this->translator->trans("recaptchaerror", [], 'studio'));
}
} else {
$erroroccurred = true;
$this->addFlash('error', $this->translator->trans("recaptchaerror", [], 'studio'));
}
if (!$erroroccurred) {
$netuserRegistration = $formNetuser->getData();
$olduser = $this->entityManager->getRepository(StdWebUsers::class)->findOneBy(["email" => $netuserRegistration->email, "isActive" => 0]);
if ($olduser) {
$this->entityManager->remove($olduser);
$oldaddresses = $this->entityManager->getRepository(StdWebUsersAddresses::class)->findBy(["webuser" => $olduser]);
foreach ($oldaddresses as $oldaddress) {
$this->entityManager->remove($oldaddress);
}
$this->entityManager->flush();
}
$date = new DateTime();
$activationkey = md5($netuserRegistration->email . $date->format('Y-m-d H:i:s'));
$netuser = new StdWebUsers();
$netuser->setName($netuserRegistration->name);
$netuser->setInfo($this->request->request->get("info"));
$netuser->setEmail($netuserRegistration->email);
$netuser->setUsername($netuserRegistration->email);
$netuser->setPhone($netuserRegistration->phone);
$netuser->setMobile($netuserRegistration->mobile);
$netuser->setVat($netuserRegistration->vat);
$netuser->setTermsAcceptedAt(new DateTime());
$defaultroles = $this->entityManager->getRepository(StdWebRoles::class)->findBy(["isDefault" => true, "isActive" => true]);
$netuser->setRoles($defaultroles);
if ($netuserRegistration->facebookId != "") {
$netuser->setFacebookId($netuserRegistration->facebookId);
$netuser->setFacebookIntegration(true);
$netuser->setPassword($this->passwordHasher->hashPassword(
$netuser,
Functions::generateString(16)
));
} else {
$netuser->setPassword($this->passwordHasher->hashPassword(
$netuser,
$netuserRegistration->plainPassword
));
}
if ($block["components"]["activation"]) {
$netuser->setActivationkey($activationkey);
$netuser->setIsActive(0);
$event = new StdWebUsersRegisteredEvent($netuser);
$this->dispatcher->dispatch($event, StdWebUsersRegisteredEvent::NAME);
} else {
$netuser->setIsActive(1);
$event = new StdWebUsersRegisteredEvent($netuser);
$this->dispatcher->dispatch($event, StdWebUsersRegisteredEvent::NAME);
$event = new StdWebUsersActivatedEvent($netuser);
$this->dispatcher->dispatch($event, StdWebUsersActivatedEvent::NAME);
}
$this->entityManager->persist($netuser);
$this->entityManager->flush();
if ($block["components"]["address1"]) {
$address1 = new StdWebUsersAddresses();
$address1->setName($netuserRegistration->address1Name);
$address1->setAddressLine1($netuserRegistration->address1AddressLine1);
$address1->setZipCode1($netuserRegistration->address1ZipCode1);
// $address1->setZipCode2($netuserRegistration->address1ZipCode2);
$address1->setPhone($netuserRegistration->address1Phone);
$address1->setMobile($netuserRegistration->address1Mobile);
$address1->setCity($netuserRegistration->address1City);
$address1->setCountry($netuserRegistration->address1Country->getMachineName());
$address1->setIsBilling(1);
$address1->setIsDefault(1);
$address1->setWebuser($netuser);
$this->entityManager->persist($address1);
$this->entityManager->flush();
}
if ($block["components"]["address2"]) {
$address2 = new StdWebUsersAddresses();
$address2->setName($netuserRegistration->address2Name);
$address2->setAddressLine1($netuserRegistration->address2AddressLine1);
$address2->setZipCode1($netuserRegistration->address2ZipCode1);
// $address2->setZipCode2($netuserRegistration->address2ZipCode2);
$address2->setPhone($netuserRegistration->address2Phone);
$address2->setMobile($netuserRegistration->address2Mobile);
$address2->setCity($netuserRegistration->address2City);
$address2->setCountry($netuserRegistration->address2Country->getMachineName());
$address2->setIsBilling(0);
$address2->setIsDefault(0);
$address2->setWebuser($netuser);
$this->entityManager->persist($address2);
$this->entityManager->flush();
}
$repNotifications = $this->entityManager->getRepository(StdNotifications::class);
if ($block["components"]["activation"]) {
$activationlink = $this->request->getUri();
if (strpos($activationlink, '?') === false) {
$activationlink .= '?_activationkey=' . $activationkey;
} else {
$activationlink .= '&_activationkey=' . $activationkey;
}
$dataform["activationlink"] = $activationlink;
$userNotification = $repNotifications->findOneBy(["machineName" => "webuseractivation", "languageCode" => $this->locale]);
} else {
$userNotification = $repNotifications->findOneBy(["machineName" => "webuserwelcome", "languageCode" => $this->locale]);
}
$emailContent = $userNotification ? $userNotification->getEmailBody() : "";
$subject = $userNotification ? $userNotification->getEmailSubject() : "";
$twig = $this->container->get('twig');
$template = Functions::twig_template_from_string($twig, '{% extends "admin/emails/base.html.twig" %}{% block content %} ' . $emailContent . ' {% endblock %}');
$body = $template->render(array_merge($dataform, ["webuser" => $netuser, "locale" => $this->locale]));
$template = Functions::twig_template_from_string($twig, html_entity_decode($subject, ENT_QUOTES | ENT_XML1, 'UTF-8'));
$subject = $template->render(array_merge($dataform, ["webuser" => $netuser]));
if (!Functions::sendEmail($this->mailer, "", "", [$netuser->getEmail()], [], [], $subject, $body, null, $this->entityManager)) {
if ($block["components"]["address1"]) {
$this->entityManager->remove($address1);
}
if ($block["components"]["address2"]) {
$this->entityManager->remove($address2);
}
$this->entityManager->remove($netuser);
$this->entityManager->flush();
$this->addFlash('error', $this->translator->trans("erroroccurred", [], 'studio'));
} else {
$this->addFlash('success', $this->translator->trans("registersuccess", [], 'register'));
if ($block["components"]["redirectto"]) {
throw new RedirectException(new RedirectResponse('/' . trim($block['components']['redirectto'], '/')));
}
//clean form fields after submission
unset($netuser);
unset($formNetuser);
$netuser = new StdWebUsersRegistrationFormModel();
$formNetuser = $this->createForm(StdWebUsersRegistrationFormType::class, $netuser, ["locale" => $this->locale, "entitymanager" => $this->entityManager, "translator" => $this->translator, "address1" => $block["components"]["address1"], "address2" => $block["components"]["address2"]]);
}
}
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'activation' => false,
'formelement' => $formNetuser->createView()
]);
}
} elseif (isset($stdsettings["isWebUsersLogin"]) && $stdsettings["isWebUsersLogin"]) {
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
]);
if (($webUser = $this->security->getUser()) && ($webUser instanceof StdWebUsers) && $block['components']['force_redirect_when_logged']) {
throw new RedirectException(new RedirectResponse('/' . trim($block['components']['redirectto'], '/')));
}
} elseif (isset($stdsettings["isWebUserPass"]) && $stdsettings["isWebUserPass"]) {
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
]);
if (($webUser = $this->security->getUser()) && ($webUser instanceof StdWebUsers)) {
$form = $this->createForm(StdWebUsersChangePasswordFormType::class, (new StdWebUsersChangePasswordFormModel()), [
//'action'=>'/pt/xixinha'
]);
$form->handleRequest($this->request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$formData = $form->getData();
$webUser->setPassword($this->passwordHasher->hashPassword($webUser, $formData->password));
$this->entityManager->persist($webUser);
$this->entityManager->flush();
$userNotification = $this->entityManager->getRepository(StdNotifications::class)->findOneBy(["machineName" => "webuserpasschanged", "languageCode" => $this->locale]);
$emailContent = $userNotification ? $userNotification->getEmailBody() : "";
$subject = $userNotification ? $userNotification->getEmailSubject() : "";
$twig = $this->container->get('twig');
$template = Functions::twig_template_from_string($twig, '{% extends "admin/emails/base.html.twig" %}{% block content %} ' . $emailContent . ' {% endblock %}');
$body = $template->render(["webuser" => $webUser, "locale" => $this->locale]);
$template = Functions::twig_template_from_string($twig, html_entity_decode($subject, ENT_QUOTES | ENT_XML1, 'UTF-8'));
$subject = $template->render(["webuser" => $webUser]);
if (!Functions::sendEmail($this->mailer, "", "", [$webUser->getEmail()], [], [], $subject, $body, null, $this->entityManager)) {
$this->addFlash('error', $this->translator->trans("changepass.error", [], 'webusers'));
} else {
$this->addFlash('success', $this->translator->trans("changepass.success", [], 'webusers'));
}
} else {
$this->addFlash('error', $this->translator->trans("changepass.invaliddata", [], 'webusers'));
}
}
$payload['webUser'] = $webUser;
$payload['form'] = $form->createView();
}
} elseif (isset($stdsettings["isWebUserDetail"]) && $stdsettings["isWebUserDetail"]) {
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
]);
if (($webUser = $this->security->getUser()) && ($webUser instanceof StdWebUsers)) {
$formFields = [];
isset($block['components']['show_erp_code']) && $block['components']['show_erp_code'] && $formFields[] = ['name' => 'erpcode', 'required' => false, 'type' => 'text', 'disabled' => true];
isset($block['components']['show_name']) && $block['components']['show_name'] && $formFields[] = ['name' => 'name', 'required' => $block['components']['required_name'], 'type' => 'text', 'disabled' => !$block['components']['editable']];
isset($block['components']['show_username']) && $block['components']['show_username'] && $formFields[] = ['name' => 'username', 'required' => $block['components']['required_username'], 'type' => 'text', 'disabled' => !$block['components']['editable']];
isset($block['components']['show_email']) && $block['components']['show_email'] && $formFields[] = ['name' => 'email', 'required' => $block['components']['required_email'], 'type' => 'email', 'disabled' => !$block['components']['editable']];
isset($block['components']['show_phone']) && $block['components']['show_phone'] && $formFields[] = ['name' => 'phone', 'required' => $block['components']['required_phone'], 'type' => 'text', 'disabled' => !$block['components']['editable']];
isset($block['components']['show_mobile']) && $block['components']['show_mobile'] && $formFields[] = ['name' => 'mobile', 'required' => $block['components']['required_mobile'], 'type' => 'text', 'disabled' => !$block['components']['editable']];
isset($block['components']['show_vat']) && $block['components']['show_vat'] && $formFields[] = ['name' => 'vat', 'required' => $block['components']['required_vat'], 'type' => 'text', 'disabled' => !$block['components']['editable']];
if (isset($block['repeatable']) && is_array($block['repeatable']) && !empty($block['repeatable'])) {
$infoFields = [];
foreach ($block['repeatable'] as $field) {
$infoFields[] = ['name' => $field['info_name'], 'required' => $field['info_required'], 'type' => $field['info_type'], 'disabled' => !$block['components']['editable']];
}
$formFields[] = ['name' => 'info', 'type' => 'form', 'fields' => $infoFields];
}
isset($block['components']['editable']) && $block['components']['editable'] && $formFields[] = ['name' => 'save', 'required' => true, 'type' => 'submit'];
$form = $this->createForm(StdWebUsersEditFormType::class, ($webUserModel = new StdWebUsersEditFormModel($webUser, $formFields)));
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
if (!$this->entityManager->getRepository(StdWebUsers::class)->emailExistsInOtherUser($webUserModel->email, $webUser->getId())) {
$this->entityManager->persist($webUserModel->getUpdatedWebUser());
$this->entityManager->flush();
$this->addFlash('success', $this->translator->trans("web_users_detail.saved_successfully", [], 'webusers'));
} else {
$this->addFlash('error', $this->translator->trans("web_users_detail.email_exists", [], 'webusers'));
}
}
//$defaultAddress = $this->entityManager->getRepository(StdWebUsersAddresses::class)->findOneBy(['webuser'=>$webUser->getid(),'isActive'=>1, 'isDefault'=>1]);
$payload['form'] = $form->createView();
$payload['webUser'] = $webUser;
//$payload['defaultAddress'] = $defaultAddress;
}
} elseif (isset($stdsettings['isWebUsersNotifications']) && $stdsettings['isWebUsersNotifications']) {
if (($webuser = $this->security->getUser()) && ($webuser instanceof StdWebUsers)) {
$payload['webuser'] = $webuser;
}
$notificationsReceived = $this->entityManager->getRepository(StdNotificationsScheduleSent::class)->findBy(['webUser' => $webuser->getId(), 'isViewed' => 0], ['createdDate' => 'DESC']);
$notifications = [];
foreach ($notificationsReceived as $notification) {
$name = $notification->getNotification()->getName();
$description = $notification->getNotification()->getDescription();
if ($notification->getNotification()->getNotification()) {
$name = $notification->getNotification()->getNotification()->getName();
$description = $notification->getNotification()->getNotification()->getShortDescription();
}
$date = $notification->getCreatedDate()->format("Y-m-d H:i:s");
$timestamp = strtotime($date);
$secDiffence = time() - $timestamp;
$minutes = floor($secDiffence / 60);
$hours = floor($secDiffence / 3600);
$days = floor($secDiffence / 86400);
if ($minutes == 0) {
$time = $this->translator->trans("now", [], 'notifications');
} else if ($minutes < 60) {
if ($minutes < 2) {
$time = sprintf("%d " . $this->translator->trans("minute", [], 'notifications'), $minutes);
} else {
$time = sprintf("%d " . $this->translator->trans("minutes", [], 'notifications'), $minutes);
}
} elseif ($hours < 24) {
if ($hours < 2) {
$time = sprintf("%d " . $this->translator->trans("hour", [], 'notifications'), $hours);
} else {
$time = sprintf("%d " . $this->translator->trans("hours", [], 'notifications'), $hours);
}
} else {
if ($days < 2) {
$time = sprintf("%d " . $this->translator->trans("day", [], 'notifications'), $days);
} else {
$time = sprintf("%d " . $this->translator->trans("days", [], 'notifications'), $days);
}
}
$type = $notification->getType() ? $notification->getType()->getMachineName() : "push_notification";
$type = $this->translator->trans($type, [], 'notifications');
$notifications[] = array("id" => $notification->getId(), 'type' => $type, 'title' => $name, 'description' => $description, 'date' => $time);
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'notifications' => $notifications
], $payload);
} elseif (isset($stdsettings["isWebUsersAddresses"]) && $stdsettings["isWebUsersAddresses"]) {
if (($webuser = $this->security->getUser()) && ($webuser instanceof StdWebUsers)) {
$payload['webuser'] = $webuser;
}
$action = "";
if ($this->request->isMethod('post')) {
$action = $this->request->request->get("_action");
if ($this->request->request->get("std_web_users_addresses_form") !== null) {
$idaddress = $this->request->request->get("std_web_users_addresses_form")["id"];
} else {
$idaddress = $this->request->request->get("id");
}
$address = $this->entityManager->getRepository(StdWebUsersAddresses::class)->findOneBy(["id" => $idaddress, "webuser" => $webuser]);
}
if ($block["components"]["addnew"] || $action == "edit" || $action == "save") {
//create form to create new address
//check form submission
if (!isset($address)) {
$address = new StdWebUsersAddresses();
}
$formAddress = $this->createForm(StdWebUsersAddressesForm::class, $address, ["locale" => $this->locale, "entitymanager" => $this->entityManager, "translator" => $this->translator]);
$formAddress->handleRequest($this->request);
if ($formAddress->isSubmitted() && $formAddress->isValid()) {
$dataform = $this->request->request->all();
$address = $formAddress->getData();
$address->setCountry($dataform["std_web_users_addresses_form"]["countrychoice"]);
//save address
$address->setWebuser($webuser);
$this->entityManager->persist($address);
if (!$address->getId()) {
$event = new StdWebUsersNewAddressEvent($address);
$this->dispatcher->dispatch($event, StdWebUsersNewAddressEvent::NAME);
} else {
$event = new StdWebUsersUpdateAddressEvent($address);
$this->dispatcher->dispatch($event, StdWebUsersUpdateAddressEvent::NAME);
}
$this->entityManager->flush();
$address = new StdWebUsersAddresses();
$formAddress = $this->createForm(StdWebUsersAddressesForm::class, $address, ["locale" => $this->locale, "entitymanager" => $this->entityManager, "translator" => $this->translator]);
}
$variables["form"] = $formAddress->createView();
}
if ($action == "setdefault" && isset($address)) {
$currentDefault = $this->entityManager->getRepository(StdWebUsersAddresses::class)->findOneBy(["isDefault" => 1, "webuser" => $webuser]);
if ($currentDefault) {
$currentDefault->setIsDefault(0);
$this->entityManager->persist($currentDefault);
}
$address->setIsDefault(1);
$this->entityManager->persist($address);
$this->entityManager->flush();
}
if ($action == "delete" && isset($address)) {
$this->entityManager->remove($address);
$this->entityManager->flush();
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
], $payload);
} elseif (isset($stdsettings["isFormDomain"]) && $stdsettings["isFormDomain"]) {
if ($block["components"]["form_parent"]) {
$parentId = $this->request->get("parentId", "");
if ($parentId) {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $block["components"]["form_select_domain"], "parentDomainValue" => $parentId]);
} else {
$domainvalues = [];
}
} else {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $block["components"]["form_select_domain"]]);
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'values' => $domainvalues
]);
} elseif (isset($stdsettings["isFormStatus"]) && $stdsettings["isFormStatus"]) {
//get the domain values for the selected domain
$domainvalues = [];
$domainobj = $this->entityManager->getRepository(StdDomains::class)->findOneBy(["machineName" => "form_status"]);
if ($domainobj) {
if ($block["components"]["form_select_default"] != "") {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id"), "machineName" => $block["components"]["form_select_default"]]);
} else {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id")]);
}
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'values' => $domainvalues
]);
} elseif (isset($stdsettings["isResultsBlock"]) && $stdsettings["isResultsBlock"]) {
$pagesSearchData = [];
$hasGeneralSearch = false;
$searchQuery = (string)$this->request->query->get('p', '');
$requestedType = strtolower((string)$this->request->query->get('type', 'all'));
$order = strtolower((string)$this->request->query->get('order', 'relevance'));
if ($order === 'recent') {
$order = 'newest';
}
if ($order === 'oldest') {
$order = 'popular';
}
$page = (int)$this->request->query->get('page', 1);
$pageSize = (int)$this->request->query->get('pageSize', 15);
$page = $page > 0 ? $page : 1;
if ($pageSize <= 0 || $pageSize > 60) {
$pageSize = 15;
}
$validTypes = ['news', 'news_reports', 'programs', 'event', 'all'];
if (!in_array($requestedType, $validTypes, true)) {
$requestedType = 'news';
}
$facetTagsRaw = $this->request->query->all('tags');
$facetThemesRaw = $this->request->query->all('themes');
$facetSubThemesRaw = $this->request->query->all('subthemes');
$facetContentTypesRaw = $this->request->query->all('content_type');
if (empty($facetContentTypesRaw)) {
$facetContentTypesRaw = ['news', 'news_reports', 'programs', 'event'];
}
$facetTags = is_array($facetTagsRaw) ? array_values(array_filter(array_map('strval', $facetTagsRaw))) : [];
$facetThemes = is_array($facetThemesRaw) ? array_values(array_filter(array_map('strval', $facetThemesRaw))) : [];
$facetSubThemes = is_array($facetSubThemesRaw) ? array_values(array_filter(array_map('strval', $facetSubThemesRaw))) : [];
$facetContentTypes = is_array($facetContentTypesRaw) ? array_values(array_filter(array_map('strval', $facetContentTypesRaw))) : [];
$shouldSearchAll = ($searchQuery === '');
if ($searchQuery !== '' || $shouldSearchAll || (isset($block['components']['show_empty_search']) && $block['components']['show_empty_search'])) {
$hasGeneralSearch = true;
$arrayContentTypes = !empty($block['components']['search_content_types']) ? $block['components']['search_content_types'] : null;
// Override content types if specified in URL parameters
if (!empty($facetContentTypes)) {
$contentTypeMapping = [
'news' => 'news',
'programs' => 'programs',
'news_reports' => 'news_reports',
'event' => 'event'
];
$mappedContentTypes = [];
foreach ($facetContentTypes as $ctName) {
if (isset($contentTypeMapping[$ctName])) {
$contentType = $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['machineName' => $contentTypeMapping[$ctName]]);
if ($contentType) {
$mappedContentTypes[] = $contentType->getId();
}
}
}
if (!empty($mappedContentTypes)) {
$arrayContentTypes = $mappedContentTypes;
}
}
$arrayCategories = !empty($block['components']['search_categories']) ? $block['components']['search_categories'] : null;
$pagesSearchData = $this->entityManager->getRepository(StdPages::class)->searchPages([
'searchQuery' => $searchQuery,
'paginate' => isset($block['components']['paginate']) ? $block['components']['paginate'] : false,
'limit' => isset($block['components']['limit']) ? $block['components']['limit'] : false,
'page' => $pagenumber,
'paginator' => $this->paginator,
'language_code' => $this->locale,
'component_types' => $arrayContentTypes,
'categories' => $arrayCategories,
'roles' => ($this->security->getUser() instanceof StdWebUsers ? $this->security->getUser()->getRoles() : null)
]);
}
$pagesSearchData = array_values(array_filter($pagesSearchData, function($item) {
if ($item instanceof StdPagesContent) {
$page = $item->getPageId();
} elseif ($item instanceof StdPages) {
$page = $item;
} else {
return false;
}
return $page && Functions::isPagePublished($page);
}));
$activeTags = $facetTags;
$activeThemes = array_merge($facetThemes, $facetSubThemes);
if (!is_array($activeTags)) {
$activeTags = [];
}
if (!is_array($activeThemes)) {
$activeThemes = [];
}
$activeTags = array_values(array_unique(array_filter(array_map(fn($v) => trim((string)$v), $activeTags))));
$activeThemes = array_values(array_unique(array_filter(array_map(fn($v) => trim((string)$v), $activeThemes))));
$requestedTagEntity = null;
if (count($activeTags) === 1) {
$tagValue = $activeTags[0];
if (is_numeric($tagValue)) {
$requestedTagEntity = $this->entityManager->getRepository(StdDomainsValues::class)->find((int)$tagValue);
}
if (!$requestedTagEntity) {
$requestedTagEntity = $this->entityManager->getRepository(StdDomainsValues::class)
->findOneBy(['machineName' => $tagValue]);
}
if (!$requestedTagEntity) {
$requestedTagEntity = $this->entityManager->getRepository(StdDomainsValues::class)
->findOneBy(['description' => $tagValue]);
}
}
$extractTagMachines = function ($item) {
$col = [];
if ($item instanceof StdPagesContent) {
$page = $item->getPageId();
if (!empty($page)) {
foreach ($page->getTags() as $tagLink) {
if ($tagLink instanceof StdPagesTag) {
$dv = $tagLink->getDomainValue();
if ($dv) {
$col[] = (string)$dv->getId();
$m = $dv->getMachineName() ?? $dv->getDescription();
if ($m) {
$col[] = strtolower(trim($m));
}
}
}
}
}
}
return array_values(array_unique($col));
};
$extractThemeLabels = function ($item) {
$col = [];
if (is_array($item)) {
if (isset($item['theme']) && $item['theme'] !== '') {
$col[] = trim((string)$item['theme']);
}
if (isset($item['categories']) && is_iterable($item['categories'])) {
foreach ($item['categories'] as $c) {
$label = is_array($c) ? ($c['label'] ?? ($c['name'] ?? ($c['title'] ?? null))) : (string)$c;
if ($label) {
$col[] = trim((string)$label);
}
}
}
}
if ($item instanceof StdPagesContent) {
$page = $item->getPageId();
if (!empty($page)) {
$conn = $this->entityManager->getConnection();
$sql = "SELECT DISTINCT pp_parent.page_id as category_page_id
FROM std_pages_pages pp_child
JOIN std_pages_pages pp_parent ON pp_parent.id = pp_child.relation_id
JOIN std_pages p_cat ON p_cat.id = pp_parent.page_id
JOIN std_content_types ct ON ct.id = p_cat.content_type
WHERE pp_child.page_id = :page_id
AND ct.machine_name = 'pages_categories'
AND p_cat.is_active = 1";
try {
$stmt = $conn->prepare($sql);
$result = $stmt->executeQuery(['page_id' => $page->getId()]);
$categoryIds = $result->fetchAllAssociative();
foreach ($categoryIds as $catRow) {
$categoryPageId = $catRow['category_page_id'];
// Add the page ID for matching
$col[] = (string)$categoryPageId;
$categoryPage = $this->entityManager->getRepository(StdPages::class)->find($categoryPageId);
if ($categoryPage) {
$name = $categoryPage->getName();
if ($name) {
$col[] = trim((string)$name);
}
// Also add machine name if available
$machineName = $categoryPage->getMachineName();
if ($machineName) {
$col[] = trim((string)$machineName);
}
}
}
} catch (\Exception $e) {
// Silently handle database errors
}
foreach ($page->getTags() as $tagLink) {
if ($tagLink instanceof StdPagesTag) {
$dv = $tagLink->getDomainValue();
if ($dv) {
$domainName = $dv->getDomain() ? $dv->getDomain()->getMachineName() : '';
if (in_array($domainName, ['themes', 'subthemes', 'categorias', 'subcategorias'])) {
// Include both ID and machine name/description for matching
$col[] = (string)$dv->getId();
$themeValue = $dv->getMachineName() ?? $dv->getDescription();
if ($themeValue) {
$col[] = trim((string)$themeValue);
}
}
}
}
}
}
}
return array_values(array_unique($col));
};
if ($activeTags || $activeThemes) {
$pagesSearchData = array_values(array_filter($pagesSearchData, function ($r) use ($activeTags, $activeThemes, $extractTagMachines, $extractThemeLabels) {
$itemTags = $extractTagMachines($r);
$itemThemes = $extractThemeLabels($r);
foreach ($activeTags as $t) {
$tNorm = strtolower(trim($t));
if (!in_array($tNorm, $itemTags, true)) {
return false;
}
}
if ($activeThemes) {
$any = false;
$normalizedItemThemes = array_map(fn($v) => mb_strtolower(trim($v)), $itemThemes);
foreach ($activeThemes as $th) {
$thNorm = mb_strtolower(trim($th));
if (in_array($thNorm, $normalizedItemThemes, true)) {
$any = true;
break;
}
}
if (!$any) {
return false;
}
}
return true;
}));
}
$allattributes = [];
foreach ($pagesSearchData as $pagecontent) {
if (!is_object($pagecontent) || !method_exists($pagecontent, 'getPageId')) {
continue;
}
$pageIdObj = $pagecontent->getPageId();
if (!is_object($pageIdObj) || !method_exists($pageIdObj, 'getId')) {
continue;
}
$allPagesAttributesValues = $this->entityManager->getRepository(StdPagesAttributesValues::class)->getPageAttributes($pageIdObj);
$attributesarr = [];
foreach ($allPagesAttributesValues as $entity) {
if ($entity instanceof StdAttributes) {
$attributesarr[$entity->getMachineName()]["attribute"] = $entity;
}
if ($entity instanceof StdAttributesValues) {
$attributesarr[$entity->getAttribute()->getMachineName()]["values"]["{$entity->getValue()}"] = $entity;
}
}
$allattributes[$pageIdObj->getId()] = $attributesarr;
}
$extractType = function ($item) {
$raw = '';
if ($item instanceof StdPagesContent) {
$raw = $item->getPageId()?->getContentType()?->getMachineName();
} elseif ($item instanceof StdPages) {
$raw = $item->getContentType()?->getMachineName();
} elseif (is_array($item)) {
$raw = $item['content_type'] ?? ($item['type'] ?? ($item['content']['type'] ?? ''));
}
if (!in_array($raw, ['programs', 'news_reports', 'event', 'news'], true)) {
return 'news';
}
return $raw;
};
$counts = ['news' => 0, 'news_reports' => 0, 'programs' => 0, 'event' => 0, 'all' => 0];
foreach ($pagesSearchData as $r) {
$k = $extractType($r);
if (isset($counts[$k])) {
$counts[$k]++;
}
$counts['all']++; // Count all items for the 'all' tab
}
// Filter by content type, unless 'all' is requested
if ($requestedType === 'all') {
$filtered = $pagesSearchData; // Show all content types
} else {
$filtered = array_filter($pagesSearchData, function ($r) use ($extractType, $requestedType) {
return $extractType($r) === $requestedType;
});
}
$getPublishTimestamp = function ($item): int {
$dt = null;
if ($item instanceof StdPagesContent) {
$dt = $item->getPageId()?->getPublishDate();
} elseif ($item instanceof StdPages) {
$dt = $item->getPublishDate();
} elseif (is_array($item)) {
$raw = $item['publish_date'] ?? ($item['content']['publish_date'] ?? ($item['content']['date'] ?? ($item['date'] ?? null)));
if (is_string($raw)) {
return strtotime($raw) ?: 0;
}
if ($raw instanceof \DateTimeInterface) {
return $raw->getTimestamp();
}
return 0;
}
if (is_string($dt)) {
return strtotime($dt) ?: 0;
}
if ($dt instanceof \DateTimeInterface) {
return $dt->getTimestamp();
}
return 0;
};
if ($order === 'newest') {
usort($filtered, function ($a, $b) use ($getPublishTimestamp) {
$ta = $getPublishTimestamp($a);
$tb = $getPublishTimestamp($b);
if ($ta === $tb) return 0;
return $ta > $tb ? -1 : 1;
});
} elseif ($order === 'popular') {
$pageIds = [];
foreach ($filtered as $it) {
if ($it instanceof StdPagesContent) {
$pid = $it->getPageId()?->getId();
} elseif ($it instanceof StdPages) {
$pid = $it->getId();
} elseif (is_array($it)) {
$pid = $it['id'] ?? null;
} else {
$pid = null;
}
if ($pid) {
$pageIds[] = $pid;
}
}
$pageIds = array_values(array_unique($pageIds));
$popularCounts = [];
if ($pageIds) {
$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');
$q->setParameter('ids', $pageIds);
foreach ($q->getResult() as $row) {
$popularCounts[(int)$row['pid']] = (int)$row['cnt'];
}
}
usort($filtered, function ($a, $b) use ($popularCounts, $getPublishTimestamp) {
$getPid = function ($x) {
if ($x instanceof StdPagesContent) return $x->getPageId()?->getId();
if ($x instanceof StdPages) return $x->getId();
if (is_array($x)) return $x['id'] ?? null;
return null;
};
$pa = $getPid($a);
$pb = $getPid($b);
$ca = $pa && isset($popularCounts[$pa]) ? $popularCounts[$pa] : 0;
$cb = $pb && isset($popularCounts[$pb]) ? $popularCounts[$pb] : 0;
if ($ca === $cb) {
$ta = $getPublishTimestamp($a);
$tb = $getPublishTimestamp($b);
if ($ta === $tb) return 0;
return $ta > $tb ? -1 : 1;
}
return $ca > $cb ? -1 : 1;
});
} else {
$locationTags = [];
$cookieLocationId = $this->request->cookies->get('CloseToYou-Location');
$sessionLocations = $this->request->getSession()->get('close_location_ids');
if ($cookieLocationId) {
$locationTags[] = (int)$cookieLocationId;
if (is_array($sessionLocations)) {
foreach ($sessionLocations as $locId) {
if ($locId != $cookieLocationId) {
$locationTags[] = (int)$locId;
}
}
}
} elseif (!empty($sessionLocations)) {
$locationTags = array_map('intval', $sessionLocations);
}
if (!empty($locationTags)) {
// Location-based ordering (like 'location' order_by in repository)
usort($filtered, function ($a, $b) use ($locationTags, $getPublishTimestamp) {
$getLocationScore = function ($item) use ($locationTags) {
$bestScore = 999999; // Start with high value (farthest)
if ($item instanceof StdPagesContent) {
$page = $item->getPageId();
if ($page) {
foreach ($page->getTags() as $tagLink) {
if ($tagLink instanceof StdPagesTag) {
$dv = $tagLink->getDomainValue();
if ($dv) {
$tagIndex = array_search($dv->getId(), $locationTags);
if ($tagIndex !== false && $tagIndex < $bestScore) {
$bestScore = $tagIndex; // Lower index = closer = better
}
}
}
}
}
} elseif ($item instanceof StdPages) {
foreach ($item->getTags() as $tagLink) {
if ($tagLink instanceof StdPagesTag) {
$dv = $tagLink->getDomainValue();
if ($dv) {
$tagIndex = array_search($dv->getId(), $locationTags);
if ($tagIndex !== false && $tagIndex < $bestScore) {
$bestScore = $tagIndex; // Lower index = closer = better
}
}
}
}
}
return $bestScore;
};
$scoreA = $getLocationScore($a);
$scoreB = $getLocationScore($b);
// Lower score (closer location) comes first
if ($scoreA !== $scoreB) {
return $scoreA - $scoreB;
}
// If same location score, sort by publish date (newest first)
$ta = $getPublishTimestamp($a);
$tb = $getPublishTimestamp($b);
if ($ta === $tb) return 0;
return $ta > $tb ? -1 : 1;
});
} else {
// Historic ordering (like 'historic' order_by in repository)
$recommended = [];
try {
$recommended = $this->stdTrackingService->getRecommendedPagesForUser();
} catch (\Throwable $e) {
$recommended = [];
}
$recommendedPageIds = [];
foreach ($recommended as $rec) {
if ($rec instanceof StdPagesContent) {
$pid = $rec->getPageId()?->getId();
} elseif ($rec instanceof StdPages) {
$pid = $rec->getId();
} elseif (is_array($rec)) {
$pid = $rec['id'] ?? null;
} else {
$pid = null;
}
if ($pid) {
$recommendedPageIds[] = $pid;
}
}
if (!empty($recommendedPageIds)) {
// Get existing page IDs from filtered results
$existingPageIds = [];
foreach ($filtered as $item) {
if ($item instanceof StdPagesContent) {
$pid = $item->getPageId()?->getId();
} elseif ($item instanceof StdPages) {
$pid = $item->getId();
} elseif (is_array($item)) {
$pid = $item['id'] ?? null;
} else {
$pid = null;
}
if ($pid) {
$existingPageIds[] = $pid;
}
}
// Find recommended pages that are NOT in current filtered results
$missingRecommendedIds = array_diff($recommendedPageIds, $existingPageIds);
if (!empty($missingRecommendedIds)) {
// Fetch missing recommended pages that match current filters
$qb = $this->entityManager->createQueryBuilder();
$qb->select('pc, p')
->from('App\Admin\Entity\StdPagesContent', 'pc')
->join('pc.pageId', 'p')
->where('p.id IN (:recommendedIds)')
->andWhere('p.isActive = 1')
->andWhere('(p.publishDate IS NULL OR p.publishDate <= :now)')
->andWhere('(p.expireDate IS NULL OR p.expireDate > :now)')
->andWhere('pc.languageCode = :language')
->setParameter('recommendedIds', $missingRecommendedIds)
->setParameter('now', new \DateTime())
->setParameter('language', $this->locale);
// Apply same search query filter if exists
if (!empty($searchQuery)) {
$qb->andWhere('(pc.title LIKE :search OR JSON_SEARCH(LOWER(pc.content), \'all\', :search) IS NOT NULL)')
->setParameter('search', '%' . strtolower($searchQuery) . '%');
}
// Apply same content type filter if exists
if (!empty($arrayContentTypes)) {
$qb->andWhere('p.contentType IN (:contentTypes)')
->setParameter('contentTypes', $arrayContentTypes);
}
// Apply same category filter if exists
if (!empty($arrayCategories)) {
$qb->join('p.tags', 'pt')
->join('pt.domainValue', 'dv')
->andWhere('dv.id IN (:categories)')
->setParameter('categories', $arrayCategories);
}
$missingRecommended = $qb->getQuery()->getResult();
if ($activeTags || $activeThemes) {
$missingRecommended = array_values(array_filter($missingRecommended, function ($r) use ($activeTags, $activeThemes, $extractTagMachines, $extractThemeLabels) {
$itemTags = $extractTagMachines($r);
$itemThemes = $extractThemeLabels($r);
foreach ($activeTags as $t) {
$tNorm = strtolower(trim($t));
if (!in_array($tNorm, $itemTags, true)) {
return false;
}
}
if ($activeThemes) {
$any = false;
$normalizedItemThemes = array_map(fn($v) => mb_strtolower(trim($v)), $itemThemes);
foreach ($activeThemes as $th) {
$thNorm = mb_strtolower(trim($th));
if (in_array($thNorm, $normalizedItemThemes, true)) {
$any = true;
break;
}
}
if (!$any) {
return false;
}
}
return true;
}));
}
// Merge with existing filtered results
$filtered = array_merge($missingRecommended, $filtered);
}
usort($filtered, function ($a, $b) use ($recommendedPageIds, $getPublishTimestamp) {
$getPid = function ($x) {
if ($x instanceof StdPagesContent) return $x->getPageId()?->getId();
if ($x instanceof StdPages) return $x->getId();
if (is_array($x)) return $x['id'] ?? null;
return null;
};
$getTagCount = function ($x) {
if ($x instanceof StdPagesContent) {
$page = $x->getPageId();
return $page ? count($page->getTags()) : 0;
} elseif ($x instanceof StdPages) {
return count($x->getTags());
}
return 0;
};
$pa = $getPid($a);
$pb = $getPid($b);
$aRec = $pa !== null && in_array($pa, $recommendedPageIds);
$bRec = $pb !== null && in_array($pb, $recommendedPageIds);
// 1. Recommended pages come first
if ($aRec && !$bRec) {
return -1;
} elseif (!$aRec && $bRec) {
return 1;
}
// 2. If both have same recommendation status, sort by tag count (DESC)
$tagCountA = $getTagCount($a);
$tagCountB = $getTagCount($b);
if ($tagCountA !== $tagCountB) {
return $tagCountA > $tagCountB ? -1 : 1;
}
// 3. Finally sort by publish date (DESC)
$ta = $getPublishTimestamp($a);
$tb = $getPublishTimestamp($b);
if ($ta === $tb) return 0;
return $ta > $tb ? -1 : 1;
});
} else {
// No recommended pages - just sort by publish date (DESC)
usort($filtered, function ($a, $b) use ($getPublishTimestamp) {
$ta = $getPublishTimestamp($a);
$tb = $getPublishTimestamp($b);
if ($ta === $tb) return 0;
return $ta > $tb ? -1 : 1;
});
}
}
}
$totalFiltered = count($filtered);
$pageCount = $totalFiltered > 0 ? (int)ceil($totalFiltered / $pageSize) : 1;
if ($page > $pageCount) {
$page = $pageCount;
}
$offset = ($page - 1) * $pageSize;
$pageItems = array_slice(array_values($filtered), $offset, $pageSize);
$nextPage = $page < $pageCount ? $page + 1 : 0;
$resultsMeta = [
'query' => $searchQuery,
'currentType' => $requestedType,
'order' => $order,
'page' => $page,
'pageSize' => $pageSize,
'pageCount' => $pageCount,
'nextPage' => $nextPage,
'counts' => $counts,
'total' => $totalFiltered,
'totalAll' => count($pagesSearchData),
'items' => $pageItems,
'hasSearch' => $hasGeneralSearch,
];
$payload = array_merge($variables, [
'settings' => $block['settings'],
'fields' => $block['components'],
'values' => $pagesSearchData,
'results' => $resultsMeta,
'attributes' => $allattributes,
'paginator' => $pagesSearchData,
'total' => $totalFiltered,
'total_all_types' => count($pagesSearchData),
'hasGeneralSearch' => $hasGeneralSearch,
'requestedTag' => $requestedTagEntity,
]);
} elseif (isset($stdsettings["isContentSnippet"]) && $stdsettings["isContentSnippet"]) {
if ($snippetContent = $this->entityManager->getRepository(StdSnippetsContent::class)->findOneBy(["snippetId" => $block["components"]["combo_content_snippet"], "languageCode" => $this->locale])) {
if ($snippetContent) {
$renderedcontent = $this->renderPageContent($pagenumber, $variables, $page, $snippetContent, null);
// isset($renderedcontent['webpackEntries']) && $webpackEntries = array_merge($webpackEntries, $renderedcontent['webpackEntries']);
isset($renderedcontent['cookies']) && $cookies = array_merge($cookies, $renderedcontent['cookies']);
if (array_key_exists('editBlocksInfo', $renderedcontent["variables"]) && count($renderedcontent["variables"]["editBlocksInfo"]) > 0) {
$variables["editBlocksInfo"] = array_merge(
$renderedcontent["variables"]["editBlocksInfo"], $variables["editBlocksInfo"]
);
}
$payload = array_merge([
'settings' => $block["settings"],
'fields' => $block["components"],
'blockuniqueid' => $block["blockuniqueid"] ?? "",
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'blockscontent' => $renderedcontent["html"],
'blockscontentjs' => $renderedcontent["js"],
], $variables);
} else {
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'blockuniqueid' => $block["blockuniqueid"] ?? "",
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array())
]);
}
}
} elseif (isset($stdsettings["isFormSequential"]) && $stdsettings["isFormSequential"]) {
$form_sequential_pad_number = isset($block["components"]["form_sequential_pad_number"]) ? $block["components"]["form_sequential_pad_number"] : 0;
$sequential = $this->entityManager->getRepository(Forms::class)->findNextFormSequentialByFormName($page->getMachineName(), $form_sequential_pad_number);
$block["components"]["form_sequential"] = $sequential;
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
]);
} elseif (isset($stdsettings["isListForYou"]) && $stdsettings["isListForYou"]) {
$limit = (int)($block['settings']['limit'] ?? 10);
$queryPage = $this->request->query->getInt('page', 0);
$pageNum = $queryPage > 0 ? $queryPage : ($pagenumber ?? 1);
$locationTags = [];
$cookieLocationId = $this->request->cookies->get('CloseToYou-Location');
$sessionLocations = $this->request->getSession()->get('close_location_ids');
if ($cookieLocationId) {
$locationTags[] = (int)$cookieLocationId;
if (is_array($sessionLocations)) {
foreach ($sessionLocations as $locId) {
if ($locId != $cookieLocationId) {
$locationTags[] = $locId;
}
}
}
} elseif (!empty($sessionLocations)) {
$locationTags = $sessionLocations;
}
$block['settings']['locationTags'] = $locationTags;
$newsData = $blocksservice->fetchNewsList(
$this->locale,
$this->entityManager,
$block['settings'],
$block['components'],
$pageNum,
$limit,
$this->paginator
);
if (!isset($locationValues)) {
try {
$locationValues = $this->entityManager->getRepository(StdDomainsValues::class)
->createQueryBuilder('dv')
->andWhere('dv.isActive = 1')
->andWhere('dv.type = :locType')
->setParameter('locType', DomainValueType::Location->value)
->addOrderBy('dv.description', 'ASC')
->getQuery()->getResult();
} catch (\Throwable $e) {
$locationValues = [];
}
}
$payload = array_merge($variables, [
'settings' => $block['settings'],
'fields' => $block['components'],
'items' => $newsData['items'],
'paginator' => $newsData['paginator'] ?? null,
'isajax' => $ajaxCall && array_key_exists('isAjax', $ajaxCall) ? true : false,
'location_values' => $locationValues ?? []
]);
} elseif (isset($stdsettings['isListNews']) && $stdsettings['isListNews']) {
$limit = (int)($block['settings']['limit'] ?? 10);
$queryPage = $this->request->query->getInt('page', 0);
$pageNum = $queryPage > 0 ? $queryPage : ($pagenumber ?? 1);
$locationTags = [];
$cookieLocationId = $this->request->cookies->get('CloseToYou-Location');
$sessionLocations = $this->request->getSession()->get('close_location_ids');
if ($cookieLocationId) {
$locationTags[] = (int)$cookieLocationId;
if (is_array($sessionLocations)) {
foreach ($sessionLocations as $locId) {
if ($locId != $cookieLocationId) {
$locationTags[] = $locId;
}
}
}
} elseif (!empty($sessionLocations)) {
$locationTags = $sessionLocations;
}
$block['settings']['locationTags'] = $locationTags;
$newsData = $blocksservice->fetchNewsList(
$this->locale,
$this->entityManager,
$block['settings'],
$block['components'],
$pageNum,
$limit,
$this->paginator
);
if (!isset($locationValues)) {
try {
$locationValues = $this->entityManager->getRepository(StdDomainsValues::class)
->createQueryBuilder('dv')
->andWhere('dv.isActive = 1')
->andWhere('dv.type = :locType')
->setParameter('locType', DomainValueType::Location->value)
->addOrderBy('dv.description', 'ASC')
->getQuery()->getResult();
} catch (\Throwable $e) {
$locationValues = [];
}
}
$payload = array_merge($variables, [
'settings' => $block['settings'],
'fields' => $block['components'],
'items' => $newsData['items'],
'paginator' => $newsData['paginator'] ?? null,
'isajax' => $ajaxCall && array_key_exists('isAjax', $ajaxCall) ? true : false,
'location_values' => $locationValues ?? []
]);
} elseif (isset($stdsettings['isListseetv']) && $stdsettings['isListseetv']) {
// Limite
$limit = (int)($block['settings']['limit'] ?? 30);
// categoria
$categoryId = isset($block['components']['category'])
? (int)$block['components']['category']
: null;
// Pega os itens do content type "see_tv".
// Requisito: todos com video_youtubeid são tratados como LIVE;
// ordenação: mais recente primeiro (start_date desc)
$channels = $blocksservice->fetchSeeTvForList(
$this->locale,
$this->entityManager,
$limit,
0,
'pt',
$categoryId
);
$payload = array_merge($variables, [
'settings' => $block['settings'],
'fields' => $block['components'],
'channels' => $channels
]);
} elseif (isset($stdsettings['isTop10']) && $stdsettings['isTop10']) {
// 1) Pega os componentes do bloco (program_1..program_10)
$components = $block['components'] ?? [];
$items = $blocksservice->fetchProgramsTop10(
$this->locale,
$this->entityManager,
$components,
10 // limit
);
// 4) Payload padrão para o Twig
$payload = array_merge($variables, [
'settings' => $block['settings'] ?? [],
'fields' => $block['components'] ?? [],
'items' => $items,
'blockuniqueid' => $block["blockuniqueid"] ?? "",
]);
} elseif (isset($stdsettings['isLike']) && $stdsettings['isLike']) {
$limit = (int)($block['settings']['limit'] ?? 30);
$pageId = $variables['page']['id'] ?? null;
$items = $blocksservice->fetchProgramsLike(
$this->locale,
$this->entityManager,
$pageId,
$limit
);
$payload = array_merge($variables, [
'settings' => $block['settings'] ?? [],
'fields' => $block['components'] ?? [],
'items' => $items,
'blockuniqueid' => $block["blockuniqueid"] ?? "",
]);
} elseif (isset($stdsettings['isConta5MinBlock']) && $stdsettings['isConta5MinBlock']) {
$limit = (int)($block['settings']['limit'] ?? 30);
$relationId = (int)($block['components']['category'] ?? -1);
// Handle category filter from query params (same logic as list blocks)
$queryCategoriesRaw = $this->request->query->all('category');
$queryCategories = is_array($queryCategoriesRaw) ? array_values(array_filter(array_map('intval', $queryCategoriesRaw))) : [];
if (!is_array($queryCategoriesRaw) && $queryCategoriesRaw !== null && $queryCategoriesRaw !== '') {
$queryCategories = [(int)$queryCategoriesRaw];
}
if (!empty($queryCategories)) {
$relationIds = [];
foreach ($queryCategories as $pageId) {
$pagesRelations = $this->entityManager->getRepository(StdPagesPages::class)->findBy([
'pageId' => $pageId
]);
foreach ($pagesRelations as $pagesRelation) {
$relationIds[] = $pagesRelation->getId();
}
}
$relationId = !empty($relationIds) ? $relationIds : $queryCategories;
}
$items = $blocksservice->fetchConta5Min(
$this->locale,
$this->entityManager,
$limit,
$relationId
);
$payload = array_merge($variables, [
'settings' => $block['settings'] ?? [],
'fields' => $block['components'] ?? [],
'items' => $items,
'blockuniqueid' => $block["blockuniqueid"] ?? "",
]);
} elseif (isset($stdsettings['isCurtasBlock']) && $stdsettings['isCurtasBlock']) {
$limit = (int)($block['settings']['limit'] ?? 30);
$relationId = (int)($block['components']['category'] ?? -1);
$items = $blocksservice->fetchCurtas(
$this->locale,
$this->entityManager,
$limit,
$relationId
);
$payload = array_merge($variables, [
'settings' => $block['settings'] ?? [],
'fields' => $block['components'] ?? [],
'items' => $items,
'blockuniqueid' => $block["blockuniqueid"] ?? "",
]);
} else {
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'blockuniqueid' => $block["blockuniqueid"] ?? "",
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array())
]);
}
$cache = new DoctrineDbalAdapter($this->registry->getConnection());
if ($ajaxCall && array_key_exists("isAjax", $ajaxCall))
$payload = array_merge($payload, ["isajax" => true]);
// DEBUG: Log pageskin value for block_list blocks
if ($block["block"] === "block_list") {
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);
}
$skin = "default";
if ($pageskin != "") {
$skin = $pageskin;
if ($this->container->get('twig')->getLoader()->exists($skin)) {
$cachekey = Functions::cleanString($this->locale . $variables["blockSequence"] . "-" . $skin . "-" . $pagenumber);
$cacheitem = $cache->getItem($cachekey);
$updated = false;
if (is_array($cacheitem->get()) && strtotime($cacheitem->get()["updated"]) < strtotime($pageContent->getUpdatedDate()->format("Y-m-d H:i:s"))) {
$updated = true;
}
if ($updated || !$cacheitem->isHit() || !$iscacheable || (getenv("APP_ENV") == "dev" && !getenv("CACHE_FORCE"))) {
$item = array("updated" => date("Y-m-d H:i:s"), "data" => $this->renderView($skin, $payload));
if ($iscacheable) {
$cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
$cache->save($cacheitem->set($item));
}
$result .= $item["data"];
} else {
$result .= $cacheitem->get()["data"];
}
}
} else {
if ($block["skin"] != "")
$skin = $block["skin"];
// DEBUG: Log ALL block_list blocks to see what's happening
if ($block["block"] === "block_list") {
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);
}
// For AJAX lazy loading requests, use the blockskin passed from the lazy loader
if ($ajaxCall && array_key_exists("isAjax", $ajaxCall) && isset($ajaxCall["blockskin"]) && !empty($ajaxCall["blockskin"])) {
$skin = $ajaxCall["blockskin"];
}
// Check if lazy loading is enabled for this block (only for block_list and non-AJAX requests)
elseif ($block["block"] === "block_list"
&& isset($block["settings"]["lazy_loading_enabled"])
&& $block["settings"]["lazy_loading_enabled"]
&& (!$ajaxCall || !array_key_exists("isAjax", $ajaxCall))) {
// Store the original block skin so the lazy template knows what to load via AJAX
// Use lazy_loading_skin if set, otherwise fall back to the block's main skin
$targetSkin = !empty($block["settings"]["lazy_loading_skin"])
? $block["settings"]["lazy_loading_skin"]
: $skin;
// DEBUG: Log blockuniqueid value
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);
// Build proper payload for lazy template
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'blockuniqueid' => $block["blockuniqueid"] ?? "",
'lazy_loading_skin' => $targetSkin
]);
$skin = "lazy";
}
if ($this->container->get('twig')->getLoader()->exists("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".html.twig")) {
$cachekey = Functions::cleanString($this->locale . $variables["blockSequence"] . "-" . "blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".html.twig" . "-" . $pagenumber);
$cacheitem = $cache->getItem($cachekey);
$updated = false;
if (isset($variables["preview"]) && $variables["preview"] || is_array($cacheitem->get()) && strtotime($cacheitem->get()["updated"]) < strtotime($pageContent->getUpdatedDate()->format("Y-m-d H:i:s"))) {
$updated = true;
}
if ($updated || !$cacheitem->isHit() || !$iscacheable || (getenv("APP_ENV") == "dev" && !getenv("CACHE_FORCE"))) {
$item = array("updated" => date("Y-m-d H:i:s"), "data" => $this->renderView("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".html.twig", $payload));
/* BLOCK GROUP */
if ($block["block"] == "block_group") {
if (array_key_exists("group_children", $block["components"]) && $block["components"]["group_children"] != "") {
$block_group_children = json_decode($block["components"]["group_children"]);
$group_last_children = end($block_group_children);
$block_groups[$group_last_children->block_uniqueid] = array();
}
$group_data = explode('<!-- @START GROUP CONTENT -->', $item['data']);
if (count($group_data) > 0) {
$item["data"] = $group_data[0];
$block_groups[$group_last_children->block_uniqueid]["end_html"] = $group_data[1];
} else {
$block_groups[$group_last_children->block_uniqueid]["end_html"] = "";
}
}
/* @END BLOCK GROUP */
if ($iscacheable && (!isset($variables["preview"]) || !$variables["preview"])) {
$cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
$cache->save($cacheitem->set($item));
}
$result .= $item["data"];
} else {
$result .= $cacheitem->get()["data"];
}
}
if ($this->container->get('twig')->getLoader()->exists("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".js.twig")) {
$cachekey = Functions::cleanString($this->locale . $variables["blockSequence"] . "-" . "blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".js.twig" . "-" . $pagenumber);
$cacheitem = $cache->getItem($cachekey);
$updated = false;
if (is_array($cacheitem->get()) && strtotime($cacheitem->get()["updated"]) < strtotime($pageContent->getUpdatedDate()->format("Y-m-d H:i:s"))) {
$updated = true;
}
if ($updated || !$cacheitem->isHit() || !$iscacheable || (getenv("APP_ENV") == "dev" && !getenv("CACHE_FORCE"))) {
$item = array("updated" => date("Y-m-d H:i:s"), "data" => $this->renderView("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".js.twig", $payload));
if ($iscacheable) {
$cacheitem->expiresAfter((int)getenv("CACHE_EXPIRATION"));
$cache->save($cacheitem->set($item));
}
$resultjs .= $item["data"];
} else {
$resultjs .= $cacheitem->get()["data"];
}
}
}
}
}
/* BLOCK GROUP */
if (isset($block["blockuniqueid"]) && isset($block_groups[$block["blockuniqueid"]])) {
if (array_key_exists("end_html", $block_groups[$block["blockuniqueid"]])) {
$result .= $block_groups[$block["blockuniqueid"]]["end_html"];
}
}
/* @END BLOCK GROUP */
}
$this->mainrequest->attributes->set('webpackEntries', array_map(function ($value) {
return str_replace('%locale%', $this->locale, $value);
}, $this->mainrequest->attributes->get('webpackEntries')));
if ($ajaxCall && array_key_exists("isAjax", $ajaxCall)) {
if ($payload) {
return array("html" => $result, "js" => $resultjs, "payload" => $payload, "variables" => $variables, 'cookies' => $cookies);
} else {
return array("html" => $result, "js" => $resultjs, "payload" => array(), "variables" => $variables, 'cookies' => $cookies);
}
} else {
return array("html" => $result, "js" => $resultjs, "variables" => $variables, 'cookies' => $cookies, 'block_groups' => $block_groups);
}
}
private function findFriendlyUrlByPageId($pageId, $entityManager, $language)
{
$friendlyUrlRepo = $entityManager->getRepository(StdFriendlyUrl::class)->getRowByPageAndRelationTreeNotNull($pageId, $language);
if (!$friendlyUrlRepo) {
$friendlyUrlRepo = $entityManager->getRepository(StdFriendlyUrl::class)->getOneRowByPage($pageId, $language);
}
return $friendlyUrlRepo;
}
private function renderPreviewPageContent($fields, array $variables = []): array
{
$blocksservice = new StdBlocksService($this->stdTrackingService, $this->entityManager);
$renderlistblocks = true;
$pagenumber = 1;
$cont = $fields;
if (isset($cont["fields"]))
$content = $cont["fields"];
else
$content = array();
$result = "";
$resultjs = "";
$payload = [];
$headercontent = [];
$publishDatePage = null;
$expireDatePage = null;
$blockSequence = 0;
$now = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
$publishDateIni = $now;
$dateFim = new DateTime("now", new DateTimeZone('Europe/Lisbon'));
$dateFim->add(new DateInterval('P10D'));
$expireDateIni = $dateFim;
$blockmachinename = "";
foreach ($content as $block) {
$publishDate = $publishDateIni;
$expireDate = $expireDateIni;
if (array_key_exists("settings", $block) && $block["settings"]) {
if (array_key_exists("publish_date", $block["settings"]) && $block["settings"]["publish_date"]) {
$dateIni = date_create_from_format("d/m/Y h:i A", $block["settings"]["publish_date"]);
$publishDate = new DateTime($dateIni->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
}
if (array_key_exists("expire_date", $block["settings"]) && $block["settings"]["expire_date"]) {
$dateFim = date_create_from_format("d/m/Y h:i A", $block["settings"]["expire_date"]);
$expireDate = new DateTime($dateFim->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
}
}
if ($publishDate <= $now && $expireDate > $now) {
if (!empty($pageskin)) {
$pageskin = "blocks/" . $block["block"] . "/" . $block["block"] . "." . $pageskin . ".html.twig";
}
$iscacheable = true;
$blockSequence++;
$variables["blockSequence"] = $block["block"] . "_1_" . $blockSequence;
if (!empty($blockmachinename) && $block["block"] != $blockmachinename && $variables["blockSequence"] != $blockmachinename) {
continue;
}
$payload = [];
$stdblock = $this->entityManager->getRepository(StdBlocks::class)->findOneBy(['machineName' => $block["block"]]);
if ($stdblock) {
$stdsettings = $stdblock->getSettings();
if (isset($block["templatesBlocksId"]) && $block["templatesBlocksId"] && isset($block["isMaster"]) && $block["isMaster"]) {
$stdtemplate = $page->getTemplateId();
if ($stdtemplate->getId()) {
$stdtemplateblock = $this->entityManager->getRepository(StdTemplatesBlocks::class)->findOneById($block["templatesBlocksId"]);
if ($stdtemplateblock) {
$blockcontent = $stdtemplateblock->getContent();
$block["settings"] = $blockcontent["settings"];
$block["components"] = $blockcontent["components"];
$block["skin"] = $blockcontent["skin"];
$block["repeatable"] = ($blockcontent["repeatable"] ? $blocksservice->filterPublishedRepeatables($blockcontent["repeatable"]) : array());
}
}
}
// Check if lazy loading is enabled - skip list processing and render lazy skeleton instead
$isLazyLoadingEnabled = $block["block"] === "block_list"
&& isset($block["settings"]["lazy_loading_enabled"])
&& $block["settings"]["lazy_loading_enabled"]
&& (!$ajaxCall || !array_key_exists("isAjax", $ajaxCall));
if (isset($stdsettings["isList"]) && $stdsettings["isList"] && $renderlistblocks && !$isLazyLoadingEnabled) {
//it's a list
//get the content_type, template and the category from block components
//get x category childs and render with selected skin
$iscacheable = false;
// Use content_type_list instead of the old content_type field
$contentType = null;
if (isset($block["components"]["content_type_list"]) && !empty($block["components"]["content_type_list"])) {
// For multiple content types, use the first one for compatibility
$contentTypeId = is_array($block["components"]["content_type_list"])
? $block["components"]["content_type_list"][0]
: $block["components"]["content_type_list"];
$contentType = $this->entityManager->getRepository(StdContentTypes::class)->findOneById($contentTypeId);
}
$levels = (isset($block["components"]["levels"]) ? $block["components"]["levels"] : 1);
$contentTypeList = (isset($block["components"]["content_type_list"]) ? $block["components"]["content_type_list"] : array());
$locationTags = [];
if (!empty($this->request->getSession()->get('close_location_ids'))) {
$locationTags = $this->request->getSession()->get('close_location_ids');
}
$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]);
$resultlist = "";
$resultlistjs = "";
$total = count($relations);
$index = 0;
foreach ($relations as $stdpagespages) {
$relationcontent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $stdpagespages["page_id"], "languageCode" => $this->locale]);
//render
$friendlyUrl = "";
if ($relationcontent) {
$friendlyUrlObj = $this->findFriendlyUrlByPageId($relationcontent->getPageId()->getId(), $this->entityManager, $this->locale);
$friendlyUrl = $friendlyUrlObj ? $friendlyUrlObj->getUrl() : "";
$fields = $this->prepareVariables($relationcontent);
$relationPageId = $relationcontent->getPageId();
$fields['isTop10'] = false;
if ($relationPageId->getPublishDate())
$publishDatePage = new DateTime($relationPageId->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
if ($relationPageId->getExpireDate())
$expireDatePage = new DateTime($relationPageId->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
} else {
$fields = array();
}
// Handle skin selection with fallback logic
$selectedSkin = 'default';
$skinparam = 'content-types/default/content_type.default.html.twig'; // Default fallback
$skinjsparam = 'content-types/default/content_type.default.js.twig'; // Default JS fallback
if (array_key_exists("skin", $block["components"]) && $block["components"]["skin"]) {
$skinValue = $block["components"]["skin"];
// If skin is an array (multiple selection), use the first one
if (is_array($skinValue) && !empty($skinValue)) {
$selectedSkin = reset($skinValue);
} elseif (is_string($skinValue)) {
$selectedSkin = $skinValue;
}
}
// Template selection with cascading fallbacks
if (!empty($contentType)) {
// 1st priority: Specific skin template
if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $selectedSkin . '.html.twig')) {
$skinparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $selectedSkin . '.html.twig';
}
// 2nd priority: Content type default template
elseif ($this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.html.twig')) {
$skinparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.html.twig';
}
// JS template with same fallback logic
if ($selectedSkin !== 'default' && $this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $selectedSkin . '.js.twig')) {
$skinjsparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $selectedSkin . '.js.twig';
}
elseif ($this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.js.twig')) {
$skinjsparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.js.twig';
}
}
if (isset($stdsettings["renderPageBlocks"]) && $stdsettings["renderPageBlocks"]) {
$content = $this->renderPageContent($pagenumber, $fields, $relationcontent->getPageId(), $relationcontent, null, false);
} else {
$content["html"] = "";
$content["js"] = "";
}
$headercontent = [
"publishdate" => ($publishDatePage != null ? $publishDatePage->format('Y-m-d H:i:s') : null),
"expiredate" => ($expireDatePage != null ? $expireDatePage->format('Y-m-d H:i:s') : null),
"lastupdate" => "",//($page->getUpdatedDate() != null ? $page->getUpdatedDate()->format('Y-m-d H:i:s') : null),
"createdby" => "",//$page->getCreatedBy()->getName(),
"order" => 0,//$page->getOrderValue()
];
$payload = array_merge([
"headercontent" => $headercontent,
"id" => $relationcontent->getPageId()->getId(),
"relationid" => $stdpagespages["relation_id"],
"currentrelationid" => $stdpagespages["id"],
"total" => $total,
"index" => $index,
"settings" => $block["settings"],
"locale" => $this->locale,
"blockscontent" => $content["html"],
"blockscontentjs" => $content["js"],
"pagination" => $relations,
'friendlyUrl' => $friendlyUrl
], $fields);
if ($this->container->get('twig')->getLoader()->exists($skinparam))
$resultlist .= $this->renderView($skinparam, $payload);
if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
$resultlistjs .= $this->renderView($skinjsparam, $payload);
$index++;
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'blockscontent' => $resultlist,
'blockscontentjs' => $resultlistjs,
'paginator' => $relations
]);
} elseif (isset($block["isPage"]) && $block["isPage"]) {
$contentType = $this->entityManager->getRepository(StdContentTypes::class)->findOneById($block["components"]["input_type_content_type"]);
$pageContent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $block["components"]["input_combo_pages"], "languageCode" => $this->locale]);
if ($pageContent)
$fields = $this->prepareVariables($pageContent);
$inputSkin = isset($block["components"]["input_combo_skin"]) && $block["components"]["input_combo_skin"] != "" ? $block["components"]["input_combo_skin"] : "default";
if ($this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.html.twig'))
$skinparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.html.twig';
else
$skinparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.html.twig';
if ($this->container->get('twig')->getLoader()->exists('content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.js.twig'))
$skinjsparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.' . $inputSkin . '.js.twig';
else
$skinjsparam = 'content-types/' . $contentType->getMachineName() . '/' . $contentType->getMachineName() . '.default.js.twig';
$content = $this->renderPageContent($pagenumber, $fields, $pageContent->getPageId(), $pageContent, null);
if ($contentType->getMachineName() == "forms") {
$form = $this->createForm(StdDynamicForm::class);
$fields = $pageContent->getContent();
$fieldsvariables = $this->prepareVariables($pageContent);
$rulesAndMessages = $this->getRulesAndMessagesForm($fields["fields"]);
$payload = array_merge([
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'blockscontent' => $content["html"],
'blockscontentjs' => $content["js"],
'form' => $form->createView(),
'messages' => $rulesAndMessages["messages"],
'rules' => $rulesAndMessages["rules"],
], $fieldsvariables);
} else {
$payload = array_merge([
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array()),
'blockscontent' => $content["html"],
'blockscontentjs' => $content["js"],
], $fields);
}
if ($this->container->get('twig')->getLoader()->exists($skinparam))
$result .= $this->renderView($skinparam, $payload);
if ($this->container->get('twig')->getLoader()->exists($skinjsparam))
$resultjs .= $this->renderView($skinjsparam, $payload);
} elseif (isset($stdsettings["isFormDomain"]) && $stdsettings["isFormDomain"]) {
//get the domain values for the selected domain
if ($block["components"]["form_select_domain"]) {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $block["components"]["form_select_domain"]]);
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'values' => $domainvalues
]);
} elseif (isset($stdsettings["isFormStatus"]) && $stdsettings["isFormStatus"]) {
//get the domain values for the selected domain
$domainvalues = [];
$domainobj = $this->entityManager->getRepository(StdDomains::class)->findOneBy(["machineName" => "form_status"]);
if ($domainobj) {
if ($block["components"]["form_select_default"] != "") {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id"), "machineName" => $block["components"]["form_select_default"]]);
} else {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $domainobj->getId("id")]);
}
}
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'values' => $domainvalues
]);
} else {
$payload = array_merge($variables, [
'settings' => $block["settings"],
'fields' => $block["components"],
'repeatable' => ($block["repeatable"] ? $blocksservice->filterPublishedRepeatables($block["repeatable"]) : array())
]);
}
if (!empty($ajaxCall) && array_key_exists("isAjax", false))
$payload = array_merge($payload, ["isajax" => true]);
$skin = "default";
if (!empty($pageskin)) {
$skin = $pageskin;
if ($this->container->get('twig')->getLoader()->exists($skin)) {
$result .= $this->renderView($skin, $payload);
}
} else {
if ($block["skin"] != "")
$skin = $block["skin"];
if ($this->container->get('twig')->getLoader()->exists("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".html.twig")) {
$result .= $this->renderView("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".html.twig", $payload);
}
if ($this->container->get('twig')->getLoader()->exists("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".js.twig")) {
$resultjs .= $this->renderView("blocks/" . $block["block"] . "/" . $block["block"] . "." . $skin . ".js.twig", $payload);
}
}
}
}
}
if (!empty($ajaxCall) && array_key_exists("isAjax", false)) {
if ($payload) {
return array("html" => $result, "js" => $resultjs, "payload" => $payload, "variables" => $variables);
} else {
return array("html" => $result, "js" => $resultjs, "payload" => array(), "variables" => $variables);
}
} else {
return array("html" => $result, "js" => $resultjs, "variables" => $variables);
}
}
private function prepareVariables(StdPagesContent $pageContent, $preview = array()): array
{
$variables = $pageContent->getContent();
unset($variables["fields"]);
$variables["title"] = $pageContent->getTitle();
$variables["pageid"] = $pageContent->getPageId()->getId();
$variables["contenttype"] = $pageContent->getPageId()->getContentType()->getMachineName();
$variables["url"] = $pageContent->getUrl();
$variables["metatitle"] = $pageContent->getMetaTitle();
$variables["metakeywords"] = $pageContent->getMetaKeywords();
$variables["metadescription"] = $pageContent->getMetaDescription();
$variables["languagecode"] = $pageContent->getLanguageCode();
$variables["ogtitle"] = $pageContent->getOgTitle();
$variables["ogimage"] = $pageContent->getOgImage();
$variables["ogdescription"] = $pageContent->getOgDescription();
$variables["ogurl"] = $pageContent->getOgUrl();
$variables["scriptshead"] = $pageContent->getScriptsHead();
$variables["scriptsbody"] = $pageContent->getScriptsBody();
$variables["scriptsfooter"] = $pageContent->getScriptsFooter();
$variables["page"] = $pageContent->getPageId();
if ($this->stdTrackingService->isPreciseTrackingEnabled()) {
$allowedPreciseLocation = $this->stdTrackingService
->getRecentPreciseLocationOfIp($this->request->getClientIp(), false);
$addTrackingPreciseJs = false;
$useGeoMapTracking = $this->stdTrackingService->isUseGeoMapForTracking();
$useApiTracking = $this->stdTrackingService->isUseApiForTracking();
if ($allowedPreciseLocation === null) {
$addTrackingPreciseJs = true;
}
$variables["scripts_tracking_precise"] = $addTrackingPreciseJs;
$variables["use_geo_map_tracking"] = $useGeoMapTracking;
$variables["use_api_tracking"] = $useApiTracking;
}
//get page attributes
if (empty($preview)) {
$allPagesAttributesValues = $this->entityManager->getRepository(StdPagesAttributesValues::class)->getPageAttributes($pageContent->getPageId());
} elseif (isset($preview['dataForm']['pages_attributes'])) {
foreach ($preview['dataForm']['pages_attributes'] as $key => $pagesattributes) {
$parts = explode('|||', $key);
$allPagesAttributesValues[] = $this->entityManager->getRepository(StdAttributes::class)->findOneBy(['machineName' => $parts[1]]);;
$allPagesAttributesValues[] = $this->entityManager->getRepository(StdAttributesValues::class)->findOneBy(['attributeMachineName' => $parts[1]]);
}
} else {
$allPagesAttributesValues = [];
}
$attributesarr = [];
foreach ($allPagesAttributesValues as $entity) {
if ($entity instanceof StdAttributes) {
$attributesarr[$entity->getMachineName()]["attribute"] = $entity;
}
if ($entity instanceof StdAttributesValues) {
$attributesarr[$entity->getAttribute()->getMachineName()]["values"][$entity->getValue()] = $entity;
}
}
$variables["pageattributes"] = $attributesarr;
$variables["isTop10"] = false;
return $variables;
}
private function getRulesAndMessagesForm(array $fields)
{
$messages = [];
$rules = [];
foreach ($fields as $field) {
$name = "";
if (isset($field["components"]["form_input_name"])) {
$name = $field["components"]["form_input_name"];
}
if ($name == "") {
continue;
}
if ($field["block"] == "form_checkbox" && isset($field["repeatable"]) && count($field["repeatable"]) > 1) {
$name .= "[]";
}
foreach ($field["settings"] as $key => $value) {
if (Functions::startsWith($key, "setting") || Functions::startsWith($key, "separator")) {
continue;
}
$keyArray = explode("_", $key);
$rule = $keyArray[1];
if ($value === "1") {
$value = true;
} else if ($value === "0" || $value === "" || !$value) {
$value = false;
}
$message = "";
if (isset($field["components"]["form_input_" . $keyArray[1] . "_label"]))
$message = $field["components"]["form_input_" . $keyArray[1] . "_label"];
if ($field["block"] == "form_checkbox" && $rule == "required") {
$rules[$name]["required"] = $value;
} else {
$rules[$name][$rule] = $value;
}
if ($message != "") {
$messages[$name][$rule] = $message;
}
}
}
return array("rules" => $rules, "messages" => $messages);
}
#[Route(path: '{_locale}/listPagesJson/{contentTypeToList}', name: 'list_pages_json')]
public function listPagesJson($contentTypeToList): Response
{
//TO DO
//receber o order (opcional)
//receber o relation_id /categoria (opcional)
//receber o paginate (opcional), se vier preenchido deve vir paginate=1
//receber o page (obrigatório se vier o paginate)
//receber o limit (obrigatório se vier o paginate)
//Acrescentar mais campos na resposta json?
$now = new \DateTime();
$contentType = $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(["machineName" => $contentTypeToList]);
if ($contentType) {
//categoria associada ao content type
$category = $this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['machineName' => $contentType->getMachineNameCategories()]);
$pageController = new StdPagesController($this->translator, $this->entityManager, $this->dispatcher);
$arrAttr = array();
// Verify filter
$dataForm = $this->request->request->all();
if ($dataForm) {
foreach ($dataForm as $search => $dataFilter) {
if (strpos($search, "ilter_")) {
$dataExplode = explode("filter_", $search);
$attributeMachineName = $dataExplode[1];
$arrAttr[$attributeMachineName] = $dataFilter;
}
}
}
// Format attributes
$attributesReturn = [];
$contentTypesAttr = $this->entityManager->getRepository(StdContentTypesAttributes::class)->findBy(["contentTypeMachineName" => $contentType->getMachineName()]);
foreach ($contentTypesAttr as $ctt) {
$attributes = $this->entityManager->getRepository(StdAttributes::class)->findBy(["machineName" => $ctt->getAttributeMachineName()]);
foreach ($attributes as $attr) {
$attrValues = $this->entityManager->getRepository(StdAttributesValues::class)->findBy(["attributeMachineName" => $attr->getMachineName()]);
foreach ($attrValues as $val) {
$attributesReturn[] = array(
"attributeMachineName" => $val->getAttributeMachineName(),
"label" => $val->getLabel(),
"value" => $val->getValue(),
"image" => $val->getImage(),
"order" => $val->getOrderValue()
);
}
}
}
usort($attributesReturn, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
$pages = $this->entityManager->getRepository(StdPages::class)->searchContent(array(
"search" => (isset($dataForm["search"]) ? $dataForm["search"] : "")
, "contentType" => $contentType->getId()
, "ajaxFilter" => sizeof($arrAttr) > 0 ? array("arrAttr" => $arrAttr) : []
));
$returnArr = [];
$categories = [];
$total = $pages["total"];
$index = 0;
foreach ($pages["stdPages"] as $page) {
$pageContent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $page["id"], "languageCode" => $this->locale]);
$attrValues = [];
if ($pageContent) {
$pageAttributes = $this->entityManager->getRepository(StdPagesAttributesValues::class)->findBy(["pageId" => $page["id"]]);
if ($pageAttributes) {
foreach ($pageAttributes as $pa) {
$attrValues[] = $this->entityManager->getRepository(StdAttributesValues::class)->findOneBy([
"attributeMachineName" => $pa->getAttributeMachineName()
, "value" => $pa->getValue()]);
}
}
$pageObj = $pageContent->getPageId();
$publishDate = null;
$expireDate = null;
if ($pageObj->getPublishDate())
$publishDate = new DateTime($pageObj->getPublishDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
if ($pageObj->getExpireDate())
$expireDate = new DateTime($pageObj->getExpireDate()->format('Y-m-d H:i:s'), new DateTimeZone('Europe/Lisbon'));
if ($pageObj->getIsActive() && ((is_null($pageObj->getPublishDate()) || $now >= $publishDate) && (is_null($pageObj->getExpireDate()) || $now <= $expireDate))) {
$pageArray = array(
"id" => $pageContent->getPageId()->getId()
, "title" => $pageContent->getPageId()->getName()
);
$contentArray = [];
foreach ($pageContent->getContent() as $key => $content) {
$contentArray[$key] = $content;
}
//ir buscar categorias associadas ao conteudo
$categoriesOfPage = [];
if ($category) {
$pagesRelations = $pageController->getRelations($category->getMachineName(), $this->entityManager, $pageObj, true);
//estas são as categorias associadas ao content type
if ($pagesRelations && count($categories) == 0) {
foreach ($pagesRelations["content"] as $pr) {
$categories[] = array("id" => $pr["value"], "title" => $pr["title"]);
}
}
if ($pagesRelations["values"] != "") {
$relationscats = explode(",", $pagesRelations["values"]);
foreach ($relationscats as $relcats) {
$pagepage = $this->entityManager->getRepository(StdPagesPages::class)->findOneBy(array("id" => $relcats));
if ($pagepage && $pagepage->getContentType()->getId() == $category->getId()) {
$categoriesOfPage[] = array("id" => $pagepage->getPageId()->getId(), "title" => $pagepage->getPageId()->getName());
}
}
}
}
$returnArr[] = array(
"canonicalUrl" => $pageContent->getCanonicalUrl()
, "url" => $pageContent->getUrl()
, "title" => $pageContent->getTitle()
, "pageId" => $pageArray
, "content" => $contentArray
, "pageAttributes" => $attrValues
, "categories" => $categoriesOfPage
, "publishDate" => ($pageObj->getPublishDate() ? $pageObj->getPublishDate()->format('Y-m-d H:i:s') : null)
);
}
}
}
$returArray = [];
$returArray["pages"] = $returnArr;
$returArray["attributes"] = $attributesReturn;
// $returArray["categories"]=array_unique($categories,SORT_REGULAR);
$returArray["categories"] = $categories;
return new Response(\json_encode($returArray));
}
return new Response(\json_encode(["sucess" => false]));
}
#[Route(path: '/subscribe-egoi', name: 'subscribe-egoi')]
public function subscribeEgoi(): JsonResponse
{
//falta a lista e api key no config
if ($this->request->isXmlHttpRequest()) {
$emailsubscribed = "";
$egoilist = "";
$egoiapikey = "";
if ($this->request->request->get('email') && $this->request->request->get('email') != "") {
$emailsubscribed = $this->request->request->get('email');
} elseif ($this->request->request->get('EMAIL') && $this->request->request->get('EMAIL') != "") {
$emailsubscribed = $this->request->request->get('EMAIL');
}
if ($this->request->request->get('egoilist') && $this->request->request->get('egoilist') != "") {
$egoilist = $this->request->request->get('egoilist');
} else {
$egoilist = getenv("EGOI_LIST_ID");
}
$egoiapikey = Functions::getConfig("egoiapikey", "", $this->entityManager);
if ($egoiapikey == "") {
$egoiapikey = getenv("EGOI_API_KEY");
}
if ($emailsubscribed != "" && $egoilist != "" && $egoiapikey != "") {
try {
$client = new \GuzzleHttp\Client(['base_uri' => 'https://api.egoiapp.com/']);
$response = $client->request(
'POST'
, '/lists/' . $egoilist . '/contacts'
, [
'body' => \GuzzleHttp\Utils::jsonEncode(["base" => ["email" => $emailsubscribed, "language" => $this->locale]])
, 'headers' => [
"Apikey: " . $egoiapikey,
"Content-Type: application/json"
]
]
);
$code = $response->getStatusCode();
if ($code == 201) {
return new JsonResponse(["success" => true]);
} else {
return new JsonResponse(["success" => false, "errorMsg" => "Erro ao subscrever"]);
}
} catch (\GuzzleHttp\Exception\RequestException $e) {
$guzzleResult = $e->getResponse();
return new JsonResponse(["success" => false, "errorMsg" => "Erro ao subscrever: " . $guzzleResult->getReasonPhrase()]);
}
} else {
return new JsonResponse(["success" => false, "errorMsg" => "Erro ao subscrever"]);
}
} else {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
}
#[Route(path: '{path}', name: 'friendly_url', requirements: ['path' => '.+'], priority: -100)]
public function showByFriendlyUrl(string $path, string $skin = "default", $thrownotfound = true): Response
{
$repLang = $this->entityManager->getRepository(StdLanguages::class);
if (!$repLang->findOneBy(['languageCode' => $this->request->getLocale(), 'isActive' => true, 'isPublic' => true])) {
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
//search redirect rules
$rule = $this->redirectsCache->get("std_redirects_" . md5($path), function (ItemInterface $item) use ($path) {
$testRule = $this->entityManager->getRepository(StdRedirects::class)->getOneRule($path);
return $testRule;
}, $_ENV["STD_REDIRECTS_CACHE_BETA"]);
if ($rule) {
return $this->redirect(preg_replace("#" . $rule->getUrlOrigin() . "#", $rule->getUrlDestination(), $path), $rule->getCode());
}
//search pages
$rep = $this->entityManager->getRepository(StdFriendlyUrl::class);
$url = $rep->findOneByUrl("/" . $path);
if ($url) {
$relationTree = $url->getRelationTree();
if (!$relationTree) {
$url2 = $rep->getRowByPageAndRelationTreeNotNull($url->getPageId()->getId(), $this->locale);
if ($url2)
$relationTree = $url2->getRelationTree();
}
if ($url->getPageId()) {
return $this->showContentById($url, $skin, true, false, $relationTree);
}
} else {
if ($thrownotfound)
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
else
return new Response("");
}
}
private function verifyPermission($page)
{
if (!$page) return;
//check if page contenttype is forms and validate the form permissions
if ($page->getContentType()->getMachineName() == "forms") {
$lang = $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $this->request->getLocale(), "isActive" => true]);
$form_content = $page->getLocalizedContents($lang)->getContent();
$form_permissions = Functions::checkFormPermissions($this->security, $this->entityManager, $form_content);
if ($this->request->query->get("edit") && (!$form_permissions["u"] || $form_content["form_allow_edit"] != 1)) {
throw $this->createAccessDeniedException('ACCESS DENIED!');
}
}
if (!count(($pageRoles = $page->getRoles()))) return true; // the page has no roles associated, so everyone can access
if (!($user = $this->security->getUser())) {
return false;
}
//if user is impersonating check with the original user
$token = $this->security->getToken();
if ($token instanceof SwitchUserToken) {
$user = $token->getOriginalToken()->getUser();
}
$roles = [];
foreach ($pageRoles as $role) {
$roles[] = $role->getName();
}
if (!$this->stdsecurity->userIsGranted($user, $roles)) {
return false;
}
return true;
}
public function RenderPages($pages, $skin, $renderblocks = false): Response
{
$strContent = "";
if (is_array($pages) && sizeof($pages) > 0) {
foreach ($pages as $pageId) {
$strContent .= $this->RenderPage((int)$pageId, $skin, $renderblocks);
}
return new Response($strContent);
}
return new Response();
}
#[Route(path: '{_locale}/preview/{contentType}/{id}', name: 'preview_page_content_type')]
public function previewContentType(
string $contentType,
int $id,
string $_locale,
StdBlocksService $stdBlocksService,
Request $request
): Response
{
$contentTypeEntity = $this->entityManager
->getRepository(StdContentTypes::class)
->findOneBy(['machineName' => $contentType]);
if (!$contentTypeEntity) {
throw $this->createNotFoundException("Content type '$contentType' not found.");
}
$page = $this->entityManager
->getRepository(StdPages::class)
->find($id);
if (!$page || $page->getContentType()?->getId() !== $contentTypeEntity->getId()) {
throw $this->createNotFoundException("Page with ID $id not found for content type '$contentType'.");
}
$friendlyUrl = $this->entityManager
->getRepository(StdFriendlyUrl::class)
->findOneBy([
'pageId' => $page,
'languageCode' => $_locale,
'isCanonical' => true,
]);
if (!$friendlyUrl) {
throw $this->createNotFoundException("No canonical URL found for page ID $id in locale $_locale.");
}
$contentRepo = $this->entityManager->getRepository(StdPagesContent::class);
$pageContent = $contentRepo->findOneBy([
'pageId' => $page,
'languageCode' => $_locale,
]);
if (!$pageContent) {
throw $this->createNotFoundException("Content not found for page ID $id in locale $_locale.");
}
$fields = $stdBlocksService->formatArrayFields($request, $pageContent->getContent());
$content = [
'url' => $friendlyUrl,
'pageContent' => $pageContent,
'fields' => $fields,
'dataForm' => [
'new' => 0
]
];
$relationTree = $friendlyUrl->getRelationTree() ?? [];
return $this->showContentById($content, 'default', true, false, $relationTree, "", "", true, true);
}
#[Route(path: '{_locale}/preview', name: 'preview_page_content')]
public function preview(Request $request, StdBlocksService $stdBlocksService, $skin = 'default'): \Symfony\Component\HttpFoundation\Response
{
$dataForm = $request->request->all();
$dataForm = AdminFunctions::processSubmittedBlockData($dataForm);
$arrFinal["page-content"] = array();
$var = "";
if (isset($dataForm["std_pages_form"]) && $dataForm["std_pages_form"]) {
$dynamicContent = $dataForm["std_pages_form"];
foreach ($dynamicContent as $k => $value) {
if (strpos($k, "age-content-")) {
if ($value) {
$var = $var ? $var . "," : '{ "page-content": [';
$dataExplode = explode("-_-", $k);
$valueN = json_encode($value);
$var .= '{"' . str_replace('-_-', '": {"', str_replace(array("ajax-page-content-_-", "page-content-_-"), "", $k)) . '" : ' . $valueN;
for ($i = 1; $i < count($dataExplode); $i++) {
$var .= "}";
}
}
}
}
if ($var) {
$var .= "]}";
$arrFinal = json_decode(str_replace(array("\r", "\n"), "", $var), true);
}
} else {
throw $this->createNotFoundException('Preview not found, please reopen preview.');
}
// Format array fields for preview
$stdPages = new StdPages();
$arr = $stdBlocksService->formatArrayFields($request, $arrFinal["page-content"]);
$fields = $arr;
//search pages
$rep = $this->entityManager->getRepository(StdFriendlyUrl::class);
$url = $rep->findOneByUrl($dataForm['std_pages_form']['canonical_url']);
$dataForm['new'] = 0;
if (!$url) {
$dataForm['new'] = 1;
}
if (!$dataForm['new']) {
$this->locale = $this->locale;
$relationTree = $url->getRelationTree();
if (!$relationTree) {
$url2 = $rep->getRowByPageAndRelationTreeNotNull($url->getPageId()->getId(), $this->locale);
if ($url2)
$relationTree = $url2->getRelationTree();
}
} else {
$stdPage = $dataForm['std_pages_form'];
$url = new StdFriendlyUrl;
$url->setUrl($stdPage['canonical_url']);
$url->setLanguageCode($stdPage['languageCode']);
$url->setIsCanonical(true);
$pageId = new StdPages;
if ($stdPage['template_id'])
$pageId->setTemplateId($stdPage['template_id']);
if ($stdPage['layout'])
$pageId->setLayout($stdPage['layout']);
$pageId->setName($stdPage['title']);
$pageId->setContentType($this->entityManager->getRepository(StdContentTypes::class)->findOneBy(['id' => 6]));
$pageId->setcreatedBy($this->getUser());
if (array_key_exists("postdaterange", $dataForm))
$postdaterange = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $dataForm['postdaterange']);
else
$postdaterange = null;
if (array_key_exists("expiredaterange", $dataForm))
$expiredaterange = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $dataForm['expiredaterange']);
else
$expiredaterange = null;
$pageId->setCreatedDate(new \DateTime());
$pageId->setUpdatedBy($this->getUser());
$pageId->setUpdatedDate(new \DateTime());
$pageId->setPublishDate($postdaterange ? new \DateTime(date('Y-m-d H:i:s', strtotime($postdaterange))) : new \DateTime());
$pageId->setExpireDate($expiredaterange ? (new \DateTime(date('Y-m-d H:i:s', strtotime($expiredaterange)))) : null);
$url->setPageId($pageId);
$relationTree = [];
}
$content['url'] = $url;
$content['dataForm'] = $dataForm;
$content['fields'] = $fields;
$dataForm = $content["dataForm"]["std_pages_form"];
$pagecontent = new stdPagesContent;
$pagecontent->setPageId($content["url"]->getPageId());
$pagecontent->setTitle($dataForm["title"]);
$pagecontent->setUrl($dataForm["url"]);
$pagecontent->setMetaKeywords($dataForm["meta_keywords"]);
$pagecontent->setMetaTitle($dataForm["meta_title"]);
$pagecontent->setMetaDescription($dataForm["meta_description"]);
$pagecontent->setOgTitle($dataForm["og_title"]);
$pagecontent->setOgImage($dataForm["og_image"]);
$pagecontent->setOgDescription($dataForm["og_description"]);
$pagecontent->setOgUrl($dataForm["og_url"]);
$pagecontent->setCanonicalUrl($dataForm["canonical_url"]);
$pagecontent->setScriptsHead($dataForm["script_head"]);
$pagecontent->setScriptsBody($dataForm["script_body"]);
$pagecontent->setScriptsFooter($dataForm["script_footer"]);
$pagecontent->setContent($content["fields"]);
$pagecontent->setUpdatedDate(new \DateTime());
$content["pageContent"] = $pagecontent;
return $this->showContentById($content, $skin, true, false, $relationTree);
}
private function findBreadCrumbs($actual, $relationTree, $entityManager, $arr = array())
{
$preview['new'] = 0;
if ($actual && !($actual instanceof stdPages)) {
$preview['new'] = 1;
$preview['data'] = $actual;
$actual = $actual['url']->getPageId();
}
$rep = $entityManager->getRepository(StdFriendlyUrl::class);
$repPageContent = $entityManager->getRepository(StdPagesContent::class);
if ($relationTree && $relationTree["relation_id"]) {
$page = $rep->findOneBy(["relationId" => $relationTree["relation_id"], "languageCode" => $this->locale]);
if (!$page) {
$page = $rep->findOneBy(["url" => "/" . $this->locale . $relationTree["url"]]);
if (!$page) {
return [];
}
}
$pageContent = $repPageContent->findOneBy(["pageId" => $page->getPageId()->getId(), "languageCode" => $this->locale]);
$arrRound = array();
$arrRound["url"] = $relationTree["url"];
$arrRound["friendlyUrlId"] = $page->getId();
$arrRound["friendlyUrl"] = $page->getUrl();
$arrRound["pageId"] = $page->getPageId()->getId();
$arrRound["title"] = $pageContent->getTitle();
$arrRound["active"] = " ";
if (sizeof($pageContent->getContent()) == 0) {
$arrRound["dontshow"] = true;
} else {
$arrRound["dontshow"] = true;
foreach ($pageContent->getContent() as $k => $content) {
if ($content != "") {
$arrRound["dontshow"] = false;
break;
}
}
}
array_push($arr, $arrRound);
if (array_key_exists("children", $relationTree)) {
$arr = $this->findBreadCrumbs(false, $relationTree["children"], $entityManager, $arr);
}
}
if ($actual) {
if (!$preview['new']) {
$pageContent = $repPageContent->findOneBy(["pageId" => $actual->getId(), "languageCode" => $this->locale]);
$arrFinal["title"] = $pageContent->getTitle();
} else {
$pageContent = $preview['data'];
$arrFinal["title"] = $pageContent['dataForm']['std_pages_form']['title'];
}
$arrFinal["url"] = "#";
$arrFinal["friendlyUrlId"] = null;
$arrFinal["friendlyUrl"] = "#";
$arrFinal["pageId"] = null;
$arrFinal["active"] = "active";
if (!$preview['new'] && sizeof($pageContent->getContent()) == 0)
$arrFinal["dontshow"] = true;
elseif ($preview['new'] && sizeof($pageContent['pageContent']->getContent()) == 0) {
} else
$arrFinal["dontshow"] = false;
array_push($arr, $arrFinal);
}
return $arr;
}
#[Route(path: '{_locale}/ics/generate', name: 'ics_generate', methods: ['GET'])]
public function icsGenerate(): \Symfony\Component\HttpFoundation\Response
{
$data = $this->request->query->all();
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"] != "") {
$startDate = date('Y-m-d h:i', strtotime($data["startdate"]));
$endDate = date('Y-m-d h:i', strtotime($data["enddate"]));
$provider = new \BOMO\IcalBundle\Provider\IcsProvider();
$tz = $provider->createTimezone();
$tz
->setTzid('Europe/London')
->setXProp('X-LIC-LOCATION', $tz->getTzid());
$cal = $provider->createCalendar($tz);
$event = $cal->newEvent();
$event
->setStartDate(new \DateTime($startDate))
->setEndDate(new \DateTime($endDate))
->setName($data["name"])
->setDescription($data["description"]);
$calStr = $cal->returnCalendar();
return new Response(
$calStr,
\Symfony\Component\HttpFoundation\Response::HTTP_OK,
array(
'Content-Type' => 'text/calendar; charset=utf-8',
'Content-Disposition' => 'attachment; filename="calendar.ics"',
)
);
}
throw $this->createNotFoundException($this->request->getRequestUri() . ' does not exist');
}
#[Route(path: '{_locale}/handle-form/', name: 'ajax_handle_form', methods: ['POST'])]
public function ajaxHandleForm(EventDispatcherInterface $dispatcher): JsonResponse
{
$event = new StdFormsSubmitEvent($this->request, $this->formsDirectory);
$dispatcher->dispatch($event, StdFormsSubmitEvent::NAME);
return new JsonResponse($event->toArray());
}
private function addCookiesToResponse(Response $response, $cookies)
{
if (is_array($cookies)) {
foreach ($cookies as $cookie) {
($cookie instanceof Cookie) && $response->headers->setCookie($cookie);
}
}
}
private function generateUserCacheKey(Security $security): string
{
if (!is_null($security->getUser())
&& $security->getUser() instanceof StdWebUsers
&& is_array($security->getUser()->getRoles())
&& !empty(is_array($security->getUser()->getRoles()))) {
$cachekey = str_replace('ROLE_', '', implode("-", $security->getUser()->getRoles()));
$cachekey = md5($cachekey);
return '-' . $cachekey;
}
return '';
}
#[Route(path: '{_locale}/forms/list/datatable', name: 'ajax_form_list_datatable', methods: ['GET'])]
public function ajaxFormListDatatable(Request $request, $_locale): JsonResponse
{
if (!$request->isXmlHttpRequest()) {
throw $this->createNotFoundException('The page does not exist');
}
$dataForm = $request->query->all();
if ($dataForm) {
$lang = $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $_locale, "isActive" => true]);
//Columns that will appear on Datatable
if (array_key_exists("table_fields", $dataForm) && $dataForm["table_fields"] != "") {
$dataForm["table_fields"] = json_decode($dataForm["table_fields"]);
$columns = $dataForm["table_fields"];
}
//Search
$search = $dataForm["search"]["value"] ?? "";
//Order
$order = $dataForm["order"] ?? [];
$orderby = [];
if (count($order) > 0) {
foreach ($order as $ord) {
if ($ord["column"] != "")
$orderby[] = ["column" => $columns[$ord["column"]], "order" => $ord["dir"]];
}
}
//Apply Start/Limits to results
$start = $dataForm["start"];
$limit = $dataForm["length"];
//Machine name of the Form
$formPageMachineName = null;
if (array_key_exists("form_name", $dataForm)) {
$formPageMachineName = $dataForm["form_name"];
}
$user = null;
if ($dataForm["form_only_user"] === "1") {
$webUser = $this->security->getUser();
if ($webUser && $webUser instanceof StdWebUsers) {
$user = $webUser->getId();
}
}
//Get all forms submitted by machinename or user
$forms = $this->entityManager->getRepository(Forms::class)->findContentBySearchQuery($columns, $_locale, $orderby, $formPageMachineName, $user, $search, $start, $limit);
//Rows
$list = $rows = [];
$page = "";
$form_page = "";
$page_url = "";
$formDomainBlocks = [];
$permissions = ["c" => true, "r" => true, "u" => true, "d" => true];
foreach ($forms["results"] as $k => $form) {
if (!$form_page) {
$form_page = $this->entityManager->getRepository(StdPages::class)->findOneBy(["machineName" => $form["form"]->getFormName()]);
if ($form_page) {
$form_localized = $form_page->getLocalizedContents($lang);
$form_content = $form_localized->getContent();
//"Check if the Form contains form_domain blocks. If it does, we need to retrieve the Domain Value for each one."
if (array_key_exists("fields", $form_content)) {
foreach ($form_content["fields"] as $field) {
if ($field['block'] === 'form_domain' && $field["components"]["form_select_domain"] != "") {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $field["components"]["form_select_domain"]]);
$domainsarr = [];
foreach ($domainvalues as $domain) {
$domainsarr[$domain->getMachineName()] = $domain->getDescription();
}
$formDomainBlocks[$field["components"]["form_input_name"]] = $domainsarr;
}
}
}
$permissions = Functions::checkFormPermissions($this->security, $this->entityManager, $form_content);
$page_url = $form_localized->getCanonicalUrl();
}
}
if (!$page) {
$page = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $form["form_page_id"], "languageCode" => $_locale]);
if ($page) {
$page_url = $page->getCanonicalUrl();
}
}
$rows[$k] = array_intersect_key($form, array_flip($columns));
if (count($formDomainBlocks)) {
foreach ($formDomainBlocks as $domain => $domainBlock) {
if (array_key_exists($domain, $rows[$k])) {
$rows[$k][$domain] = $formDomainBlocks[$domain][$rows[$k][$domain]];
}
}
}
//If datatable has form sequential column, will merge the prefix and sufix with the sequential value
if (array_key_exists("form_sequential", $rows[$k])) {
$formdata = $form["form"]->getContent();
$form_seq_prefix = $form_seq_sufix = "";
if (array_key_exists("form_sequential_prefix", $formdata)) {
$form_seq_prefix = $formdata["form_sequential_prefix"];
}
if (array_key_exists("form_sequential_sufix", $formdata)) {
$form_seq_sufix = $formdata["form_sequential_sufix"];
}
$rows[$k]["form_sequential"] = $form_seq_prefix . "" . $rows[$k]["form_sequential"] . "" . $form_seq_sufix;
}
$actions_view = $this->renderView('blocks/submitted_forms_list/submitted_forms_list.actions.html.twig',
array(
'locale' => $_locale,
'form' => $form,
'form_content' => $form_content,
'page_url' => $page_url,
'permissions' => $permissions
)
);
$rows[$k] = array_merge($rows[$k], ['actions' => $actions_view]);
}
//Total
$list["total"] = $forms["total"];
}
//Results
$result = array(
'draw' => $dataForm["draw"],
'recordsTotal' => $list["total"],
'recordsFiltered' => $list["total"],
'permissions' => $permissions,
'data' => $rows
);
return new JsonResponse($result);
}
#[Route(path: '{_locale}/forms/view/{id}', name: 'form_generate_view')]
public function formGenerateView(Request $request, $id, $_locale): JsonResponse
{
$lang = $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $_locale, "isActive" => true]);
$form = $this->entityManager->getRepository(Forms::class)->findOneBy(["id" => $id]);
if ($form) {
$formdata = $form->getContent();
$page = $this->entityManager->getRepository(StdPages::class)->findOneBy(["machineName" => $form->getFormName()]);
$content = $page->getLocalizedContents($lang)->getContent();
//Check if the Form contains form_domain blocks. If it does, we need to retrieve the Domain Value for each one.
if (array_key_exists("fields", $content)) {
foreach ($content["fields"] as $field) {
if ($field['block'] === 'form_domain' && $field["components"]["form_select_domain"] != "") {
$domainvalues = $this->entityManager->getRepository(StdDomainsValues::class)->findBy(["domain" => $field["components"]["form_select_domain"]]);
$domainsarr = [];
foreach ($domainvalues as $domain) {
$domainsarr[$domain->getMachineName()] = $domain->getDescription();
}
$formDomainBlocks[$field["components"]["form_input_name"]] = $domainsarr;
}
}
}
if (count($formDomainBlocks)) {
foreach ($formDomainBlocks as $domain => $domainBlock) {
if (array_key_exists($domain, $formdata) && $formdata[$domain] != "") {
$formdata[$domain] = $formDomainBlocks[$domain][$formdata[$domain]];
}
}
}
if ($content) {
$form_permissions = Functions::checkFormPermissions($this->security, $this->entityManager, $content);
if ($form_permissions) {
if (!$form_permissions["r"]) {
throw $this->createNotFoundException('The page does not exist');
} else {
$html = $this->renderView('blocks/submitted_forms_list/form.view.html.twig', [
'content' => $content,
'formdata' => $formdata,
'request' => $request->request->all(),
'query' => $request->query->all(),
]);
return new JsonResponse($html);
}
}
}
}
throw $this->createNotFoundException('The page does not exist');
}
#[Route(path: '/{_locale}/forms/delete/{id}', name: 'form_delete')]
public function formDelete(int $id, $_locale): Response
{
$lang = $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $_locale, "isActive" => true]);
$form = $this->entityManager->getRepository(Forms::class)->findOneBy(["id" => $id]);
if ($form) {
$page = $this->entityManager->getRepository(StdPages::class)->findOneBy(["machineName" => $form->getFormName()]);
$page_localized = $page->getLocalizedContents($lang);
$content = $page_localized->getContent();
if ($content) {
$form_permissions = Functions::checkFormPermissions($this->security, $this->entityManager, $content);
if ($form_permissions) {
if ($form_permissions["d"]) {
$this->entityManager->remove($form);
$this->entityManager->flush();
// $this->addFlash('success', $this->translator->trans('deleted_successfully', [], 'studio'));
return $this->redirect($_SERVER["HTTP_REFERER"]);
} else {
throw $this->createAccessDeniedException('ACCESS DENIED!');
}
}
}
}
}
/**
* Refactored from RenderPages to allow a single page to be rendered without the fuss of walking through an array and concatenating the results
* @param int $pageId Page Id (field id from DB)
* @param skin $page
*/
public function RenderPage(int|StdPages $pageId, $skin, $renderblocks = false, bool $returnResponse = false): string|Response
{
$strContent = "";
$page = $pageId instanceof StdPages ?
$pageId :
$this->entityManager->getRepository(StdPages::class)->findOneBy(["id" => $pageId]);
if ($page) {
$pagecontent = $this->entityManager->getRepository(StdPagesContent::class)->findOneBy(["pageId" => $pageId, "languageCode" => $this->locale]);
if ($pagecontent) {
$response = $this->showContentById($page, $skin, true, true, array(), "", "", $renderblocks);
if ($response instanceof Response) {
$strContent = $response->getContent();
} else {
$strContent = $response;
}
}
}
return $returnResponse ? new Response($strContent) : $strContent;
}
function renderSnippet(?StdSnippets $stdSnippets = null, $pageId = null): Response
{
$strContent = "";
if ($stdSnippets) {
$language = $this->entityManager->getRepository(StdLanguages::class)->findOneBy(["languageCode" => $this->locale]);
$stdSnippetsContent = $stdSnippets->getLocalizedContents($language);
if ($stdSnippetsContent) {
if($pageId != null) {
$pageId = $this->entityManager->getRepository(StdPages::class)->findOneBy(["id" => $pageId]);
}
$response = $this->renderPageContent(0, [], $pageId, $stdSnippetsContent, null);
if ($response instanceof Response) {
$strContent = $response->getContent();
} else {
$strContent = $response;
}
}
}
return new Response(isset($strContent["html"]) ? $strContent["html"] : $strContent);
}
}