Skip to content
Merged
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
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,29 @@ All notable changes to **initphp/translator** will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Security

- `setDefault()` and `change()` now reject a language identifier that is empty or
contains anything other than letters, digits, `_` and `-` (checked with `\A…\z`,
so a trailing newline is rejected too) by throwing `TranslatorException` before
any file is read. Previously the identifier was joined into the path of a file
that was `require`d, so a request-supplied value such as `../config/install`
could run PHP files outside the language directory. The translator's state is
unchanged when a code is rejected. Codes such as `en`, `en_US` and `pt-BR` keep
working; a language pack whose name used `.` or `/` must be renamed.

### Fixed

- `setDefault()` and `change()` no longer change the active or default language
when the language cannot be loaded (missing file or directory, a file that does
not return an array): the pack is loaded first and the state is assigned after.
Before, `change('xx')` left `xx` as the active language.
- In directory mode a language is cached only after all of its files have
loaded. Before, a broken file left a half-loaded language in the cache, and
the next `change()` to it succeeded silently with the missing namespaces.

## [2.0.0] - 2026-11-22

### Changed (breaking)
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,11 @@ $lang->translate('errorMsg', null, ['code' => 2005]);
All configuration methods return `$this`, so calls can be chained.

> **Security:** the identifier given to `setDefault()` / `change()` is joined into
> a file path and the file is `require`d, without validation. Never pass request
> input (`$_GET`, cookies, headers) directly — check it against an allow-list such
> as `['en', 'tr', 'fr']` first. See
> a file path and the file is `require`d, so only letters, digits, `_` and `-` are
> accepted; anything else throws a `TranslatorException` before a file is touched.
> Still check request input (`$_GET`, cookies, headers) against an allow-list such
> as `['en', 'tr', 'fr']` first, so an unsupported language falls back instead of
> throwing. See
> [Exceptions](docs/Exceptions.md#validate-user-supplied-language-codes).

## Documentation
Expand Down
16 changes: 10 additions & 6 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,13 @@ has been chosen yet, this language also becomes the active one.

- **`$default`** — language identifier (a file name without extension in file
mode, or a sub-directory name in directory mode). It is joined into a path and
the file is `require`d without any validation, so pass only values you
control — see [Validate user-supplied language codes](Exceptions.md#validate-user-supplied-language-codes).
- **Throws** [`TranslatorException`](Exceptions.md) if the directory is unset, or
the language pack is missing, unreadable, or does not return an array.
the file is `require`d, so only letters, digits, `_` and `-` are accepted;
validate request input against an allow-list anyway — see
[Validate user-supplied language codes](Exceptions.md#validate-user-supplied-language-codes).
- **Throws** [`TranslatorException`](Exceptions.md) if the identifier is empty or
contains any other character, if the directory is unset, or the language pack
is missing, unreadable, or does not return an array. On any of these the
translator keeps its previous state (see [Exceptions](Exceptions.md)).

```php
$lang->setDefault('en');
Expand All @@ -116,8 +119,9 @@ Switches the active language, loading it on first use. If no default language ha
been set yet, the given language also becomes the default.

- **`$current`** — language identifier to activate. Like `setDefault()`, it is
joined into a path and the file is `require`d without any validation. Never
pass request input directly; check it against an allow-list first — see
joined into a path and the file is `require`d, so only letters, digits, `_` and
`-` are accepted. Do not pass request input directly; check it against an
allow-list first — see
[Validate user-supplied language codes](Exceptions.md#validate-user-supplied-language-codes).
- **Throws** [`TranslatorException`](Exceptions.md) under the same conditions as
[`setDefault()`](#setdefault).
Expand Down
33 changes: 23 additions & 10 deletions docs/Exceptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,18 @@ class TranslatorException extends \Exception {}
| A language **file** is missing (file mode) | `setDefault()` / `change()` | `The translation file was not found: "/app/languages/de.php".` |
| A language **directory** is missing (directory mode) | `setDefault()` / `change()` | `The translation directory was not found: "/app/languages/de/".` |
| A directory could not be read | `setDefault()` / `change()` | `The translation directory could not be read: "...".` |
| The language identifier contains anything other than letters, digits, `_` and `-` (or is empty) | `setDefault()` / `change()` | `The language code is invalid. Only letters, digits, "_" and "-" are allowed.` |
| A language file does not `return` an array | `setDefault()` / `change()` | `The translation file "/app/languages/en.php" must return an array.` |

Every message names the offending path or condition.

When `setDefault()` or `change()` throws — an invalid code, a missing or unreadable
pack, a file that does not return an array — the translator is left exactly as it
was: the active and default languages are unchanged, and nothing is cached for
the language that failed. In directory mode a language is cached only after every
file in it has loaded, so retrying a broken language throws again instead of
silently using the part that loaded.

## What does *not* throw

These are handled gracefully and never raise an exception:
Expand Down Expand Up @@ -69,16 +77,21 @@ try {

## Validate user-supplied language codes

`setDefault()` and `change()` do **not** validate the identifier. It is appended
to the directory you gave `setDir()` (`<dir>/<identifier>.php` in file mode,
`<dir>/<identifier>/*.php` in directory mode) and the result is `require`d. A
value such as `../config/install` therefore reaches PHP files outside the
language directory and runs them. A harmless unknown value only throws a
`TranslatorException`; a crafted one can execute code.

If you accept a language identifier from user input (query string, cookie,
header, form field), validate it against a known list **before** calling
`change()` or `setDefault()`, so an unknown value falls back to a default:
`setDefault()` and `change()` only accept identifiers made of letters, digits,
`_` and `-` (`en`, `en_US`, `pt-BR`). The identifier is appended to the directory
you gave `setDir()` (`<dir>/<identifier>.php` in file mode,
`<dir>/<identifier>/*.php` in directory mode) and the result is `require`d, so
anything else — `../config/install`, a `/`, a `.`, a trailing newline, a NUL
byte, an empty string — is rejected with a `TranslatorException` **before** any
file is touched.

The check only keeps the lookup inside the language directory. It does not know
which languages you support: a well-formed code such as `xx` still throws
`TranslatorException` (file or directory not found), and any file that really
exists in the language directory can be loaded. If you accept a language
identifier from user input (query string, cookie, header, form field), validate
it against a known list **before** calling `change()` or `setDefault()`, so an
unknown value falls back to a default instead of raising an exception:

```php
$supported = ['en', 'tr', 'fr'];
Expand Down
8 changes: 5 additions & 3 deletions docs/Quick-Start.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,9 @@ $lang = new Translator();
$lang->setDir(__DIR__ . '/languages/')
->setDefault('en');

// Per request, choose a language. The identifier becomes part of a file path,
// so only ever pass a value from your own allow-list:
// Per request, choose a language. The identifier becomes part of a file path
// (anything but letters, digits, "_" and "-" is rejected), and an unknown but
// well-formed code throws, so pass a value from your own allow-list:
$supported = ['en', 'tr', 'fr'];
$requested = $_GET['lang'] ?? 'en';

Expand All @@ -129,7 +130,8 @@ echo $lang->translate('welcome', 'Welcome {user}', [
## Common mistakes

- **Passing request input straight to `change()`.** The identifier is joined
into a path and the file is `require`d, and nothing checks it — see
into a path and the file is `require`d. Characters outside `[A-Za-z0-9_-]` are
rejected, but an unsupported code still throws — see
[Exceptions](Exceptions.md#validate-user-supplied-language-codes).
- **Setting the layout mode too late.** Calling `useDirectory()` after a language
has loaded throws. Set the mode first — see [Troubleshooting](Troubleshooting.md).
Expand Down
5 changes: 3 additions & 2 deletions docs/Recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ te('hello'); // echoes
## Pick the language per request

Resolve the active language from the request, always validating against a known
list. `change()` does not check its argument and builds a file path from it, so
an unvalidated value can load files outside your language directory (see
list. `change()` builds a file path from its argument: characters outside
`[A-Za-z0-9_-]` throw, and an unsupported code throws a file-not-found error, so
an unvalidated value breaks the request instead of falling back (see
[Exceptions](Exceptions.md#validate-user-supplied-language-codes)):

```php
Expand Down
39 changes: 35 additions & 4 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use function is_dir;
use function is_file;
use function method_exists;
use function preg_match;
use function rtrim;
use function str_contains;
use function strtolower;
Expand Down Expand Up @@ -97,8 +98,11 @@ public function setDir(string $dir): self
*/
public function setDefault(string $default): self
{
$this->default = $default;
$this->assertValidLanguageCode($default);

// Load first: if the pack cannot be loaded, nothing has been changed.
$this->ensureLoaded($default);
$this->default = $default;
$this->current ??= $default;

return $this;
Expand All @@ -125,8 +129,11 @@ public function useDirectory(): self
*/
public function change(string $current): self
{
$this->current = $current;
$this->assertValidLanguageCode($current);

// Load first: if the pack cannot be loaded, nothing has been changed.
$this->ensureLoaded($current);
$this->current = $current;
$this->default ??= $current;

return $this;
Expand Down Expand Up @@ -249,6 +256,26 @@ private function interpolate(string $message, array $context): string
return $replace === [] ? $message : strtr($message, $replace);
}

/**
* Rejects a language identifier that could escape the language directory.
*
* The identifier is joined into a path that is then `require`d, so only
* letters, digits, `_` and `-` are accepted. `\z` (not `$`) keeps a trailing
* newline from slipping through.
*
* @param string $lang The language identifier to check.
* @return void
* @throws TranslatorException If the identifier contains any other character, or is empty.
*/
private function assertValidLanguageCode(string $lang): void
{
if (preg_match('/\A[A-Za-z0-9_-]+\z/', $lang) !== 1) {
throw new TranslatorException(
'The language code is invalid. Only letters, digits, "_" and "-" are allowed.',
);
}
}

/**
* Loads a language into the in-memory cache if it is not already present.
*
Expand Down Expand Up @@ -322,11 +349,15 @@ private function load(string $lang): void
throw new TranslatorException('The translation directory could not be read: "' . $path . '".');
}

$this->container[$lang] = [];
// Collected locally and cached only once every file has loaded, so a
// broken file cannot leave a half-loaded language that a later call
// would accept from the cache.
$loaded = [];
foreach ($files as $file) {
$namespace = strtolower(basename($file, '.php'));
$this->container[$lang][$namespace] = $this->requireFile($file);
$loaded[$namespace] = $this->requireFile($file);
}
$this->container[$lang] = $loaded;
}

/**
Expand Down
14 changes: 10 additions & 4 deletions src/TranslatorInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,11 @@ public function setDir(string $dir): TranslatorInterface;
* extension in file mode, or a sub-directory name in
* directory mode).
* @return TranslatorInterface The same instance, for chaining.
* @throws TranslatorException If the directory is not set, or the language
* pack cannot be found, read or does not return an array.
* @throws TranslatorException If the identifier is empty or contains anything
* other than letters, digits, `_` and `-`, the
* directory is not set, or the language pack cannot
* be found, read or does not return an array. The
* translator keeps its previous state on failure.
*/
public function setDefault(string $default): TranslatorInterface;

Expand Down Expand Up @@ -88,8 +91,11 @@ public function useDirectory(): TranslatorInterface;
*
* @param string $current Language identifier to activate.
* @return TranslatorInterface The same instance, for chaining.
* @throws TranslatorException If the directory is not set, or the language
* pack cannot be found, read or does not return an array.
* @throws TranslatorException If the identifier is empty or contains anything
* other than letters, digits, `_` and `-`, the
* directory is not set, or the language pack cannot
* be found, read or does not return an array. The
* translator keeps its previous state on failure.
*/
public function change(string $current): TranslatorInterface;

Expand Down
93 changes: 93 additions & 0 deletions tests/Unit/FailedLoadTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

declare(strict_types=1);

namespace Tests\InitPHP\Translator\Unit;

use InitPHP\Translator\Translator;
use InitPHP\Translator\TranslatorException;
use PHPUnit\Framework\TestCase;

/**
* A language that cannot be loaded must leave the translator exactly as it was.
*/
final class FailedLoadTest extends TestCase
{
public function testChangeToAMissingLanguageKeepsTheCurrentAndDefaultLanguage(): void
{
$lang = (new Translator())->setDir(__DIR__ . '/FileLanguages/')->setDefault('en');

try {
$lang->change('xx');
self::fail('Expected a TranslatorException.');
} catch (TranslatorException) {
// Expected.
}

self::assertSame('en', $lang->__debugInfo()['current']);
self::assertSame('en', $lang->__debugInfo()['default']);
self::assertSame('Hello', $lang->translate('hello'));
}

public function testChangeToAMissingLanguageDoesNotMakeItTheDefault(): void
{
$lang = (new Translator())->setDir(__DIR__ . '/FileLanguages/');

try {
$lang->change('xx');
self::fail('Expected a TranslatorException.');
} catch (TranslatorException) {
// Expected.
}

self::assertNull($lang->__debugInfo()['current']);
self::assertNull($lang->__debugInfo()['default']);
}

public function testSetDefaultWithAMissingLanguageChangesNothing(): void
{
$lang = (new Translator())->setDir(__DIR__ . '/FileLanguages/');

try {
$lang->setDefault('xx');
self::fail('Expected a TranslatorException.');
} catch (TranslatorException) {
// Expected.
}

self::assertNull($lang->__debugInfo()['default']);
self::assertNull($lang->__debugInfo()['current']);
}

public function testSetDefaultWithAMissingLanguageKeepsAnExistingDefault(): void
{
$lang = (new Translator())->setDir(__DIR__ . '/FileLanguages/')->setDefault('en');

try {
$lang->setDefault('xx');
self::fail('Expected a TranslatorException.');
} catch (TranslatorException) {
// Expected.
}

self::assertSame('en', $lang->__debugInfo()['default']);
}

public function testAPartiallyLoadedDirectoryLanguageIsNotCached(): void
{
$lang = (new Translator())->useDirectory()->setDir(__DIR__ . '/Fixtures/BrokenDir/')->setDefault('en');

foreach ([1, 2] as $attempt) {
try {
$lang->change('bad');
self::fail('Expected a TranslatorException on attempt ' . $attempt . '.');
} catch (TranslatorException $e) {
self::assertStringContainsString('must return an array', $e->getMessage());
}
}

self::assertSame('en', $lang->__debugInfo()['current']);
self::assertSame('Hello', $lang->translate('main.hello'));
self::assertSame('bad.half', $lang->change('en')->translate('bad.half'));
}
}
3 changes: 3 additions & 0 deletions tests/Unit/Fixtures/BrokenDir/bad/a.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

return ['half' => 'loaded'];
3 changes: 3 additions & 0 deletions tests/Unit/Fixtures/BrokenDir/bad/b.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

return 'not an array';
3 changes: 3 additions & 0 deletions tests/Unit/Fixtures/BrokenDir/en/main.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

return ['hello' => 'Hello'];
Loading
Loading