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