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