trans_real.py 22 KB

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