Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate event URLs using the content URL generator #6607

Merged
merged 9 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions calendar-bundle/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ services:
arguments:
- '@contao.framework'
- '@security.helper'
- '@contao.routing.content_url_generator'
tags:
- kernel.event_listener

Expand All @@ -66,6 +67,11 @@ services:
tags:
- { name: contao.picker_provider, priority: 96 }

contao_calendar.routing.calendar_events_resolver:
class: Contao\CalendarBundle\Routing\CalendarEventsResolver
arguments:
- '@contao.framework'

contao_calendar.security.calendar_access_voter:
class: Contao\CalendarBundle\Security\Voter\CalendarAccessVoter
arguments:
Expand Down
40 changes: 8 additions & 32 deletions calendar-bundle/contao/classes/Calendar.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Routing\Exception\ExceptionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
* Provide methods regarding calendars.
Expand Down Expand Up @@ -372,40 +374,14 @@ private function addEvent($objEvent, $intStart, $intEnd, $objParent, $isRepeated

// Add title and link
$title .= ' ' . $objEvent->title;
$link = '';

switch ($objEvent->source)
try
{
case 'external':
$url = $objEvent->url;

if (Validator::isRelativeUrl($url))
{
$url = Environment::get('path') . '/' . $url;
}

$link = $url;
break;

case 'internal':
if (($objTarget = $objEvent->getRelated('jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
$link = $objTarget->getAbsoluteUrl();
}
break;

case 'article':
if (($objArticle = ArticleModel::findByPk($objEvent->articleId)) instanceof ArticleModel && ($objPid = $objArticle->getRelated('pid')) instanceof PageModel)
{
/** @var PageModel $objPid */
$link = StringUtil::ampersand($objPid->getAbsoluteUrl('/articles/' . ($objArticle->alias ?: $objArticle->id)));
}
break;

default:
$link = $objParent->getAbsoluteUrl('/' . ($objEvent->alias ?: $objEvent->id));
break;
$link = System::getContainer()->get('contao.routing.content_url_generator')->generate($objEvent, array(), UrlGeneratorInterface::ABSOLUTE_URL);
}
catch (ExceptionInterface)
{
$link = '';
}

// Store the whole row (see #5085)
Expand Down
79 changes: 8 additions & 71 deletions calendar-bundle/contao/classes/Events.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
namespace Contao;

use Contao\CoreBundle\Security\ContaoCorePermissions;
use Symfony\Component\Routing\Exception\ExceptionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
* Provide methods to get all events of a certain period from the database.
Expand Down Expand Up @@ -43,12 +45,6 @@ abstract class Events extends Module
*/
protected $arrEvents = array();

/**
* URL cache array
* @var array
*/
private static $arrUrlCache = array();

/**
* Sort out protected archives
*
Expand Down Expand Up @@ -411,77 +407,18 @@ protected function addEvent($objEvents, $intStart, $intEnd, $intBegin, $intLimit
*/
public static function generateEventUrl($objEvent, $blnAbsolute=false)
{
$strCacheKey = 'id_' . $objEvent->id . ($blnAbsolute ? '_absolute' : '');
trigger_deprecation('contao/core-bundle', '5.3', __METHOD__ . ' is deprecated, use the content URL generator instead.');

// Load the URL from cache
if (isset(self::$arrUrlCache[$strCacheKey]))
try
{
return self::$arrUrlCache[$strCacheKey];
$url = System::getContainer()->get('contao.routing.content_url_generator')->generate($objEvent, array(), $blnAbsolute ? UrlGeneratorInterface::ABSOLUTE_URL : UrlGeneratorInterface::ABSOLUTE_PATH);
}

// Initialize the cache
self::$arrUrlCache[$strCacheKey] = null;

switch ($objEvent->source)
catch (ExceptionInterface)
{
// Link to an external page
case 'external':
if (str_starts_with($objEvent->url, 'mailto:'))
{
self::$arrUrlCache[$strCacheKey] = StringUtil::encodeEmail($objEvent->url);
}
else
{
$url = $objEvent->url;

if (Validator::isRelativeUrl($url))
{
$url = Environment::get('path') . '/' . $url;
}

self::$arrUrlCache[$strCacheKey] = StringUtil::ampersand($url);
}
break;

// Link to an internal page
case 'internal':
if (($objTarget = $objEvent->getRelated('jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
self::$arrUrlCache[$strCacheKey] = StringUtil::ampersand($blnAbsolute ? $objTarget->getAbsoluteUrl() : $objTarget->getFrontendUrl());
}
break;

// Link to an article
case 'article':
if (($objArticle = ArticleModel::findByPk($objEvent->articleId)) instanceof ArticleModel && ($objPid = $objArticle->getRelated('pid')) instanceof PageModel)
{
$params = '/articles/' . ($objArticle->alias ?: $objArticle->id);

/** @var PageModel $objPid */
self::$arrUrlCache[$strCacheKey] = StringUtil::ampersand($blnAbsolute ? $objPid->getAbsoluteUrl($params) : $objPid->getFrontendUrl($params));
}
break;
}

// Link to the default page
if (self::$arrUrlCache[$strCacheKey] === null)
{
$objPage = PageModel::findByPk($objEvent->getRelated('pid')->jumpTo);

if (!$objPage instanceof PageModel)
{
self::$arrUrlCache[$strCacheKey] = StringUtil::ampersand(Environment::get('requestUri'));
}
else
{
$params = '/' . ($objEvent->alias ?: $objEvent->id);

self::$arrUrlCache[$strCacheKey] = StringUtil::ampersand($blnAbsolute ? $objPage->getAbsoluteUrl($params) : $objPage->getFrontendUrl($params));
}
return StringUtil::ampersand(Environment::get('requestUri'));
}

return self::$arrUrlCache[$strCacheKey];
return $url;
}

/**
Expand Down
11 changes: 9 additions & 2 deletions calendar-bundle/contao/modules/ModuleCalendar.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace Contao;

use Contao\CoreBundle\Exception\PageNotFoundException;
use Symfony\Component\Routing\Exception\ExceptionInterface;

/**
* Front end module "calendar".
Expand Down Expand Up @@ -74,8 +75,14 @@ public function generate()

if (($objTarget = $this->objModel->getRelated('jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
$this->strLink = $objTarget->getFrontendUrl();
try
{
$this->strLink = System::getContainer()->get('contao.routing.content_url_generator')->generate($objTarget);
}
catch (ExceptionInterface)
{
// Ignore if target URL cannot be generated and use the current request URL
}
}

// Tag the calendars (see #2137)
Expand Down
29 changes: 4 additions & 25 deletions calendar-bundle/contao/modules/ModuleEventReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Contao\CoreBundle\Exception\RedirectResponseException;
use Contao\CoreBundle\Routing\ResponseContext\HtmlHeadBag\HtmlHeadBag;
use Contao\CoreBundle\Util\UrlUtil;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
* Front end module "event reader".
Expand Down Expand Up @@ -81,9 +82,9 @@ protected function compile()

$this->Template->event = '';

if ($this->overviewPage)
if ($this->overviewPage && ($overviewPage = PageModel::findById($this->overviewPage)))
{
$this->Template->referer = PageModel::findById($this->overviewPage)->getFrontendUrl();
$this->Template->referer = System::getContainer()->get('contao.routing.content_url_generator')->generate($overviewPage);
$this->Template->back = $this->customLabel ?: $GLOBALS['TL_LANG']['MSC']['eventOverview'];
}

Expand All @@ -100,31 +101,9 @@ protected function compile()
switch ($objEvent->source)
{
case 'internal':
if ($page = PageModel::findPublishedById($objEvent->jumpTo))
{
throw new RedirectResponseException($page->getAbsoluteUrl(), 301);
}

throw new InternalServerErrorException('Invalid "jumpTo" value or target page not public');

case 'article':
if (($article = ArticleModel::findByPk($objEvent->articleId)) && ($page = PageModel::findPublishedById($article->pid)))
{
throw new RedirectResponseException($page->getAbsoluteUrl('/articles/' . ($article->alias ?: $article->id)), 301);
}

throw new InternalServerErrorException('Invalid "articleId" value or target page not public');

case 'external':
if ($objEvent->url)
{
$url = System::getContainer()->get('contao.insert_tag.parser')->replaceInline($objEvent->url);
$url = UrlUtil::makeAbsolute($url, Environment::get('base'));

throw new RedirectResponseException($url, 301);
}

throw new InternalServerErrorException('Empty target URL');
throw new RedirectResponseException(System::getContainer()->get('contao.routing.content_url_generator')->generate($objEvent, array(), UrlGeneratorInterface::ABSOLUTE_URL), 301);
}

// Overwrite the page metadata (see #2853, #4955 and #87)
Expand Down
9 changes: 8 additions & 1 deletion calendar-bundle/src/EventListener/SitemapListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,20 @@
use Contao\CalendarModel;
use Contao\CoreBundle\Event\SitemapEvent;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\CoreBundle\Routing\ContentUrlGenerator;
use Contao\CoreBundle\Security\ContaoCorePermissions;
use Contao\Database;
use Contao\PageModel;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Routing\Exception\ExceptionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SitemapListener
{
public function __construct(
private readonly ContaoFramework $framework,
private readonly Security $security,
private readonly ContentUrlGenerator $urlGenerator,
) {
}

Expand Down Expand Up @@ -103,7 +107,10 @@ public function __invoke(SitemapEvent $event): void
continue;
}

$arrPages[] = $objParent->getAbsoluteUrl('/'.($objEvent->alias ?: $objEvent->id));
try {
$arrPages[] = $this->urlGenerator->generate($objEvent, [], UrlGeneratorInterface::ABSOLUTE_URL);
} catch (ExceptionInterface) {
}
}
}

Expand Down
68 changes: 68 additions & 0 deletions calendar-bundle/src/Routing/CalendarEventsResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/

namespace Contao\CalendarBundle\Routing;

use Contao\ArticleModel;
use Contao\CalendarEventsModel;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\CoreBundle\Routing\Content\ContentUrlResolverInterface;
use Contao\CoreBundle\Routing\Content\ContentUrlResult;
use Contao\PageModel;

class CalendarEventsResolver implements ContentUrlResolverInterface
{
public function __construct(private readonly ContaoFramework $framework)
{
}

public function resolve(object $content): ContentUrlResult|null
{
if (!$content instanceof CalendarEventsModel) {
return null;
}

switch ($content->source) {
// Link to an external page
case 'external':
return ContentUrlResult::url($content->url);

// Link to an internal page
case 'internal':
$pageAdapter = $this->framework->getAdapter(PageModel::class);

return ContentUrlResult::redirect($pageAdapter->findPublishedById($content->jumpTo));

// Link to an article
case 'article':
$articleAdapter = $this->framework->getAdapter(ArticleModel::class);

return ContentUrlResult::redirect($articleAdapter->findPublishedById($content->articleId));
}

$pageAdapter = $this->framework->getAdapter(PageModel::class);

// Link to the default page
return ContentUrlResult::resolve($pageAdapter->findPublishedById((int) $content->getRelated('pid')?->jumpTo));
}

public function getParametersForContent(object $content, PageModel $pageModel): array
{
if (!$content instanceof CalendarEventsModel) {
return [];
}

return [
'parameters' => '/'.($content->alias ?: $content->id),
];
}
}
13 changes: 8 additions & 5 deletions calendar-bundle/tests/EventListener/SitemapListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Contao\CalendarEventsModel;
use Contao\CalendarModel;
use Contao\CoreBundle\Event\SitemapEvent;
use Contao\CoreBundle\Routing\ContentUrlGenerator;
use Contao\Database;
use Contao\PageModel;
use Contao\TestCase\ContaoTestCase;
Expand Down Expand Up @@ -50,10 +51,6 @@ public function testNothingIsAddedIfNoPublishedCalendar(): void
public function testCalendarEventIsAdded(array $pageProperties, array $calendarProperties, bool $hasAuthenticatedMember): void
{
$jumpToPage = $this->mockClassWithProperties(PageModel::class, $pageProperties);
$jumpToPage
->method('getAbsoluteUrl')
->willReturn('https://contao.org')
;

$adapters = [
CalendarModel::class => $this->mockConfiguredAdapter([
Expand Down Expand Up @@ -143,7 +140,13 @@ private function createListener(array $allPages, array $adapters, bool $hasAuthe
;
}

return new SitemapListener($framework, $security);
$urlGenerator = $this->createMock(ContentUrlGenerator::class);
$urlGenerator
->method('generate')
->willReturn('https://contao.org')
;

return new SitemapListener($framework, $security, $urlGenerator);
}

private function createSitemapEvent(array $rootPages): SitemapEvent
Expand Down