diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index d926b104e39..012c01358fb 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -38,6 +38,7 @@ 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 #21072: Use the full 64-bit keyspace for PostgreSQL advisory lock keys in `PgsqlMutex` (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) diff --git a/framework/i18n/GettextPoFile.php b/framework/i18n/GettextPoFile.php index ec1c02f826a..6619686d224 100644 --- a/framework/i18n/GettextPoFile.php +++ b/framework/i18n/GettextPoFile.php @@ -9,6 +9,7 @@ namespace yii\i18n; use Yii; +use yii\base\Exception; /** * GettextPoFile represents a PO Gettext message file. @@ -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+"(.*?(?decode($matches[2][$i]) === $context) { $id = $this->decode($matches[3][$i]); $message = $this->decode($matches[4][$i]); $messages[$id] = $message; @@ -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"; @@ -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 ); } @@ -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; } } diff --git a/tests/framework/i18n/GettextPoFileTest.php b/tests/framework/i18n/GettextPoFileTest.php index e7b913fb62b..396728d3b4d 100644 --- a/tests/framework/i18n/GettextPoFileTest.php +++ b/tests/framework/i18n/GettextPoFileTest.php @@ -9,7 +9,9 @@ namespace yiiunit\framework\i18n; use yii\i18n\GettextPoFile; +use yii\base\Exception; use yiiunit\TestCase; +use Yii; /** * @group i18n @@ -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)); @@ -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 @@ -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); + } }