| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504 |
- <?php declare(strict_types=1);
- /**
- * PrivateBin
- *
- * a zero-knowledge paste bin
- *
- * @link https://github.com/PrivateBin/PrivateBin
- * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
- * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
- */
- namespace PrivateBin;
- use AppendIterator;
- use GlobIterator;
- /**
- * I18n
- *
- * provides internationalization tools like translation, browser language detection, etc.
- */
- class I18n
- {
- /**
- * language
- *
- * @access protected
- * @static
- * @var string
- */
- protected static $_language = 'en';
- /**
- * language fallback
- *
- * @access protected
- * @static
- * @var string
- */
- protected static $_languageFallback = 'en';
- /**
- * language labels
- *
- * @access protected
- * @static
- * @var array
- */
- protected static $_languageLabels = [];
- /**
- * available languages
- *
- * @access protected
- * @static
- * @var array
- */
- protected static $_availableLanguages = [];
- /**
- * path to language files
- *
- * @access protected
- * @static
- * @var string
- */
- protected static $_path = '';
- /**
- * translation cache
- *
- * @access protected
- * @static
- * @var array
- */
- protected static $_translations = [];
- /**
- * translate a string, alias for translate()
- *
- * @access public
- * @static
- * @param string|array $messageId
- * @param mixed $args one or multiple parameters injected into placeholders
- * @return string
- */
- public static function _($messageId, ...$args)
- {
- return forward_static_call_array('PrivateBin\I18n::translate', func_get_args());
- }
- /**
- * translate a string
- *
- * @access public
- * @static
- * @param string|array $messageId
- * @param mixed $args one or multiple parameters injected into placeholders
- * @return string
- */
- public static function translate($messageId, ...$args)
- {
- if (empty($messageId)) {
- return $messageId;
- }
- if (empty(self::$_translations)) {
- self::loadTranslations();
- }
- $messages = $messageId;
- if (is_array($messageId)) {
- $messageId = count($messageId) > 1 ? $messageId[1] : $messageId[0];
- }
- if (!array_key_exists($messageId, self::$_translations)) {
- self::$_translations[$messageId] = $messages;
- }
- array_unshift($args, $messageId);
- if (is_array(self::$_translations[$messageId])) {
- $number = (int) $args[1];
- $key = self::_getPluralForm($number);
- $max = count(self::$_translations[$messageId]) - 1;
- if ($key > $max) {
- $key = $max;
- }
- $args[0] = self::$_translations[$messageId][$key];
- $args[1] = $number;
- } else {
- $args[0] = self::$_translations[$messageId];
- }
- // encode any non-integer arguments, but not the message itself
- // The message ID comes from trusted sources (code or translation JSON files),
- // while parameters may come from untrusted sources and need HTML entity encoding
- // to prevent XSS attacks when the message is inserted into HTML context
- $argsCount = count($args);
- for ($i = 1; $i < $argsCount; ++$i) {
- if (is_int($args[$i])) {
- continue;
- }
- $args[$i] = self::encode($args[$i]);
- }
- return call_user_func_array('sprintf', $args);
- }
- /**
- * encode HTML entities for output into an HTML5 document
- *
- * @access public
- * @static
- * @param string $string
- * @return string
- */
- public static function encode($string)
- {
- return htmlspecialchars($string, ENT_QUOTES | ENT_HTML5 | ENT_DISALLOWED, 'UTF-8', false);
- }
- /**
- * loads translations
- *
- * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
- *
- * @access public
- * @static
- * @throws JsonException
- */
- public static function loadTranslations()
- {
- $availableLanguages = self::getAvailableLanguages();
- // check if the lang cookie was set and that language exists
- if (
- array_key_exists('lang', $_COOKIE) &&
- ($key = array_search($_COOKIE['lang'], $availableLanguages)) !== false
- ) {
- self::$_language = $availableLanguages[$key];
- }
- // find a translation file matching the browsers language preferences
- else {
- self::$_language = self::_getMatchingLanguage(
- self::_normalizeBrowserLanguages(
- self::getBrowserLanguages(), $availableLanguages
- ),
- $availableLanguages
- );
- }
- // load translations
- if (self::$_language === 'en') {
- self::$_translations = [];
- } else {
- $data = file_get_contents(self::_getPath(self::$_language . '.json'));
- self::$_translations = Json::decode($data);
- }
- }
- /**
- * get list of available translations based on files found
- *
- * @access public
- * @static
- * @return array
- */
- public static function getAvailableLanguages()
- {
- if (count(self::$_availableLanguages) === 0) {
- self::$_availableLanguages[] = 'en'; // en.json is not part of the release archive
- $languageIterator = new AppendIterator();
- $languageIterator->append(new GlobIterator(self::_getPath('??.json')));
- $languageIterator->append(new GlobIterator(self::_getPath('???.json'))); // for jbo
- $languageIterator->append(new GlobIterator(self::_getPath('??-??.json'))); // for regional variants like zh-tw
- foreach ($languageIterator as $file) {
- $language = $file->getBasename('.json');
- if ($language !== 'en') {
- self::$_availableLanguages[] = $language;
- }
- }
- }
- return self::$_availableLanguages;
- }
- /**
- * detect the clients supported languages and return them ordered by preference
- *
- * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
- *
- * @access public
- * @static
- * @return array
- */
- public static function getBrowserLanguages()
- {
- $languages = [];
- if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
- $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
- foreach ($languageRanges as $languageRange) {
- if (preg_match(
- '/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/',
- trim($languageRange), $match
- )) {
- if (!isset($match[2])) {
- $match[2] = '1.0';
- } else {
- $match[2] = (string) floatval($match[2]);
- }
- if (!isset($languages[$match[2]])) {
- $languages[$match[2]] = [];
- }
- $languages[$match[2]][] = strtolower($match[1]);
- }
- }
- krsort($languages);
- }
- return $languages;
- }
- /**
- * normalize browser language aliases to available locale IDs
- *
- * @access protected
- * @static
- * @param array $languages
- * @param array $availableLanguages
- * @return array
- */
- protected static function _normalizeBrowserLanguages($languages, $availableLanguages)
- {
- // Base zh stays before zh-tw because regional locales are appended after base locales.
- $hasSimplifiedChinese = in_array('zh', $availableLanguages, true);
- $hasTraditionalChinese = in_array('zh-tw', $availableLanguages, true);
- foreach ($languages as $quality => $languageRanges) {
- foreach ($languageRanges as $index => $languageRange) {
- $isSimplifiedChinese = $languageRange === 'zh-hans' || str_starts_with($languageRange, 'zh-hans-') ||
- $languageRange === 'zh-cn' || str_starts_with($languageRange, 'zh-cn-') ||
- $languageRange === 'zh-sg' || str_starts_with($languageRange, 'zh-sg-');
- $isTraditionalChinese = str_starts_with($languageRange, 'zh-tw-') ||
- $languageRange === 'zh-hant' || str_starts_with($languageRange, 'zh-hant-') ||
- $languageRange === 'zh-hk' || str_starts_with($languageRange, 'zh-hk-') ||
- $languageRange === 'zh-mo' || str_starts_with($languageRange, 'zh-mo-');
- if ($hasSimplifiedChinese && $isSimplifiedChinese) {
- $languages[$quality][$index] = 'zh';
- } elseif ($hasTraditionalChinese && $isTraditionalChinese) {
- $languages[$quality][$index] = 'zh-tw';
- }
- }
- }
- return $languages;
- }
- /**
- * get currently loaded language
- *
- * @access public
- * @static
- * @return string
- */
- public static function getLanguage()
- {
- return self::$_language;
- }
- /**
- * get list of language labels
- *
- * Only for given language codes, otherwise all labels.
- *
- * @access public
- * @static
- * @param array $languages
- * @throws JsonException
- * @return array
- */
- public static function getLanguageLabels($languages = [])
- {
- $file = self::_getPath('languages.json');
- if (count(self::$_languageLabels) === 0 && is_readable($file)) {
- $data = file_get_contents($file);
- self::$_languageLabels = Json::decode($data);
- }
- if (count($languages) === 0) {
- return self::$_languageLabels;
- }
- return array_intersect_key(self::$_languageLabels, array_flip($languages));
- }
- /**
- * determines if the current language is written right-to-left (RTL)
- *
- * @access public
- * @static
- * @return bool
- */
- public static function isRtl()
- {
- return in_array(self::$_language, ['ar', 'he']);
- }
- /**
- * get OS-specific copy hotkey modifier key name based on user agent
- *
- * @access public
- * @static
- * @return string 'Cmd' on macOS, 'Ctrl' otherwise
- */
- public static function getCopyHotkey()
- {
- return array_key_exists('HTTP_USER_AGENT', $_SERVER) &&
- str_contains($_SERVER['HTTP_USER_AGENT'], 'Mac') ? self::_('Cmd') : self::_('Ctrl');
- }
- /**
- * set the default language
- *
- * @access public
- * @static
- * @param string $lang
- */
- public static function setLanguageFallback($lang)
- {
- if (in_array($lang, self::getAvailableLanguages())) {
- self::$_languageFallback = $lang;
- }
- }
- /**
- * get language file path
- *
- * @access protected
- * @static
- * @param string $file
- * @return string
- */
- protected static function _getPath($file = '')
- {
- if (empty(self::$_path)) {
- self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
- }
- return self::$_path . (empty($file) ? '' : DIRECTORY_SEPARATOR . $file);
- }
- /**
- * determines the plural form to use based on current language and given number
- *
- * From: https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
- *
- * @access protected
- * @static
- * @param int $n
- * @return int
- */
- protected static function _getPluralForm($n)
- {
- switch (self::$_language) {
- case 'ar':
- return $n === 0 ? 0 : ($n === 1 ? 1 : ($n === 2 ? 2 : ($n % 100 >= 3 && $n % 100 <= 10 ? 3 : ($n % 100 >= 11 ? 4 : 5))));
- case 'cs':
- case 'sk':
- return $n === 1 ? 0 : ($n >= 2 && $n <= 4 ? 1 : 2);
- case 'co':
- case 'fa':
- case 'fr':
- case 'oc':
- case 'tr':
- case 'zh':
- case 'zh-tw':
- return $n > 1 ? 1 : 0;
- case 'he':
- return $n === 1 ? 0 : ($n === 2 ? 1 : (($n < 0 || $n > 10) && ($n % 10 === 0) ? 2 : 3));
- case 'id':
- case 'ja':
- case 'jbo':
- case 'th':
- return 0;
- case 'lt':
- return $n % 10 === 1 && $n % 100 !== 11 ? 0 : (($n % 10 >= 2 && $n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
- case 'pl':
- return $n === 1 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
- case 'ro':
- return $n === 1 ? 0 : (($n === 0 || ($n % 100 > 0 && $n % 100 < 20)) ? 1 : 2);
- case 'ru':
- case 'uk':
- return $n % 10 === 1 && $n % 100 !== 11 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
- case 'sl':
- return $n % 100 === 1 ? 1 : ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0));
- default:
- // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt, sv
- return $n !== 1 ? 1 : 0;
- }
- }
- /**
- * compares two language preference arrays and returns the preferred match
- *
- * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
- *
- * @access protected
- * @static
- * @param array $acceptedLanguages
- * @param array $availableLanguages
- * @return string
- */
- protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
- {
- $matches = [];
- $any = false;
- foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
- $acceptedQuality = floatval($acceptedQuality);
- if ($acceptedQuality === 0.0) {
- continue;
- }
- foreach ($availableLanguages as $availableValue) {
- $availableQuality = 1.0;
- foreach ($acceptedValues as $acceptedValue) {
- if ($acceptedValue === '*') {
- $any = true;
- }
- $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
- if ($matchingGrade > 0) {
- $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
- if (!isset($matches[$q])) {
- $matches[$q] = [];
- }
- if (!in_array($availableValue, $matches[$q])) {
- $matches[$q][] = $availableValue;
- }
- }
- }
- }
- }
- if (count($matches) === 0 && $any) {
- if (count($availableLanguages) > 0) {
- $matches['1.0'] = $availableLanguages;
- }
- }
- if (count($matches) === 0) {
- return self::$_languageFallback;
- }
- krsort($matches);
- $topmatches = current($matches);
- return current($topmatches);
- }
- /**
- * compare two language IDs and return the degree they match
- *
- * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
- *
- * @access protected
- * @static
- * @param string $a
- * @param string $b
- * @return float
- */
- protected static function _matchLanguage($a, $b)
- {
- $a = explode('-', $a);
- $b = explode('-', $b);
- for ($i = 0, $n = min(count($a), count($b)); $i < $n; ++$i) {
- if ($a[$i] !== $b[$i]) {
- break;
- }
- }
- return $i === 0 ? 0 : (float) $i / count($a);
- }
- }
|