trans_real.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. """Translation helper functions."""
  2. import functools
  3. import gettext as gettext_module
  4. import os
  5. import re
  6. import sys
  7. import warnings
  8. from asgiref.local import Local
  9. from django.apps import apps
  10. from django.conf import settings
  11. from django.conf.locale import LANG_INFO
  12. from django.core.exceptions import AppRegistryNotReady
  13. from django.core.signals import setting_changed
  14. from django.dispatch import receiver
  15. from django.utils.regex_helper import _lazy_re_compile
  16. from django.utils.safestring import SafeData, mark_safe
  17. from . import to_language, to_locale
  18. # Translations are cached in a dictionary for every language.
  19. # The active translations are stored by threadid to make them thread local.
  20. _translations = {}
  21. _active = Local()
  22. # The default translation is based on the settings file.
  23. _default = None
  24. # magic gettext number to separate context from message
  25. CONTEXT_SEPARATOR = "\x04"
  26. # Maximum number of characters that will be parsed from the Accept-Language
  27. # header to prevent possible denial of service or memory exhaustion attacks.
  28. # About 10x longer than the longest value shown on MDN’s Accept-Language page.
  29. ACCEPT_LANGUAGE_HEADER_MAX_LENGTH = 500
  30. # Format of Accept-Language header values. From RFC 9110 Sections 12.4.2 and
  31. # 12.5.4, and RFC 5646 Section 2.1.
  32. accept_language_re = _lazy_re_compile(
  33. r"""
  34. # "en", "en-au", "x-y-z", "es-419", "*"
  35. ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*)
  36. # Optional "q=1.00", "q=0.8"
  37. (?:\s*;\s*q=(0(?:\.[0-9]{,3})?|1(?:\.0{,3})?))?
  38. # Multiple accepts per header.
  39. (?:\s*,\s*|$)
  40. """,
  41. re.VERBOSE,
  42. )
  43. language_code_re = _lazy_re_compile(
  44. r"^[a-z]{1,8}(?:-[a-z0-9]{1,8})*(?:@[a-z0-9]{1,20})?$", re.IGNORECASE
  45. )
  46. language_code_prefix_re = _lazy_re_compile(r"^/(\w+([@-]\w+){0,2})(/|$)")
  47. @receiver(setting_changed)
  48. def reset_cache(*, setting, **kwargs):
  49. """
  50. Reset global state when LANGUAGES setting has been changed, as some
  51. languages should no longer be accepted.
  52. """
  53. if setting in ("LANGUAGES", "LANGUAGE_CODE"):
  54. check_for_language.cache_clear()
  55. get_languages.cache_clear()
  56. get_supported_language_variant.cache_clear()
  57. class TranslationCatalog:
  58. """
  59. Simulate a dict for DjangoTranslation._catalog so as multiple catalogs
  60. with different plural equations are kept separate.
  61. """
  62. def __init__(self, trans=None):
  63. self._catalogs = [trans._catalog.copy()] if trans else [{}]
  64. self._plurals = [trans.plural] if trans else [lambda n: int(n != 1)]
  65. def __getitem__(self, key):
  66. for cat in self._catalogs:
  67. try:
  68. return cat[key]
  69. except KeyError:
  70. pass
  71. raise KeyError(key)
  72. def __setitem__(self, key, value):
  73. self._catalogs[0][key] = value
  74. def __contains__(self, key):
  75. return any(key in cat for cat in self._catalogs)
  76. def items(self):
  77. for cat in self._catalogs:
  78. yield from cat.items()
  79. def keys(self):
  80. for cat in self._catalogs:
  81. yield from cat.keys()
  82. def update(self, trans):
  83. # Merge if plural function is the same, else prepend.
  84. for cat, plural in zip(self._catalogs, self._plurals):
  85. if trans.plural.__code__ == plural.__code__:
  86. cat.update(trans._catalog)
  87. break
  88. else:
  89. self._catalogs.insert(0, trans._catalog.copy())
  90. self._plurals.insert(0, trans.plural)
  91. def get(self, key, default=None):
  92. missing = object()
  93. for cat in self._catalogs:
  94. result = cat.get(key, missing)
  95. if result is not missing:
  96. return result
  97. return default
  98. def plural(self, msgid, num):
  99. for cat, plural in zip(self._catalogs, self._plurals):
  100. tmsg = cat.get((msgid, plural(num)))
  101. if tmsg is not None:
  102. return tmsg
  103. raise KeyError
  104. class DjangoTranslation(gettext_module.GNUTranslations):
  105. """
  106. Set up the GNUTranslations context with regard to output charset.
  107. This translation object will be constructed out of multiple GNUTranslations
  108. objects by merging their catalogs. It will construct an object for the
  109. requested language and add a fallback to the default language, if it's
  110. different from the requested language.
  111. """
  112. domain = "django"
  113. def __init__(self, language, domain=None, localedirs=None):
  114. """Create a GNUTranslations() using many locale directories"""
  115. gettext_module.GNUTranslations.__init__(self)
  116. if domain is not None:
  117. self.domain = domain
  118. self.__language = language
  119. self.__to_language = to_language(language)
  120. self.__locale = to_locale(language)
  121. self._catalog = None
  122. # If a language doesn't have a catalog, use the Germanic default for
  123. # pluralization: anything except one is pluralized.
  124. self.plural = lambda n: int(n != 1)
  125. if self.domain == "django":
  126. if localedirs is not None:
  127. # A module-level cache is used for caching 'django' translations
  128. warnings.warn(
  129. "localedirs is ignored when domain is 'django'.", RuntimeWarning
  130. )
  131. localedirs = None
  132. self._init_translation_catalog()
  133. if localedirs:
  134. for localedir in localedirs:
  135. translation = self._new_gnu_trans(localedir)
  136. self.merge(translation)
  137. else:
  138. self._add_installed_apps_translations()
  139. self._add_local_translations()
  140. if (
  141. self.__language == settings.LANGUAGE_CODE
  142. and self.domain == "django"
  143. and self._catalog is None
  144. ):
  145. # default lang should have at least one translation file available.
  146. raise OSError(
  147. "No translation files found for default language %s."
  148. % settings.LANGUAGE_CODE
  149. )
  150. self._add_fallback(localedirs)
  151. if self._catalog is None:
  152. # No catalogs found for this language, set an empty catalog.
  153. self._catalog = TranslationCatalog()
  154. def __repr__(self):
  155. return "<DjangoTranslation lang:%s>" % self.__language
  156. def _new_gnu_trans(self, localedir, use_null_fallback=True):
  157. """
  158. Return a mergeable gettext.GNUTranslations instance.
  159. A convenience wrapper. By default gettext uses 'fallback=False'.
  160. Using param `use_null_fallback` to avoid confusion with any other
  161. references to 'fallback'.
  162. """
  163. return gettext_module.translation(
  164. domain=self.domain,
  165. localedir=localedir,
  166. languages=[self.__locale],
  167. fallback=use_null_fallback,
  168. )
  169. def _init_translation_catalog(self):
  170. """Create a base catalog using global django translations."""
  171. settingsfile = sys.modules[settings.__module__].__file__
  172. localedir = os.path.join(os.path.dirname(settingsfile), "locale")
  173. translation = self._new_gnu_trans(localedir)
  174. self.merge(translation)
  175. def _add_installed_apps_translations(self):
  176. """Merge translations from each installed app."""
  177. try:
  178. app_configs = reversed(apps.get_app_configs())
  179. except AppRegistryNotReady:
  180. raise AppRegistryNotReady(
  181. "The translation infrastructure cannot be initialized before the "
  182. "apps registry is ready. Check that you don't make non-lazy "
  183. "gettext calls at import time."
  184. )
  185. for app_config in app_configs:
  186. localedir = os.path.join(app_config.path, "locale")
  187. if os.path.exists(localedir):
  188. translation = self._new_gnu_trans(localedir)
  189. self.merge(translation)
  190. def _add_local_translations(self):
  191. """Merge translations defined in LOCALE_PATHS."""
  192. for localedir in reversed(settings.LOCALE_PATHS):
  193. translation = self._new_gnu_trans(localedir)
  194. self.merge(translation)
  195. def _add_fallback(self, localedirs=None):
  196. """Set the GNUTranslations() fallback with the default language."""
  197. # Don't set a fallback for the default language or any English variant
  198. # (as it's empty, so it'll ALWAYS fall back to the default language)
  199. if self.__language == settings.LANGUAGE_CODE or self.__language.startswith(
  200. "en"
  201. ):
  202. return
  203. if self.domain == "django":
  204. # Get from cache
  205. default_translation = translation(settings.LANGUAGE_CODE)
  206. else:
  207. default_translation = DjangoTranslation(
  208. settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs
  209. )
  210. self.add_fallback(default_translation)
  211. def merge(self, other):
  212. """Merge another translation into this catalog."""
  213. if not getattr(other, "_catalog", None):
  214. return # NullTranslations() has no _catalog
  215. if self._catalog is None:
  216. # Take plural and _info from first catalog found (generally Django's).
  217. self.plural = other.plural
  218. self._info = other._info.copy()
  219. self._catalog = TranslationCatalog(other)
  220. else:
  221. self._catalog.update(other)
  222. if other._fallback:
  223. self.add_fallback(other._fallback)
  224. def language(self):
  225. """Return the translation language."""
  226. return self.__language
  227. def to_language(self):
  228. """Return the translation language name."""
  229. return self.__to_language
  230. def ngettext(self, msgid1, msgid2, n):
  231. try:
  232. tmsg = self._catalog.plural(msgid1, n)
  233. except KeyError:
  234. if self._fallback:
  235. return self._fallback.ngettext(msgid1, msgid2, n)
  236. if n == 1:
  237. tmsg = msgid1
  238. else:
  239. tmsg = msgid2
  240. return tmsg
  241. def translation(language):
  242. """
  243. Return a translation object in the default 'django' domain.
  244. """
  245. global _translations
  246. if language not in _translations:
  247. _translations[language] = DjangoTranslation(language)
  248. return _translations[language]
  249. def activate(language):
  250. """
  251. Fetch the translation object for a given language and install it as the
  252. current translation object for the current thread.
  253. """
  254. if not language:
  255. return
  256. _active.value = translation(language)
  257. def deactivate():
  258. """
  259. Uninstall the active translation object so that further _() calls resolve
  260. to the default translation object.
  261. """
  262. if hasattr(_active, "value"):
  263. del _active.value
  264. def deactivate_all():
  265. """
  266. Make the active translation object a NullTranslations() instance. This is
  267. useful when we want delayed translations to appear as the original string
  268. for some reason.
  269. """
  270. _active.value = gettext_module.NullTranslations()
  271. _active.value.to_language = lambda *args: None
  272. def get_language():
  273. """Return the currently selected language."""
  274. t = getattr(_active, "value", None)
  275. if t is not None:
  276. try:
  277. return t.to_language()
  278. except AttributeError:
  279. pass
  280. # If we don't have a real translation object, assume it's the default language.
  281. return settings.LANGUAGE_CODE
  282. def get_language_bidi():
  283. """
  284. Return selected language's BiDi layout.
  285. * False = left-to-right layout
  286. * True = right-to-left layout
  287. """
  288. lang = get_language()
  289. if lang is None:
  290. return False
  291. else:
  292. base_lang = get_language().split("-")[0]
  293. return base_lang in settings.LANGUAGES_BIDI
  294. def catalog():
  295. """
  296. Return the current active catalog for further processing.
  297. This can be used if you need to modify the catalog or want to access the
  298. whole message catalog instead of just translating one string.
  299. """
  300. global _default
  301. t = getattr(_active, "value", None)
  302. if t is not None:
  303. return t
  304. if _default is None:
  305. _default = translation(settings.LANGUAGE_CODE)
  306. return _default
  307. def gettext(message):
  308. """
  309. Translate the 'message' string. It uses the current thread to find the
  310. translation object to use. If no current translation is activated, the
  311. message will be run through the default translation object.
  312. """
  313. global _default
  314. eol_message = message.replace("\r\n", "\n").replace("\r", "\n")
  315. if eol_message:
  316. _default = _default or translation(settings.LANGUAGE_CODE)
  317. translation_object = getattr(_active, "value", _default)
  318. result = translation_object.gettext(eol_message)
  319. else:
  320. # Return an empty value of the corresponding type if an empty message
  321. # is given, instead of metadata, which is the default gettext behavior.
  322. result = type(message)("")
  323. if isinstance(message, SafeData):
  324. return mark_safe(result)
  325. return result
  326. def pgettext(context, message):
  327. msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
  328. result = gettext(msg_with_ctxt)
  329. if CONTEXT_SEPARATOR in result:
  330. # Translation not found
  331. result = message
  332. elif isinstance(message, SafeData):
  333. result = mark_safe(result)
  334. return result
  335. def gettext_noop(message):
  336. """
  337. Mark strings for translation but don't translate them now. This can be
  338. used to store strings in global variables that should stay in the base
  339. language (because they might be used externally) and will be translated
  340. later.
  341. """
  342. return message
  343. def do_ntranslate(singular, plural, number, translation_function):
  344. global _default
  345. t = getattr(_active, "value", None)
  346. if t is not None:
  347. return getattr(t, translation_function)(singular, plural, number)
  348. if _default is None:
  349. _default = translation(settings.LANGUAGE_CODE)
  350. return getattr(_default, translation_function)(singular, plural, number)
  351. def ngettext(singular, plural, number):
  352. """
  353. Return a string of the translation of either the singular or plural,
  354. based on the number.
  355. """
  356. return do_ntranslate(singular, plural, number, "ngettext")
  357. def npgettext(context, singular, plural, number):
  358. msgs_with_ctxt = (
  359. "%s%s%s" % (context, CONTEXT_SEPARATOR, singular),
  360. "%s%s%s" % (context, CONTEXT_SEPARATOR, plural),
  361. number,
  362. )
  363. result = ngettext(*msgs_with_ctxt)
  364. if CONTEXT_SEPARATOR in result:
  365. # Translation not found
  366. result = ngettext(singular, plural, number)
  367. return result
  368. def all_locale_paths():
  369. """
  370. Return a list of paths to user-provides languages files.
  371. """
  372. globalpath = os.path.join(
  373. os.path.dirname(sys.modules[settings.__module__].__file__), "locale"
  374. )
  375. app_paths = []
  376. for app_config in apps.get_app_configs():
  377. locale_path = os.path.join(app_config.path, "locale")
  378. if os.path.exists(locale_path):
  379. app_paths.append(locale_path)
  380. return [globalpath, *settings.LOCALE_PATHS, *app_paths]
  381. @functools.lru_cache(maxsize=1000)
  382. def check_for_language(lang_code):
  383. """
  384. Check whether there is a global language file for the given language
  385. code. This is used to decide whether a user-provided language is
  386. available.
  387. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  388. as the provided language codes are taken from the HTTP request. See also
  389. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  390. """
  391. # First, a quick check to make sure lang_code is well-formed (#21458)
  392. if lang_code is None or not language_code_re.search(lang_code):
  393. return False
  394. return any(
  395. gettext_module.find("django", path, [to_locale(lang_code)]) is not None
  396. for path in all_locale_paths()
  397. )
  398. @functools.lru_cache
  399. def get_languages():
  400. """
  401. Cache of settings.LANGUAGES in a dictionary for easy lookups by key.
  402. Convert keys to lowercase as they should be treated as case-insensitive.
  403. """
  404. return {key.lower(): value for key, value in dict(settings.LANGUAGES).items()}
  405. @functools.lru_cache(maxsize=1000)
  406. def get_supported_language_variant(lang_code, strict=False):
  407. """
  408. Return the language code that's listed in supported languages, possibly
  409. selecting a more generic variant. Raise LookupError if nothing is found.
  410. If `strict` is False (the default), look for a country-specific variant
  411. when neither the language code nor its generic variant is found.
  412. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  413. as the provided language codes are taken from the HTTP request. See also
  414. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  415. """
  416. if lang_code:
  417. # If 'zh-hant-tw' is not supported, try special fallback or subsequent
  418. # language codes i.e. 'zh-hant' and 'zh'.
  419. possible_lang_codes = [lang_code]
  420. try:
  421. possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"])
  422. except KeyError:
  423. pass
  424. i = None
  425. while (i := lang_code.rfind("-", 0, i)) > -1:
  426. possible_lang_codes.append(lang_code[:i])
  427. generic_lang_code = possible_lang_codes[-1]
  428. supported_lang_codes = get_languages()
  429. for code in possible_lang_codes:
  430. if code.lower() in supported_lang_codes and check_for_language(code):
  431. return code
  432. if not strict:
  433. # if fr-fr is not supported, try fr-ca.
  434. for supported_code in supported_lang_codes:
  435. if supported_code.startswith(generic_lang_code + "-"):
  436. return supported_code
  437. raise LookupError(lang_code)
  438. def get_language_from_path(path, strict=False):
  439. """
  440. Return the language code if there's a valid language code found in `path`.
  441. If `strict` is False (the default), look for a country-specific variant
  442. when neither the language code nor its generic variant is found.
  443. """
  444. regex_match = language_code_prefix_re.match(path)
  445. if not regex_match:
  446. return None
  447. lang_code = regex_match[1]
  448. try:
  449. return get_supported_language_variant(lang_code, strict=strict)
  450. except LookupError:
  451. return None
  452. def get_language_from_request(request, check_path=False):
  453. """
  454. Analyze the request to find what language the user wants the system to
  455. show. Only languages listed in settings.LANGUAGES are taken into account.
  456. If the user requests a sublanguage where we have a main language, we send
  457. out the main language.
  458. If check_path is True, the URL path prefix will be checked for a language
  459. code, otherwise this is skipped for backwards compatibility.
  460. """
  461. if check_path:
  462. lang_code = get_language_from_path(request.path_info)
  463. if lang_code is not None:
  464. return lang_code
  465. lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
  466. if (
  467. lang_code is not None
  468. and lang_code in get_languages()
  469. and check_for_language(lang_code)
  470. ):
  471. return lang_code
  472. try:
  473. return get_supported_language_variant(lang_code)
  474. except LookupError:
  475. pass
  476. accept = request.META.get("HTTP_ACCEPT_LANGUAGE", "")
  477. for accept_lang, unused in parse_accept_lang_header(accept):
  478. if accept_lang == "*":
  479. break
  480. if not language_code_re.search(accept_lang):
  481. continue
  482. try:
  483. return get_supported_language_variant(accept_lang)
  484. except LookupError:
  485. continue
  486. try:
  487. return get_supported_language_variant(settings.LANGUAGE_CODE)
  488. except LookupError:
  489. return settings.LANGUAGE_CODE
  490. @functools.lru_cache(maxsize=1000)
  491. def _parse_accept_lang_header(lang_string):
  492. """
  493. Parse the lang_string, which is the body of an HTTP Accept-Language
  494. header, and return a tuple of (lang, q-value), ordered by 'q' values.
  495. Return an empty tuple if there are any format errors in lang_string.
  496. """
  497. result = []
  498. pieces = accept_language_re.split(lang_string.lower())
  499. if pieces[-1]:
  500. return ()
  501. for i in range(0, len(pieces) - 1, 3):
  502. first, lang, priority = pieces[i : i + 3]
  503. if first:
  504. return ()
  505. if priority:
  506. priority = float(priority)
  507. else:
  508. priority = 1.0
  509. result.append((lang, priority))
  510. result.sort(key=lambda k: k[1], reverse=True)
  511. return tuple(result)
  512. def parse_accept_lang_header(lang_string):
  513. """
  514. Parse the value of the Accept-Language header up to a maximum length.
  515. The value of the header is truncated to a maximum length to avoid potential
  516. denial of service and memory exhaustion attacks. Excessive memory could be
  517. used if the raw value is very large as it would be cached due to the use of
  518. functools.lru_cache() to avoid repetitive parsing of common header values.
  519. """
  520. # If the header value doesn't exceed the maximum allowed length, parse it.
  521. if len(lang_string) <= ACCEPT_LANGUAGE_HEADER_MAX_LENGTH:
  522. return _parse_accept_lang_header(lang_string)
  523. # If there is at least one comma in the value, parse up to the last comma
  524. # before the max length, skipping any truncated parts at the end of the
  525. # header value.
  526. if (index := lang_string.rfind(",", 0, ACCEPT_LANGUAGE_HEADER_MAX_LENGTH)) > 0:
  527. return _parse_accept_lang_header(lang_string[:index])
  528. # Don't attempt to parse if there is only one language-range value which is
  529. # longer than the maximum allowed length and so truncated.
  530. return ()