Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 120 additions & 3 deletions lib/Controller/PublicViewController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,20 @@

namespace OCA\Calendar\Controller;

use OCA\DAV\CalDAV\CalDavBackend;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\Template\PublicTemplateResponse;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IInitialStateService;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\Util;
use Sabre\DAV\Exception\NotFound;

/**
* Class PublicViewController
Expand All @@ -31,13 +36,19 @@ class PublicViewController extends Controller {
* @param IConfig $config
* @param IInitialStateService $initialStateService
* @param IURLGenerator $urlGenerator
* @param IL10N $l10n
* @param Defaults $defaults
* @param CalDavBackend $calDavBackend
*/
public function __construct(
string $appName,
IRequest $request,
private IConfig $config,
private IInitialStateService $initialStateService,
private IURLGenerator $urlGenerator,
private IL10N $l10n,
private Defaults $defaults,
private CalDavBackend $calDavBackend,
) {
parent::__construct($appName, $request);
}
Expand Down Expand Up @@ -110,10 +121,116 @@ private function publicIndex(string $token):PublicTemplateResponse {
$this->initialStateService->provideInitialState($this->appName, 'can_subscribe_link', $defaultCanSubscribeLink);
$this->initialStateService->provideInitialState($this->appName, 'show_resources', false);

return new PublicTemplateResponse($this->appName, 'main', [
'share_url' => $this->getShareURL(),
'preview_image' => $this->getPreviewImage(),
$shareUrl = $this->getShareURL();
$previewImage = $this->getPreviewImage();

$response = new PublicTemplateResponse($this->appName, 'main', [
'share_url' => $shareUrl,
'preview_image' => $previewImage,
]);

[$title, $description, $sharedBy] = $this->resolvePublicShareMeta($token);
$response->setHeaderTitle($title);
if ($sharedBy !== null) {
$response->setHeaderDetails($sharedBy);
}
$this->addOpenGraphHeaders($title, $description, $shareUrl, $previewImage);

return $response;
}

/**
* Resolve calendar display name and owner for Open Graph / public header.
*
* @return array{0: string, 1: string, 2: ?string} title, description, shared-by details
*/
private function resolvePublicShareMeta(string $token): array {
$fallbackTitle = $this->l10n->t('Calendar');
$fallbackDescription = $this->l10n->t('A publicly shared calendar');

if ($token === '') {
return [$fallbackTitle, $fallbackDescription, null];
}

try {
$calendarInfo = $this->calDavBackend->getPublicCalendar($token);
} catch (NotFound) {
return [$fallbackTitle, $fallbackDescription, null];
}

$calendarName = $this->extractPublicCalendarDisplayName($calendarInfo);
$ownerDisplayName = $calendarInfo['{http://nextcloud.com/ns}owner-displayname'] ?? null;
if (!is_string($ownerDisplayName) || $ownerDisplayName === '') {
$ownerDisplayName = null;
}

if ($calendarName === null) {
return [$fallbackTitle, $fallbackDescription, $ownerDisplayName !== null
? $this->l10n->t('Shared by %s', [$ownerDisplayName])
: null];
}

$title = $calendarName;
if ($ownerDisplayName !== null) {
$description = $this->l10n->t('%s is a publicly shared calendar by %s', [$calendarName, $ownerDisplayName]);
$sharedBy = $this->l10n->t('Shared by %s', [$ownerDisplayName]);
} else {
$description = $this->l10n->t('%s is a publicly shared calendar', [$calendarName]);
$sharedBy = null;
}

return [$title, $description, $sharedBy];
}

/**
* @param array<string, mixed> $calendarInfo
*/
private function extractPublicCalendarDisplayName(array $calendarInfo): ?string {
$displayName = $calendarInfo['{DAV:}displayname'] ?? null;
if (!is_string($displayName) || $displayName === '') {
return null;
}

// getPublicCalendar() appends " (uid)" to the display name for DAV clients.
$principalUri = $calendarInfo['principaluri'] ?? '';
if (is_string($principalUri) && $principalUri !== '') {
$uid = basename($principalUri);
if ($uid !== '') {
$suffix = ' (' . $uid . ')';
if (str_ends_with($displayName, $suffix)) {
$displayName = substr($displayName, 0, -strlen($suffix));
}
}
}

$displayName = trim($displayName);
return $displayName !== '' ? $displayName : null;
}

/**
* Add Open Graph / Twitter meta tags so crawlers see title and description without JS.
*/
private function addOpenGraphHeaders(
string $title,
string $description,
string $shareUrl,
string $previewImage,
): void {
$siteName = $this->defaults->getName();

// Open Graph: https://ogp.me/
Util::addHeader('meta', ['property' => 'og:title', 'content' => $title]);
Util::addHeader('meta', ['property' => 'og:description', 'content' => $description]);
Util::addHeader('meta', ['property' => 'og:site_name', 'content' => $siteName]);
Util::addHeader('meta', ['property' => 'og:url', 'content' => $shareUrl]);
Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
Util::addHeader('meta', ['property' => 'og:image', 'content' => $previewImage]);

// Twitter / X cards
Util::addHeader('meta', ['property' => 'twitter:title', 'content' => $title]);
Util::addHeader('meta', ['property' => 'twitter:description', 'content' => $description]);
Util::addHeader('meta', ['property' => 'twitter:card', 'content' => 'summary']);
Util::addHeader('meta', ['property' => 'twitter:image', 'content' => $previewImage]);
}

/**
Expand Down
2 changes: 2 additions & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@
<referencedClass name="OCA\Circles\Api\v1\Circles" />
<referencedClass name="OCA\Circles\Exceptions\CircleNotFoundException" />
<referencedClass name="OCA\Calendar\Controller\Exception" />
<referencedClass name="OCA\DAV\CalDAV\CalDavBackend" />
<referencedClass name="OCA\DAV\CalDAV\Calendar" />
<referencedClass name="OCA\DAV\CalDAV\CalendarHome" />
<referencedClass name="OCA\DAV\CalDAV\InvitationResponse\InvitationResponseServer" />
<referencedClass name="OCA\NotifyPush\Queue\IQueue" />
<referencedClass name="Psr\Http\Client\ClientExceptionInterface" />
<referencedClass name="Sabre\DAV\Exception\NotFound" />
<referencedClass name="Sabre\VObject\Component\VCalendar" />
<referencedClass name="Sabre\VObject\Component\VEvent" />
<referencedClass name="Sabre\VObject\Component\VTimezone" />
Expand Down
90 changes: 88 additions & 2 deletions tests/php/unit/Controller/PublicViewControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@
namespace OCA\Calendar\Controller;

use ChristophWurst\Nextcloud\Testing\TestCase;
use OCA\DAV\CalDAV\CalDavBackend;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\Template\PublicTemplateResponse;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IInitialStateService;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IURLGenerator;
use PHPUnit\Framework\MockObject\MockObject;
use Sabre\DAV\Exception\NotFound;

class PublicViewControllerTest extends TestCase {
/** @var string */
Expand All @@ -33,7 +37,16 @@ class PublicViewControllerTest extends TestCase {
/** @var IURLGenerator|MockObject */
private $urlGenerator;

/** @var ViewController */
/** @var IL10N|MockObject */
private $l10n;

/** @var Defaults|MockObject */
private $defaults;

/** @var CalDavBackend|MockObject */
private $calDavBackend;

/** @var PublicViewController */
private $controller;

protected function setUp():void {
Expand All @@ -42,9 +55,22 @@ protected function setUp():void {
$this->config = $this->createMock(IConfig::class);
$this->initialStateService = $this->createMock(IInitialStateService::class);
$this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->l10n = $this->createMock(IL10N::class);
$this->defaults = $this->createMock(Defaults::class);
$this->calDavBackend = $this->createMock(CalDavBackend::class);

$this->l10n->method('t')
->willReturnCallback(function (string $text, array $parameters = []) {
if ($parameters === []) {
return $text;
}
return vsprintf(str_replace('%s', '%s', $text), $parameters);
});
$this->defaults->method('getName')->willReturn('Nextcloud');

$this->controller = new PublicViewController($this->appName, $this->request,
$this->config, $this->initialStateService, $this->urlGenerator);
$this->config, $this->initialStateService, $this->urlGenerator,
$this->l10n, $this->defaults, $this->calDavBackend);
}

public function testPublicIndexWithBranding():void {
Expand Down Expand Up @@ -109,6 +135,7 @@ public function testPublicIndexWithBranding():void {
['calendar', 'show_resources', false],
]);

// Empty token → fallback meta (no CalDAV lookup)
$response = $this->controller->publicIndexWithBranding('');

$this->assertInstanceOf(PublicTemplateResponse::class, $response);
Expand All @@ -118,6 +145,65 @@ public function testPublicIndexWithBranding():void {
], $response->getParams());
$this->assertEquals('public', $response->getRenderAs());
$this->assertEquals('main', $response->getTemplateName());
$this->assertEquals('Calendar', $response->getHeaderTitle());
$this->assertEquals('', $response->getHeaderDetails());
}

public function testPublicIndexWithBrandingUsesCalendarMeta(): void {
$this->config->method('getAppValue')->willReturnMap([
['calendar', 'eventLimit', 'yes', 'yes'],
['calendar', 'currentView', 'dayGridMonth', 'dayGridMonth'],
['calendar', 'showWeekends', 'yes', 'yes'],
['calendar', 'showWeekNr', 'no', 'no'],
['calendar', 'skipPopover', 'yes', 'yes'],
['calendar', 'timezone', 'automatic', 'automatic'],
['calendar', 'slotDuration', '00:30:00', '00:30:00'],
['calendar', 'showTasks', 'yes', 'yes'],
['calendar', 'tasksSidebar', 'yes', 'yes'],
['dav', 'allow_calendar_link_subscriptions', 'yes', 'yes'],
['calendar', 'installed_version', '', '1.0.0'],
]);
$this->request->method('getServerProtocol')->willReturn('https');
$this->request->method('getServerHost')->willReturn('cloud.example');
$this->request->method('getRequestUri')->willReturn('/apps/calendar/p/token123');
$this->urlGenerator->method('imagePath')->willReturn('img');
$this->urlGenerator->method('getAbsoluteURL')->willReturn('https://cloud.example/img');

$this->request->method('getHeader')->with('Accept')->willReturn('text/html');
$this->calDavBackend->expects(self::once())
->method('getPublicCalendar')
->with('token123')
->willReturn([
'{DAV:}displayname' => 'Team events (alice)',
'principaluri' => 'principals/users/alice',
'{http://nextcloud.com/ns}owner-displayname' => 'Alice Wonder',
]);

$response = $this->controller->publicIndexWithBranding('token123');

$this->assertInstanceOf(PublicTemplateResponse::class, $response);
$this->assertEquals('Team events', $response->getHeaderTitle());
$this->assertEquals('Shared by Alice Wonder', $response->getHeaderDetails());
}

public function testPublicIndexWithBrandingFallsBackWhenCalendarMissing(): void {
$this->config->method('getAppValue')->willReturn('yes');
$this->request->method('getServerProtocol')->willReturn('https');
$this->request->method('getServerHost')->willReturn('cloud.example');
$this->request->method('getRequestUri')->willReturn('/apps/calendar/p/missing');
$this->urlGenerator->method('imagePath')->willReturn('img');
$this->urlGenerator->method('getAbsoluteURL')->willReturn('https://cloud.example/img');

$this->request->method('getHeader')->with('Accept')->willReturn('text/html');
$this->calDavBackend->expects(self::once())
->method('getPublicCalendar')
->with('missing')
->willThrowException(new NotFound());

$response = $this->controller->publicIndexWithBranding('missing');

$this->assertEquals('Calendar', $response->getHeaderTitle());
$this->assertEquals('', $response->getHeaderDetails());
}

public function testRedirectionIfRequestedWithAcceptCalendarHeader(): void {
Expand Down