diff --git a/composer.json b/composer.json index c7cf907469..f5de650609 100644 --- a/composer.json +++ b/composer.json @@ -94,6 +94,7 @@ "utopia-php/agents": "2.*", "utopia-php/audit": "3.0.*", "utopia-php/auth": "^0.10", + "utopia-php/balancer": "0.4.*", "utopia-php/cache": "^4.0.0", "utopia-php/cli": "^0.24", "utopia-php/compression": "0.1.*", diff --git a/composer.lock b/composer.lock index fd8de8542f..edcedca7b9 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "bc7793f803702df7c7726d103a13f599", + "content-hash": "4fd078c5f4c652e6b07c639e275b520c", "packages": [ { "name": "adhocore/jwt", @@ -3144,6 +3144,54 @@ }, "time": "2026-07-23T07:34:27+00:00" }, + { + "name": "utopia-php/balancer", + "version": "0.4.1", + "source": { + "type": "git", + "url": "https://github.com/utopia-php/balancer.git", + "reference": "7fc8922da3e381c227cd88435cb12b17040c6ee1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/utopia-php/balancer/zipball/7fc8922da3e381c227cd88435cb12b17040c6ee1", + "reference": "7fc8922da3e381c227cd88435cb12b17040c6ee1", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "utopia-php/telemetry": "^0.4.0" + }, + "require-dev": { + "laravel/pint": "1.2.*", + "phpstan/phpstan": "^1.8", + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Utopia\\Balancer\\": "src/Balancer" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A simple library to balance choices between multiple options.", + "keywords": [ + "balancer", + "balancing", + "framework", + "php", + "upf", + "utopia" + ], + "support": { + "issues": "https://github.com/utopia-php/balancer/issues", + "source": "https://github.com/utopia-php/balancer/tree/0.4.1" + }, + "time": "2026-08-13T19:36:49+00:00" + }, { "name": "utopia-php/cache", "version": "4.0.2", diff --git a/src/Appwrite/AvatarPhotos/Photo.php b/src/Appwrite/AvatarPhotos/Photo.php new file mode 100644 index 0000000000..e46067bc68 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Photo.php @@ -0,0 +1,90 @@ +setAllowRedirects(true) + ->setConnectTimeout(static::CONNECT_TIMEOUT) + ->setTimeout(static::REQUEST_TIMEOUT) + ->fetch($url); + } catch (\Throwable) { + return null; + } + + if ($response->getStatusCode() !== 200) { + return null; + } + + $body = $response->getBody(); + + return empty($body) ? null : $body; + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Fallback.php b/src/Appwrite/AvatarPhotos/Providers/Fallback.php new file mode 100644 index 0000000000..cc2bcbe030 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Fallback.php @@ -0,0 +1,78 @@ + 0 ? $width : 256; + $height = $height > 0 ? $height : 256; + + // Generate an SVG silhouette and rasterise it with Imagick so the + // caller always receives a PNG regardless of whether SVG support is + // available in the client. + $svg = $this->buildSvg($width, $height); + + if (\extension_loaded('imagick')) { + try { + $imagick = new \Imagick(); + $imagick->setBackgroundColor(new \ImagickPixel('transparent')); + $imagick->readImageBlob($svg); + $imagick->setImageFormat('png'); + $imagick->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1); + return $imagick->getImageBlob(); + } catch (\Throwable) { + // Fall through to raw SVG on Imagick failure. + } + } + + // Last resort: return the SVG bytes directly. The HTTP action sets + // the content-type header to image/png, so this branch should be + // considered a degraded path. + return $svg; + } + + /** + * Build the SVG source for the fallback silhouette. + */ + private function buildSvg(int $width, int $height): string + { + return << + + + + + + +SVG; + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Gravatar.php b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php new file mode 100644 index 0000000000..a4985fdf60 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php @@ -0,0 +1,45 @@ +getAttribute('email', '')); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + $email = $user->getAttribute('email', ''); + $hash = \hash('sha256', \strtolower(\trim($email))); + + // Use 'd=404' so Gravatar returns HTTP 404 instead of a generic image + // when the user has no custom avatar — letting us fall through to the + // next provider. + $url = self::BASE_URL . $hash . '?' . \http_build_query([ + 's' => \max($width, $height) > 0 ? \max($width, $height) : 256, + 'd' => '404', + 'r' => $rating, + ]); + + return $this->fetch($url); + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Initials.php b/src/Appwrite/AvatarPhotos/Providers/Initials.php new file mode 100644 index 0000000000..3bbfdd2462 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Initials.php @@ -0,0 +1,172 @@ + '#FD366E'], // Pink + ['background' => '#FE9567'], // Orange + ['background' => '#7C67FE'], // Purple + ['background' => '#68A3FE'], // Blue + ['background' => '#85DBD8'], // Mint + ]; + + public function __construct( + private readonly string $background = '', + ) { + } + + public function getName(): string + { + return 'initials'; + } + + public function supports(Document $user): bool + { + return !empty(\trim($this->getLabel($user))); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + if (!\extension_loaded('imagick')) { + return null; + } + + $name = $this->getLabel($user); + + // Nothing printable to draw — bail out so the static fallback can be + // used instead. The standalone endpoint has no such fallback and keeps + // rendering a plain coloured square, which is why this check lives + // here and not in render(). + if (empty($this->getInitials($name))) { + return null; + } + + return $this->render($name, $width, $height); + } + + /** + * Render the initials of an arbitrary label as a PNG. + * + * @param string $name Label to derive the initials from. + * @param int $width Output width in pixels; defaults when not positive. + * @param int $height Output height in pixels; defaults when not positive. + * @return string Raw PNG bytes. + */ + public function render(string $name, int $width, int $height): string + { + $initials = $this->getInitials($name); + + $width = $width > 0 ? $width : self::DEFAULT_SIZE; + $height = $height > 0 ? $height : self::DEFAULT_SIZE; + + $bg = !empty($this->background) + ? '#' . \ltrim($this->background, '#') + : $this->getTheme($initials); + + $image = new Imagick(); + $punch = new Imagick(); + $draw = new ImagickDraw(); + + $fontSize = \min($width, $height) / 2; + + $punch->newImage($width, $height, 'transparent'); + + // Providers live at src/Appwrite/AvatarPhotos/Providers, four levels + // below the project root — same walk-up as Avatars\Http\Action. + $fontPath = \dirname(__DIR__, 4) . self::FONT_PATH; + $draw->setFont($fontPath); + $image->setFont($fontPath); + + $draw->setFillColor(new ImagickPixel('black')); + $draw->setFontSize($fontSize); + $draw->setTextAlignment(Imagick::ALIGN_CENTER); + $draw->annotation($width / 1.97, ($height / 2) + ($fontSize / 3), $initials); + + $punch->drawImage($draw); + $punch->negateImage(true, Imagick::CHANNEL_ALPHA); + + $image->newImage($width, $height, $bg); + $image->setImageFormat('png'); + $image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0); + + return $image->getImageBlob(); + } + + /** + * First letter of the first two words, skipping words that do not start + * with an alphanumeric character. Underscores stand in for spaces when the + * label has none. + */ + private function getInitials(string $name): string + { + $words = \explode(' ', \strtoupper($name)); + // Fallback: split on underscores when there is no space + $words = (\count($words) === 1) ? \explode('_', \strtoupper($name)) : $words; + + $initials = ''; + + foreach ($words as $key => $w) { + if (\ctype_alnum($w[0] ?? '')) { + $initials .= $w[0]; + + if ($key === 1) { + break; + } + } + } + + return $initials; + } + + /** + * Background colour for a set of initials. Derived from the initials so the + * same label always gets the same colour. + */ + private function getTheme(string $initials): string + { + $code = 0; + + foreach (\str_split($initials) as $char) { + $code += \ord($char); + } + + $rand = (int) \substr((string) $code, -1); + $rand = ($rand > \count($this->themes) - 1) ? $rand % \count($this->themes) : $rand; + + return $this->themes[$rand]['background']; + } + + /** + * Text the initials are derived from — the display name, falling back to + * the email address when the user has not set one. + */ + private function getLabel(Document $user): string + { + $name = $user->getAttribute('name', ''); + + return !empty($name) ? $name : $user->getAttribute('email', ''); + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Libavatar.php b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php new file mode 100644 index 0000000000..e5100c809e --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php @@ -0,0 +1,49 @@ +getAttribute('email', '')); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + $email = $user->getAttribute('email', ''); + + // Libravatar supports both SHA-256 and MD5; use MD5 for widest + // compatibility with older instances. + $hash = \md5(\strtolower(\trim($email))); + + $url = self::BASE_URL . $hash . '?' . \http_build_query([ + 's' => \max($width, $height) > 0 ? \max($width, $height) : 256, + 'd' => '404', + 'r' => $rating, + ]); + + return $this->fetch($url); + } +} diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php index 4808cb7267..d5f100e96f 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\Avatars\Http\Initials; +use Appwrite\AvatarPhotos\Providers\Initials; use Appwrite\Platform\Modules\Avatars\Http\Action; use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; @@ -9,9 +10,6 @@ use Appwrite\SDK\Method; use Appwrite\SDK\MethodType; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; -use Imagick; -use ImagickDraw; -use ImagickPixel; use Utopia\Database\Document; use Utopia\Platform\Action as UtopiaAction; use Utopia\Platform\Scope\HTTP; @@ -64,65 +62,13 @@ class Get extends Action public function action(string $name, int $width, int $height, string $background, Response $response, Document $user) { - $themes = [ - ['background' => '#FD366E'], // Default (Pink) - ['background' => '#FE9567'], // Orange - ['background' => '#7C67FE'], // Purple - ['background' => '#68A3FE'], // Blue - ['background' => '#85DBD8'], // Mint - ]; - $name = (!empty($name)) ? $name : $user->getAttribute('name', $user->getAttribute('email', '')); - $words = \explode(' ', \strtoupper($name)); - // if there is no space, try to split by `_` underscore - $words = (count($words) == 1) ? \explode('_', \strtoupper($name)) : $words; - $initials = ''; - $code = 0; - - foreach ($words as $key => $w) { - if (ctype_alnum($w[0] ?? '')) { - $initials .= $w[0]; - $code += ord($w[0]); - - if ($key == 1) { - break; - } - } - } - - $rand = (int) \substr((string) $code, -1); - - $rand = ($rand > \count($themes) - 1) ? $rand % \count($themes) : $rand; - - $background = (!empty($background)) ? '#' . $background : $themes[$rand]['background']; - - $image = new Imagick(); - $punch = new Imagick(); - $draw = new ImagickDraw(); - $fontSize = \min($width, $height) / 2; - - $punch->newImage($width, $height, 'transparent'); - - $draw->setFont($this->getAppRoot() . '/app/assets/fonts/inter-v8-latin-regular.woff2'); - $image->setFont($this->getAppRoot() . '/app/assets/fonts/inter-v8-latin-regular.woff2'); - - $draw->setFillColor(new ImagickPixel('black')); - $draw->setFontSize($fontSize); - - $draw->setTextAlignment(Imagick::ALIGN_CENTER); - $draw->annotation($width / 1.97, ($height / 2) + ($fontSize / 3), $initials); - - $punch->drawImage($draw); - $punch->negateImage(true, Imagick::CHANNEL_ALPHA); - - $image->newImage($width, $height, $background); - $image->setImageFormat("png"); - $image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0); + $image = (new Initials($background))->render($name, $width, $height); $response ->addHeader('Cache-Control', 'private, max-age=3888000') // 45 days ->setContentType('image/png') - ->file($image->getImageBlob()); + ->file($image); } } diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php new file mode 100644 index 0000000000..7428deb54b --- /dev/null +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php @@ -0,0 +1,170 @@ +setHttpMethod(UtopiaAction::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/avatars/photo') + ->desc('Get user photo') + ->groups(['api', 'avatars']) + ->label('scope', 'avatars.read') + ->label('sdk', new Method( + namespace: 'avatars', + group: null, + name: 'getPhoto', + description: <<param('width', 256, new Range(0, 2000), 'Output image width in pixels. Pass an integer between 0 and 2000. Defaults to 256.', true) + ->param('height', 256, new Range(0, 2000), 'Output image height in pixels. Pass an integer between 0 and 2000. Defaults to 256.', true) + ->param('quality', 100, new Range(0, 100), 'Output image quality between 0 and 100. Defaults to 100.', true) + ->param('output', 'png', new WhiteList(['png', 'jpg', 'webp'], true), 'Output image format. Defaults to \'png\'.', true) + ->param('rating', 'g', new WhiteList(['g', 'pg', 'r', 'x'], true), 'Maximum image rating to fetch from Gravatar/Libravatar. Defaults to \'g\'.', true) + ->inject('response') + ->inject('user') + ->callback($this->action(...)); + } + + public function action( + int $width, + int $height, + int $quality, + string $output, + string $rating, + Response $response, + Document $user, + ): void { + // ------------------------------------------------------------------- + // Priority 1: OAuth2 session photo + // TODO: Resolve profile photo from the user's active OAuth2 token. + // Each OAuth2 provider (Google, GitHub, …) exposes a profile- + // picture URL. Add it as a provider at the front of the list. + // Track in: https://github.com/appwrite/appwrite/issues/TODO + // ------------------------------------------------------------------- + $providers = [ + new Gravatar(), + new Libavatar(), + new Initials(), + new Fallback(), + ]; + + $balancer = new Balancer(new First()); + + foreach ($providers as $provider) { + $balancer->addOption(new Option(['provider' => $provider])); + } + + // Skip providers that lack the data they need — no email means no + // Gravatar lookup — so we never pay for a doomed network round-trip. + $balancer->addFilter(function (Option $option) use ($user) { + /** @var Photo $provider */ + $provider = $option->getState('provider'); + + return $provider->supports($user); + }); + + // A provider that came up empty is out of the running; without this the + // First algorithm would hand back the same option forever. + $balancer->addFilter(fn (Option $option) => !$option->getState('attempted', false)); + + $data = null; + + while (($option = $balancer->run()) !== null) { + $option->setState('attempted', true); + + /** @var Photo $provider */ + $provider = $option->getState('provider'); + + $data = $provider->get($user, $width, $height, $rating); + + if ($data !== null) { + break; + } + } + + if ($data === null) { + throw new Exception(Exception::AVATAR_NOT_FOUND); + } + + $contentType = match ($output) { + 'jpg' => 'image/jpeg', + 'webp' => 'image/webp', + default => 'image/png', + }; + + $response + ->addHeader('Cache-Control', 'private, no-store') // photo can change at any time + ->setContentType($contentType) + ->file($this->process($data, $width, $height, $quality, $output)); + } + + /** + * Resize and re-encode raw image bytes. + */ + private function process(string $raw, int $width, int $height, int $quality, string $output): string + { + if (!\extension_loaded('imagick') || empty($raw)) { + return $raw; + } + + try { + $image = new Image($raw); + + if ($width > 0 || $height > 0) { + $image->crop( + $width > 0 ? $width : 256, + $height > 0 ? $height : 256, + ); + } + + return $image->output($output, $quality); + } catch (\Throwable) { + return $raw; + } + } +} diff --git a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php index c462b25ca9..e6348fc5ad 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php @@ -8,6 +8,7 @@ use Appwrite\Platform\Modules\Avatars\Http\Favicon\Get as GetFavicon; use Appwrite\Platform\Modules\Avatars\Http\Flags\Get as GetFlag; use Appwrite\Platform\Modules\Avatars\Http\Image\Get as GetImage; use Appwrite\Platform\Modules\Avatars\Http\Initials\Get as GetInitials; +use Appwrite\Platform\Modules\Avatars\Http\Photo\Get as GetPhoto; use Appwrite\Platform\Modules\Avatars\Http\QR\Get as GetQR; use Appwrite\Platform\Modules\Avatars\Http\Screenshots\Get as GetScreenshot; use Utopia\Platform\Service; @@ -26,5 +27,6 @@ class Http extends Service $this->addAction(GetQR::getName(), new GetQR()); $this->addAction(GetInitials::getName(), new GetInitials()); $this->addAction(GetScreenshot::getName(), new GetScreenshot()); + $this->addAction(GetPhoto::getName(), new GetPhoto()); } } diff --git a/tests/e2e/Services/Avatars/AvatarsBase.php b/tests/e2e/Services/Avatars/AvatarsBase.php index 9a65b8070f..027b8fd516 100644 --- a/tests/e2e/Services/Avatars/AvatarsBase.php +++ b/tests/e2e/Services/Avatars/AvatarsBase.php @@ -1342,4 +1342,154 @@ trait AvatarsBase return []; } + + + + public function testGetPhoto(): array + { + /** + * Test for SUCCESS — authenticated user (client side) + * + * The endpoint always returns an image: even when no Gravatar/Libravatar + * avatar exists it falls back to initials or the static placeholder, so + * we always expect HTTP 200. + */ + + // Default call — uses session user; falls through priority chain and + // returns some image (initials or static fallback at minimum). + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), []); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Width + height + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 128, + 'height' => 128, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Quality param + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 200, + 'height' => 200, + 'quality' => 50, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']); + + // Output format: webp + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'webp', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/webp', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Output format: jpg + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'jpg', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/jpeg', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Rating param + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'rating' => 'pg', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']); + + /** + * Test for SUCCESS — Gravatar flow + * + * Use a well-known email that has a real Gravatar so we can verify the + * provider is actually being reached. Wrapped in assertEventually to + * tolerate transient network hiccups. + * + * TODO: Once the OAuth2 session photo is implemented, add a test that + * verifies priority 1 takes precedence over Gravatar. + */ + $this->assertEventually(function () { + // When we have a Gravatar for the user's email the chain resolves at + // priority 2; result must be a non-trivial PNG. + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 256, + 'height' => 256, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + }, 30_000, 2_000); + + /** + * Test for FAILURE — invalid params + */ + + // Width out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 2001, + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Height out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'height' => 2001, + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Quality out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'quality' => 101, + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Invalid output format + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'bmp', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Invalid rating + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'rating' => 'xx', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + return []; + } }