1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2023 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 = Registry::container()->get(ModuleService::class) 222 ->findByInterface(ModuleLanguageInterface::class, false, true) 223 ->map(static fn(ModuleLanguageInterface $module): LocaleInterface => $module->locale()); 224 225 if ($locales->isEmpty()) { 226 return [new LocaleEnUs()]; 227 } 228 229 return $locales->all(); 230 } 231 232 /** 233 * What format is used to display dates in the current locale? 234 * 235 * @return string 236 */ 237 public static function dateFormat(): string 238 { 239 /* I18N: This is the format string for full dates. See https://php.net/date for codes */ 240 return self::$translator->translate('%j %F %Y'); 241 } 242 243 /** 244 * Convert the digits 0-9 into the local script 245 * Used for years, etc., where we do not want thousands-separators, decimals, etc. 246 * 247 * @param string|int $n 248 * 249 * @return string 250 */ 251 public static function digits(string|int $n): string 252 { 253 return self::$locale->digits((string) $n); 254 } 255 256 /** 257 * What is the direction of the current locale 258 * 259 * @return string "ltr" or "rtl" 260 */ 261 public static function direction(): string 262 { 263 return self::$locale->direction(); 264 } 265 266 /** 267 * Initialise the translation adapter with a locale setting. 268 * 269 * @param string $code 270 * @param bool $setup 271 * 272 * @return void 273 */ 274 public static function init(string $code, bool $setup = false): void 275 { 276 self::$locale = Locale::create($code); 277 278 // Load the translation file 279 $translation_file = __DIR__ . '/../resources/lang/' . self::$locale->languageTag() . '/messages.php'; 280 281 try { 282 $translation = new Translation($translation_file); 283 $translations = $translation->asArray(); 284 } catch (Exception) { 285 // The translations files are created during the build process, and are 286 // not included in the source code. 287 // Assuming we are using dev code, and build (or rebuild) the files. 288 $po_file = Webtrees::ROOT_DIR . 'resources/lang/' . self::$locale->languageTag() . '/messages.po'; 289 $translation = new Translation($po_file); 290 $translations = $translation->asArray(); 291 file_put_contents($translation_file, "<?php\n\nreturn " . var_export($translations, true) . ";\n"); 292 } 293 294 // Add translations from custom modules (but not during setup, as we have no database/modules) 295 if (!$setup) { 296 $module_service = Registry::container()->get(ModuleService::class); 297 298 $translations = $module_service 299 ->findByInterface(ModuleCustomInterface::class) 300 ->reduce(static fn(array $carry, ModuleCustomInterface $item): array => array_merge($carry, $item->customTranslations(self::$locale->languageTag())), $translations); 301 302 self::$language = $module_service 303 ->findByInterface(ModuleLanguageInterface::class, true) 304 ->first(fn (ModuleLanguageInterface $module): bool => $module->locale()->languageTag() === $code); 305 } 306 307 // Create a translator 308 self::$translator = new Translator($translations, self::$locale->pluralRule()); 309 310 /* I18N: This punctuation is used to separate lists of items */ 311 self::$list_separator = self::translate(', '); 312 313 // Create a collator 314 try { 315 // Symfony provides a very incomplete polyfill - which cannot be used. 316 if (class_exists('Collator')) { 317 // Need phonebook collation rules for German Ä, Ö and Ü. 318 if (str_contains(self::$locale->code(), '@')) { 319 self::$collator = new Collator(self::$locale->code() . ';collation=phonebook'); 320 } else { 321 self::$collator = new Collator(self::$locale->code() . '@collation=phonebook'); 322 } 323 // Ignore upper/lower case differences 324 self::$collator->setStrength(Collator::SECONDARY); 325 } 326 } catch (Exception) { 327 // PHP-INTL is not installed? We'll use a fallback later. 328 } 329 } 330 331 /** 332 * Translate a string, and then substitute placeholders 333 * echo I18N::translate('Hello World!'); 334 * echo I18N::translate('The %s sat on the mat', 'cat'); 335 * 336 * @param string $message 337 * @param string ...$args 338 * 339 * @return string 340 */ 341 public static function translate(string $message, ...$args): string 342 { 343 $message = self::$translator->translate($message); 344 345 return sprintf($message, ...$args); 346 } 347 348 /** 349 * @return string 350 */ 351 public static function languageTag(): string 352 { 353 return self::$locale->languageTag(); 354 } 355 356 /** 357 * @return LocaleInterface 358 */ 359 public static function locale(): LocaleInterface 360 { 361 return self::$locale; 362 } 363 364 /** 365 * @return ModuleLanguageInterface 366 */ 367 public static function language(): ModuleLanguageInterface 368 { 369 return self::$language; 370 } 371 372 /** 373 * Translate a number into the local representation. 374 * e.g. 12345.67 becomes 375 * en: 12,345.67 376 * fr: 12 345,67 377 * de: 12.345,67 378 * 379 * @param float $n 380 * @param int $precision 381 * 382 * @return string 383 */ 384 public static function number(float $n, int $precision = 0): string 385 { 386 return self::$locale->number(round($n, $precision)); 387 } 388 389 /** 390 * Translate a fraction into a percentage. 391 * e.g. 0.123 becomes 392 * en: 12.3% 393 * fr: 12,3 % 394 * de: 12,3% 395 * 396 * @param float $n 397 * @param int $precision 398 * 399 * @return string 400 */ 401 public static function percentage(float $n, int $precision = 0): string 402 { 403 return self::$locale->percent(round($n, $precision + 2)); 404 } 405 406 /** 407 * Translate a plural string 408 * echo self::plural('There is an error', 'There are errors', $num_errors); 409 * echo self::plural('There is one error', 'There are %s errors', $num_errors); 410 * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour); 411 * 412 * @param string $singular 413 * @param string $plural 414 * @param int $count 415 * @param string ...$args 416 * 417 * @return string 418 */ 419 public static function plural(string $singular, string $plural, int $count, ...$args): string 420 { 421 $message = self::$translator->translatePlural($singular, $plural, $count); 422 423 return sprintf($message, ...$args); 424 } 425 426 /** 427 * UTF8 version of PHP::strrev() 428 * Reverse RTL text for third-party libraries such as GD2 and googlechart. 429 * These do not support UTF8 text direction, so we must mimic it for them. 430 * Numbers are always rendered LTR, even in RTL text. 431 * The visual direction of characters such as parentheses should be reversed. 432 * 433 * @param string $text Text to be reversed 434 * 435 * @return string 436 */ 437 public static function reverseText(string $text): string 438 { 439 // Remove HTML markup - we can't display it and it is LTR. 440 $text = strip_tags($text); 441 // Remove HTML entities. 442 $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); 443 444 // LTR text doesn't need reversing 445 if (self::scriptDirection(self::textScript($text)) === 'ltr') { 446 return $text; 447 } 448 449 // Mirrored characters 450 $text = strtr($text, self::MIRROR_CHARACTERS); 451 452 $reversed = ''; 453 $digits = ''; 454 while ($text !== '') { 455 $letter = mb_substr($text, 0, 1); 456 $text = mb_substr($text, 1); 457 if (str_contains(self::DIGITS, $letter)) { 458 $digits .= $letter; 459 } else { 460 $reversed = $letter . $digits . $reversed; 461 $digits = ''; 462 } 463 } 464 465 return $digits . $reversed; 466 } 467 468 /** 469 * Return the direction (ltr or rtl) for a given script 470 * The PHP/intl library does not provde this information, so we need 471 * our own lookup table. 472 * 473 * @param string $script 474 * 475 * @return string 476 */ 477 public static function scriptDirection(string $script): string 478 { 479 switch ($script) { 480 case 'Arab': 481 case 'Hebr': 482 case 'Mong': 483 case 'Thaa': 484 return 'rtl'; 485 default: 486 return 'ltr'; 487 } 488 } 489 490 /** 491 * Identify the script used for a piece of text 492 * 493 * @param string $string 494 * 495 * @return string 496 */ 497 public static function textScript(string $string): string 498 { 499 $string = strip_tags($string); // otherwise HTML tags show up as latin 500 $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin 501 $string = str_replace([ 502 Individual::NOMEN_NESCIO, 503 Individual::PRAENOMEN_NESCIO, 504 ], '', $string); 505 $pos = 0; 506 $strlen = strlen($string); 507 while ($pos < $strlen) { 508 // get the Unicode Code Point for the character at position $pos 509 $byte1 = ord($string[$pos]); 510 if ($byte1 < 0x80) { 511 $code_point = $byte1; 512 $chrlen = 1; 513 } elseif ($byte1 < 0xC0) { 514 // Invalid continuation character 515 return 'Latn'; 516 } elseif ($byte1 < 0xE0) { 517 $code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F); 518 $chrlen = 2; 519 } elseif ($byte1 < 0xF0) { 520 $code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F); 521 $chrlen = 3; 522 } elseif ($byte1 < 0xF8) { 523 $code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F); 524 $chrlen = 3; 525 } else { 526 // Invalid UTF 527 return 'Latn'; 528 } 529 530 foreach (self::SCRIPT_CHARACTER_RANGES as $range) { 531 if ($code_point >= $range[1] && $code_point <= $range[2]) { 532 return $range[0]; 533 } 534 } 535 // Not a recognised script. Maybe punctuation, spacing, etc. Keep looking. 536 $pos += $chrlen; 537 } 538 539 return 'Latn'; 540 } 541 542 /** 543 * A closure which will compare strings using local collation rules. 544 * 545 * @return Closure(string,string):int 546 */ 547 public static function comparator(): Closure 548 { 549 $collator = self::$collator; 550 551 if ($collator instanceof Collator) { 552 return static fn (string $x, string $y): int => (int) $collator->compare($x, $y); 553 } 554 555 return static fn (string $x, string $y): int => strcmp(self::strtolower($x), self::strtolower($y)); 556 } 557 558 559 560 /** 561 * Convert a string to lower case. 562 * 563 * @param string $string 564 * 565 * @return string 566 */ 567 public static function strtolower(string $string): string 568 { 569 if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES, true)) { 570 $string = strtr($string, self::DOTLESS_I_TOLOWER); 571 } 572 573 return mb_strtolower($string); 574 } 575 576 /** 577 * Convert a string to upper case. 578 * 579 * @param string $string 580 * 581 * @return string 582 */ 583 public static function strtoupper(string $string): string 584 { 585 if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES, true)) { 586 $string = strtr($string, self::DOTLESS_I_TOUPPER); 587 } 588 589 return mb_strtoupper($string); 590 } 591 592 /** 593 * What format is used to display dates in the current locale? 594 * 595 * @return string 596 */ 597 public static function timeFormat(): string 598 { 599 /* I18N: This is the format string for the time-of-day. See https://php.net/date for codes */ 600 return self::$translator->translate('%H:%i:%s'); 601 } 602 603 /** 604 * Context sensitive version of translate. 605 * echo I18N::translateContext('NOMINATIVE', 'January'); 606 * echo I18N::translateContext('GENITIVE', 'January'); 607 * 608 * @param string $context 609 * @param string $message 610 * @param string ...$args 611 * 612 * @return string 613 */ 614 public static function translateContext(string $context, string $message, ...$args): string 615 { 616 $message = self::$translator->translateContext($context, $message); 617 618 return sprintf($message, ...$args); 619 } 620} 621