I18nTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. use PrivateBin\I18n;
  4. use PrivateBin\Json;
  5. class I18nMock extends I18n
  6. {
  7. public static function resetAvailableLanguages()
  8. {
  9. self::$_availableLanguages = [];
  10. }
  11. public static function resetPath($path = '')
  12. {
  13. self::$_path = $path;
  14. }
  15. public static function getPath($file = '')
  16. {
  17. return self::_getPath($file);
  18. }
  19. }
  20. class I18nTest extends TestCase
  21. {
  22. private $_translations = [];
  23. public static function setUpBeforeClass(): void
  24. {
  25. parent::setUpBeforeClass();
  26. fwrite(
  27. STDERR,
  28. sprintf(
  29. "I18n tests: Intl extension loaded=%s; locale_accept_from_http exists=%s; ICU version=%s\n",
  30. extension_loaded('intl') ? 'yes' : 'no',
  31. function_exists('locale_accept_from_http') ? 'yes' : 'no',
  32. defined('INTL_ICU_VERSION') ? INTL_ICU_VERSION : 'none'
  33. )
  34. );
  35. }
  36. public function setUp(): void
  37. {
  38. /* Setup Routine */
  39. $this->_translations = json_decode(
  40. file_get_contents(PATH . 'i18n' . DIRECTORY_SEPARATOR . 'de.json'),
  41. true
  42. );
  43. }
  44. public function tearDown(): void
  45. {
  46. unset($_COOKIE['lang'], $_SERVER['HTTP_ACCEPT_LANGUAGE']);
  47. I18n::loadTranslations();
  48. }
  49. public function testTranslationFallback()
  50. {
  51. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'foobar';
  52. $messageId = 'It does not matter if the message ID exists';
  53. I18n::loadTranslations();
  54. $this->assertEquals($messageId, I18n::_($messageId), 'fallback to en');
  55. I18n::getLanguageLabels();
  56. }
  57. public function testCookieLanguageDeDetection()
  58. {
  59. $_COOKIE['lang'] = 'de';
  60. I18n::loadTranslations();
  61. $this->assertEquals($_COOKIE['lang'], I18n::getLanguage(), 'browser language de');
  62. $this->assertEquals('0 Stunden', I18n::_('%d hours', 0), '0 hours in German');
  63. $this->assertEquals('1 Stunde', I18n::_('%d hours', 1), '1 hour in German');
  64. $this->assertEquals('2 Stunden', I18n::_('%d hours', 2), '2 hours in German');
  65. }
  66. public function testBrowserLanguageDeDetection()
  67. {
  68. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'de-CH,de;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2,fr;q=0.0';
  69. I18n::loadTranslations();
  70. $this->assertEquals('de', I18n::getLanguage(), 'browser language de');
  71. $this->assertEquals('0 Stunden', I18n::_('%d hours', 0), '0 hours in German');
  72. $this->assertEquals('1 Stunde', I18n::_('%d hours', 1), '1 hour in German');
  73. $this->assertEquals('2 Stunden', I18n::_('%d hours', 2), '2 hours in German');
  74. }
  75. public function testBrowserLanguageFrDetection()
  76. {
  77. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr-CH,fr;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2,de;q=0.0';
  78. I18n::loadTranslations();
  79. $this->assertEquals('fr', I18n::getLanguage(), 'browser language fr');
  80. $this->assertEquals('0 heure', I18n::_('%d hours', 0), '0 hours in French');
  81. $this->assertEquals('1 heure', I18n::_('%d hours', 1), '1 hour in French');
  82. $this->assertEquals('2 heures', I18n::_('%d hours', 2), '2 hours in French');
  83. }
  84. /**
  85. * @dataProvider provideEqualQualityHeaders
  86. */
  87. public function testEqualQualityPreservesBrowserOrder($acceptedLanguage, $language)
  88. {
  89. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $acceptedLanguage;
  90. I18n::loadTranslations();
  91. $this->assertEquals($language, I18n::getLanguage(), 'browser language ' . $acceptedLanguage);
  92. }
  93. public function provideEqualQualityHeaders()
  94. {
  95. // ICU before version 67 sorts languages of equal quality alphabetically
  96. return [
  97. 'fr;q=0.8,de;q=0.8' => ['fr;q=0.8,de;q=0.8', 'fr'],
  98. 'fr,de' => ['fr,de', 'fr'],
  99. ];
  100. }
  101. /**
  102. * @dataProvider provideLanguagesUnknownToIcuHeaders
  103. */
  104. public function testBrowserLanguageUnknownToIcuDetection($acceptedLanguage, $language)
  105. {
  106. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $acceptedLanguage;
  107. I18n::loadTranslations();
  108. $this->assertEquals($language, I18n::getLanguage(), 'browser language ' . $acceptedLanguage);
  109. }
  110. public function provideLanguagesUnknownToIcuHeaders()
  111. {
  112. // ICU has no locale data for these languages, so it can only match the next one in the header
  113. return [
  114. 'co,fr;q=0.8' => ['co,fr;q=0.8', 'co'],
  115. 'jbo,de;q=0.8' => ['jbo,de;q=0.8', 'jbo'],
  116. 'la,it;q=0.8' => ['la,it;q=0.8', 'la'],
  117. ];
  118. }
  119. public function testBulgarianMonthExpirationTranslation()
  120. {
  121. $_COOKIE['lang'] = 'bg';
  122. I18n::loadTranslations();
  123. $this->assertEquals(
  124. 'Този документ изтича след един месец.',
  125. I18n::_('This document will expire in %d months.', 1)
  126. );
  127. $this->assertEquals(
  128. 'Този документ изтича след 2 месеца.',
  129. I18n::_('This document will expire in %d months.', 2)
  130. );
  131. }
  132. public function testBrowserLanguageLtDetection()
  133. {
  134. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'lt;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  135. I18n::loadTranslations();
  136. $this->assertEquals('lt', I18n::getLanguage(), 'browser language lt');
  137. $this->assertEquals('1 sekundę', I18n::_('%d seconds', 1), '1 second in Lithuanian');
  138. $this->assertEquals('2 sekundės', I18n::_('%d seconds', 2), '2 seconds in Lithuanian');
  139. $this->assertEquals('10 sekundžių', I18n::_('%d seconds', 10), '10 seconds in Lithuanian');
  140. $this->assertEquals('22 sekundės', I18n::_('%d seconds', 22), '22 seconds in Lithuanian');
  141. $this->assertEquals('110 sekundžių', I18n::_('%d seconds', 110), '110 seconds in Lithuanian');
  142. $this->assertEquals('111 sekundžių', I18n::_('%d seconds', 111), '111 seconds in Lithuanian');
  143. $this->assertEquals('120 sekundžių', I18n::_('%d seconds', 120), '120 seconds in Lithuanian');
  144. }
  145. public function testBrowserLanguageNoDetection()
  146. {
  147. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'no;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  148. I18n::loadTranslations();
  149. $this->assertEquals('no', I18n::getLanguage(), 'browser language no');
  150. $this->assertEquals('0 timer', I18n::_('%d hours', 0), '0 hours in Norwegian');
  151. $this->assertEquals('1 time', I18n::_('%d hours', 1), '1 hour in Norwegian');
  152. $this->assertEquals('2 timer', I18n::_('%d hours', 2), '2 hours in Norwegian');
  153. }
  154. public function testBrowserLanguageOcDetection()
  155. {
  156. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'oc;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  157. I18n::loadTranslations();
  158. $this->assertEquals('oc', I18n::getLanguage(), 'browser language oc');
  159. $this->assertEquals('0 ora', I18n::_('%d hours', 0), '0 hours in Occitan');
  160. $this->assertEquals('1 ora', I18n::_('%d hours', 1), '1 hour in Occitan');
  161. $this->assertEquals('2 oras', I18n::_('%d hours', 2), '2 hours in Occitan');
  162. }
  163. public function testBrowserLanguageZhDetection()
  164. {
  165. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'zh;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  166. I18n::loadTranslations();
  167. $this->assertEquals('zh', I18n::getLanguage(), 'browser language zh');
  168. $this->assertEquals('0 小时', I18n::_('%d hours', 0), '0 hours in Chinese');
  169. $this->assertEquals('1 小时', I18n::_('%d hours', 1), '1 hour in Chinese');
  170. $this->assertEquals('2 小时', I18n::_('%d hours', 2), '2 hours in Chinese');
  171. }
  172. public function testBrowserLanguageZhHantDetection()
  173. {
  174. foreach ([
  175. 'zh-Hant,zh;q=0.8,en;q=0.2' => 'zh-tw',
  176. 'zh-Hant-TW,zh;q=0.8,en;q=0.2' => 'zh-tw',
  177. 'zh-TW,en;q=0.2' => 'zh-tw',
  178. 'zh-TW-u-nu-hanidec,en;q=0.2' => 'zh-tw',
  179. 'zh-HK,zh;q=0.8,en;q=0.2' => 'zh-tw',
  180. 'zh-MO,zh;q=0.8,en;q=0.2' => 'zh-tw',
  181. 'zh-Hant,zh-Hans;q=0.8,en;q=0.2' => 'zh-tw',
  182. 'zh-CN,zh-Hant;q=0.8,en;q=0.2' => 'zh',
  183. 'zh-Hans,zh-Hant;q=0.8,en;q=0.2' => 'zh',
  184. 'zh-Hans-CN,en;q=0.2' => 'zh',
  185. 'zh;q=0.9,zh-Hant;q=0.8,en;q=0.2' => 'zh',
  186. ] as $acceptedLanguage => $language) {
  187. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $acceptedLanguage;
  188. I18n::loadTranslations();
  189. $this->assertEquals($language, I18n::getLanguage(), 'browser language ' . $acceptedLanguage);
  190. }
  191. }
  192. /**
  193. * @dataProvider provideTraditionalChineseWithZhFallbackHeaders
  194. */
  195. public function testBrowserLanguageZhHantWithZhFallbackDetection($acceptedLanguage, $language)
  196. {
  197. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $acceptedLanguage;
  198. I18n::loadTranslations();
  199. $this->assertEquals($language, I18n::getLanguage(), 'browser language ' . $acceptedLanguage);
  200. }
  201. public function provideTraditionalChineseWithZhFallbackHeaders()
  202. {
  203. // typical Chrome headers from Taiwan and Hong Kong, ICU before version 67
  204. // has zh_TW and zh_HK only as aliases, skips them and returns zh instead
  205. return [
  206. 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7' => ['zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'zh-tw'],
  207. 'zh-HK,zh;q=0.9,en;q=0.8' => ['zh-HK,zh;q=0.9,en;q=0.8', 'zh-tw'],
  208. ];
  209. }
  210. public function testBrowserLanguagePlDetection()
  211. {
  212. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'pl;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  213. I18n::loadTranslations();
  214. $this->assertEquals('pl', I18n::getLanguage(), 'browser language pl');
  215. $this->assertEquals('1 godzina', I18n::_('%d hours', 1), '1 hour in Polish');
  216. $this->assertEquals('2 godziny', I18n::_('%d hours', 2), '2 hours in Polish');
  217. $this->assertEquals('12 godzin', I18n::_('%d hours', 12), '12 hours in Polish');
  218. $this->assertEquals('22 godziny', I18n::_('%d hours', 22), '22 hours in Polish');
  219. $this->assertEquals('1 minuta', I18n::_('%d minutes', 1), '1 minute in Polish');
  220. $this->assertEquals('3 minuty', I18n::_('%d minutes', 3), '3 minutes in Polish');
  221. $this->assertEquals('13 minut', I18n::_('%d minutes', 13), '13 minutes in Polish');
  222. $this->assertEquals('23 minuty', I18n::_('%d minutes', 23), '23 minutes in Polish');
  223. }
  224. public function testBrowserLanguageRuDetection()
  225. {
  226. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'ru;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  227. I18n::loadTranslations();
  228. $this->assertEquals('ru', I18n::getLanguage(), 'browser language ru');
  229. $this->assertEquals('1 минуту', I18n::_('%d minutes', 1), '1 minute in Russian');
  230. $this->assertEquals('3 минуты', I18n::_('%d minutes', 3), '3 minutes in Russian');
  231. $this->assertEquals('10 минут', I18n::_('%d minutes', 10), '10 minutes in Russian');
  232. $this->assertEquals('21 минуту', I18n::_('%d minutes', 21), '21 minutes in Russian');
  233. }
  234. public function testBrowserLanguageSlDetection()
  235. {
  236. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'sl;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  237. I18n::loadTranslations();
  238. $this->assertEquals('sl', I18n::getLanguage(), 'browser language sl');
  239. $this->assertEquals('0 ur', I18n::_('%d hours', 0), '0 hours in Slovene');
  240. $this->assertEquals('1 ura', I18n::_('%d hours', 1), '1 hour in Slovene');
  241. $this->assertEquals('2 uri', I18n::_('%d hours', 2), '2 hours in Slovene');
  242. $this->assertEquals('3 ure', I18n::_('%d hours', 3), '3 hours in Slovene');
  243. $this->assertEquals('11 ur', I18n::_('%d hours', 11), '11 hours in Slovene');
  244. $this->assertEquals('101 ura', I18n::_('%d hours', 101), '101 hours in Slovene');
  245. $this->assertEquals('102 uri', I18n::_('%d hours', 102), '102 hours in Slovene');
  246. $this->assertEquals('104 ure', I18n::_('%d hours', 104), '104 hours in Slovene');
  247. }
  248. public function testBrowserLanguageCsDetection()
  249. {
  250. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'cs;q=0.8,en-GB;q=0.6,en-US;q=0.4,en;q=0.2';
  251. I18n::loadTranslations();
  252. $this->assertEquals('cs', I18n::getLanguage(), 'browser language cs');
  253. $this->assertEquals('1 hodina', I18n::_('%d hours', 1), '1 hour in Czech');
  254. $this->assertEquals('2 hodiny', I18n::_('%d hours', 2), '2 hours in Czech');
  255. $this->assertEquals('5 minut', I18n::_('%d minutes', 5), '5 minutes in Czech');
  256. $this->assertEquals('14 minut', I18n::_('%d minutes', 14), '14 minutes in Czech');
  257. }
  258. public function testInvalidBrowserLanguageQualityIsIgnored()
  259. {
  260. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'de;q=2,en;q=0.8';
  261. $this->assertSame(['0.8' => ['en']], I18n::getBrowserLanguages());
  262. }
  263. public function testBrowserLanguageAnyDetection()
  264. {
  265. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = '*';
  266. I18n::loadTranslations();
  267. $this->assertTrue(strlen(I18n::getLanguage()) >= 2, 'browser language any');
  268. }
  269. public function testVariableInjection()
  270. {
  271. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'foobar';
  272. I18n::loadTranslations();
  273. $this->assertEquals('some string + 1', I18n::_('some %s + %d', 'string', 1), 'browser language en');
  274. }
  275. public function testHtmlEntityEncoding()
  276. {
  277. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'foobar';
  278. I18n::loadTranslations();
  279. $input = '&<>"\'/`=';
  280. $result = htmlspecialchars($input, ENT_QUOTES | ENT_HTML5 | ENT_DISALLOWED, 'UTF-8', false);
  281. $this->assertEquals($result, I18n::encode($input), 'encodes HTML entities');
  282. $this->assertEquals('<a>some ' . $result . ' + 1</a>', I18n::_('<a>some %s + %d</a>', $input, 1), 'encodes parameters in translations');
  283. // Message ID should NOT be encoded (it comes from trusted source), only the parameter should be
  284. $this->assertEquals($input . $result, I18n::_($input . '%s', $input), 'encodes only parameters, not message ID');
  285. }
  286. public function testApostropheEncodngInMessage()
  287. {
  288. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr';
  289. I18n::loadTranslations();
  290. // For example, the French translation should not have the apostrophe encoded
  291. // See https://github.com/PrivateBin/PrivateBin/issues/1712
  292. $message = I18n::_('Document does not exist, has expired or has been deleted.');
  293. $this->assertFalse(str_contains($message, '&apos;'), 'French apostrophe should not be encoded in translation message');
  294. $this->assertTrue(str_contains($message, "n'existe"), 'French apostrophe should be present as literal character');
  295. }
  296. public function testFallbackAlwaysPresent()
  297. {
  298. $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_i18n';
  299. if (!is_dir($path)) {
  300. mkdir($path);
  301. }
  302. $languageIterator = new AppendIterator();
  303. $languageIterator->append(new GlobIterator(I18nMock::getPath('??.json')));
  304. $languageIterator->append(new GlobIterator(I18nMock::getPath('???.json'))); // for jbo
  305. $languageIterator->append(new GlobIterator(I18nMock::getPath('??-??.json'))); // for regional variants like zh-tw
  306. $languageCount = 0;
  307. foreach ($languageIterator as $file) {
  308. ++$languageCount;
  309. $this->assertTrue(copy($file->getPathname(), $path . DIRECTORY_SEPARATOR . $file->getBasename()));
  310. }
  311. I18nMock::resetPath($path);
  312. $languagesDevelopment = I18nMock::getAvailableLanguages();
  313. $this->assertEquals($languageCount, count($languagesDevelopment), 'all copied languages detected');
  314. $this->assertTrue(in_array('en', $languagesDevelopment), 'English fallback present');
  315. unlink($path . DIRECTORY_SEPARATOR . 'en.json');
  316. I18nMock::resetAvailableLanguages();
  317. $languagesDeployed = I18nMock::getAvailableLanguages();
  318. $this->assertEquals($languageCount, count($languagesDeployed), 'all copied languages detected, plus fallback');
  319. $this->assertTrue(in_array('en', $languagesDeployed), 'English fallback still present');
  320. I18nMock::resetAvailableLanguages();
  321. I18nMock::resetPath();
  322. Helper::rmDir($path);
  323. }
  324. public function testGetCopyHotkey()
  325. {
  326. $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)';
  327. $this->assertEquals('Cmd', I18n::getCopyHotkey(), 'returns Cmd on macOS');
  328. $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)';
  329. $this->assertEquals('Ctrl', I18n::getCopyHotkey(), 'returns Ctrl on Windows');
  330. $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (X11; Linux x86_64)';
  331. $this->assertEquals('Ctrl', I18n::getCopyHotkey(), 'returns Ctrl on Linux');
  332. unset($_SERVER['HTTP_USER_AGENT']);
  333. $this->assertEquals('Ctrl', I18n::getCopyHotkey(), 'returns Ctrl when user agent absent');
  334. }
  335. public function testRightToLeftLanguages()
  336. {
  337. foreach (['ar', 'fa', 'he'] as $language) {
  338. $_COOKIE['lang'] = $language;
  339. I18n::loadTranslations();
  340. $this->assertTrue(I18n::isRtl(), "$language is right-to-left");
  341. }
  342. $_COOKIE['lang'] = 'en';
  343. I18n::loadTranslations();
  344. $this->assertFalse(I18n::isRtl(), 'English is left-to-right');
  345. }
  346. public function testMessageIdsExistInAllLanguages()
  347. {
  348. $messageIds = [];
  349. $languages = [];
  350. foreach (new DirectoryIterator(PATH . 'i18n') as $file) {
  351. $fileNameLength = strlen($file->getFilename());
  352. if ($fileNameLength === 7) { // xx.json
  353. $language = substr($file->getFilename(), 0, 2);
  354. } elseif ($fileNameLength === 8) { // jbo.json
  355. $language = substr($file->getFilename(), 0, 3);
  356. } elseif ($fileNameLength === 10) { // xx-xx.json
  357. $language = substr($file->getFilename(), 0, 5);
  358. } else {
  359. continue;
  360. }
  361. $languageJson = file_get_contents($file->getPathname());
  362. $languageMessageIds = array_keys(Json::decode($languageJson));
  363. $messageIds = array_unique(array_merge($messageIds, $languageMessageIds));
  364. $languages[$language] = $languageMessageIds;
  365. }
  366. foreach ($messageIds as $messageId) {
  367. foreach (array_keys($languages) as $language) {
  368. // most languages don't translate the data size units, ignore those
  369. if ($messageId !== 'B' && strlen($messageId) !== 3 && strpos($messageId, 'B', 2) !== 2) {
  370. $this->assertContains(
  371. $messageId,
  372. $languages[$language],
  373. "message ID '$messageId' exists in translation file $language.json"
  374. );
  375. }
  376. }
  377. }
  378. }
  379. }