language.inc.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * CustomPages : Browser language detection
  5. * Include this file in your custom page if you want to set the language variable of the Chamilo session
  6. * to the best pick according to the visitor's browser's options.
  7. * 2011, Jean-Karim Bockstael, CBlue <jeankarim@cblue.be>
  8. * This requires the Chamilo system to be initialized
  9. * (note that it's easier to do the following include in the parent page).
  10. *
  11. * @package chamilo.custompages
  12. */
  13. /**
  14. * Returns the best match between available languages and visitor preferences.
  15. *
  16. * @return string the best match as 2-chars code, null when none match
  17. */
  18. function get_preferred_language($available_langs)
  19. {
  20. // Parsing the Accept-languages HTTP header
  21. $langs = [];
  22. foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $httplang) {
  23. $rawlang = explode(';q=', $httplang);
  24. if (strpos($rawlang[0], '-') !== false) {
  25. // We ignore the locale part, as in en-GB vs en-US
  26. $rawlang[0] = substr($rawlang[0], 0, strpos($rawlang[0], '-'));
  27. }
  28. if (count($rawlang) == 1) {
  29. $rawlang[1] = 1.0; // The absence of weighting means a weight of 1 (max)
  30. }
  31. $langs[$rawlang[1]][] = $rawlang[0];
  32. }
  33. krsort($langs, SORT_NUMERIC);
  34. // Choosing the best match
  35. foreach ($langs as $weight => $codes) {
  36. foreach ($codes as $code) {
  37. if (in_array($code, $available_langs)) {
  38. return $code;
  39. }
  40. }
  41. }
  42. // No match
  43. return null;
  44. }
  45. /**
  46. * Get a language variable in a specific language.
  47. */
  48. function custompages_get_lang($variable)
  49. {
  50. return get_lang($variable, null, $_SESSION['user_language_choice']);
  51. }