From 56f4fdc88a5e51525d926aac77fd8e3cfe9e8aac Mon Sep 17 00:00:00 2001 From: Joshua Ramon Enslin Date: Wed, 14 Apr 2021 17:59:11 +0200 Subject: [PATCH] Add function get_user_lang for getting user language based on cookies --- src/MD_STD.php | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/MD_STD.php b/src/MD_STD.php index fc3ff05..a3500b2 100644 --- a/src/MD_STD.php +++ b/src/MD_STD.php @@ -334,6 +334,45 @@ final class MD_STD { } + /** + * Sets and returns user language based on a session cookie. + * + * @param array $allowed_langs Allowed languages. + * @param string $default_lang Default language. + * + * @return string + */ + public function get_user_lang(array $allowed_langs, string $default_lang):string { + + $cookie_options = [ + 'expires' => self::strtotime("+1 month"), + 'path' => '/', + 'domain' => $_SERVER['SERVER_NAME'], + 'secure' => true, + 'httponly' => true, + 'samesite' => 'Lax' // None || Lax || Strict + ]; + + if (isset($_GET['navlang']) and in_array($_GET['navlang'], $allowed_langs, true)) { + if (!(setcookie('lang', $_GET['navlang'], $cookie_options))) { + throw new Exception("Failed to set language"); + } + $lang = $_GET['navlang']; + } + else if (isset($_COOKIE['lang']) and in_array($_COOKIE['lang'], $allowed_langs, true)) { + $lang = $_COOKIE['lang']; + } + else { + $lang = self::lang_getfrombrowser($allowed_langs, $default_lang, "", false); + if (!(setcookie('lang', $lang, $cookie_options))) { + throw new Exception("Failed to set language"); + } + } + + return $lang; + + } + /** * Function lang_getfrombrowser gets the browser language based on HTTP headers. *