1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2021 webtrees development team 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <https://www.gnu.org/licenses/>. 16 */ 17 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees; 21 22use Closure; 23use Collator; 24use Exception; 25use Fisharebest\Localization\Locale; 26use Fisharebest\Localization\Locale\LocaleEnUs; 27use Fisharebest\Localization\Locale\LocaleInterface; 28use Fisharebest\Localization\Translation; 29use Fisharebest\Localization\Translator; 30use Fisharebest\Webtrees\Module\ModuleCustomInterface; 31use Fisharebest\Webtrees\Module\ModuleLanguageInterface; 32use Fisharebest\Webtrees\Services\ModuleService; 33 34use function array_merge; 35use function class_exists; 36use function html_entity_decode; 37use function in_array; 38use function mb_strtolower; 39use function mb_strtoupper; 40use function mb_substr; 41use function ord; 42use function sprintf; 43use function str_contains; 44use function str_replace; 45use function strcmp; 46use function strip_tags; 47use function strlen; 48use function strtr; 49use function var_export; 50 51/** 52 * Internationalization (i18n) and localization (l10n). 53 */ 54class I18N 55{ 56 // MO files use special characters for plurals and context. 57 public const PLURAL = "\x00"; 58 public const CONTEXT = "\x04"; 59 60 // Digits are always rendered LTR, even in RTL text. 61 private const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹'; 62 63 // These locales need special handling for the dotless letter I. 64 private const DOTLESS_I_LOCALES = [ 65 'az', 66 'tr', 67 ]; 68 69 private const DOTLESS_I_TOLOWER = [ 70 'I' => 'ı', 71 'İ' => 'i', 72 ]; 73 74 private const DOTLESS_I_TOUPPER = [ 75 'ı' => 'I', 76 'i' => 'İ', 77 ]; 78 79 // The ranges of characters used by each script. 80 private const SCRIPT_CHARACTER_RANGES = [ 81 [ 82 'Latn', 83 0x0041, 84 0x005A, 85 ], 86 [ 87 'Latn', 88 0x0061, 89 0x007A, 90 ], 91 [ 92 'Latn', 93 0x0100, 94 0x02AF, 95 ], 96 [ 97 'Grek', 98 0x0370, 99 0x03FF, 100 ], 101 [ 102 'Cyrl', 103 0x0400, 104 0x052F, 105 ], 106 [ 107 'Hebr', 108 0x0590, 109 0x05FF, 110 ], 111 [ 112 'Arab', 113 0x0600, 114 0x06FF, 115 ], 116 [ 117 'Arab', 118 0x0750, 119 0x077F, 120 ], 121 [ 122 'Arab', 123 0x08A0, 124 0x08FF, 125 ], 126 [ 127 'Deva', 128 0x0900, 129 0x097F, 130 ], 131 [ 132 'Taml', 133 0x0B80, 134 0x0BFF, 135 ], 136 [ 137 'Sinh', 138 0x0D80, 139 0x0DFF, 140 ], 141 [ 142 'Thai', 143 0x0E00, 144 0x0E7F, 145 ], 146 [ 147 'Geor', 148 0x10A0, 149 0x10FF, 150 ], 151 [ 152 'Grek', 153 0x1F00, 154 0x1FFF, 155 ], 156 [ 157 'Deva', 158 0xA8E0, 159 0xA8FF, 160 ], 161 [ 162 'Hans', 163 0x3000, 164 0x303F, 165 ], 166 // Mixed CJK, not just Hans 167 [ 168 'Hans', 169 0x3400, 170 0xFAFF, 171 ], 172 // Mixed CJK, not just Hans 173 [ 174 'Hans', 175 0x20000, 176 0x2FA1F, 177 ], 178 // Mixed CJK, not just Hans 179 ]; 180 181 // Characters that are displayed in mirror form in RTL text. 182 private const MIRROR_CHARACTERS = [ 183 '(' => ')', 184 ')' => '(', 185 '[' => ']', 186 ']' => '[', 187 '{' => '}', 188 '}' => '{', 189 '<' => '>', 190 '>' => '<', 191 '‹ ' => '›', 192 '› ' => '‹', 193 '«' => '»', 194 '»' => '«', 195 '﴾ ' => '﴿', 196 '﴿ ' => '﴾', 197 '“ ' => '”', 198 '” ' => '“', 199 '‘ ' => '’', 200 '’ ' => '‘', 201 ]; 202 203 // Punctuation used to separate list items, typically a comma 204 public static string $list_separator; 205 206 private static ?ModuleLanguageInterface $language; 207 208 private static LocaleInterface $locale; 209 210 private static Translator $translator; 211 212 private static ?Collator $collator = null; 213 214 /** 215 * The preferred locales for this site, or a default list if no preference. 216 * 217 * @return array<LocaleInterface> 218 */ 219 public static function activeLocales(): array 220 { 221 $locales = app(ModuleService::class) 222 ->findByInterface(ModuleLanguageInterface::class, false, true) 223 ->map(static function (ModuleLanguageInterface $module): LocaleInterface { 224 return $module->locale(); 225 }); 226 227 if ($locales->isEmpty()) { 228 return [new LocaleEnUs()]; 229 } 230 231 return $locales->all(); 232 } 233 234 /** 235 * Which MySQL collation should be used for this locale? 236 * 237 * @return string 238 */ 239 public static function collation(): string 240 { 241 $collation = self::$locale->collation(); 242 switch ($collation) { 243 case 'croatian_ci': 244 case 'german2_ci': 245 case 'vietnamese_ci': 246 // Only available in MySQL 5.6 247 return 'utf8_unicode_ci'; 248 default: 249 return 'utf8_' . $collation; 250 } 251 } 252 253 /** 254 * What format is used to display dates in the current locale? 255 * 256 * @return string 257 */ 258 public static function dateFormat(): string 259 { 260 /* I18N: This is the format string for full dates. See https://php.net/date for codes */ 261 return self::$translator->translate('%j %F %Y'); 262 } 263 264 /** 265 * Convert the digits 0-9 into the local script 266 * Used for years, etc., where we do not want thousands-separators, decimals, etc. 267 * 268 * @param string|int $n 269 * 270 * @return string 271 */ 272 public static function digits($n): string 273 { 274 return self::$locale->digits((string) $n); 275 } 276 277 /** 278 * What is the direction of the current locale 279 * 280 * @return string "ltr" or "rtl" 281 */ 282 public static function direction(): string 283 { 284 return self::$locale->direction(); 285 } 286 287 /** 288 * Initialise the translation adapter with a locale setting. 289 * 290 * @param string $code 291 * @param bool $setup 292 * 293 * @return void 294 */ 295 public static function init(string $code, bool $setup = false): void 296 { 297 self::$locale = Locale::create($code); 298 299 // Load the translation file 300 $translation_file = __DIR__ . '/../resources/lang/' . self::$locale->languageTag() . '/messages.php'; 301 302 try { 303 $translation = new Translation($translation_file); 304 $translations = $translation->asArray(); 305 } catch (Exception $ex) { 306 // The translations files are created during the build process, and are 307 // not included in the source code. 308 // Assuming we are using dev code, and build (or rebuild) the files. 309 $po_file = Webtrees::ROOT_DIR . 'resources/lang/' . self::$locale->languageTag() . '/messages.po'; 310 $translation = new Translation($po_file); 311 $translations = $translation->asArray(); 312 file_put_contents($translation_file, "<?php\n\nreturn " . var_export($translations, true) . ";\n"); 313 } 314 315 // Add translations from custom modules (but not during setup, as we have no database/modules) 316 if (!$setup) { 317 $module_service = app(ModuleService::class); 318 319 $translations = $module_service 320 ->findByInterface(ModuleCustomInterface::class) 321 ->reduce(static function (array $carry, ModuleCustomInterface $item): array { 322 return array_merge($carry, $item->customTranslations(self::$locale->languageTag())); 323 }, $translations); 324 325 self::$language = $module_service 326 ->findByInterface(ModuleLanguageInterface::class) 327 ->first(fn (ModuleLanguageInterface $module): bool => $module->locale()->languageTag() === $code); 328 } 329 330 // Create a translator 331 self::$translator = new Translator($translations, self::$locale->pluralRule()); 332 333 /* I18N: This punctuation is used to separate lists of items */ 334 self::$list_separator = self::translate(', '); 335 336 // Create a collator 337 try { 338 if (class_exists('Collator')) { 339 // Symfony provides a very incomplete polyfill - which cannot be used. 340 self::$collator = new Collator(self::$locale->code()); 341 // Ignore upper/lower case differences 342 self::$collator->setStrength(Collator::SECONDARY); 343 } 344 } catch (Exception $ex) { 345 // PHP-INTL is not installed? We'll use a fallback later. 346 } 347 } 348 349 /** 350 * Translate a string, and then substitute placeholders 351 * echo I18N::translate('Hello World!'); 352 * echo I18N::translate('The %s sat on the mat', 'cat'); 353 * 354 * @param string $message 355 * @param string ...$args 356 * 357 * @return string 358 */ 359 public static function translate(string $message, ...$args): string 360 { 361 $message = self::$translator->translate($message); 362 363 return sprintf($message, ...$args); 364 } 365 366 /** 367 * @return string 368 */ 369 public static function languageTag(): string 370 { 371 return self::$locale->languageTag(); 372 } 373 374 /** 375 * @return LocaleInterface 376 */ 377 public static function locale(): LocaleInterface 378 { 379 return self::$locale; 380 } 381 382 /** 383 * @return ModuleLanguageInterface 384 */ 385 public static function language(): ModuleLanguageInterface 386 { 387 return self::$language; 388 } 389 390 /** 391 * Translate a number into the local representation. 392 * e.g. 12345.67 becomes 393 * en: 12,345.67 394 * fr: 12 345,67 395 * de: 12.345,67 396 * 397 * @param float $n 398 * @param int $precision 399 * 400 * @return string 401 */ 402 public static function number(float $n, int $precision = 0): string 403 { 404 return self::$locale->number(round($n, $precision)); 405 } 406 407 /** 408 * Translate a fraction into a percentage. 409 * e.g. 0.123 becomes 410 * en: 12.3% 411 * fr: 12,3 % 412 * de: 12,3% 413 * 414 * @param float $n 415 * @param int $precision 416 * 417 * @return string 418 */ 419 public static function percentage(float $n, int $precision = 0): string 420 { 421 return self::$locale->percent(round($n, $precision + 2)); 422 } 423 424 /** 425 * Translate a plural string 426 * echo self::plural('There is an error', 'There are errors', $num_errors); 427 * echo self::plural('There is one error', 'There are %s errors', $num_errors); 428 * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour); 429 * 430 * @param string $singular 431 * @param string $plural 432 * @param int $count 433 * @param string ...$args 434 * 435 * @return string 436 */ 437 public static function plural(string $singular, string $plural, int $count, ...$args): string 438 { 439 $message = self::$translator->translatePlural($singular, $plural, $count); 440 441 return sprintf($message, ...$args); 442 } 443 444 /** 445 * UTF8 version of PHP::strrev() 446 * Reverse RTL text for third-party libraries such as GD2 and googlechart. 447 * These do not support UTF8 text direction, so we must mimic it for them. 448 * Numbers are always rendered LTR, even in RTL text. 449 * The visual direction of characters such as parentheses should be reversed. 450 * 451 * @param string $text Text to be reversed 452 * 453 * @return string 454 */ 455 public static function reverseText(string $text): string 456 { 457 // Remove HTML markup - we can't display it and it is LTR. 458 $text = strip_tags($text); 459 // Remove HTML entities. 460 $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); 461 462 // LTR text doesn't need reversing 463 if (self::scriptDirection(self::textScript($text)) === 'ltr') { 464 return $text; 465 } 466 467 // Mirrored characters 468 $text = strtr($text, self::MIRROR_CHARACTERS); 469 470 $reversed = ''; 471 $digits = ''; 472 while ($text !== '') { 473 $letter = mb_substr($text, 0, 1); 474 $text = mb_substr($text, 1); 475 if (str_contains(self::DIGITS, $letter)) { 476 $digits .= $letter; 477 } else { 478 $reversed = $letter . $digits . $reversed; 479 $digits = ''; 480 } 481 } 482 483 return $digits . $reversed; 484 } 485 486 /** 487 * Return the direction (ltr or rtl) for a given script 488 * The PHP/intl library does not provde this information, so we need 489 * our own lookup table. 490 * 491 * @param string $script 492 * 493 * @return string 494 */ 495 public static function scriptDirection(string $script): string 496 { 497 switch ($script) { 498 case 'Arab': 499 case 'Hebr': 500 case 'Mong': 501 case 'Thaa': 502 return 'rtl'; 503 default: 504 return 'ltr'; 505 } 506 } 507 508 /** 509 * Identify the script used for a piece of text 510 * 511 * @param string $string 512 * 513 * @return string 514 */ 515 public static function textScript(string $string): string 516 { 517 $string = strip_tags($string); // otherwise HTML tags show up as latin 518 $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin 519 $string = str_replace([ 520 Individual::NOMEN_NESCIO, 521 Individual::PRAENOMEN_NESCIO, 522 ], '', $string); 523 $pos = 0; 524 $strlen = strlen($string); 525 while ($pos < $strlen) { 526 // get the Unicode Code Point for the character at position $pos 527 $byte1 = ord($string[$pos]); 528 if ($byte1 < 0x80) { 529 $code_point = $byte1; 530 $chrlen = 1; 531 } elseif ($byte1 < 0xC0) { 532 // Invalid continuation character 533 return 'Latn'; 534 } elseif ($byte1 < 0xE0) { 535 $code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F); 536 $chrlen = 2; 537 } elseif ($byte1 < 0xF0) { 538 $code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F); 539 $chrlen = 3; 540 } elseif ($byte1 < 0xF8) { 541 $code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F); 542 $chrlen = 3; 543 } else { 544 // Invalid UTF 545 return 'Latn'; 546 } 547 548 foreach (self::SCRIPT_CHARACTER_RANGES as $range) { 549 if ($code_point >= $range[1] && $code_point <= $range[2]) { 550 return $range[0]; 551 } 552 } 553 // Not a recognised script. Maybe punctuation, spacing, etc. Keep looking. 554 $pos += $chrlen; 555 } 556 557 return 'Latn'; 558 } 559 560 /** 561 * A closure which will compare strings using local collation rules. 562 * 563 * @return Closure 564 */ 565 public static function comparator(): Closure 566 { 567 if (self::$collator instanceof Collator) { 568 return static fn (string $x, string $y): int => (int) self::$collator->compare($x, $y); 569 } 570 571 return static fn (string $x, string $y): int => strcmp(self::strtolower($x), self::strtolower($y)); 572 } 573 574 575 576 /** 577 * Convert a string to lower case. 578 * 579 * @param string $string 580 * 581 * @return string 582 */ 583 public static function strtolower(string $string): string 584 { 585 if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES, true)) { 586 $string = strtr($string, self::DOTLESS_I_TOLOWER); 587 } 588 589 return mb_strtolower($string); 590 } 591 592 /** 593 * Convert a string to upper case. 594 * 595 * @param string $string 596 * 597 * @return string 598 */ 599 public static function strtoupper(string $string): string 600 { 601 if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES, true)) { 602 $string = strtr($string, self::DOTLESS_I_TOUPPER); 603 } 604 605 return mb_strtoupper($string); 606 } 607 608 /** 609 * What format is used to display dates in the current locale? 610 * 611 * @return string 612 */ 613 public static function timeFormat(): string 614 { 615 /* I18N: This is the format string for the time-of-day. See https://php.net/date for codes */ 616 return self::$translator->translate('%H:%i:%s'); 617 } 618 619 /** 620 * Context sensitive version of translate. 621 * echo I18N::translateContext('NOMINATIVE', 'January'); 622 * echo I18N::translateContext('GENITIVE', 'January'); 623 * 624 * @param string $context 625 * @param string $message 626 * @param string ...$args 627 * 628 * @return string 629 */ 630 public static function translateContext(string $context, string $message, ...$args): string 631 { 632 $message = self::$translator->translateContext($context, $message); 633 634 return sprintf($message, ...$args); 635 } 636} 637