Skip to content
Snippets Groups Projects
Commit 387774a0 authored by Jaime Perez Crespo's avatar Jaime Perez Crespo
Browse files

Reformat \SimpleSAML\Locale\Translate.

parent 61ecaba3
No related branches found
No related tags found
No related merge requests found
...@@ -10,7 +10,8 @@ ...@@ -10,7 +10,8 @@
namespace SimpleSAML\Locale; namespace SimpleSAML\Locale;
class Translate { class Translate
{
private $configuration = null; private $configuration = null;
...@@ -26,25 +27,29 @@ class Translate { ...@@ -26,25 +27,29 @@ class Translate {
/** /**
* The default dictionary. * The default dictionary.
*/ */
private $defaultDictionary = NULL; private $defaultDictionary = null;
/** /**
* Constructor * Constructor
* *
* @param \SimpleSAML_Configuration $configuration Configuration object * @param \SimpleSAML_Configuration $configuration Configuration object
* @param string|null $defaultDictionary The default dictionary where tags will come from. * @param string|null $defaultDictionary The default dictionary where tags will come from.
*/ */
function __construct(\SimpleSAML_Configuration $configuration, $defaultDictionary = NULL) { public function __construct(\SimpleSAML_Configuration $configuration, $defaultDictionary = null)
{
$this->configuration = $configuration; $this->configuration = $configuration;
$this->language = new Language($configuration); $this->language = new Language($configuration);
if($defaultDictionary !== NULL && substr($defaultDictionary, -4) === '.php') { if ($defaultDictionary !== null && substr($defaultDictionary, -4) === '.php') {
/* For backwards compatibility - print warning. */ // TODO: drop this entire if clause for 2.0
// for backwards compatibility - print warning
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
$where = $backtrace[0]['file'] . ':' . $backtrace[0]['line']; $where = $backtrace[0]['file'].':'.$backtrace[0]['line'];
\SimpleSAML_Logger::warning('Deprecated use of new SimpleSAML\Locale\Translate(...) at ' . $where . \SimpleSAML_Logger::warning(
'. The last parameter is now a dictionary name, which should not end in ".php".'); 'Deprecated use of new SimpleSAML\Locale\Translate(...) at '.$where.
'. The last parameter is now a dictionary name, which should not end in ".php".'
);
$this->defaultDictionary = substr($defaultDictionary, 0, -4); $this->defaultDictionary = substr($defaultDictionary, 0, -4);
} else { } else {
...@@ -58,23 +63,25 @@ class Translate { ...@@ -58,23 +63,25 @@ class Translate {
* *
* @param string $name The name of the dictionary, as the filename in the dictionary directory, without the * @param string $name The name of the dictionary, as the filename in the dictionary directory, without the
* '.php' ending. * '.php' ending.
*
* @return array An associative array with the dictionary. * @return array An associative array with the dictionary.
*/ */
private function getDictionary($name) { private function getDictionary($name)
{
assert('is_string($name)'); assert('is_string($name)');
if(!array_key_exists($name, $this->dictionaries)) { if (!array_key_exists($name, $this->dictionaries)) {
$sepPos = strpos($name, ':'); $sepPos = strpos($name, ':');
if($sepPos !== FALSE) { if ($sepPos !== false) {
$module = substr($name, 0, $sepPos); $module = substr($name, 0, $sepPos);
$fileName = substr($name, $sepPos + 1); $fileName = substr($name, $sepPos + 1);
$dictDir = \SimpleSAML_Module::getModuleDir($module) . '/dictionaries/'; $dictDir = \SimpleSAML_Module::getModuleDir($module).'/dictionaries/';
} else { } else {
$dictDir = $this->configuration->getPathValue('dictionarydir', 'dictionaries/'); $dictDir = $this->configuration->getPathValue('dictionarydir', 'dictionaries/');
$fileName = $name; $fileName = $name;
} }
$this->dictionaries[$name] = $this->readDictionaryFile($dictDir . $fileName); $this->dictionaries[$name] = $this->readDictionaryFile($dictDir.$fileName);
} }
return $this->dictionaries[$name]; return $this->dictionaries[$name];
...@@ -86,31 +93,33 @@ class Translate { ...@@ -86,31 +93,33 @@ class Translate {
* *
* @param string $tag The tag name. The tag name can also be on the form '{<dictionary>:<tag>}', to retrieve a tag * @param string $tag The tag name. The tag name can also be on the form '{<dictionary>:<tag>}', to retrieve a tag
* from the specific dictionary. * from the specific dictionary.
*
* @return array An associative array with language => string mappings, or null if the tag wasn't found. * @return array An associative array with language => string mappings, or null if the tag wasn't found.
*/ */
public function getTag($tag) { public function getTag($tag)
{
assert('is_string($tag)'); assert('is_string($tag)');
/* First check translations loaded by the includeInlineTranslation and includeLanguageFile methods. */ // first check translations loaded by the includeInlineTranslation and includeLanguageFile methods
if(array_key_exists($tag, $this->langtext)) { if (array_key_exists($tag, $this->langtext)) {
return $this->langtext[$tag]; return $this->langtext[$tag];
} }
/* Check whether we should use the default dictionary or a dictionary specified in the tag. */ // check whether we should use the default dictionary or a dictionary specified in the tag
if(substr($tag, 0, 1) === '{' && preg_match('/^{((?:\w+:)?\w+?):(.*)}$/D', $tag, $matches)) { if (substr($tag, 0, 1) === '{' && preg_match('/^{((?:\w+:)?\w+?):(.*)}$/D', $tag, $matches)) {
$dictionary = $matches[1]; $dictionary = $matches[1];
$tag = $matches[2]; $tag = $matches[2];
} else { } else {
$dictionary = $this->defaultDictionary; $dictionary = $this->defaultDictionary;
if($dictionary === NULL) { if ($dictionary === null) {
/* We don't have any dictionary to load the tag from. */ // we don't have any dictionary to load the tag from
return NULL; return null;
} }
} }
$dictionary = $this->getDictionary($dictionary); $dictionary = $this->getDictionary($dictionary);
if(!array_key_exists($tag, $dictionary)) { if (!array_key_exists($tag, $dictionary)) {
return NULL; return null;
} }
return $dictionary[$tag]; return $dictionary[$tag];
...@@ -121,37 +130,39 @@ class Translate { ...@@ -121,37 +130,39 @@ class Translate {
* Retrieve the preferred translation of a given text. * Retrieve the preferred translation of a given text.
* *
* @param array $translations The translations, as an associative array with language => text mappings. * @param array $translations The translations, as an associative array with language => text mappings.
*
* @return string The preferred translation. * @return string The preferred translation.
* *
* @throws \Exception If there's no suitable translation. * @throws \Exception If there's no suitable translation.
*/ */
public function getPreferredTranslation($translations) { public function getPreferredTranslation($translations)
{
assert('is_array($translations)'); assert('is_array($translations)');
/* Look up translation of tag in the selected language. */ // look up translation of tag in the selected language
$selected_language = $this->language->getLanguage(); $selected_language = $this->language->getLanguage();
if (array_key_exists($selected_language, $translations)) { if (array_key_exists($selected_language, $translations)) {
return $translations[$selected_language]; return $translations[$selected_language];
} }
/* Look up translation of tag in the default language. */ // look up translation of tag in the default language
$default_language = $this->language->getDefaultLanguage(); $default_language = $this->language->getDefaultLanguage();
if(array_key_exists($default_language, $translations)) { if (array_key_exists($default_language, $translations)) {
return $translations[$default_language]; return $translations[$default_language];
} }
/* Check for english translation. */ // check for english translation
if(array_key_exists('en', $translations)) { if (array_key_exists('en', $translations)) {
return $translations['en']; return $translations['en'];
} }
/* Pick the first translation available. */ // pick the first translation available
if(count($translations) > 0) { if (count($translations) > 0) {
$languages = array_keys($translations); $languages = array_keys($translations);
return $translations[$languages[0]]; return $translations[$languages[0]];
} }
/* We don't have anything to return. */ // we don't have anything to return
throw new \Exception('Nothing to return from translation.'); throw new \Exception('Nothing to return from translation.');
} }
...@@ -160,30 +171,31 @@ class Translate { ...@@ -160,30 +171,31 @@ class Translate {
* Translate the name of an attribute. * Translate the name of an attribute.
* *
* @param string $name The attribute name. * @param string $name The attribute name.
*
* @return string The translated attribute name, or the original attribute name if no translation was found. * @return string The translated attribute name, or the original attribute name if no translation was found.
*/ */
public function getAttributeTranslation($name) { public function getAttributeTranslation($name)
{
/* Normalize attribute name. */ // normalize attribute name
$normName = strtolower($name); $normName = strtolower($name);
$normName = str_replace(":", "_", $normName); $normName = str_replace(":", "_", $normName);
/* Check for an extra dictionary. */ // check for an extra dictionary
$extraDict = $this->configuration->getString('attributes.extradictionary', NULL); $extraDict = $this->configuration->getString('attributes.extradictionary', null);
if ($extraDict !== NULL) { if ($extraDict !== null) {
$dict = $this->getDictionary($extraDict); $dict = $this->getDictionary($extraDict);
if (array_key_exists($normName, $dict)) { if (array_key_exists($normName, $dict)) {
return $this->getPreferredTranslation($dict[$normName]); return $this->getPreferredTranslation($dict[$normName]);
} }
} }
/* Search the default attribute dictionary. */ // search the default attribute dictionary
$dict = $this->getDictionary('attributes'); $dict = $this->getDictionary('attributes');
if (array_key_exists('attribute_' . $normName, $dict)) { if (array_key_exists('attribute_'.$normName, $dict)) {
return $this->getPreferredTranslation($dict['attribute_' . $normName]); return $this->getPreferredTranslation($dict['attribute_'.$normName]);
} }
/* No translations found. */ // no translations found
return $name; return $name;
} }
...@@ -201,11 +213,12 @@ class Translate { ...@@ -201,11 +213,12 @@ class Translate {
* This function can also do replacements into the translated tag. It will search the translated tag for the keys * This function can also do replacements into the translated tag. It will search the translated tag for the keys
* provided in $replacements, and replace any found occurrences with the value of the key. * provided in $replacements, and replace any found occurrences with the value of the key.
* *
* @param string|array $tag A tag name for the translation which should be looked up, or an array with * @param string|array $tag A tag name for the translation which should be looked up, or an array with
* (language => text) mappings. * (language => text) mappings.
* @param array $replacements An associative array of keys that should be replaced with values in the translated * @param array $replacements An associative array of keys that should be replaced with values in the
* string. * translated string.
* @param boolean $fallbackdefault Default translation to use as a fallback if no valid translation was found. * @param boolean $fallbackdefault Default translation to use as a fallback if no valid translation was found.
*
* @return string The translated tag, or a placeholder value if the tag wasn't found. * @return string The translated tag, or a placeholder value if the tag wasn't found.
*/ */
public function t( public function t(
...@@ -213,60 +226,67 @@ class Translate { ...@@ -213,60 +226,67 @@ class Translate {
$replacements = array(), $replacements = array(),
$fallbackdefault = true, $fallbackdefault = true,
$oldreplacements = array(), // TODO: remove this for 2.0 $oldreplacements = array(), // TODO: remove this for 2.0
$striptags = FALSE // TODO: remove this for 2.0 $striptags = false // TODO: remove this for 2.0
) { ) {
if(!is_array($replacements)) { if (!is_array($replacements)) {
// TODO: remove this entire if for 2.0
/* Old style call to t(...). Print warning to log. */ // old style call to t(...). Print warning to log
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
$where = $backtrace[0]['file'] . ':' . $backtrace[0]['line']; $where = $backtrace[0]['file'].':'.$backtrace[0]['line'];
\SimpleSAML_Logger::warning('Deprecated use of SimpleSAML_Template::t(...) at ' . $where . \SimpleSAML_Logger::warning(
'. Please update the code to use the new style of parameters.'); 'Deprecated use of SimpleSAML_Template::t(...) at '.$where.
'. Please update the code to use the new style of parameters.'
/* For backwards compatibility. */ );
if(!$replacements && $this->getTag($tag) === NULL) {
\SimpleSAML_Logger::warning('Code which uses $fallbackdefault === FALSE should be' . // for backwards compatibility
' updated to use the getTag() method instead.'); if (!$replacements && $this->getTag($tag) === null) {
return NULL; \SimpleSAML_Logger::warning(
'Code which uses $fallbackdefault === FALSE should be updated to use the getTag() method instead.'
);
return null;
} }
$replacements = $oldreplacements; $replacements = $oldreplacements;
} }
if(is_array($tag)) { if (is_array($tag)) {
$tagData = $tag; $tagData = $tag;
} else { } else {
$tagData = $this->getTag($tag); $tagData = $this->getTag($tag);
if($tagData === NULL) { if ($tagData === null) {
/* Tag not found. */ // tag not found
\SimpleSAML_Logger::info('Template: Looking up [' . $tag . ']: not translated at all.'); \SimpleSAML_Logger::info('Template: Looking up ['.$tag.']: not translated at all.');
return $this->t_not_translated($tag, $fallbackdefault); return $this->t_not_translated($tag, $fallbackdefault);
} }
} }
$translated = $this->getPreferredTranslation($tagData); $translated = $this->getPreferredTranslation($tagData);
# if (!empty($replacements)){ echo('<pre> [' . $tag . ']'); print_r($replacements); exit; }
foreach ($replacements as $k => $v) { foreach ($replacements as $k => $v) {
/* try to translate if no replacement is given */ // try to translate if no replacement is given
if ($v == NULL) $v = $this->t($k); if ($v == null) {
$v = $this->t($k);
}
$translated = str_replace($k, $v, $translated); $translated = str_replace($k, $v, $translated);
} }
return $translated; return $translated;
} }
/** /**
* Return the string that should be used when no translation was found. * Return the string that should be used when no translation was found.
* *
* @param string $tag A name tag of the string that should be returned. * @param string $tag A name tag of the string that should be returned.
* @param boolean $fallbacktag If set to true and string was not found in any languages, return the tag itself. If * @param boolean $fallbacktag If set to true and string was not found in any languages, return the tag itself. If
* false return null. * false return null.
* *
* @return string The string that should be used, or the tag name if $fallbacktag is set to false. * @return string The string that should be used, or the tag name if $fallbacktag is set to false.
*/ */
private function t_not_translated($tag, $fallbacktag) { private function t_not_translated($tag, $fallbacktag)
{
if ($fallbacktag) { if ($fallbacktag) {
return 'not translated (' . $tag . ')'; return 'not translated ('.$tag.')';
} else { } else {
return $tag; return $tag;
} }
...@@ -278,34 +298,35 @@ class Translate { ...@@ -278,34 +298,35 @@ class Translate {
* used ONLU from variable data, or when the translation is already provided by an external source, as a database * used ONLU from variable data, or when the translation is already provided by an external source, as a database
* or in metadata. * or in metadata.
* *
* @param string $tag The tag that has a translation * @param string $tag The tag that has a translation
* @param array|string $translation The translation array * @param array|string $translation The translation array
* *
* @throws \Exception If $translation is neither a string nor an array. * @throws \Exception If $translation is neither a string nor an array.
*/ */
public function includeInlineTranslation($tag, $translation) { public function includeInlineTranslation($tag, $translation)
{
if (is_string($translation)) { if (is_string($translation)) {
$translation = array('en' => $translation); $translation = array('en' => $translation);
} elseif (!is_array($translation)) { } elseif (!is_array($translation)) {
throw new \Exception("Inline translation should be string or array. Is " . gettype($translation) . " now!"); throw new \Exception("Inline translation should be string or array. Is ".gettype($translation)." now!");
} }
\SimpleSAML_Logger::debug('Template: Adding inline language translation for tag [' . $tag . ']'); \SimpleSAML_Logger::debug('Template: Adding inline language translation for tag ['.$tag.']');
$this->langtext[$tag] = $translation; $this->langtext[$tag] = $translation;
} }
/** /**
* Include a language file from the dictionaries directory. * Include a language file from the dictionaries directory.
* *
* @param string $file File name of dictionary to include * @param string $file File name of dictionary to include
* @param \SimpleSAML_Configuration|null $otherConfig Optionally provide a different configuration object than the * @param \SimpleSAML_Configuration|null $otherConfig Optionally provide a different configuration object than the
* one provided in the constructor to be used to find the directory of the dictionary. This allows to combine * one provided in the constructor to be used to find the directory of the dictionary. This allows to combine
* dictionaries inside the SimpleSAMLphp main code distribution together with external dictionaries. Defaults to * dictionaries inside the SimpleSAMLphp main code distribution together with external dictionaries. Defaults to
* null. * null.
*/ */
public function includeLanguageFile($file, $otherConfig = null) { public function includeLanguageFile($file, $otherConfig = null)
{
$filebase = null; $filebase = null;
if (!empty($otherConfig)) { if (!empty($otherConfig)) {
$filebase = $otherConfig->getPathValue('dictionarydir', 'dictionaries/'); $filebase = $otherConfig->getPathValue('dictionarydir', 'dictionaries/');
...@@ -313,9 +334,8 @@ class Translate { ...@@ -313,9 +334,8 @@ class Translate {
$filebase = $this->configuration->getPathValue('dictionarydir', 'dictionaries/'); $filebase = $this->configuration->getPathValue('dictionarydir', 'dictionaries/');
} }
$lang = $this->readDictionaryFile($filebase.$file);
$lang = $this->readDictionaryFile($filebase . $file); \SimpleSAML_Logger::debug('Template: Merging language array. Loading ['.$file.']');
\SimpleSAML_Logger::debug('Template: Merging language array. Loading [' . $file . ']');
$this->langtext = array_merge($this->langtext, $lang); $this->langtext = array_merge($this->langtext, $lang);
} }
...@@ -324,24 +344,26 @@ class Translate { ...@@ -324,24 +344,26 @@ class Translate {
* Read a dictionary file in JSON format. * Read a dictionary file in JSON format.
* *
* @param string $filename The absolute path to the dictionary file, minus the .definition.json ending. * @param string $filename The absolute path to the dictionary file, minus the .definition.json ending.
*
* @return array An array holding all the translations in the file. * @return array An array holding all the translations in the file.
*/ */
private function readDictionaryJSON($filename) { private function readDictionaryJSON($filename)
$definitionFile = $filename . '.definition.json'; {
$definitionFile = $filename.'.definition.json';
assert('file_exists($definitionFile)'); assert('file_exists($definitionFile)');
$fileContent = file_get_contents($definitionFile); $fileContent = file_get_contents($definitionFile);
$lang = json_decode($fileContent, TRUE); $lang = json_decode($fileContent, true);
if (empty($lang)) { if (empty($lang)) {
\SimpleSAML_Logger::error('Invalid dictionary definition file [' . $definitionFile . ']'); \SimpleSAML_Logger::error('Invalid dictionary definition file ['.$definitionFile.']');
return array(); return array();
} }
$translationFile = $filename . '.translation.json'; $translationFile = $filename.'.translation.json';
if (file_exists($translationFile)) { if (file_exists($translationFile)) {
$fileContent = file_get_contents($translationFile); $fileContent = file_get_contents($translationFile);
$moreTrans = json_decode($fileContent, TRUE); $moreTrans = json_decode($fileContent, true);
if (!empty($moreTrans)) { if (!empty($moreTrans)) {
$lang = self::lang_merge($lang, $moreTrans); $lang = self::lang_merge($lang, $moreTrans);
} }
...@@ -355,13 +377,15 @@ class Translate { ...@@ -355,13 +377,15 @@ class Translate {
* Read a dictionary file in PHP format. * Read a dictionary file in PHP format.
* *
* @param string $filename The absolute path to the dictionary file. * @param string $filename The absolute path to the dictionary file.
*
* @return array An array holding all the translations in the file. * @return array An array holding all the translations in the file.
*/ */
private function readDictionaryPHP($filename) { private function readDictionaryPHP($filename)
$phpFile = $filename . '.php'; {
$phpFile = $filename.'.php';
assert('file_exists($phpFile)'); assert('file_exists($phpFile)');
$lang = NULL; $lang = null;
include($phpFile); include($phpFile);
if (isset($lang)) { if (isset($lang)) {
return $lang; return $lang;
...@@ -375,37 +399,40 @@ class Translate { ...@@ -375,37 +399,40 @@ class Translate {
* Read a dictionary file. * Read a dictionary file.
* *
* @param string $filename The absolute path to the dictionary file. * @param string $filename The absolute path to the dictionary file.
*
* @return array An array holding all the translations in the file. * @return array An array holding all the translations in the file.
*/ */
private function readDictionaryFile($filename) { private function readDictionaryFile($filename)
{
assert('is_string($filename)'); assert('is_string($filename)');
\SimpleSAML_Logger::debug('Template: Reading [' . $filename . ']'); \SimpleSAML_Logger::debug('Template: Reading ['.$filename.']');
$jsonFile = $filename . '.definition.json'; $jsonFile = $filename.'.definition.json';
if (file_exists($jsonFile)) { if (file_exists($jsonFile)) {
return $this->readDictionaryJSON($filename); return $this->readDictionaryJSON($filename);
} }
$phpFile = $filename.'.php';
$phpFile = $filename . '.php';
if (file_exists($phpFile)) { if (file_exists($phpFile)) {
return $this->readDictionaryPHP($filename); return $this->readDictionaryPHP($filename);
} }
\SimpleSAML_Logger::error($_SERVER['PHP_SELF'].' - Template: Could not find template file [' . $this->template . '] at [' . $filename . ']'); \SimpleSAML_Logger::error(
$_SERVER['PHP_SELF'].' - Template: Could not find template file ['.$this->template.'] at ['.$filename.']'
);
return array(); return array();
} }
// Merge two translation arrays. // Merge two translation arrays.
public static function lang_merge($def, $lang) { public static function lang_merge($def, $lang)
foreach($def AS $key => $value) { {
if (array_key_exists($key, $lang)) foreach ($def as $key => $value) {
if (array_key_exists($key, $lang)) {
$def[$key] = array_merge($value, $lang[$key]); $def[$key] = array_merge($value, $lang[$key]);
}
} }
return $def; return $def;
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment