LocaleStringIsSafeTest.php in Drupal 8
File
core/modules/locale/tests/src/Kernel/LocaleStringIsSafeTest.php
View source
<?php
namespace Drupal\Tests\locale\Kernel;
use Drupal\KernelTests\KernelTestBase;
class LocaleStringIsSafeTest extends KernelTestBase {
public static $modules = [
'locale',
'locale_test',
];
public function testLocaleStringIsSafe() {
$string = 'Hello world!';
$result = locale_string_is_safe($string);
$this
->assertTrue($result);
$string = 'Hello <strong>world</strong>!';
$result = locale_string_is_safe($string);
$this
->assertTrue($result);
$string = 'Hello <img src="world.png" alt="world" />!';
$result = locale_string_is_safe($string);
$this
->assertFalse($result);
$string = 'Hi <a href="[current-user:url]">user</a>';
$result = locale_string_is_safe($string);
$this
->assertTrue($result);
}
public function testLocalizedTokenizedString() {
$tests_to_do = [
1 => [
'original' => 'Go to the <a href="[locale_test:security_test1]">frontpage</a>',
'replaced' => 'Go to the <a href="javascript:alert(&#039;Mooooh!&#039;);">frontpage</a>',
],
2 => [
'original' => 'Hello <strong>[locale_test:security_test2]</strong>!',
'replaced' => 'Hello <strong>&lt;script&gt;alert(&#039;Mooooh!&#039;);&lt;/script&gt;</strong>!',
],
];
foreach ($tests_to_do as $i => $test) {
$original_string = $test['original'];
$rendered_original_string = \Drupal::theme()
->render('locale_test_tokenized', [
'content' => $original_string,
]);
$this
->assertNotEqual($rendered_original_string, $original_string . "\n", 'Security test ' . $i . ' before translation');
$safe_string = t($original_string);
$rendered_safe_string = \Drupal::theme()
->render('locale_test_tokenized', [
'content' => $safe_string,
]);
$this
->assertEqual($rendered_safe_string, $original_string . "\n", 'Security test ' . $i . ' after translation before token replacement');
$unsafe_string = \Drupal::token()
->replace($safe_string);
$rendered_unsafe_string = \Drupal::theme()
->render('locale_test_tokenized', [
'content' => $unsafe_string,
]);
$this
->assertEqual($rendered_unsafe_string, $test['replaced'] . "\n", 'Security test ' . $i . ' after translation after token replacement');
}
}
}