Move LSsession lang stuff to dedicated LSlang class

This commit is contained in:
Benjamin Renard 2020-05-06 16:06:05 +02:00
parent 1f24bdb531
commit 52f7c3a205
6 changed files with 219 additions and 160 deletions

View file

@ -164,7 +164,7 @@ class LSformElement_date extends LSformElement {
); );
LSsession :: addJSconfigParam($this -> name, $params); LSsession :: addJSconfigParam($this -> name, $params);
$codeLang = str_replace('_','-',preg_replace('/\..*$/','',LSsession :: getLang())); $codeLang = str_replace('_','-',preg_replace('/\..*$/','', LSlang :: getLang()));
LSsession :: addLibJSscript('arian-mootools-datepicker/Picker.js'); LSsession :: addLibJSscript('arian-mootools-datepicker/Picker.js');
LSsession :: addLibJSscript('arian-mootools-datepicker/Picker.Attach.js'); LSsession :: addLibJSscript('arian-mootools-datepicker/Picker.Attach.js');

View file

@ -0,0 +1,192 @@
<?php
/*******************************************************************************
* Copyright (C) 2007 Easter-eggs
* http://ldapsaisie.labs.libre-entreprise.org
*
* Author: See AUTHORS file in top-level directory.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
******************************************************************************/
class LSlang {
// Current lang and encoding
private static $lang = NULL;
private static $encoding = NULL;
/**
* Define current locale (and encoding)
*
* @param[in] $lang string|null The lang (optional, default: default current LDAP
* server lang, or default lang)
* @param[in] $encoding string|null The encoding (optional, default: default current LDAP
* server encoding, or default encoding)
*
* @retval void
*/
public static function setLocale($lang=null, $encoding=null) {
// Handle $lang parameter
if (is_null($lang)) {
if (isset($_REQUEST['lang'])) {
$lang = $_REQUEST['lang'];
}
elseif (isset($_SESSION['LSlang'])) {
$lang = $_SESSION['LSlang'];
}
elseif (isset(LSsession :: $ldapServer['lang'])) {
$lang = LSsession :: $ldapServer['lang'];
}
else {
$lang = LSconfig :: get('lang');
}
}
// Handle $encoding parameter
if (is_null($encoding)) {
if (isset($_REQUEST['encoding'])) {
$encoding = $_REQUEST['encoding'];
}
elseif (isset($_SESSION['LSencoding'])) {
$encoding = $_SESSION['LSencoding'];
}
elseif (isset(LSsession :: $ldapServer['encoding'])) {
$encoding = LSsession :: $ldapServer['encoding'];
}
else {
$encoding = LSconfig :: get('encoding');
}
}
// Set session and self variables
$_SESSION['LSlang'] = self :: $lang = $lang;
$_SESSION['LSencoding'] = self :: $encoding = $encoding;
// Check
if (self :: localeExist($lang, $encoding)) {
LSlog :: debug("LSsession :: setLocale() : Use local '$lang.$encoding'");
if ($encoding) {
$lang .= '.'.$encoding;
}
// Gettext firstly look the LANGUAGE env variable, so set it
putenv("LANGUAGE=$lang");
// Set the locale
if (setlocale(LC_ALL, $lang) === false)
LSlog :: error("An error occured setting locale to '$lang'");
// Configure and set the text domain
$fullpath = bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR_PATH);
LSlog :: debug("Text domain fullpath is '$fullpath'.");
LSlog :: debug("Text domain is : ".textdomain(LS_TEXT_DOMAIN));
// Include local translation file
LSsession :: includeFile(LS_I18N_DIR.'/'.$lang.'/lang.php');
// Include other local translation file(s)
foreach(array(LS_I18N_DIR_PATH.'/'.$lang, LS_LOCAL_DIR.'/'.LS_I18N_DIR.'/'.$lang) as $lang_dir) {
if (is_dir($lang_dir)) {
foreach (listFiles($lang_dir, '/^lang.+\.php$/') as $file) {
$path = "$lang_dir/$file";
LSlog :: debug("LSession :: setLocale() : Local '$lang.$encoding' : load translation file '$path'");
include($path);
}
}
}
}
else {
if ($encoding && $lang) $lang .= '.'.$encoding;
LSlog :: error("The local '$lang' does not exists, use default one.");
}
}
/**
* Return list of available languages
*
* @retval array List of available languages.
**/
public static function getLangList() {
$list = array('en_US');
if (self :: $encoding) {
$regex = '/^([a-zA-Z_]*)\.'.self :: $encoding.'$/';
}
else {
$regex = '/^([a-zA-Z_]*)$/';
}
foreach(array(LS_I18N_DIR_PATH, LS_LOCAL_DIR.'/'.LS_I18N_DIR) as $lang_dir) {
if (!is_dir($lang_dir))
continue;
if ($handle = opendir($lang_dir)) {
while (false !== ($file = readdir($handle))) {
if(is_dir("$lang_dir/$file")) {
if (preg_match($regex, $file, $regs)) {
if (!in_array($regs[1], $list)) {
$list[]=$regs[1];
}
}
}
}
}
}
return $list;
}
/**
* Return current language
*
* @param[in] boolean If true, only return the two first characters of the language
* (For instance, 'fr' for 'fr_FR')
*
* @retval string The current language (ex: fr_FR, or fr if $short==true)
**/
public static function getLang($short=false) {
if ($short) {
return strtolower(substr(self :: $lang, 0, 2));
}
return self :: $lang;
}
/**
* Return current encoding
*
* @retval string The current encoding (ex: UTF8)
**/
public static function getEncoding() {
return self :: $encoding;
}
/**
* Check a locale exists
*
* @param[in] $lang string The language (ex: fr_FR)
* @param[in] $encoding string The encoding (ex: UTF8)
*
* @retval boolean True if the locale is available, False otherwise
**/
public static function localeExist($lang, $encoding) {
if ( !$lang && !$encoding ) {
return;
}
$locale=$lang.(($encoding)?'.'.$encoding:'');
if ($locale == 'en_US.UTF8') {
return true;
}
foreach(array(LS_I18N_DIR_PATH, LS_LOCAL_DIR.'/'.LS_I18N_DIR) as $lang_dir)
if (is_dir("$lang_dir/$locale"))
return true;
return false;
}
}

View file

@ -57,10 +57,6 @@ class LSsession {
// Les fichiers temporaires // Les fichiers temporaires
private static $tmp_file = array(); private static $tmp_file = array();
// Langue et encodage actuel
private static $lang = NULL;
private static $encoding = NULL;
/* /*
* Constante de classe non stockée en session * Constante de classe non stockée en session
*/ */
@ -402,162 +398,34 @@ class LSsession {
return true; return true;
} }
/** /**
* Défini la locale * Load and start LSlang, the I18N manager
* *
* @retval void * @param[in] $lang string|null The lang (optional, default: see LSlang :: setLocale())
* @param[in] $encoding string|null The encoding (optional, default: see LSlang :: setLocale())
*
* @author Benjamin Renard <brenard@easter-eggs.com
*
* @retval boolean true if LSlang started, false otherwise
*/ */
public static function setLocale($lang=null,$encoding=null) { private static function startLSlang($lang=null, $encoding=null) {
if (is_null($lang)) { if(!self :: loadLSclass('LSlang')) {
if (isset($_REQUEST['lang'])) {
$lang = $_REQUEST['lang'];
}
elseif (isset($_SESSION['LSlang'])) {
$lang = $_SESSION['LSlang'];
}
elseif (isset(self :: $ldapServer['lang'])) {
$lang = self :: $ldapServer['lang'];
}
else {
$lang = LSconfig :: get('lang');
}
}
if (is_null($encoding)) {
if (isset($_REQUEST['encoding'])) {
$encoding = $_REQUEST['encoding'];
}
elseif (isset($_SESSION['LSencoding'])) {
$encoding = $_SESSION['LSencoding'];
}
elseif (isset(self :: $ldapServer['encoding'])) {
$encoding = self :: $ldapServer['encoding'];
}
else {
$encoding = LSconfig :: get('encoding');
}
}
$_SESSION['LSlang']=$lang;
self :: $lang=$lang;
$_SESSION['LSencoding']=$encoding;
self :: $encoding=$encoding;
if (self :: localeExist($lang,$encoding)) {
LSlog :: debug("LSsession :: setLocale() : Use local '$lang.$encoding'");
if ($encoding) {
$lang.='.'.$encoding;
}
// Gettext firstly look the LANGUAGE env variable, so set it
putenv("LANGUAGE=$lang");
// Set the locale
if (setlocale(LC_ALL, $lang) === false)
LSlog :: error("An error occured setting locale to '$lang'");
// Configure and set the text domain
$fullpath = bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR_PATH);
LSlog :: debug("Text domain fullpath is '$fullpath'.");
LSlog :: debug("Text domain is : ".textdomain(LS_TEXT_DOMAIN));
// Include local translation file
self :: includeFile(LS_I18N_DIR.'/'.$lang.'/lang.php');
// Include other local translation file(s)
foreach(array(LS_I18N_DIR_PATH.'/'.$lang, LS_LOCAL_DIR.'/'.LS_I18N_DIR.'/'.$lang) as $lang_dir) {
if (is_dir($lang_dir)) {
foreach (listFiles($lang_dir, '/^lang.+\.php$/') as $file) {
$path = "$lang_dir/$file";
LSlog :: debug("LSession :: setLocale() : Local '$lang.$encoding' : load translation file '$path'");
include($path);
}
}
}
}
else {
if ($encoding && $lang) {
$lang.='.'.$encoding;
}
LSlog :: error("The local '$lang' does not exists , use default one.");
}
}
/**
* Retourne la liste des langues disponibles
*
* @retval array Tableau/Liste des langues disponibles
**/
public static function getLangList() {
$list=array('en_US');
if (self :: $encoding) {
$regex = '/^([a-zA-Z_]*)\.'.self :: $encoding.'$/';
}
else {
$regex = '/^([a-zA-Z_]*)$/';
}
foreach(array(LS_I18N_DIR_PATH, LS_LOCAL_DIR.'/'.LS_I18N_DIR) as $lang_dir) {
if (!is_dir($lang_dir))
continue;
if ($handle = opendir($lang_dir)) {
while (false !== ($file = readdir($handle))) {
if(is_dir("$lang_dir/$file")) {
if (preg_match($regex, $file, $regs)) {
if (!in_array($regs[1], $list)) {
$list[]=$regs[1];
}
}
}
}
}
}
return $list;
}
/**
* Retourne la langue courante de la session
*
* @param[in] boolean Si true, le code langue retourné sera court
*
* @retval string La langue de la session
**/
public static function getLang($short=false) {
if ($short) {
return strtolower(self :: $lang[0].self :: $lang[1]);
}
return self :: $lang;
}
/**
* Vérifie si une locale est disponible
*
* @param[in] $lang string La langue (Ex : fr_FR)
* @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
*
* @retval boolean True si la locale est disponible, False sinon
**/
public static function localeExist($lang, $encoding) {
if ( !$lang && !$encoding ) {
return; return;
} }
$locale=$lang.(($encoding)?'.'.$encoding:''); LSlang :: setLocale($lang, $encoding);
if ($locale == 'en_US.UTF8') { return true;
return true;
}
foreach(array(LS_I18N_DIR_PATH, LS_LOCAL_DIR.'/'.LS_I18N_DIR) as $lang_dir)
if (is_dir("$lang_dir/$locale"))
return true;
return false;
} }
/** /**
* Initialisation LdapSaisie * Initialize LdapSaisie
* *
* @param[in] $lang string La langue (Ex : fr_FR / Optionnel) * @param[in] $lang string|null The lang (optional, default: see LSlang :: setLocale())
* @param[in] $encoding string L'encodage de caractère (Ex : UTF8 / Optionnel) * @param[in] $encoding string|null The encoding (optional, default: see LSlang :: setLocale())
* *
* @retval boolean True si l'initialisation à réussi, false sinon. * @retval boolean True if initialized, false otherwise
*/ */
public static function initialize($lang=null,$encoding=null) { public static function initialize($lang=null, $encoding=null) {
if (self :: $initialized) if (self :: $initialized)
return true; return true;
try { try {
@ -574,7 +442,7 @@ class LSsession {
if (php_sapi_name() != "cli") if (php_sapi_name() != "cli")
session_start(); session_start();
self :: setLocale($lang,$encoding); self :: startLSlang($lang, $encoding);
self :: loadLSaddons(); self :: loadLSaddons();
self :: loadLSauth(); self :: loadLSauth();
@ -1112,7 +980,7 @@ class LSsession {
if ( is_array($conf) ) { if ( is_array($conf) ) {
self :: $ldapServerId = $id; self :: $ldapServerId = $id;
self :: $ldapServer = $conf; self :: $ldapServer = $conf;
self :: setLocale(); LSlang :: setLocale();
self :: setGlobals(); self :: setGlobals();
return true; return true;
} }
@ -1557,10 +1425,9 @@ class LSsession {
LStemplate :: assign('LSsession_subDnName',self :: getSubDnName()); LStemplate :: assign('LSsession_subDnName',self :: getSubDnName());
} }
LStemplate :: assign('LSlanguages',self :: getLangList()); LStemplate :: assign('LSlanguages', LSlang :: getLangList());
LStemplate :: assign('LSlang',self :: $lang); LStemplate :: assign('LSlang', LSlang :: getLang());
LStemplate :: assign('LSencoding',self :: $encoding); LStemplate :: assign('LSencoding', LSlang :: getEncoding());
LStemplate :: assign('lang_label',_('Language'));
LStemplate :: assign('displayLogoutBtn',LSauth :: displayLogoutBtn()); LStemplate :: assign('displayLogoutBtn',LSauth :: displayLogoutBtn());
LStemplate :: assign('displaySelfAccess',LSauth :: displaySelfAccess()); LStemplate :: assign('displaySelfAccess',LSauth :: displaySelfAccess());

View file

@ -28,7 +28,7 @@
<dd><input type='text' name='LSauth_user' /></dd> <dd><input type='text' name='LSauth_user' /></dd>
<dt>{$loginform_label_pwd|escape:"htmlall"}</dt> <dt>{$loginform_label_pwd|escape:"htmlall"}</dt>
<dd><input type='password' name='LSauth_pwd' /></dd> <dd><input type='password' name='LSauth_pwd' /></dd>
<dt class='LSlang_hidden'>{$lang_label|escape:"htmlall"}</dt> <dt class='LSlang_hidden'>{tr msg="Language"}</dt>
<dd class='LSlang_hidden'> <dd class='LSlang_hidden'>
<select name='lang'> <select name='lang'>
{foreach from=$LSlanguages item=lang} {foreach from=$LSlanguages item=lang}
@ -39,7 +39,7 @@
<dd><input type='submit' value='{$loginform_label_submit|escape:"htmlall"}' /></dd> <dd><input type='submit' value='{$loginform_label_submit|escape:"htmlall"}' /></dd>
</dl> </dl>
</form> </form>
<span>{$lang_label} : <img id='LSlang' src='{img name=$LSlang}' alt='{$LSlang|escape:"htmlall"}' title='{$LSlang|escape:"htmlall"}'/></span> <span>{tr msg="Language"} : <img id='LSlang' src='{img name=$LSlang}' alt='{$LSlang|escape:"htmlall"}' title='{$LSlang|escape:"htmlall"}'/></span>
<a href='index.php?LSsession_recoverPassword' class='LSsession_recoverPassword LSsession_recoverPassword_hidden'>{$loginform_label_recoverPassword|escape:"htmlall"}</a> <a href='index.php?LSsession_recoverPassword' class='LSsession_recoverPassword LSsession_recoverPassword_hidden'>{$loginform_label_recoverPassword|escape:"htmlall"}</a>
</div> </div>
{include file='ls:LSsession_js.tpl'} {include file='ls:LSsession_js.tpl'}

View file

@ -30,7 +30,7 @@
{/if} {/if}
<p id='recoverpassword_msg'>{$recoverpassword_msg|escape:"htmlall"}</p> <p id='recoverpassword_msg'>{$recoverpassword_msg|escape:"htmlall"}</p>
<span>{$lang_label|escape:"htmlall"} : <img id='LSlang' src='{img name=$LSlang}' alt='{$LSlang|escape:"htmlall"}' title='{$LSlang|escape:"htmlall"}'/></span> <span>{tr msg="Language"} : <img id='LSlang' src='{img name=$LSlang}' alt='{$LSlang|escape:"htmlall"}' title='{$LSlang|escape:"htmlall"}'/></span>
<a href='index.php' id='recoverpassword_back'>{$recoverpasswordform_label_back|escape:"htmlall"}</a> <a href='index.php' id='recoverpassword_back'>{$recoverpasswordform_label_back|escape:"htmlall"}</a>
</div> </div>
{include file='ls:LSsession_js.tpl'} {include file='ls:LSsession_js.tpl'}

View file

@ -50,7 +50,7 @@
</ul> </ul>
</td> </td>
<td id='status'> <td id='status'>
<span>{$lang_label|escape:"htmlall"} : <img id='LSlang' src='{img name=$LSlang}' alt='{$LSlang|escape:"htmlall"}' title='{$LSlang|escape:"htmlall"}'/></span> <span>{tr msg="Language"} : <img id='LSlang' src='{img name=$LSlang}' alt='{$LSlang|escape:"htmlall"}' title='{$LSlang|escape:"htmlall"}'/></span>
<form action='' methode='post' style='display: none' class='LSlang_hidden'> <form action='' methode='post' style='display: none' class='LSlang_hidden'>
<select name='lang'> <select name='lang'>
{foreach from=$LSlanguages item=lang} {foreach from=$LSlanguages item=lang}