1<?php 2/** 3 * webtrees: online genealogy 4 * Copyright (C) 2018 webtrees development team 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 */ 16declare(strict_types=1); 17 18namespace Fisharebest\Webtrees; 19 20use Collator; 21use Exception; 22use Fisharebest\Localization\Locale; 23use Fisharebest\Localization\Locale\LocaleEnUs; 24use Fisharebest\Localization\Locale\LocaleInterface; 25use Fisharebest\Localization\Translation; 26use Fisharebest\Localization\Translator; 27use Fisharebest\Webtrees\Functions\FunctionsEdit; 28 29/** 30 * Internationalization (i18n) and localization (l10n). 31 */ 32class I18N 33{ 34 /** @var LocaleInterface The current locale (e.g. LocaleEnGb) */ 35 private static $locale; 36 37 /** @var Translator An object that performs translation */ 38 private static $translator; 39 40 /** @var Collator From the php-intl library */ 41 private static $collator; 42 43 // Digits are always rendered LTR, even in RTL text. 44 const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹'; 45 46 // These locales need special handling for the dotless letter I. 47 const DOTLESS_I_LOCALES = [ 48 'az', 49 'tr', 50 ]; 51 const DOTLESS_I_TOLOWER = [ 52 'I' => 'ı', 53 'İ' => 'i', 54 ]; 55 const DOTLESS_I_TOUPPER = [ 56 'ı' => 'I', 57 'i' => 'İ', 58 ]; 59 60 // The ranges of characters used by each script. 61 const SCRIPT_CHARACTER_RANGES = [ 62 [ 63 'Latn', 64 0x0041, 65 0x005A, 66 ], 67 [ 68 'Latn', 69 0x0061, 70 0x007A, 71 ], 72 [ 73 'Latn', 74 0x0100, 75 0x02AF, 76 ], 77 [ 78 'Grek', 79 0x0370, 80 0x03FF, 81 ], 82 [ 83 'Cyrl', 84 0x0400, 85 0x052F, 86 ], 87 [ 88 'Hebr', 89 0x0590, 90 0x05FF, 91 ], 92 [ 93 'Arab', 94 0x0600, 95 0x06FF, 96 ], 97 [ 98 'Arab', 99 0x0750, 100 0x077F, 101 ], 102 [ 103 'Arab', 104 0x08A0, 105 0x08FF, 106 ], 107 [ 108 'Deva', 109 0x0900, 110 0x097F, 111 ], 112 [ 113 'Taml', 114 0x0B80, 115 0x0BFF, 116 ], 117 [ 118 'Sinh', 119 0x0D80, 120 0x0DFF, 121 ], 122 [ 123 'Thai', 124 0x0E00, 125 0x0E7F, 126 ], 127 [ 128 'Geor', 129 0x10A0, 130 0x10FF, 131 ], 132 [ 133 'Grek', 134 0x1F00, 135 0x1FFF, 136 ], 137 [ 138 'Deva', 139 0xA8E0, 140 0xA8FF, 141 ], 142 [ 143 'Hans', 144 0x3000, 145 0x303F, 146 ], 147 // Mixed CJK, not just Hans 148 [ 149 'Hans', 150 0x3400, 151 0xFAFF, 152 ], 153 // Mixed CJK, not just Hans 154 [ 155 'Hans', 156 0x20000, 157 0x2FA1F, 158 ], 159 // Mixed CJK, not just Hans 160 ]; 161 162 // Characters that are displayed in mirror form in RTL text. 163 const MIRROR_CHARACTERS = [ 164 '(' => ')', 165 ')' => '(', 166 '[' => ']', 167 ']' => '[', 168 '{' => '}', 169 '}' => '{', 170 '<' => '>', 171 '>' => '<', 172 '‹ ' => '›', 173 '› ' => '‹', 174 '«' => '»', 175 '»' => '«', 176 '﴾ ' => '﴿', 177 '﴿ ' => '﴾', 178 '“ ' => '”', 179 '” ' => '“', 180 '‘ ' => '’', 181 '’ ' => '‘', 182 ]; 183 184 // Default list of locales to show in the menu. 185 const DEFAULT_LOCALES = [ 186 'ar', 187 'bg', 188 'bs', 189 'ca', 190 'cs', 191 'da', 192 'de', 193 'el', 194 'en-GB', 195 'en-US', 196 'es', 197 'et', 198 'fi', 199 'fr', 200 'he', 201 'hr', 202 'hu', 203 'is', 204 'it', 205 'ka', 206 'kk', 207 'lt', 208 'mr', 209 'nb', 210 'nl', 211 'nn', 212 'pl', 213 'pt', 214 'ru', 215 'sk', 216 'sv', 217 'tr', 218 'uk', 219 'vi', 220 'zh-Hans', 221 ]; 222 223 /** @var string Punctuation used to separate list items, typically a comma */ 224 public static $list_separator; 225 226 /** 227 * The prefered locales for this site, or a default list if no preference. 228 * 229 * @return LocaleInterface[] 230 */ 231 public static function activeLocales(): array 232 { 233 $code_list = Site::getPreference('LANGUAGES'); 234 235 if ($code_list === '') { 236 $codes = self::DEFAULT_LOCALES; 237 } else { 238 $codes = explode(',', $code_list); 239 } 240 241 $locales = []; 242 foreach ($codes as $code) { 243 if (file_exists(WT_ROOT . 'language/' . $code . '.mo')) { 244 try { 245 $locales[] = Locale::create($code); 246 } catch (\Exception $ex) { 247 DebugBar::addThrowable($ex); 248 249 // No such locale exists? 250 } 251 } 252 } 253 usort($locales, '\Fisharebest\Localization\Locale::compare'); 254 255 return $locales; 256 } 257 258 /** 259 * Which MySQL collation should be used for this locale? 260 * 261 * @return string 262 */ 263 public static function collation() 264 { 265 $collation = self::$locale->collation(); 266 switch ($collation) { 267 case 'croatian_ci': 268 case 'german2_ci': 269 case 'vietnamese_ci': 270 // Only available in MySQL 5.6 271 return 'utf8_unicode_ci'; 272 default: 273 return 'utf8_' . $collation; 274 } 275 } 276 277 /** 278 * What format is used to display dates in the current locale? 279 * 280 * @return string 281 */ 282 public static function dateFormat(): string 283 { 284 /* I18N: This is the format string for full dates. See http://php.net/date for codes */ 285 return self::$translator->translate('%j %F %Y'); 286 } 287 288 /** 289 * Generate consistent I18N for datatables.js 290 * 291 * @param int[] $lengths An optional array of page lengths 292 * 293 * @return string 294 */ 295 public static function datatablesI18N(array $lengths = [ 296 10, 297 20, 298 30, 299 50, 300 100, 301 -1, 302 ]): string 303 { 304 $length_options = Bootstrap4::select(FunctionsEdit::numericOptions($lengths), '10'); 305 306 return 307 '"formatNumber": function(n) { return String(n).replace(/[0-9]/g, function(w) { return ("' . self::$locale->digits('0123456789') . '")[+w]; }); },' . 308 '"language": {' . 309 ' "paginate": {' . 310 ' "first": "' . self::translate('first') . '",' . 311 ' "last": "' . self::translate('last') . '",' . 312 ' "next": "' . self::translate('next') . '",' . 313 ' "previous": "' . self::translate('previous') . '"' . 314 ' },' . 315 ' "emptyTable": "' . self::translate('No records to display') . '",' . 316 ' "info": "' . /* I18N: %s are placeholders for numbers */ 317 self::translate('Showing %1$s to %2$s of %3$s', '_START_', '_END_', '_TOTAL_') . '",' . 318 ' "infoEmpty": "' . self::translate('Showing %1$s to %2$s of %3$s', self::$locale->digits('0'), self::$locale->digits('0'), self::$locale->digits('0')) . '",' . 319 ' "infoFiltered": "' . /* I18N: %s is a placeholder for a number */ 320 self::translate('(filtered from %s total entries)', '_MAX_') . '",' . 321 ' "lengthMenu": "' . /* I18N: %s is a number of records per page */ 322 self::translate('Display %s', addslashes($length_options)) . '",' . 323 ' "loadingRecords": "' . self::translate('Loading…') . '",' . 324 ' "processing": "' . self::translate('Loading…') . '",' . 325 ' "search": "' . self::translate('Filter') . '",' . 326 ' "zeroRecords": "' . self::translate('No records to display') . '"' . 327 '}'; 328 } 329 330 /** 331 * Convert the digits 0-9 into the local script 332 * 333 * Used for years, etc., where we do not want thousands-separators, decimals, etc. 334 * 335 * @param string|int $n 336 * 337 * @return string 338 */ 339 public static function digits($n): string 340 { 341 return self::$locale->digits((string) $n); 342 } 343 344 /** 345 * What is the direction of the current locale 346 * 347 * @return string "ltr" or "rtl" 348 */ 349 public static function direction(): string 350 { 351 return self::$locale->direction(); 352 } 353 354 /** 355 * What is the first day of the week. 356 * 357 * @return int Sunday=0, Monday=1, etc. 358 */ 359 public static function firstDay(): int 360 { 361 return self::$locale->territory()->firstDay(); 362 } 363 364 /** 365 * Convert a GEDCOM age string into translated_text 366 * 367 * NB: The import function will have normalised this, so we don't need 368 * to worry about badly formatted strings 369 * NOTE: this function is not yet complete - eventually it will replace FunctionsDate::get_age_at_event() 370 * 371 * @param $string 372 * 373 * @return string 374 */ 375 public static function gedcomAge(string $string): string 376 { 377 switch ($string) { 378 case 'STILLBORN': 379 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (stillborn) 380 return self::translate('(stillborn)'); 381 case 'INFANT': 382 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in infancy) 383 return self::translate('(in infancy)'); 384 case 'CHILD': 385 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in childhood) 386 return self::translate('(in childhood)'); 387 } 388 $age = []; 389 if (preg_match('/(\d+)y/', $string, $match)) { 390 $years = (int) $match[1]; 391 // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days 392 $age[] = self::plural('%s year', '%s years', $years, self::number($years)); 393 } else { 394 $years = -1; 395 } 396 if (preg_match('/(\d+)m/', $string, $match)) { 397 $months = (int) $match[1]; 398 // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days 399 $age[] = self::plural('%s month', '%s months', $months, self::number($months)); 400 } 401 if (preg_match('/(\d+)w/', $string, $match)) { 402 $weeks = (int) $match[1]; 403 // I18N: Part of an age string. e.g. 7 weeks and 3 days 404 $age[] = self::plural('%s week', '%s weeks', $weeks, self::number($weeks)); 405 } 406 if (preg_match('/(\d+)d/', $string, $match)) { 407 $days = (int) $match[1]; 408 // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days 409 $age[] = self::plural('%s day', '%s days', $days, self::number($days)); 410 } 411 // If an age is just a number of years, only show the number 412 if (count($age) === 1 && $years >= 0) { 413 $age = $years; 414 } 415 if ($age) { 416 if (!substr_compare($string, '<', 0, 1)) { 417 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged less than 21 years) 418 return self::translate('(aged less than %s)', $age); 419 } 420 421 if (!substr_compare($string, '>', 0, 1)) { 422 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged more than 21 years) 423 return self::translate('(aged more than %s)', $age); 424 } 425 426 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged 43 years) 427 return self::translate('(aged %s)', $age); 428 } 429 430 // Not a valid string? 431 return self::translate('(aged %s)', $string); 432 } 433 434 /** 435 * Generate i18n markup for the <html> tag, e.g. lang="ar" dir="rtl" 436 * 437 * @return string 438 */ 439 public static function htmlAttributes(): string 440 { 441 return self::$locale->htmlAttributes(); 442 } 443 444 /** 445 * Initialise the translation adapter with a locale setting. 446 * 447 * @param string $code Use this locale/language code, or choose one automatically 448 * @param Tree|null $tree 449 * 450 * @return string $string 451 */ 452 public static function init(string $code = '', Tree $tree = null): string 453 { 454 mb_internal_encoding('UTF-8'); 455 456 if ($code !== '') { 457 // Create the specified locale 458 self::$locale = Locale::create($code); 459 } elseif (Session::has('locale') && file_exists(WT_ROOT . 'language/' . Session::get('locale') . '.mo')) { 460 // Select a previously used locale 461 self::$locale = Locale::create(Session::get('locale')); 462 } else { 463 if ($tree instanceof Tree) { 464 $default_locale = Locale::create($tree->getPreference('LANGUAGE', 'en-US')); 465 } else { 466 $default_locale = new LocaleEnUs(); 467 } 468 469 // Negotiate with the browser. 470 // Search engines don't negotiate. They get the default locale of the tree. 471 self::$locale = Locale::httpAcceptLanguage($_SERVER, self::installedLocales(), $default_locale); 472 } 473 474 $cache_dir = WT_DATA_DIR . 'cache/'; 475 $cache_file = $cache_dir . 'language-' . self::$locale->languageTag() . '-cache.php'; 476 if (file_exists($cache_file)) { 477 $filemtime = filemtime($cache_file); 478 } else { 479 $filemtime = 0; 480 } 481 482 // Load the translation file(s) 483 // Note that glob() returns false instead of an empty array when open_basedir_restriction 484 // is in force and no files are found. See PHP bug #47358. 485 if (defined('GLOB_BRACE')) { 486 $translation_files = array_merge( 487 [WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'], 488 glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: [], 489 glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: [] 490 ); 491 } else { 492 // Some servers do not have GLOB_BRACE - see http://php.net/manual/en/function.glob.php 493 $translation_files = array_merge( 494 [WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'], 495 glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.csv') ?: [], 496 glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.php') ?: [], 497 glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.mo') ?: [], 498 glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.csv') ?: [], 499 glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.php') ?: [], 500 glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.mo') ?: [] 501 ); 502 } 503 // Rebuild files after one hour 504 $rebuild_cache = time() > $filemtime + 3600; 505 // Rebuild files if any translation file has been updated 506 foreach ($translation_files as $translation_file) { 507 if (filemtime($translation_file) > $filemtime) { 508 $rebuild_cache = true; 509 break; 510 } 511 } 512 513 if ($rebuild_cache) { 514 $translations = []; 515 foreach ($translation_files as $translation_file) { 516 $translation = new Translation($translation_file); 517 $translations = array_merge($translations, $translation->asArray()); 518 } 519 try { 520 File::mkdir($cache_dir); 521 file_put_contents($cache_file, '<?php return ' . var_export($translations, true) . ';'); 522 } catch (Exception $ex) { 523 DebugBar::addThrowable($ex); 524 525 // During setup, we may not have been able to create it. 526 } 527 } else { 528 $translations = include $cache_file; 529 } 530 531 // Create a translator 532 self::$translator = new Translator($translations, self::$locale->pluralRule()); 533 534 /* I18N: This punctuation is used to separate lists of items */ 535 self::$list_separator = self::translate(', '); 536 537 // Create a collator 538 try { 539 // PHP 5.6 cannot catch errors, so test first 540 if (class_exists('Collator')) { 541 self::$collator = new Collator(self::$locale->code()); 542 // Ignore upper/lower case differences 543 self::$collator->setStrength(Collator::SECONDARY); 544 } 545 } catch (Exception $ex) { 546 DebugBar::addThrowable($ex); 547 548 // PHP-INTL is not installed? We'll use a fallback later. 549 } 550 551 return self::$locale->languageTag(); 552 } 553 554 /** 555 * All locales for which a translation file exists. 556 * 557 * @return LocaleInterface[] 558 */ 559 public static function installedLocales(): array 560 { 561 $locales = []; 562 foreach (glob(WT_ROOT . 'language/*.mo') as $file) { 563 try { 564 $locales[] = Locale::create(basename($file, '.mo')); 565 } catch (\Exception $ex) { 566 DebugBar::addThrowable($ex); 567 568 // Not a recognised locale 569 } 570 } 571 usort($locales, '\Fisharebest\Localization\Locale::compare'); 572 573 return $locales; 574 } 575 576 /** 577 * Return the endonym for a given language - as per http://cldr.unicode.org/ 578 * 579 * @param string $locale 580 * 581 * @return string 582 */ 583 public static function languageName(string $locale): string 584 { 585 return Locale::create($locale)->endonym(); 586 } 587 588 /** 589 * Return the script used by a given language 590 * 591 * @param string $locale 592 * 593 * @return string 594 */ 595 public static function languageScript(string $locale): string 596 { 597 return Locale::create($locale)->script()->code(); 598 } 599 600 /** 601 * Translate a number into the local representation. 602 * 603 * e.g. 12345.67 becomes 604 * en: 12,345.67 605 * fr: 12 345,67 606 * de: 12.345,67 607 * 608 * @param float $n 609 * @param int $precision 610 * 611 * @return string 612 */ 613 public static function number(float $n, int $precision = 0): string 614 { 615 return self::$locale->number(round($n, $precision)); 616 } 617 618 /** 619 * Translate a fraction into a percentage. 620 * 621 * e.g. 0.123 becomes 622 * en: 12.3% 623 * fr: 12,3 % 624 * de: 12,3% 625 * 626 * @param float $n 627 * @param int $precision 628 * 629 * @return string 630 */ 631 public static function percentage(float $n, int $precision = 0): string 632 { 633 return self::$locale->percent(round($n, $precision + 2)); 634 } 635 636 /** 637 * Translate a plural string 638 * echo self::plural('There is an error', 'There are errors', $num_errors); 639 * echo self::plural('There is one error', 'There are %s errors', $num_errors); 640 * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour); 641 * 642 * @param string $singular 643 * @param string $plural 644 * @param int $count 645 * @param string ...$args 646 * 647 * @return string 648 */ 649 public static function plural(string $singular, string $plural, int $count, ...$args): string 650 { 651 $message = self::$translator->translatePlural($singular, $plural, $count); 652 653 return sprintf($message, ...$args); 654 } 655 656 /** 657 * UTF8 version of PHP::strrev() 658 * 659 * Reverse RTL text for third-party libraries such as GD2 and googlechart. 660 * 661 * These do not support UTF8 text direction, so we must mimic it for them. 662 * 663 * Numbers are always rendered LTR, even in RTL text. 664 * The visual direction of characters such as parentheses should be reversed. 665 * 666 * @param string $text Text to be reversed 667 * 668 * @return string 669 */ 670 public static function reverseText($text): string 671 { 672 // Remove HTML markup - we can't display it and it is LTR. 673 $text = strip_tags($text); 674 // Remove HTML entities. 675 $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); 676 677 // LTR text doesn't need reversing 678 if (self::scriptDirection(self::textScript($text)) === 'ltr') { 679 return $text; 680 } 681 682 // Mirrored characters 683 $text = strtr($text, self::MIRROR_CHARACTERS); 684 685 $reversed = ''; 686 $digits = ''; 687 while ($text != '') { 688 $letter = mb_substr($text, 0, 1); 689 $text = mb_substr($text, 1); 690 if (strpos(self::DIGITS, $letter) !== false) { 691 $digits .= $letter; 692 } else { 693 $reversed = $letter . $digits . $reversed; 694 $digits = ''; 695 } 696 } 697 698 return $digits . $reversed; 699 } 700 701 /** 702 * Return the direction (ltr or rtl) for a given script 703 * 704 * The PHP/intl library does not provde this information, so we need 705 * our own lookup table. 706 * 707 * @param string $script 708 * 709 * @return string 710 */ 711 public static function scriptDirection($script) 712 { 713 switch ($script) { 714 case 'Arab': 715 case 'Hebr': 716 case 'Mong': 717 case 'Thaa': 718 return 'rtl'; 719 default: 720 return 'ltr'; 721 } 722 } 723 724 /** 725 * Perform a case-insensitive comparison of two strings. 726 * 727 * @param string $string1 728 * @param string $string2 729 * 730 * @return int 731 */ 732 public static function strcasecmp($string1, $string2) 733 { 734 if (self::$collator instanceof Collator) { 735 return self::$collator->compare($string1, $string2); 736 } 737 738 return strcmp(self::strtolower($string1), self::strtolower($string2)); 739 } 740 741 /** 742 * Convert a string to lower case. 743 * 744 * @param string $string 745 * 746 * @return string 747 */ 748 public static function strtolower($string): string 749 { 750 if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) { 751 $string = strtr($string, self::DOTLESS_I_TOLOWER); 752 } 753 754 return mb_strtolower($string); 755 } 756 757 /** 758 * Convert a string to upper case. 759 * 760 * @param string $string 761 * 762 * @return string 763 */ 764 public static function strtoupper($string): string 765 { 766 if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) { 767 $string = strtr($string, self::DOTLESS_I_TOUPPER); 768 } 769 770 return mb_strtoupper($string); 771 } 772 773 /** 774 * Identify the script used for a piece of text 775 * 776 * @param $string 777 * 778 * @return string 779 */ 780 public static function textScript($string): string 781 { 782 $string = strip_tags($string); // otherwise HTML tags show up as latin 783 $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin 784 $string = str_replace([ 785 '@N.N.', 786 '@P.N.', 787 ], '', $string); // otherwise unknown names show up as latin 788 $pos = 0; 789 $strlen = strlen($string); 790 while ($pos < $strlen) { 791 // get the Unicode Code Point for the character at position $pos 792 $byte1 = ord($string[$pos]); 793 if ($byte1 < 0x80) { 794 $code_point = $byte1; 795 $chrlen = 1; 796 } elseif ($byte1 < 0xC0) { 797 // Invalid continuation character 798 return 'Latn'; 799 } elseif ($byte1 < 0xE0) { 800 $code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F); 801 $chrlen = 2; 802 } elseif ($byte1 < 0xF0) { 803 $code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F); 804 $chrlen = 3; 805 } elseif ($byte1 < 0xF8) { 806 $code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F); 807 $chrlen = 3; 808 } else { 809 // Invalid UTF 810 return 'Latn'; 811 } 812 813 foreach (self::SCRIPT_CHARACTER_RANGES as $range) { 814 if ($code_point >= $range[1] && $code_point <= $range[2]) { 815 return $range[0]; 816 } 817 } 818 // Not a recognised script. Maybe punctuation, spacing, etc. Keep looking. 819 $pos += $chrlen; 820 } 821 822 return 'Latn'; 823 } 824 825 /** 826 * Convert a number of seconds into a relative time. For example, 630 => "10 hours, 30 minutes ago" 827 * 828 * @param int $seconds 829 * 830 * @return string 831 */ 832 public static function timeAgo($seconds) 833 { 834 $minute = 60; 835 $hour = 60 * $minute; 836 $day = 24 * $hour; 837 $month = 30 * $day; 838 $year = 365 * $day; 839 840 if ($seconds > $year) { 841 $years = intdiv($seconds, $year); 842 843 return self::plural('%s year ago', '%s years ago', $years, self::number($years)); 844 } 845 846 if ($seconds > $month) { 847 $months = intdiv($seconds, $month); 848 849 return self::plural('%s month ago', '%s months ago', $months, self::number($months)); 850 } 851 852 if ($seconds > $day) { 853 $days = intdiv($seconds, $day); 854 855 return self::plural('%s day ago', '%s days ago', $days, self::number($days)); 856 } 857 858 if ($seconds > $hour) { 859 $hours = intdiv($seconds, $hour); 860 861 return self::plural('%s hour ago', '%s hours ago', $hours, self::number($hours)); 862 } 863 864 if ($seconds > $minute) { 865 $minutes = intdiv($seconds, $minute); 866 867 return self::plural('%s minute ago', '%s minutes ago', $minutes, self::number($minutes)); 868 } 869 870 return self::plural('%s second ago', '%s seconds ago', $seconds, self::number($seconds)); 871 } 872 873 /** 874 * What format is used to display dates in the current locale? 875 * 876 * @return string 877 */ 878 public static function timeFormat(): string 879 { 880 /* I18N: This is the format string for the time-of-day. See http://php.net/date for codes */ 881 return self::$translator->translate('%H:%i:%s'); 882 } 883 884 /** 885 * Translate a string, and then substitute placeholders 886 * 887 * echo I18N::translate('Hello World!'); 888 * echo I18N::translate('The %s sat on the mat', 'cat'); 889 * 890 * @param string $message 891 * @param string ...$args 892 * 893 * @return string 894 */ 895 public static function translate(string $message, ...$args): string 896 { 897 $message = self::$translator->translate($message); 898 899 return sprintf($message, ...$args); 900 } 901 902 /** 903 * Context sensitive version of translate. 904 * echo I18N::translateContext('NOMINATIVE', 'January'); 905 * echo I18N::translateContext('GENITIVE', 'January'); 906 * 907 * @param string $context 908 * @param string $message 909 * @param string ...$args 910 * 911 * @return string 912 */ 913 public static function translateContext(string $context, string $message, ...$args): string 914 { 915 $message = self::$translator->translateContext($context, $message); 916 917 return sprintf($message, ...$args); 918 } 919} 920