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
4 changes: 4 additions & 0 deletions core/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use OC\Authentication\Notifications\Notifier as AuthenticationNotifier;
use OC\Core\Listener\AddMissingIndicesListener;
use OC\Core\Listener\AddMissingPrimaryKeyListener;
use OC\Core\Listener\AvatarVersionListener;
use OC\Core\Listener\BeforeTemplateRenderedListener;
use OC\Core\Listener\LoadAdditionalEntriesListener;
use OC\Core\Listener\PasswordUpdatedListener;
Expand All @@ -42,6 +43,7 @@
use OC\DirectEditing\Listeners\UserDisabledTokenCleanupListener as UserDisabledDirectEditingTokenCleanupListener;
use OC\OCM\OCMDiscoveryHandler;
use OC\TagManager;
use OCP\Accounts\UserUpdatedEvent;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
Expand Down Expand Up @@ -104,6 +106,8 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(UserDeletedEvent::class, UserDeletedFilesCleanupListener::class);
$context->registerEventListener(UserDeletedEvent::class, UserDeletedWebAuthnCleanupListener::class);
$context->registerEventListener(PasswordUpdatedEvent::class, PasswordUpdatedListener::class);
$context->registerEventListener(UserUpdatedEvent::class, AvatarVersionListener::class);
$context->registerEventListener(UserChangedEvent::class, AvatarVersionListener::class);

// Tags
$context->registerEventListener(UserDeletedEvent::class, TagManager::class);
Expand Down
37 changes: 29 additions & 8 deletions core/Controller/AvatarController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace OC\Core\Controller;

use OC\AppFramework\Utility\TimeFactory;
use OC\Avatar\AvatarManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\FrontpageRoute;
Expand All @@ -23,7 +24,6 @@
use OCP\Files\File;
use OCP\Files\IRootFolder;
use OCP\Files\NotPermittedException;
use OCP\IAvatarManager;
use OCP\IL10N;
use OCP\Image;
use OCP\IRequest;
Expand All @@ -36,10 +36,19 @@
* @package OC\Core\Controller
*/
class AvatarController extends Controller {
private const CACHE_DEFAULT = 60 * 60 * 24;

/**
* Long enough to span the gap between infrequent large calls, which is where
* the cost of refetching everyone's avatar lands. Not longer, because a
* cached avatar outlives the account it belongs to.
*/
private const CACHE_VERSIONED = 60 * 60 * 24 * 30;

public function __construct(
string $appName,
IRequest $request,
protected IAvatarManager $avatarManager,
protected AvatarManager $avatarManager,
protected IL10N $l10n,
protected IUserManager $userManager,
protected IRootFolder $rootFolder,
Expand All @@ -57,6 +66,7 @@ public function __construct(
* @param string $userId ID of the user
* @param 64|512 $size Size of the avatar
* @param bool $guestFallback Fallback to guest avatar if not found
* @param string $v Avatar version, which lets the response be cached for longer. A stale version still returns the current avatar
* @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, list<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}>
*
* 200: Avatar returned
Expand All @@ -68,7 +78,7 @@ public function __construct(
#[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}/dark')]
#[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)]
#[NoSameSiteCookieRequired]
public function getAvatarDark(string $userId, int $size, bool $guestFallback = false) {
public function getAvatarDark(string $userId, int $size, bool $guestFallback = false, string $v = '') {
if ($size <= 64) {
if ($size !== 64) {
$this->logger->debug('Avatar requested in deprecated size ' . $size);
Expand Down Expand Up @@ -96,8 +106,7 @@ public function getAvatarDark(string $userId, int $size, bool $guestFallback = f
return new JSONResponse([], Http::STATUS_NOT_FOUND);
}

// Cache for 1 day
$response->cacheFor(60 * 60 * 24, false, true);
$response->cacheFor($this->cacheSecondsFor($userId, $v), false, true);
return $response;
}

Expand All @@ -107,6 +116,7 @@ public function getAvatarDark(string $userId, int $size, bool $guestFallback = f
* @param string $userId ID of the user
* @param 64|512 $size Size of the avatar
* @param bool $guestFallback Fallback to guest avatar if not found
* @param string $v Avatar version, which lets the response be cached for longer. A stale version still returns the current avatar
* @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, list<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}>
*
* 200: Avatar returned
Expand All @@ -118,7 +128,7 @@ public function getAvatarDark(string $userId, int $size, bool $guestFallback = f
#[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}')]
#[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)]
#[NoSameSiteCookieRequired]
public function getAvatar(string $userId, int $size, bool $guestFallback = false) {
public function getAvatar(string $userId, int $size, bool $guestFallback = false, string $v = '') {
if ($size <= 64) {
if ($size !== 64) {
$this->logger->debug('Avatar requested in deprecated size ' . $size);
Expand Down Expand Up @@ -146,11 +156,22 @@ public function getAvatar(string $userId, int $size, bool $guestFallback = false
return new JSONResponse([], Http::STATUS_NOT_FOUND);
}

// Cache for 1 day
$response->cacheFor(60 * 60 * 24, false, true);
$response->cacheFor($this->cacheSecondsFor($userId, $v), false, true);
return $response;
}

/**
* Decided here rather than by the caller: attaching a version to an avatar
* whose visibility depends on the viewer must not buy a month of caching.
*/
private function cacheSecondsFor(string $userId, string $version): int {
if ($version !== '' && $this->avatarManager->canCacheAvatarLongTerm($userId)) {
return self::CACHE_VERSIONED;
}

return self::CACHE_DEFAULT;
}

#[NoAdminRequired]
#[FrontpageRoute(verb: 'POST', url: '/avatar/')]
public function postAvatar(?string $path = null): JSONResponse {
Expand Down
49 changes: 49 additions & 0 deletions core/Listener/AvatarVersionListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\Core\Listener;

use OC\Avatar\AvatarVersion;
use OCP\Accounts\UserUpdatedEvent;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\User\Events\UserChangedEvent;

/**
* Bumps the avatar version when something outside the avatar itself changes
* what a viewer would be served.
*
* Uploading or removing an avatar bumps it already. The avatar scope lives in
* the account, so switching to v2-private has to invalidate too, and a disabled
* account starts serving a guest avatar without touching the avatar at all.
*
* Bumping on any account change rather than diffing the scope: AccountManager
* only dispatches this when something actually changed. Editing an unrelated
* profile field then costs every viewer one avatar refetch, which is cheaper
* than carrying a second copy of the scope around to compare against.
*
* @template-implements IEventListener<UserUpdatedEvent|UserChangedEvent>
*/
class AvatarVersionListener implements IEventListener {
public function __construct(
private AvatarVersion $avatarVersion,
) {
}

#[\Override]
public function handle(Event $event): void {
if ($event instanceof UserUpdatedEvent) {
$this->avatarVersion->bump($event->getUser()->getUID());
return;
}

if ($event instanceof UserChangedEvent && $event->getFeature() === 'enabled') {
$this->avatarVersion->bump($event->getUser()->getUID());
}
}
}
18 changes: 18 additions & 0 deletions core/openapi-full.json
Original file line number Diff line number Diff line change
Expand Up @@ -9328,6 +9328,15 @@
"type": "boolean",
"default": false
}
},
{
"name": "v",
"in": "query",
"description": "Avatar version, which lets the response be cached for longer. A stale version still returns the current avatar",
"schema": {
"type": "string",
"default": ""
}
}
],
"responses": {
Expand Down Expand Up @@ -9431,6 +9440,15 @@
"type": "boolean",
"default": false
}
},
{
"name": "v",
"in": "query",
"description": "Avatar version, which lets the response be cached for longer. A stale version still returns the current avatar",
"schema": {
"type": "string",
"default": ""
}
}
],
"responses": {
Expand Down
18 changes: 18 additions & 0 deletions core/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -9328,6 +9328,15 @@
"type": "boolean",
"default": false
}
},
{
"name": "v",
"in": "query",
"description": "Avatar version, which lets the response be cached for longer. A stale version still returns the current avatar",
"schema": {
"type": "string",
"default": ""
}
}
],
"responses": {
Expand Down Expand Up @@ -9431,6 +9440,15 @@
"type": "boolean",
"default": false
}
},
{
"name": "v",
"in": "query",
"description": "Avatar version, which lets the response be cached for longer. A stale version still returns the current avatar",
"schema": {
"type": "string",
"default": ""
}
}
],
"responses": {
Expand Down
2 changes: 2 additions & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1349,6 +1349,7 @@
'OC\\Authentication\\WebAuthn\\Manager' => $baseDir . '/lib/private/Authentication/WebAuthn/Manager.php',
'OC\\Avatar\\Avatar' => $baseDir . '/lib/private/Avatar/Avatar.php',
'OC\\Avatar\\AvatarManager' => $baseDir . '/lib/private/Avatar/AvatarManager.php',
'OC\\Avatar\\AvatarVersion' => $baseDir . '/lib/private/Avatar/AvatarVersion.php',
'OC\\Avatar\\GuestAvatar' => $baseDir . '/lib/private/Avatar/GuestAvatar.php',
'OC\\Avatar\\PlaceholderAvatar' => $baseDir . '/lib/private/Avatar/PlaceholderAvatar.php',
'OC\\Avatar\\RemoteAvatar' => $baseDir . '/lib/private/Avatar/RemoteAvatar.php',
Expand Down Expand Up @@ -1634,6 +1635,7 @@
'OC\\Core\\Exception\\ResetPasswordException' => $baseDir . '/core/Exception/ResetPasswordException.php',
'OC\\Core\\Listener\\AddMissingIndicesListener' => $baseDir . '/core/Listener/AddMissingIndicesListener.php',
'OC\\Core\\Listener\\AddMissingPrimaryKeyListener' => $baseDir . '/core/Listener/AddMissingPrimaryKeyListener.php',
'OC\\Core\\Listener\\AvatarVersionListener' => $baseDir . '/core/Listener/AvatarVersionListener.php',
'OC\\Core\\Listener\\BeforeMessageLoggedEventListener' => $baseDir . '/core/Listener/BeforeMessageLoggedEventListener.php',
'OC\\Core\\Listener\\BeforeTemplateRenderedListener' => $baseDir . '/core/Listener/BeforeTemplateRenderedListener.php',
'OC\\Core\\Listener\\FeedBackHandler' => $baseDir . '/core/Listener/FeedBackHandler.php',
Expand Down
2 changes: 2 additions & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1390,6 +1390,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Authentication\\WebAuthn\\Manager' => __DIR__ . '/../../..' . '/lib/private/Authentication/WebAuthn/Manager.php',
'OC\\Avatar\\Avatar' => __DIR__ . '/../../..' . '/lib/private/Avatar/Avatar.php',
'OC\\Avatar\\AvatarManager' => __DIR__ . '/../../..' . '/lib/private/Avatar/AvatarManager.php',
'OC\\Avatar\\AvatarVersion' => __DIR__ . '/../../..' . '/lib/private/Avatar/AvatarVersion.php',
'OC\\Avatar\\GuestAvatar' => __DIR__ . '/../../..' . '/lib/private/Avatar/GuestAvatar.php',
'OC\\Avatar\\PlaceholderAvatar' => __DIR__ . '/../../..' . '/lib/private/Avatar/PlaceholderAvatar.php',
'OC\\Avatar\\RemoteAvatar' => __DIR__ . '/../../..' . '/lib/private/Avatar/RemoteAvatar.php',
Expand Down Expand Up @@ -1675,6 +1676,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Core\\Exception\\ResetPasswordException' => __DIR__ . '/../../..' . '/core/Exception/ResetPasswordException.php',
'OC\\Core\\Listener\\AddMissingIndicesListener' => __DIR__ . '/../../..' . '/core/Listener/AddMissingIndicesListener.php',
'OC\\Core\\Listener\\AddMissingPrimaryKeyListener' => __DIR__ . '/../../..' . '/core/Listener/AddMissingPrimaryKeyListener.php',
'OC\\Core\\Listener\\AvatarVersionListener' => __DIR__ . '/../../..' . '/core/Listener/AvatarVersionListener.php',
'OC\\Core\\Listener\\BeforeMessageLoggedEventListener' => __DIR__ . '/../../..' . '/core/Listener/BeforeMessageLoggedEventListener.php',
'OC\\Core\\Listener\\BeforeTemplateRenderedListener' => __DIR__ . '/../../..' . '/core/Listener/BeforeTemplateRenderedListener.php',
'OC\\Core\\Listener\\FeedBackHandler' => __DIR__ . '/../../..' . '/core/Listener/FeedBackHandler.php',
Expand Down
47 changes: 36 additions & 11 deletions lib/private/Avatar/AvatarManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IUser;
use OCP\IUserSession;
use OCP\User\Exceptions\UserNotFoundException;
use Psr\Log\LoggerInterface;
Expand All @@ -40,6 +41,7 @@ public function __construct(
private IAccountManager $accountManager,
private KnownUserService $knownUserService,
private ICloudIdManager $cloudIdManager,
private AvatarVersion $avatarVersion,
) {
}

Expand Down Expand Up @@ -79,31 +81,54 @@ public function getAvatar(string $userId): IAvatar {
$folder = $this->appData->newFolder($userId);
}

try {
$account = $this->accountManager->getAccount($user);
$avatarProperties = $account->getProperty(IAccountManager::PROPERTY_AVATAR);
$avatarScope = $avatarProperties->getScope();
} catch (PropertyDoesNotExistException $e) {
$avatarScope = '';
}
$avatarScope = $this->getAvatarScope($user);

switch ($avatarScope) {
// v2-private scope hides the avatar from public access and from unknown users
case IAccountManager::SCOPE_PRIVATE:
if ($requestingUser !== null && $this->knownUserService->isKnownToUser($requestingUser->getUID(), $userId)) {
return new UserAvatar($folder, $this->l, $user, $this->logger, $this->config);
return new UserAvatar($folder, $this->l, $user, $this->logger, $this->config, $this->avatarVersion);
}
break;
case IAccountManager::SCOPE_LOCAL:
case IAccountManager::SCOPE_FEDERATED:
case IAccountManager::SCOPE_PUBLISHED:
return new UserAvatar($folder, $this->l, $user, $this->logger, $this->config);
return new UserAvatar($folder, $this->l, $user, $this->logger, $this->config, $this->avatarVersion);
default:
// use a placeholder avatar which caches the generated images
return new PlaceholderAvatar($folder, $user, $this->config, $this->logger);
return new PlaceholderAvatar($folder, $user, $this->config, $this->logger, $this->avatarVersion);
}

return new PlaceholderAvatar($folder, $user, $this->config, $this->logger, $this->avatarVersion);
}

private function getAvatarScope(IUser $user): string {
try {
return $this->accountManager->getAccount($user)
->getProperty(IAccountManager::PROPERTY_AVATAR)
->getScope();
} catch (PropertyDoesNotExistException $e) {
return '';
}
}

/**
* `SCOPE_PRIVATE` resolves through `isKnownToUser()` in {@see getAvatar()}, so
* one URL gives two viewers different bytes and no per-user version tracks that.
*/
public function canCacheAvatarLongTerm(string $userId): bool {
$user = $this->userManager->get($userId);
if ($user === null) {
// Federated avatar fetched from another instance, or nothing at all.
return false;
}

if (!$user->isEnabled()) {
// Serves a guest avatar, and re-enabling bumps no version.
return false;
}

return new PlaceholderAvatar($folder, $user, $this->config, $this->logger);
return $this->getAvatarScope($user) !== IAccountManager::SCOPE_PRIVATE;
}

/**
Expand Down
33 changes: 33 additions & 0 deletions lib/private/Avatar/AvatarVersion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\Avatar;

use OCP\Config\IUserConfig;

/**
* The counter that invalidates a cached avatar URL.
*
* Anything that changes what a viewer would see has to bump it, or they keep
* the old picture for the full cache window.
*/
class AvatarVersion {
public function __construct(
private IUserConfig $userConfig,
) {
}

public function bump(string $userId): void {
$this->userConfig->setValueInt(
$userId,
'avatar',
'version',
$this->userConfig->getValueInt($userId, 'avatar', 'version') + 1,
);
}
}
Loading
Loading