Temporary removal of listEmailTemplates

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matej BačoandClaude Opus 4.7 committed 2026-04-19 10:15:48 +02:00
1 parent 0a71efc244
commit 8a1f8c71b2
6 files changed
-627

No files matched your search

@@ -1,173 +0,0 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Templates\Email;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Template\Template;
use Appwrite\Utopia\Database\InMemoryQuery;
use Appwrite\Utopia\Database\Validator\Queries\ProjectTemplates;
use Appwrite\Utopia\Response;
use Utopia\Config\Config;
use Utopia\Database\Document;
use Utopia\Database\Exception\Query as QueryException;
use Utopia\Database\Query;
use Utopia\Locale\Locale;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\System\System;
use Utopia\Validator\Boolean;
class XList extends Action
{
use HTTP;
public static function getName()
{
return 'listProjectEmailTemplates';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/project/templates/email')
->desc('List project email templates')
->groups(['api', 'project'])
->label('scope', 'templates.read')
->label('sdk', new Method(
namespace: 'project',
group: 'templates',
name: 'listEmailTemplates',
description: <<<EOT
Get a list of all email templates available for the project. Each entry represents a type and locale combination, with the `custom` flag indicating whether the template has been customized.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_EMAIL_TEMPLATE_LIST,
)
]
))
->param('queries', [], new ProjectTemplates(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter and order on the following attributes: ' . implode(', ', array_keys(ProjectTemplates::ALLOWED_ATTRIBUTES)), true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('project')
->inject('response')
->inject('localeCodes')
->callback($this->action(...));
}
/**
* @param array<string> $queries
* @param array<string> $localeCodes
*/
public function action(
array $queries,
bool $includeTotal,
Document $project,
Response $response,
array $localeCodes,
) {
try {
$queries = Query::parseQueries($queries);
} catch (QueryException $e) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage());
}
$grouped = Query::groupByType($queries);
$types = Config::getParam('locale-templates')['email'] ?? [];
$projectTemplates = $project->getAttribute('templates', []);
$templates = [];
foreach ($types as $type) {
foreach ($localeCodes as $locale) {
$key = 'email.' . $type . '-' . $locale;
$stored = $projectTemplates[$key] ?? null;
$localeObj = new Locale($locale);
$localeObj->setFallback(System::getEnv('_APP_LOCALE', 'en'));
if (is_null($stored)) {
/**
* different templates, different placeholders.
*/
$templateConfigs = [
'magicSession' => [
'file' => 'email-magic-url.tpl',
'placeholders' => ['optionButton', 'buttonText', 'optionUrl', 'clientInfo', 'securityPhrase']
],
'mfaChallenge' => [
'file' => 'email-mfa-challenge.tpl',
'placeholders' => ['description', 'clientInfo']
],
'otpSession' => [
'file' => 'email-otp.tpl',
'placeholders' => ['description', 'clientInfo', 'securityPhrase']
],
'sessionAlert' => [
'file' => 'email-session-alert.tpl',
'placeholders' => ['body', 'listDevice', 'listIpAddress', 'listCountry', 'footer']
],
];
// fallback to the base template.
$config = $templateConfigs[$type] ?? [
'file' => 'email-inner-base.tpl',
'placeholders' => ['buttonText', 'body', 'footer']
];
$templateString = file_get_contents(APP_CE_CONFIG_DIR . '/locale/templates/' . $config['file']);
// We use `fromString` due to the replace above
$message = Template::fromString($templateString);
// Set type-specific parameters
foreach ($config['placeholders'] as $param) {
$escapeHtml = !in_array($param, ['clientInfo', 'body', 'footer', 'description']);
$message->setParam("{{{$param}}}", $localeObj->getText("emails.{$type}.{$param}"), escapeHtml: $escapeHtml);
}
$message
// common placeholders on all the templates
->setParam('{{hello}}', $localeObj->getText("emails.{$type}.hello"))
->setParam('{{thanks}}', $localeObj->getText("emails.{$type}.thanks"))
->setParam('{{signature}}', $localeObj->getText("emails.{$type}.signature"));
// `useContent: false` will strip new lines!
$message = $message->render(useContent: true);
$template = [
'message' => $message,
'subject' => $localeObj->getText('emails.' . $type . '.subject'),
'senderEmail' => '',
'senderName' => '',
'custom' => false,
];
} else {
$template = $stored;
$template['custom'] = true;
}
$template['type'] = $type;
$template['locale'] = $locale;
$templates[] = new Document($template);
}
}
$templates = InMemoryQuery::filter($templates, $grouped['filters']);
$templates = InMemoryQuery::order($templates, $grouped['orderAttributes'], $grouped['orderTypes']);
$total = $includeTotal ? \count($templates) : 0;
$templates = InMemoryQuery::paginate($templates, $grouped['limit'] ?? APP_LIMIT_COUNT, $grouped['offset']);
$response->dynamic(new Document([
'templates' => $templates,
'total' => $total,
]), Response::MODEL_EMAIL_TEMPLATE_LIST);
}
}
@@ -27,7 +27,6 @@ use Appwrite\Platform\Modules\Project\Http\Project\Services\Update as UpdateProj
use Appwrite\Platform\Modules\Project\Http\Project\Templates\Email\Delete as DeleteTemplate;
use Appwrite\Platform\Modules\Project\Http\Project\Templates\Email\Get as GetTemplate;
use Appwrite\Platform\Modules\Project\Http\Project\Templates\Email\Update as UpdateTemplate;
use Appwrite\Platform\Modules\Project\Http\Project\Templates\Email\XList as ListTemplates;
use Appwrite\Platform\Modules\Project\Http\Project\Variables\Create as CreateVariable;
use Appwrite\Platform\Modules\Project\Http\Project\Variables\Delete as DeleteVariable;
use Appwrite\Platform\Modules\Project\Http\Project\Variables\Get as GetVariable;
@@ -50,7 +49,6 @@ class Http extends Service
$this->addAction(UpdateProjectService::getName(), new UpdateProjectService());
// Templates
$this->addAction(ListTemplates::getName(), new ListTemplates());
$this->addAction(GetTemplate::getName(), new GetTemplate());
$this->addAction(DeleteTemplate::getName(), new DeleteTemplate());
$this->addAction(UpdateTemplate::getName(), new UpdateTemplate());
@@ -1,159 +0,0 @@
<?php
namespace Appwrite\Utopia\Database;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
/**
* Applies filter, order, and pagination queries to an in-memory array of Documents.
*
* Intended for list endpoints whose full dataset is materialized in memory (e.g. built
* from config and project attributes rather than a database collection).
*/
class InMemoryQuery
{
/**
* Filter documents using AND-combined query filters.
*
* @param array<Document> $documents
* @param array<Query> $filters
* @return array<Document>
*/
public static function filter(array $documents, array $filters): array
{
if (empty($filters)) {
return \array_values($documents);
}
return \array_values(\array_filter($documents, function (Document $document) use ($filters) {
foreach ($filters as $filter) {
if (!self::matches($document, $filter)) {
return false;
}
}
return true;
}));
}
/**
* Evaluate a single filter query against a document.
*/
public static function matches(Document $document, Query $filter): bool
{
$attribute = $filter->getAttribute();
$values = $filter->getValues();
$actual = $document->getAttribute($attribute);
$needle = (string) ($values[0] ?? '');
return match ($filter->getMethod()) {
Query::TYPE_EQUAL => \in_array($actual, $values, false),
Query::TYPE_NOT_EQUAL => !\in_array($actual, $values, false),
Query::TYPE_LESSER => self::compareScalar($actual, $values[0] ?? null) < 0,
Query::TYPE_LESSER_EQUAL => self::compareScalar($actual, $values[0] ?? null) <= 0,
Query::TYPE_GREATER => self::compareScalar($actual, $values[0] ?? null) > 0,
Query::TYPE_GREATER_EQUAL => self::compareScalar($actual, $values[0] ?? null) >= 0,
Query::TYPE_BETWEEN => self::compareScalar($actual, $values[0] ?? null) >= 0 && self::compareScalar($actual, $values[1] ?? null) <= 0,
Query::TYPE_NOT_BETWEEN => self::compareScalar($actual, $values[0] ?? null) < 0 || self::compareScalar($actual, $values[1] ?? null) > 0,
Query::TYPE_STARTS_WITH => \is_string($actual) && \str_starts_with($actual, $needle),
Query::TYPE_NOT_STARTS_WITH => \is_string($actual) && !\str_starts_with($actual, $needle),
Query::TYPE_ENDS_WITH => \is_string($actual) && \str_ends_with($actual, $needle),
Query::TYPE_NOT_ENDS_WITH => \is_string($actual) && !\str_ends_with($actual, $needle),
Query::TYPE_CONTAINS => self::containsValue($actual, $values),
Query::TYPE_NOT_CONTAINS => !self::containsValue($actual, $values),
Query::TYPE_SEARCH => \is_string($actual) && $needle !== '' && \stripos($actual, $needle) !== false,
Query::TYPE_NOT_SEARCH => \is_string($actual) && ($needle === '' || \stripos($actual, $needle) === false),
Query::TYPE_IS_NULL => $actual === null,
Query::TYPE_IS_NOT_NULL => $actual !== null,
default => throw new \InvalidArgumentException('Unsupported query method: ' . $filter->getMethod()),
};
}
/**
* Sort documents by one or more attributes.
*
* @param array<Document> $documents
* @param array<string> $orderAttributes
* @param array<string> $orderTypes
* @return array<Document>
*/
public static function order(array $documents, array $orderAttributes, array $orderTypes): array
{
if (empty($orderAttributes)) {
return \array_values($documents);
}
$documents = \array_values($documents);
\usort($documents, function (Document $a, Document $b) use ($orderAttributes, $orderTypes) {
foreach ($orderAttributes as $index => $attribute) {
$direction = \strtoupper($orderTypes[$index] ?? Database::ORDER_ASC);
$cmp = self::compareScalar($a->getAttribute($attribute), $b->getAttribute($attribute));
if ($cmp !== 0) {
return $direction === Database::ORDER_DESC ? -$cmp : $cmp;
}
}
return 0;
});
return $documents;
}
/**
* Apply limit and offset.
*
* @param array<Document> $documents
* @return array<Document>
*/
public static function paginate(array $documents, ?int $limit, ?int $offset): array
{
return \array_slice(\array_values($documents), $offset ?? 0, $limit);
}
/**
* Compare two scalars in a way that handles null consistently (null sorts before any value).
*/
private static function compareScalar(mixed $a, mixed $b): int
{
if ($a === null && $b === null) {
return 0;
}
if ($a === null) {
return -1;
}
if ($b === null) {
return 1;
}
return $a <=> $b;
}
/**
* Check if an attribute contains any of the given values. Handles both array attributes
* (checks membership) and string attributes (checks substring).
*
* @param array<mixed> $values
*/
private static function containsValue(mixed $actual, array $values): bool
{
if (\is_array($actual)) {
foreach ($values as $value) {
if (\in_array($value, $actual, false)) {
return true;
}
}
return false;
}
if (\is_string($actual)) {
foreach ($values as $value) {
if (\str_contains($actual, (string) $value)) {
return true;
}
}
return false;
}
return false;
}
}
@@ -1,41 +0,0 @@
<?php
namespace Appwrite\Utopia\Database\Validator\Queries;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Queries;
use Utopia\Database\Validator\Query\Filter;
use Utopia\Database\Validator\Query\Limit;
use Utopia\Database\Validator\Query\Offset;
use Utopia\Database\Validator\Query\Order;
/**
* Queries validator for list endpoints whose dataset is materialized in memory rather
* than backed by a database collection. Pairs with {@see \Appwrite\Utopia\Database\InMemoryQuery}
* to apply the validated queries.
*/
class BaseInMemory extends Queries
{
/**
* @param array<string, string> $allowedAttributes Map of attribute key to Database::VAR_* type
*/
public function __construct(array $allowedAttributes)
{
$attributes = [];
foreach ($allowedAttributes as $key => $type) {
$attributes[] = new Document([
'key' => $key,
'type' => $type,
'array' => false,
]);
}
parent::__construct([
new Limit(),
new Offset(),
new Filter($attributes, Database::VAR_STRING, APP_DATABASE_QUERY_MAX_VALUES),
new Order($attributes),
]);
}
}
@@ -1,24 +0,0 @@
<?php
namespace Appwrite\Utopia\Database\Validator\Queries;
use Utopia\Database\Database;
class ProjectTemplates extends BaseInMemory
{
public const ALLOWED_ATTRIBUTES = [
'type' => Database::VAR_STRING,
'locale' => Database::VAR_STRING,
'subject' => Database::VAR_STRING,
'message' => Database::VAR_STRING,
'senderName' => Database::VAR_STRING,
'senderEmail' => Database::VAR_STRING,
'replyTo' => Database::VAR_STRING,
'custom' => Database::VAR_BOOLEAN,
];
public function __construct()
{
parent::__construct(self::ALLOWED_ATTRIBUTES);
}
}
@@ -3,7 +3,6 @@
namespace Tests\E2E\Services\Project;
use Tests\E2E\Client;
use Utopia\Database\Query;
trait TemplatesBase
{
@@ -72,208 +71,6 @@ trait TemplatesBase
$this->assertSame(401, $template['headers']['status-code']);
}
// =========================================================================
// List email templates tests
// =========================================================================
public function testListEmailTemplates(): void
{
$list = $this->listEmailTemplates(null, true);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertIsArray($list['body']['templates']);
$this->assertGreaterThan(0, $list['body']['total']);
$this->assertGreaterThan(0, \count($list['body']['templates']));
foreach ($list['body']['templates'] as $template) {
$this->assertArrayHasKey('type', $template);
$this->assertArrayHasKey('locale', $template);
$this->assertArrayHasKey('custom', $template);
$this->assertArrayHasKey('subject', $template);
$this->assertArrayHasKey('message', $template);
}
}
public function testListEmailTemplatesWithLimit(): void
{
$list = $this->listEmailTemplates([
Query::limit(5)->toString(),
], true);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertCount(5, $list['body']['templates']);
$this->assertGreaterThanOrEqual(5, $list['body']['total']);
}
public function testListEmailTemplatesWithOffset(): void
{
$first = $this->listEmailTemplates([
Query::limit(2)->toString(),
], true);
$this->assertSame(200, $first['headers']['status-code']);
$second = $this->listEmailTemplates([
Query::limit(2)->toString(),
Query::offset(2)->toString(),
], true);
$this->assertSame(200, $second['headers']['status-code']);
$firstIds = \array_map(
fn ($t) => $t['type'] . '-' . $t['locale'],
$first['body']['templates']
);
$secondIds = \array_map(
fn ($t) => $t['type'] . '-' . $t['locale'],
$second['body']['templates']
);
$this->assertEmpty(\array_intersect($firstIds, $secondIds));
}
public function testListEmailTemplatesWithoutTotal(): void
{
$list = $this->listEmailTemplates(null, false);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertSame(0, $list['body']['total']);
$this->assertGreaterThan(0, \count($list['body']['templates']));
}
public function testListEmailTemplatesFilterByType(): void
{
$list = $this->listEmailTemplates([
Query::equal('type', ['verification'])->toString(),
], true);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertGreaterThan(0, $list['body']['total']);
foreach ($list['body']['templates'] as $template) {
$this->assertSame('verification', $template['type']);
}
}
public function testListEmailTemplatesFilterByLocale(): void
{
$list = $this->listEmailTemplates([
Query::equal('locale', ['en'])->toString(),
], true);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertGreaterThan(0, $list['body']['total']);
foreach ($list['body']['templates'] as $template) {
$this->assertSame('en', $template['locale']);
}
}
public function testListEmailTemplatesFilterByCustom(): void
{
$update = $this->updateEmailTemplate('recovery', 'en', 'Recovery Subject', 'Recovery Body');
$this->assertSame(200, $update['headers']['status-code']);
$list = $this->listEmailTemplates([
Query::equal('custom', [true])->toString(),
Query::limit(100)->toString(),
], true);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertGreaterThanOrEqual(1, $list['body']['total']);
$found = false;
foreach ($list['body']['templates'] as $template) {
$this->assertTrue($template['custom']);
if ($template['type'] === 'recovery' && $template['locale'] === 'en') {
$found = true;
}
}
$this->assertTrue($found, 'Customized template should appear in custom=true filter');
// Cleanup
$this->deleteEmailTemplate('recovery', 'en');
}
public function testListEmailTemplatesCombinedFilters(): void
{
$list = $this->listEmailTemplates([
Query::equal('type', ['verification'])->toString(),
Query::equal('locale', ['en'])->toString(),
], true);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertSame(1, $list['body']['total']);
$this->assertCount(1, $list['body']['templates']);
$this->assertSame('verification', $list['body']['templates'][0]['type']);
$this->assertSame('en', $list['body']['templates'][0]['locale']);
}
public function testListEmailTemplatesDefaultMatchesGet(): void
{
$get = $this->getEmailTemplate('verification', 'en');
$this->assertSame(200, $get['headers']['status-code']);
$this->assertFalse($get['body']['custom']);
$list = $this->listEmailTemplates([
Query::equal('type', ['verification'])->toString(),
Query::equal('locale', ['en'])->toString(),
], true);
$this->assertSame(200, $list['headers']['status-code']);
$this->assertCount(1, $list['body']['templates']);
$listed = $list['body']['templates'][0];
$this->assertSame($get['body']['type'], $listed['type']);
$this->assertSame($get['body']['locale'], $listed['locale']);
$this->assertSame($get['body']['custom'], $listed['custom']);
$this->assertSame($get['body']['subject'], $listed['subject']);
$this->assertSame($get['body']['message'], $listed['message']);
$this->assertSame($get['body']['senderName'], $listed['senderName']);
$this->assertSame($get['body']['senderEmail'], $listed['senderEmail']);
$this->assertSame($get['body']['replyTo'], $listed['replyTo']);
}
public function testListEmailTemplatesOrderByType(): void
{
$asc = $this->listEmailTemplates([
Query::orderAsc('type')->toString(),
Query::limit(100)->toString(),
], true);
$this->assertSame(200, $asc['headers']['status-code']);
$ascTypes = \array_map(fn ($t) => $t['type'], $asc['body']['templates']);
$sorted = $ascTypes;
\sort($sorted);
$this->assertSame($sorted, $ascTypes);
$desc = $this->listEmailTemplates([
Query::orderDesc('type')->toString(),
Query::limit(100)->toString(),
], true);
$this->assertSame(200, $desc['headers']['status-code']);
$descTypes = \array_map(fn ($t) => $t['type'], $desc['body']['templates']);
$sorted = $descTypes;
\rsort($sorted);
$this->assertSame($sorted, $descTypes);
}
public function testListEmailTemplatesInvalidQuery(): void
{
$list = $this->listEmailTemplates([
Query::equal('notAnAttribute', ['foo'])->toString(),
], true);
$this->assertSame(400, $list['headers']['status-code']);
}
public function testListEmailTemplatesWithoutAuthentication(): void
{
$list = $this->listEmailTemplates(null, true, false);
$this->assertSame(401, $list['headers']['status-code']);
}
// =========================================================================
// Update email template tests
// =========================================================================
@@ -507,31 +304,6 @@ trait TemplatesBase
return $this->client->call(Client::METHOD_GET, '/project/templates/email/' . $type, $headers, $params);
}
/**
* @param array<string>|null $queries
*/
protected function listEmailTemplates(?array $queries, ?bool $total, bool $authenticated = true): mixed
{
$headers = [
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
];
if ($authenticated) {
$headers = \array_merge($headers, $this->getHeaders());
}
$params = [];
if ($queries !== null) {
$params['queries'] = $queries;
}
if ($total !== null) {
$params['total'] = $total;
}
return $this->client->call(Client::METHOD_GET, '/project/templates/email', $headers, $params);
}
protected function updateEmailTemplate(
string $type,
?string $locale,