Skip to content

Commit

Permalink
MDL-72882 core: Use default site lang when user lang no longer available
Browse files Browse the repository at this point in the history
* Check that the lang attribute for the output HTML exists. If not,
use the default site language.
* Also fix the current language for the user.
  • Loading branch information
junpataleta committed Nov 3, 2022
1 parent 720bd60 commit 03f298a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
33 changes: 33 additions & 0 deletions lib/moodlelib.php
Expand Up @@ -7161,6 +7161,39 @@ function current_language() {
return $return;
}

/**
* Fix the current language to the given language code.
*
* @param string $lang The language code to use.
* @return void
*/
function fix_current_language(string $lang): void {
global $CFG, $COURSE, $SESSION, $USER;

if (!get_string_manager()->translation_exists($lang)) {
throw new coding_exception("The language pack for $lang is not available");
}

$fixglobal = '';
$fixlang = 'lang';
if (!empty($SESSION->forcelang)) {
$fixglobal = $SESSION;
$fixlang = 'forcelang';
} else if (!empty($COURSE->id) && $COURSE->id != SITEID && !empty($COURSE->lang)) {
$fixglobal = $COURSE;
} else if (!empty($SESSION->lang)) {
$fixglobal = $SESSION;
} else if (!empty($USER->lang)) {
$fixglobal = $USER;
} else if (isset($CFG->lang)) {
set_config('lang', $lang);
}

if ($fixglobal) {
$fixglobal->$fixlang = $lang;
}
}

/**
* Returns parent language of current active language if defined
*
Expand Down
13 changes: 12 additions & 1 deletion lib/weblib.php
Expand Up @@ -2233,6 +2233,16 @@ function get_html_lang_attribute_value(string $langcode): string {
* @return string Attributes
*/
function get_html_lang($dir = false) {
global $CFG;

$currentlang = current_language();
if ($currentlang !== $CFG->lang && !get_string_manager()->translation_exists($currentlang)) {
// Use the default site language when the current language is not available.
$currentlang = $CFG->lang;
// Fix the current language.
fix_current_language($currentlang);
}

$direction = '';
if ($dir) {
if (right_to_left()) {
Expand All @@ -2241,8 +2251,9 @@ function get_html_lang($dir = false) {
$direction = ' dir="ltr"';
}
}

// Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
$language = get_html_lang_attribute_value(current_language());
$language = get_html_lang_attribute_value($currentlang);
@header('Content-Language: '.$language);
return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
}
Expand Down

0 comments on commit 03f298a

Please sign in to comment.