Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Yii Framework 2 Change Log
- Bug #21047: Fix PHPDoc annotations in `Theme`, `AccessRule` and `View` (mspirkov)
- Bug #20217: Apply `ActiveForm::$validationDelay` only while the user is typing, so validation on blur, change and manual trigger is no longer delayed (veksa)
- Bug #19865: Ignore validators with a `when` condition while `AttributeTypecastBehavior` detects `attributeTypes` automatically (veksa)
- Bug #21074: Fix Gettext PO file escaping of backslashes and parsing of escaped quotes (iliaal)

- Bug #20322: Pad hex escapes to four digits in `yii\helpers\Html::escapeJsRegularExpression()` so that they stay valid in JavaScript (veksa)
- Bug #20456: Fix `yii\helpers\Html::escapeJsRegularExpression()` truncating patterns that use bracket style delimiters (veksa)
- Enh #21079: Add the missing `@property` tags (mspirkov)
Expand Down
47 changes: 34 additions & 13 deletions framework/i18n/GettextPoFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace yii\i18n;

use Yii;
use yii\base\Exception;

/**
* GettextPoFile represents a PO Gettext message file.
Expand All @@ -18,25 +19,35 @@
*/
class GettextPoFile extends GettextFile
{
/**
* Quoted PO string that stays on one physical line, including the surrounding quotes.
* Excluding CR/LF prevents a legacy entry that ends with a single backslash from consuming
* the next entry's closing quote.
*/
private const QUOTED_STRING_PATTERN = '"(?:[^"\\\\\r\n]|\\\\[^\r\n])*+"';

/**
* Loads messages from a PO file.
* @param string $filePath file path
* @param string $context message context
* @return array message translations. Array keys are source messages and array values are translated messages:
* source message => translated message.
* @throws Exception if a regular expression fails
*/
public function load($filePath, $context)
{
$pattern = '/(msgctxt\s+"(.*?(?<!\\\\))")?\s+' // context
. 'msgid\s+((?:".*(?<!\\\\)"\s*)+)\s+' // message ID, i.e. original string
. 'msgstr\s+((?:".*(?<!\\\\)"\s*)+)/'; // translated string
$quoted = self::QUOTED_STRING_PATTERN;
$pattern = '/(msgctxt\s+((?:' . $quoted . '\s*)++))?\s*msgid\s*((?:' . $quoted . '\s*)++)\s*msgstr\s*((?:' . $quoted . '\s*)++)/';
$content = file_get_contents($filePath);
$matches = [];
$matchCount = preg_match_all($pattern, $content, $matches);
if ($matchCount === false) {
throw new Exception('Unable to parse PO file "' . $filePath . '" (PCRE error ' . preg_last_error() . ').');
}

$messages = [];
for ($i = 0; $i < $matchCount; ++$i) {
if ($matches[2][$i] === $context) {
if ($this->decode($matches[2][$i]) === $context) {
$id = $this->decode($matches[3][$i]);
$message = $this->decode($matches[4][$i]);
$messages[$id] = $message;
Expand Down Expand Up @@ -73,7 +84,7 @@ public function save($filePath, $messages)
foreach ($messages as $id => $message) {
$separatorPosition = strpos($id, chr(4));
if ($separatorPosition !== false) {
$content .= 'msgctxt "' . substr($id, 0, $separatorPosition) . "\"\n";
$content .= 'msgctxt "' . $this->encode(substr($id, 0, $separatorPosition)) . "\"\n";
$id = substr($id, $separatorPosition + 1);
}
$content .= 'msgid "' . $this->encode($id) . "\"\n";
Expand All @@ -90,8 +101,8 @@ public function save($filePath, $messages)
protected function encode($string)
{
return str_replace(
['"', "\n", "\t", "\r"],
['\\"', '\\n', '\\t', '\\r'],
['\\', '"', "\n", "\t", "\r"],
['\\\\', '\\"', '\\n', '\\t', '\\r'],
$string
);
}
Expand All @@ -100,15 +111,25 @@ protected function encode($string)
* Decodes special characters in a message.
* @param string $string message to be decoded
* @return string the decoded message
* @throws Exception if a regular expression fails
*/
protected function decode($string)
{
$string = preg_replace(
['/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/'],
['', "\n", "\r", "\t", '"'],
$string
);
if (preg_match_all('/' . self::QUOTED_STRING_PATTERN . '/', $string, $matches) === false) {
throw new Exception('Unable to decode PO string (PCRE error ' . preg_last_error() . ').');
}

$decoded = '';
foreach ($matches[0] as $fragment) {
$decoded .= strtr(substr($fragment, 1, -1), [
'\n' => "\n",
'\r' => "\r",
'\t' => "\t",
'\"' => '"',
'\\\\' => '\\',
]);
}

return substr(rtrim($string), 1, -1);
return $decoded;
}
}
155 changes: 153 additions & 2 deletions tests/framework/i18n/GettextPoFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
namespace yiiunit\framework\i18n;

use yii\i18n\GettextPoFile;
use yii\base\Exception;
use yiiunit\TestCase;
use Yii;

/**
* @group i18n
Expand Down Expand Up @@ -40,7 +42,7 @@ public function testLoad(): void
$this->assertArrayHasKey("Nunc vel sapien nunc, a pretium nulla.\nPellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.", $context1);

$this->assertArrayHasKey("The other\n\ncontext.\n", $context2);
$this->assertArrayHasKey("test1\\\ntest2\n\\\\\ntest3", $context2);
$this->assertArrayHasKey("test1\\ntest2\n\\\ntest3", $context2);

// translated messages
$this->assertTrue(in_array('', $context1));
Expand All @@ -49,7 +51,7 @@ public function testLoad(): void
$this->assertTrue(in_array('Короткий перевод.', $context1));

$this->assertTrue(in_array("Другой\n\nконтекст.\n", $context2));
$this->assertTrue(in_array("тест1\\\nтест2\n\\\\\nтест3", $context2));
$this->assertTrue(in_array("тест1\\nтест2\n\\\nтест3", $context2));
}

public function testSave(): void
Expand Down Expand Up @@ -107,4 +109,153 @@ public function testSave(): void
$this->assertArrayHasKey("\rCarriage returns\r", $context2);
$this->assertTrue(in_array("\rВозвраты кареток\r", $context2));
}

public function testSaveLoadRoundTripWithSpecialCharacters(): void
{
$poFile = new GettextPoFile();
$filePath = Yii::getAlias('@yiiunit/runtime') . '/po-roundtrip-' . getmypid() . '.po';

$context = 'round\\trip"ctx';
$rawMessages = [
'msg1' => 'back\\slash',
'msg2' => 'trailing\\',
'msg3' => 'quote"inside',
'msg4' => "new\nline",
'msg5' => 'C:\\temp\\file "q"\nend',
'msg6' => 'quote" ',
];
$messages = [];
foreach ($rawMessages as $id => $message) {
$messages[$context . chr(4) . $id] = $message;
}

$poFile->save($filePath, $messages);
$loaded = $poFile->load($filePath, $context);

$this->assertSame($rawMessages, $loaded);

unlink($filePath);
}

/**
* @dataProvider longStringsProvider
*/
public function testSaveLoadRoundTripWithLongStrings($context, $id, $translation): void
{
$poFile = new GettextPoFile();
$filePath = Yii::getAlias('@yiiunit/runtime') . '/po-long-' . getmypid() . '.po';
$expected = [
'before' => 'First translation',
$id => $translation,
'after' => 'Last translation',
];
$messages = [];
foreach ($expected as $source => $message) {
$messages[$context . chr(4) . $source] = $message;
}

try {
$poFile->save($filePath, $messages);
$loaded = $poFile->load($filePath, $context);

$this->assertSame(array_keys($expected), array_keys($loaded));
$this->assertSame($expected, $loaded);
} finally {
unlink($filePath);
}
}

public function longStringsProvider(): array
{
$plain = str_repeat('a', 10000);
$escaped = str_repeat("a\\\"\n\r\t", 2000);

return [
'long translation' => ['context', 'source', $plain],
'long ID' => ['context', $plain, 'translation'],
'long context' => [$plain, 'source', 'translation'],
'escaped translation' => ['context', 'source', $escaped],
'escaped ID' => ['context', $escaped, 'translation'],
'escaped context' => [$escaped, 'source', 'translation'],
];
}

public function testLoadWithManyContinuationLines(): void
{
$poFile = new GettextPoFile();
$filePath = Yii::getAlias('@yiiunit/runtime') . '/po-fragments-' . getmypid() . '.po';
$fragments = str_repeat('"a\n"' . "\n", 10000);
$content = 'msgid "before"' . "\n" . 'msgstr "First translation"' . "\n\n"
. 'msgid "source"' . "\n" . 'msgstr ""' . "\n" . $fragments . "\n"
. 'msgid "after"' . "\n" . 'msgstr "Last translation"' . "\n";
$expected = [
'before' => 'First translation',
'source' => str_repeat("a\n", 10000),
'after' => 'Last translation',
];

try {
file_put_contents($filePath, $content);
$loaded = $poFile->load($filePath, '');

$this->assertSame(array_keys($expected), array_keys($loaded));
$this->assertSame($expected, $loaded);
} finally {
unlink($filePath);
}
}

public function testLoadReportsRegexErrors(): void
{
$poFile = new GettextPoFile();
$limit = ini_set('pcre.backtrack_limit', '0');
$this->expectException(Exception::class);
$this->expectExceptionMessage('PCRE error ' . PREG_BACKTRACK_LIMIT_ERROR);

try {
$poFile->load(__DIR__ . '/../../data/i18n/test.po', 'context1');
} finally {
ini_set('pcre.backtrack_limit', $limit);
}
}

public function testDecodeReportsRegexErrors(): void
{
$poFile = new class extends GettextPoFile {
public function decode($string)
{
return parent::decode($string);
}
};
$limit = ini_set('pcre.backtrack_limit', '0');
$this->expectException(Exception::class);
$this->expectExceptionMessage('PCRE error ' . PREG_BACKTRACK_LIMIT_ERROR);

try {
$poFile->decode('"translation"');
} finally {
ini_set('pcre.backtrack_limit', $limit);
}
}

public function testLoadDoesNotLoseFollowingEntryAfterMalformedQuotedString(): void
{
$poFile = new GettextPoFile();
$filePath = Yii::getAlias('@yiiunit/runtime') . '/po-malformed-' . getmypid() . '.po';

$content = <<<'PO'
msgid "first"
msgstr "broken\"

msgid "valid"
msgstr "ok"
PO;
file_put_contents($filePath, $content . "\n");

$loaded = $poFile->load($filePath, '');

$this->assertSame(['valid' => 'ok'], $loaded);

unlink($filePath);
}
}
Loading