Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

410 lines
11KB

  1. <?php
  2. /**
  3. * @file src/Core/L10n.php
  4. */
  5. namespace Friendica\Core;
  6. use Friendica\BaseObject;
  7. use Friendica\Database\DBA;
  8. use Friendica\Core\Addon;
  9. use Friendica\Core\Logger;
  10. use Friendica\Core\System;
  11. /**
  12. * Provide Language, Translation, and Localization functions to the application
  13. * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
  14. */
  15. class L10n extends BaseObject
  16. {
  17. /**
  18. * A string indicating the current language used for translation:
  19. * - Two-letter ISO 639-1 code.
  20. * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
  21. * @var string
  22. */
  23. private static $lang = '';
  24. /**
  25. * A language code saved for later after pushLang() has been called.
  26. *
  27. * @var string
  28. */
  29. private static $langSave = '';
  30. /**
  31. * An array of translation strings whose key is the neutral english message.
  32. *
  33. * @var array
  34. */
  35. private static $strings = [];
  36. /**
  37. * An array of translation strings saved for later after pushLang() has been called.
  38. *
  39. * @var array
  40. */
  41. private static $stringsSave = [];
  42. /**
  43. * Detects the language and sets the translation table
  44. */
  45. public static function init()
  46. {
  47. $lang = self::detectLanguage();
  48. self::loadTranslationTable($lang);
  49. }
  50. /**
  51. * Returns the current language code
  52. *
  53. * @return string Language code
  54. */
  55. public static function getCurrentLang()
  56. {
  57. return self::$lang;
  58. }
  59. /**
  60. * Sets the language session variable
  61. */
  62. public static function setSessionVariable()
  63. {
  64. if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) {
  65. $_SESSION['language'] = self::$lang;
  66. // we haven't loaded user data yet, but we need user language
  67. if (!empty($_SESSION['uid'])) {
  68. $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
  69. if (DBA::isResult($user)) {
  70. $_SESSION['language'] = $user['language'];
  71. }
  72. }
  73. }
  74. }
  75. public static function setLangFromSession()
  76. {
  77. if (!empty($_SESSION['language']) && $_SESSION['language'] !== self::$lang) {
  78. self::loadTranslationTable($_SESSION['language']);
  79. }
  80. }
  81. /**
  82. * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
  83. * @return string The two-letter language code
  84. */
  85. public static function detectLanguage()
  86. {
  87. $lang_list = [];
  88. if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  89. // break up string into pieces (languages and q factors)
  90. preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);
  91. if (count($lang_parse[1])) {
  92. // go through the list of prefered languages and add a generic language
  93. // for sub-linguas (e.g. de-ch will add de) if not already in array
  94. for ($i = 0; $i < count($lang_parse[1]); $i++) {
  95. $lang_list[] = strtolower($lang_parse[1][$i]);
  96. if (strlen($lang_parse[1][$i])>3) {
  97. $dashpos = strpos($lang_parse[1][$i], '-');
  98. if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) {
  99. $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos));
  100. }
  101. }
  102. }
  103. }
  104. }
  105. // check if we have translations for the preferred languages and pick the 1st that has
  106. foreach ($lang_list as $lang) {
  107. if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) {
  108. $preferred = $lang;
  109. break;
  110. }
  111. }
  112. if (isset($preferred)) {
  113. return $preferred;
  114. }
  115. // in case none matches, get the system wide configured language, or fall back to English
  116. return Config::get('system', 'language', 'en');
  117. }
  118. /**
  119. * This function should be called before formatting messages in a specific target language
  120. * different from the current user/system language.
  121. *
  122. * It saves the current translation strings in a separate variable and loads new translations strings.
  123. *
  124. * If called repeatedly, it won't save the translation strings again, just load the new ones.
  125. *
  126. * @see popLang()
  127. * @brief Stores the current language strings and load a different language.
  128. * @param string $lang Language code
  129. */
  130. public static function pushLang($lang)
  131. {
  132. if (!self::$lang) {
  133. self::init();
  134. }
  135. if ($lang === self::$lang) {
  136. return;
  137. }
  138. if (!self::$langSave) {
  139. self::$langSave = self::$lang;
  140. self::$stringsSave = self::$strings;
  141. }
  142. self::loadTranslationTable($lang);
  143. }
  144. /**
  145. * Restores the original user/system language after having used pushLang()
  146. */
  147. public static function popLang()
  148. {
  149. if (!self::$langSave) {
  150. return;
  151. }
  152. self::$strings = self::$stringsSave;
  153. self::$lang = self::$langSave;
  154. self::$stringsSave = [];
  155. self::$langSave = '';
  156. }
  157. /**
  158. * Loads string translation table
  159. *
  160. * First addon strings are loaded, then globals
  161. *
  162. * Uses an App object shim since all the strings files refer to $a->strings
  163. *
  164. * @param string $lang language code to load
  165. */
  166. private static function loadTranslationTable($lang)
  167. {
  168. if ($lang === self::$lang) {
  169. return;
  170. }
  171. $a = new \stdClass();
  172. $a->strings = [];
  173. // load enabled addons strings
  174. $addons = DBA::select('addon', ['name'], ['installed' => true]);
  175. while ($p = DBA::fetch($addons)) {
  176. $name = $p['name'];
  177. if (file_exists("addon/$name/lang/$lang/strings.php")) {
  178. include "addon/$name/lang/$lang/strings.php";
  179. }
  180. }
  181. if (file_exists("view/lang/$lang/strings.php")) {
  182. include "view/lang/$lang/strings.php";
  183. }
  184. self::$lang = $lang;
  185. self::$strings = $a->strings;
  186. unset($a);
  187. }
  188. /**
  189. * @brief Return the localized version of the provided string with optional string interpolation
  190. *
  191. * This function takes a english string as parameter, and if a localized version
  192. * exists for the current language, substitutes it before performing an eventual
  193. * string interpolation (sprintf) with additional optional arguments.
  194. *
  195. * Usages:
  196. * - L10n::t('This is an example')
  197. * - L10n::t('URL %s returned no result', $url)
  198. * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
  199. *
  200. * @param string $s
  201. * @param array $vars Variables to interpolate in the translation string
  202. * @return string
  203. */
  204. public static function t($s, ...$vars)
  205. {
  206. if (empty($s)) {
  207. return '';
  208. }
  209. if (!self::$lang) {
  210. self::init();
  211. }
  212. if (!empty(self::$strings[$s])) {
  213. $t = self::$strings[$s];
  214. $s = is_array($t) ? $t[0] : $t;
  215. }
  216. if (count($vars) > 0) {
  217. $s = sprintf($s, ...$vars);
  218. }
  219. return $s;
  220. }
  221. /**
  222. * @brief Return the localized version of a singular/plural string with optional string interpolation
  223. *
  224. * This function takes two english strings as parameters, singular and plural, as
  225. * well as a count. If a localized version exists for the current language, they
  226. * are used instead. Discrimination between singular and plural is done using the
  227. * localized function if any or the default one. Finally, a string interpolation
  228. * is performed using the count as parameter.
  229. *
  230. * Usages:
  231. * - L10n::tt('Like', 'Likes', $count)
  232. * - L10n::tt("%s user deleted", "%s users deleted", count($users))
  233. *
  234. * @param string $singular
  235. * @param string $plural
  236. * @param int $count
  237. * @return string
  238. */
  239. public static function tt($singular, $plural, $count)
  240. {
  241. if (!is_numeric($count)) {
  242. Logger::log('Non numeric count called by ' . System::callstack(20));
  243. }
  244. if (!self::$lang) {
  245. self::init();
  246. }
  247. if (!empty(self::$strings[$singular])) {
  248. $t = self::$strings[$singular];
  249. if (is_array($t)) {
  250. $plural_function = 'string_plural_select_' . str_replace('-', '_', self::$lang);
  251. if (function_exists($plural_function)) {
  252. $i = $plural_function($count);
  253. } else {
  254. $i = self::stringPluralSelectDefault($count);
  255. }
  256. // for some languages there is only a single array item
  257. if (!isset($t[$i])) {
  258. $s = $t[0];
  259. } else {
  260. $s = $t[$i];
  261. }
  262. } else {
  263. $s = $t;
  264. }
  265. } elseif (self::stringPluralSelectDefault($count)) {
  266. $s = $plural;
  267. } else {
  268. $s = $singular;
  269. }
  270. $s = @sprintf($s, $count);
  271. return $s;
  272. }
  273. /**
  274. * Provide a fallback which will not collide with a function defined in any language file
  275. */
  276. private static function stringPluralSelectDefault($n)
  277. {
  278. return $n != 1;
  279. }
  280. /**
  281. * @brief Return installed languages codes as associative array
  282. *
  283. * Scans the view/lang directory for the existence of "strings.php" files, and
  284. * returns an alphabetical list of their folder names (@-char language codes).
  285. * Adds the english language if it's missing from the list.
  286. *
  287. * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
  288. *
  289. * @return array
  290. */
  291. public static function getAvailableLanguages()
  292. {
  293. $langs = [];
  294. $strings_file_paths = glob('view/lang/*/strings.php');
  295. if (is_array($strings_file_paths) && count($strings_file_paths)) {
  296. if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
  297. $strings_file_paths[] = 'view/lang/en/strings.php';
  298. }
  299. asort($strings_file_paths);
  300. foreach ($strings_file_paths as $strings_file_path) {
  301. $path_array = explode('/', $strings_file_path);
  302. $langs[$path_array[2]] = $path_array[2];
  303. }
  304. }
  305. return $langs;
  306. }
  307. /**
  308. * @brief Translate days and months names.
  309. *
  310. * @param string $s String with day or month name.
  311. * @return string Translated string.
  312. */
  313. public static function getDay($s)
  314. {
  315. $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
  316. [self::t('Monday'), self::t('Tuesday'), self::t('Wednesday'), self::t('Thursday'), self::t('Friday'), self::t('Saturday'), self::t('Sunday')],
  317. $s);
  318. $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  319. [self::t('January'), self::t('February'), self::t('March'), self::t('April'), self::t('May'), self::t('June'), self::t('July'), self::t('August'), self::t('September'), self::t('October'), self::t('November'), self::t('December')],
  320. $ret);
  321. return $ret;
  322. }
  323. /**
  324. * @brief Translate short days and months names.
  325. *
  326. * @param string $s String with short day or month name.
  327. * @return string Translated string.
  328. */
  329. public static function getDayShort($s)
  330. {
  331. $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  332. [self::t('Mon'), self::t('Tue'), self::t('Wed'), self::t('Thu'), self::t('Fri'), self::t('Sat'), self::t('Sun')],
  333. $s);
  334. $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  335. [self::t('Jan'), self::t('Feb'), self::t('Mar'), self::t('Apr'), self::t('May'), ('Jun'), self::t('Jul'), self::t('Aug'), self::t('Sep'), self::t('Oct'), self::t('Nov'), self::t('Dec')],
  336. $ret);
  337. return $ret;
  338. }
  339. /**
  340. * Load poke verbs
  341. *
  342. * @return array index is present tense verb
  343. * value is array containing past tense verb, translation of present, translation of past
  344. * @hook poke_verbs pokes array
  345. */
  346. public static function getPokeVerbs()
  347. {
  348. // index is present tense verb
  349. // value is array containing past tense verb, translation of present, translation of past
  350. $arr = [
  351. 'poke' => ['poked', self::t('poke'), self::t('poked')],
  352. 'ping' => ['pinged', self::t('ping'), self::t('pinged')],
  353. 'prod' => ['prodded', self::t('prod'), self::t('prodded')],
  354. 'slap' => ['slapped', self::t('slap'), self::t('slapped')],
  355. 'finger' => ['fingered', self::t('finger'), self::t('fingered')],
  356. 'rebuff' => ['rebuffed', self::t('rebuff'), self::t('rebuffed')],
  357. ];
  358. Addon::callHooks('poke_verbs', $arr);
  359. return $arr;
  360. }
  361. }