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
6 changes: 6 additions & 0 deletions scripts/validate-translations.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use App\Support\Translation\TranslationMarkupValidator;
use App\Support\Translation\TranslationTemplateSyntaxValidator;
use LibreSign\JigsawLocalization\Catalog\JsonTranslationCatalog;
use LibreSign\JigsawLocalization\Catalog\TranslationCatalogValidator;
Expand All @@ -13,6 +14,7 @@
$source = (new JsonTranslationCatalog($sourcePath))->read();
$validator = new TranslationCatalogValidator();
$templateSyntaxValidator = new TranslationTemplateSyntaxValidator();
$markupValidator = new TranslationMarkupValidator();
$errors = [];

if (in_array('--canonical-source', $argv, true)) {
Expand All @@ -35,6 +37,10 @@
foreach ($templateSyntaxValidator->validate($source, $translation) as $error) {
$errors[] = "{$locale}: {$error}";
}

foreach ($markupValidator->validate($source, $translation) as $error) {
$errors[] = "{$locale}: {$error}";
}
}

if ($errors === []) {
Expand Down
4 changes: 2 additions & 2 deletions source/_layouts/post_base.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@
@endif
<span>
@php
$author = '<a href="' . locale_url($page, $authorPath($page->author)) . '"> ' . $page->author . '</a>';
$author = '<a href="' . e(locale_url($page, $authorPath($page->author))) . '"> ' . e($page->author) . '</a>';
@endphp
{!! $page->t("By %s", [$author]) !!}
{!! vsprintf(e($page->t('By %s')), [$author]) !!}
</span>
</div>

Expand Down
2 changes: 1 addition & 1 deletion source/faq.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class="ud-faq-btn collapsed"
</button>
<div id="faq-item-{{ $item }}" class="accordion-collapse collapse">
<div class="ud-faq-body">
{!! $page->t($frequentlyQuestion->answer)!!}
{!! \App\Support\Translation\TranslatedHtmlSanitizer::sanitize($page->t($frequentlyQuestion->answer)) !!}
</div>
</div>
</div>
Expand Down
27 changes: 27 additions & 0 deletions support/Translation/TranslatedHtmlSanitizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace App\Support\Translation;

final class TranslatedHtmlSanitizer
{
public static function sanitize(string $translatedHtml): string
{
$escapedHtml = htmlspecialchars($translatedHtml, ENT_QUOTES, 'UTF-8', false);

return preg_replace(
[
'/&lt;a href=&quot;(https:\/\/[^\s&]+)&quot;&gt;/',
'/&lt;\/a&gt;/',
'/&lt;(\/?)(strong|em)&gt;/',
],
[
'<a href="$1">',
'</a>',
'<$1$2>',
],
$escapedHtml,
);
}
}
64 changes: 64 additions & 0 deletions support/Translation/TranslationMarkupValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

declare(strict_types=1);

namespace App\Support\Translation;

final class TranslationMarkupValidator
{
private const HTML_TAG_PATTERN = '/<\/?([A-Za-z][\w-]*)((?:[^>"\']|"[^"]*"|\'[^\']*\')*)>/';
private const HTML_ATTRIBUTE_PATTERN = '/([A-Za-z_:@][-\w:.]*)\s*(?:=\s*(?:"[^"]*"|\'[^\']*\'|[^\s>]+))?/';

/**
* @param array<string, string> $source
* @param array<string, string> $translation
* @return list<string>
*/
public function validate(array $source, array $translation): array
{
$errors = [];

foreach ($translation as $key => $translatedText) {
if (!array_key_exists($key, $source)) {
continue;
}

$sourceMarkup = $this->markup($source[$key]);
$translatedMarkup = $this->markup($translatedText);
if ($sourceMarkup === $translatedMarkup) {
continue;
}

$errors[] = sprintf(
'HTML markup mismatch in translation of "%s": expected [%s], got [%s].',
strtok($key, "\n"),
implode(', ', $sourceMarkup),
implode(', ', $translatedMarkup),
);
}

return $errors;
}

/**
* @return list<string>
*/
private function markup(string $text): array
{
$markup = [];
preg_match_all(self::HTML_TAG_PATTERN, $text, $tags, PREG_SET_ORDER);
foreach ($tags as [, $tagName, $attributes]) {
$tagName = strtolower($tagName);
$markup[] = $tagName;
preg_match_all(self::HTML_ATTRIBUTE_PATTERN, $attributes, $attributeMatches);
foreach ($attributeMatches[1] as $attributeName) {
$markup[] = $tagName . '[' . strtolower($attributeName) . ']';
}
}

$markup = array_values(array_unique($markup));
sort($markup);

return $markup;
}
}
47 changes: 47 additions & 0 deletions tests/Unit/Support/Translation/TranslatedHtmlSanitizerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

namespace Tests\Unit\Support\Translation;

use App\Support\Translation\TranslatedHtmlSanitizer;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

final class TranslatedHtmlSanitizerTest extends TestCase
{
#[DataProvider('translatedHtmlProvider')]
public function testKeepsOnlyBasicMarkup(string $translatedHtml, string $expectedHtml): void
{
self::assertSame($expectedHtml, TranslatedHtmlSanitizer::sanitize($translatedHtml));
}

public static function translatedHtmlProvider(): iterable
{
yield 'HTTPS link' => [
'Code on <a href="https://github.com/LibreSign/libresign">GitHub</a>.',
'Code on <a href="https://github.com/LibreSign/libresign">GitHub</a>.',
];

yield 'emphasis' => ['<strong>Yes</strong>, <em>free</em>.', '<strong>Yes</strong>, <em>free</em>.'];

yield 'image with event handler' => [
'Oui <img src=x onerror="alert(1)">',
'Oui &lt;img src=x onerror=&quot;alert(1)&quot;&gt;',
];

yield 'script tag' => ['<script>alert(1)</script>', '&lt;script&gt;alert(1)&lt;/script&gt;'];

yield 'link with extra attribute' => [
'<a href="https://example.org" onclick="alert(1)">x</a>',
'&lt;a href=&quot;https://example.org&quot; onclick=&quot;alert(1)&quot;&gt;x</a>',
];

yield 'javascript link' => [
'<a href="javascript:alert(1)">x</a>',
'&lt;a href=&quot;javascript:alert(1)&quot;&gt;x</a>',
];

yield 'existing entity' => ['Q&amp;A', 'Q&amp;A'];
}
}
46 changes: 46 additions & 0 deletions tests/Unit/Support/Translation/TranslationMarkupValidatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace Tests\Unit\Support\Translation;

use App\Support\Translation\TranslationMarkupValidator;
use PHPUnit\Framework\TestCase;

final class TranslationMarkupValidatorTest extends TestCase
{
public function testAcceptsTranslationWithSameMarkup(): void
{
$source = "Code on <a href=\"https://github.com/LibreSign/libresign\">GitHub</a>.\n\n<div style=\"text-align: center;\">\n <img src=\"image.png\" alt=\"Settings\">\n</div>";
$translation = "Código no <a href=\"https://github.com/LibreSign/libresign\">GitHub</a>.\n\n<div style=\"text-align: center;\">\n <img src=\"image.png\" alt=\"Configurações\">\n</div>";

self::assertSame([], (new TranslationMarkupValidator())->validate([$source => $source], [$source => $translation]));
}

public function testRejectsTagMissingFromSource(): void
{
$source = "## Post title\n\nPost body.";
$translation = "## Titre\n\nTexte <img src=x>";

self::assertSame(
['HTML markup mismatch in translation of "## Post title": expected [], got [img, img[src]].'],
(new TranslationMarkupValidator())->validate([$source => $source], [$source => $translation]),
);
}

public function testRejectsAttributeMissingFromSource(): void
{
$source = 'See <a href="https://libresign.coop">the site</a>.';
$translation = 'Voir <a href="https://libresign.coop" onclick="alert(1)">le site</a>.';

self::assertSame(
['HTML markup mismatch in translation of "See <a href="https://libresign.coop">the site</a>.": expected [a, a[href]], got [a, a[href], a[onclick]].'],
(new TranslationMarkupValidator())->validate([$source => $source], [$source => $translation]),
);
}

public function testIgnoresKeysMissingFromSource(): void
{
self::assertSame([], (new TranslationMarkupValidator())->validate([], ['Removed' => '<script>']));
}
}
Loading