dict.class.inc.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Class Dict
  20. * Management of localizable strings
  21. *
  22. * @copyright Copyright (C) 2010-2012 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  24. */
  25. class DictException extends CoreException
  26. {
  27. }
  28. class DictExceptionUnknownLanguage extends DictException
  29. {
  30. public function __construct($sLanguageCode)
  31. {
  32. $aContext = array();
  33. $aContext['language_code'] = $sLanguageCode;
  34. parent::__construct('Unknown localization language', $aContext);
  35. }
  36. }
  37. class DictExceptionMissingString extends DictException
  38. {
  39. public function __construct($sLanguageCode, $sStringCode)
  40. {
  41. $aContext = array();
  42. $aContext['language_code'] = $sLanguageCode;
  43. $aContext['string_code'] = $sStringCode;
  44. parent::__construct('Missing localized string', $aContext);
  45. }
  46. }
  47. define('DICT_ERR_STRING', 1); // when a string is missing, return the identifier
  48. define('DICT_ERR_EXCEPTION', 2); // when a string is missing, throw an exception
  49. //define('DICT_ERR_LOG', 3); // when a string is missing, log an error
  50. class Dict
  51. {
  52. protected static $m_iErrorMode = DICT_ERR_STRING;
  53. protected static $m_sDefaultLanguage = 'EN US';
  54. protected static $m_sCurrentLanguage = null; // No language selected by default
  55. protected static $m_aLanguages = array(); // array( code => array( 'description' => '...', 'localized_description' => '...') ...)
  56. protected static $m_aData = array();
  57. protected static $m_sApplicationPrefix = null;
  58. public static function SetDefaultLanguage($sLanguageCode)
  59. {
  60. if (!array_key_exists($sLanguageCode, self::$m_aLanguages))
  61. {
  62. throw new DictExceptionUnknownLanguage($sLanguageCode);
  63. }
  64. self::$m_sDefaultLanguage = $sLanguageCode;
  65. }
  66. public static function SetUserLanguage($sLanguageCode)
  67. {
  68. if (!array_key_exists($sLanguageCode, self::$m_aLanguages))
  69. {
  70. throw new DictExceptionUnknownLanguage($sLanguageCode);
  71. }
  72. self::$m_sCurrentLanguage = $sLanguageCode;
  73. }
  74. public static function GetUserLanguage()
  75. {
  76. if (self::$m_sCurrentLanguage == null) // May happen when no user is logged in (i.e login screen, non authentifed page)
  77. {
  78. // In which case let's use the default language
  79. return self::$m_sDefaultLanguage;
  80. }
  81. return self::$m_sCurrentLanguage;
  82. }
  83. //returns a hash array( code => array( 'description' => '...', 'localized_description' => '...') ...)
  84. public static function GetLanguages()
  85. {
  86. return self::$m_aLanguages;
  87. }
  88. // iErrorMode from {DICT_ERR_STRING, DICT_ERR_EXCEPTION}
  89. public static function SetErrorMode($iErrorMode)
  90. {
  91. self::$m_iErrorMode = $iErrorMode;
  92. }
  93. /**
  94. * Returns a localised string from the dictonary
  95. * @param string $sStringCode The code identifying the dictionary entry
  96. * @param string $sDefault Default value if there is no match in the dictionary
  97. * @param bool $bUserLanguageOnly True to allow the use of the default language as a fallback, false otherwise
  98. * @throws DictExceptionMissingString
  99. * @return unknown|Ambigous <>|string
  100. */
  101. public static function S($sStringCode, $sDefault = null, $bUserLanguageOnly = false)
  102. {
  103. // Attempt to find the string in the user language
  104. //
  105. self::InitLangIfNeeded(self::GetUserLanguage());
  106. if (!array_key_exists(self::GetUserLanguage(), self::$m_aData))
  107. {
  108. // It may happen, when something happens before the dictionnaries get loaded
  109. return $sStringCode;
  110. }
  111. $aCurrentDictionary = self::$m_aData[self::GetUserLanguage()];
  112. if (array_key_exists($sStringCode, $aCurrentDictionary))
  113. {
  114. return $aCurrentDictionary[$sStringCode];
  115. }
  116. if (!$bUserLanguageOnly)
  117. {
  118. // Attempt to find the string in the default language
  119. //
  120. self::InitLangIfNeeded(self::$m_sDefaultLanguage);
  121. $aDefaultDictionary = self::$m_aData[self::$m_sDefaultLanguage];
  122. if (array_key_exists($sStringCode, $aDefaultDictionary))
  123. {
  124. return $aDefaultDictionary[$sStringCode];
  125. }
  126. // Attempt to find the string in english
  127. //
  128. $aDefaultDictionary = self::$m_aData['EN US'];
  129. if (array_key_exists($sStringCode, $aDefaultDictionary))
  130. {
  131. return $aDefaultDictionary[$sStringCode];
  132. }
  133. }
  134. // Could not find the string...
  135. //
  136. switch (self::$m_iErrorMode)
  137. {
  138. case DICT_ERR_STRING:
  139. if (is_null($sDefault))
  140. {
  141. return $sStringCode;
  142. }
  143. else
  144. {
  145. return $sDefault;
  146. }
  147. break;
  148. case DICT_ERR_EXCEPTION:
  149. default:
  150. throw new DictExceptionMissingString(self::$m_sCurrentLanguage, $sStringCode);
  151. break;
  152. }
  153. return 'bug!';
  154. }
  155. /**
  156. * Formats a localized string with numbered placeholders (%1$s...) for the additional arguments
  157. * See vsprintf for more information about the syntax of the placeholders
  158. * @param string $sFormatCode
  159. * @return string
  160. */
  161. public static function Format($sFormatCode /*, ... arguments ....*/)
  162. {
  163. $sLocalizedFormat = self::S($sFormatCode);
  164. $aArguments = func_get_args();
  165. array_shift($aArguments);
  166. if ($sLocalizedFormat == $sFormatCode)
  167. {
  168. // Make sure the information will be displayed (ex: an error occuring before the dictionary gets loaded)
  169. return $sFormatCode.' - '.implode(', ', $aArguments);
  170. }
  171. return vsprintf($sLocalizedFormat, $aArguments);
  172. }
  173. /**
  174. * Initialize a the entries for a given language (replaces the former Add() method)
  175. * @param string $sLanguageCode Code identifying the language i.e. 'FR-FR', 'EN-US'
  176. * @param hash $aEntries Hash array of dictionnary entries
  177. */
  178. public static function SetEntries($sLanguageCode, $aEntries)
  179. {
  180. self::$m_aData[$sLanguageCode] = $aEntries;
  181. }
  182. /**
  183. * Set the list of available languages
  184. * @param hash $aLanguagesList
  185. */
  186. public static function SetLanguagesList($aLanguagesList)
  187. {
  188. self::$m_aLanguages = $aLanguagesList;
  189. }
  190. /**
  191. * Load a language from the language dictionary, if not already loaded
  192. * @param string $sLangCode Language code
  193. * @return boolean
  194. */
  195. public static function InitLangIfNeeded($sLangCode)
  196. {
  197. if (array_key_exists($sLangCode, self::$m_aData)) return true;
  198. $bResult = false;
  199. if (function_exists('apc_fetch') && (self::$m_sApplicationPrefix !== null))
  200. {
  201. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  202. //
  203. self::$m_aData[$sLangCode] = apc_fetch(self::$m_sApplicationPrefix.'-dict-'.$sLangCode);
  204. if (self::$m_aData[$sLangCode] === false)
  205. {
  206. unset(self::$m_aData[$sLangCode]);
  207. }
  208. else
  209. {
  210. $bResult = true;
  211. }
  212. }
  213. if (!$bResult)
  214. {
  215. $sDictFile = APPROOT.'env-'.utils::GetCurrentEnvironment().'/dictionaries/'.str_replace(' ', '-', strtolower($sLangCode)).'.dict.php';
  216. require_once($sDictFile);
  217. if (function_exists('apc_store') && (self::$m_sApplicationPrefix !== null))
  218. {
  219. apc_store(self::$m_sApplicationPrefix.'-dict-'.$sLangCode, self::$m_aData[$sLangCode]);
  220. }
  221. $bResult = true;
  222. }
  223. return $bResult;
  224. }
  225. /**
  226. * Enable caching (cached using APC)
  227. * @param string $sApplicationPrefix The prefix for uniquely identiying this iTop instance
  228. */
  229. public static function EnableCache($sApplicationPrefix)
  230. {
  231. self::$m_sApplicationPrefix = $sApplicationPrefix;
  232. }
  233. /**
  234. * Reset the cached entries (cached using APC)
  235. * @param string $sApplicationPrefix The prefix for uniquely identiying this iTop instance
  236. */
  237. public static function ResetCache($sApplicationPrefix)
  238. {
  239. if (function_exists('apc_delete'))
  240. {
  241. foreach(self::$m_aLanguages as $sLang => $void)
  242. {
  243. apc_delete($sApplicationPrefix.'-dict-'.$sLang);
  244. }
  245. }
  246. }
  247. /////////////////////////////////////////////////////////////////////////
  248. /**
  249. * Clone a string in every language (if it exists in that language)
  250. */
  251. public static function CloneString($sSourceCode, $sDestCode)
  252. {
  253. foreach(self::$m_aLanguages as $sLanguageCode => $foo)
  254. {
  255. if (isset(self::$m_aData[$sLanguageCode][$sSourceCode]))
  256. {
  257. self::$m_aData[$sLanguageCode][$sDestCode] = self::$m_aData[$sLanguageCode][$sSourceCode];
  258. }
  259. }
  260. }
  261. public static function MakeStats($sLanguageCode, $sLanguageRef = 'EN US')
  262. {
  263. $aMissing = array(); // Strings missing for the target language
  264. $aUnexpected = array(); // Strings defined for the target language, but not found in the reference dictionary
  265. $aNotTranslated = array(); // Strings having the same value in both dictionaries
  266. $aOK = array(); // Strings having different values in both dictionaries
  267. foreach (self::$m_aData[$sLanguageRef] as $sStringCode => $sValue)
  268. {
  269. if (!array_key_exists($sStringCode, self::$m_aData[$sLanguageCode]))
  270. {
  271. $aMissing[$sStringCode] = $sValue;
  272. }
  273. }
  274. foreach (self::$m_aData[$sLanguageCode] as $sStringCode => $sValue)
  275. {
  276. if (!array_key_exists($sStringCode, self::$m_aData[$sLanguageRef]))
  277. {
  278. $aUnexpected[$sStringCode] = $sValue;
  279. }
  280. else
  281. {
  282. // The value exists in the reference
  283. $sRefValue = self::$m_aData[$sLanguageRef][$sStringCode];
  284. if ($sValue == $sRefValue)
  285. {
  286. $aNotTranslated[$sStringCode] = $sValue;
  287. }
  288. else
  289. {
  290. $aOK[$sStringCode] = $sValue;
  291. }
  292. }
  293. }
  294. return array($aMissing, $aUnexpected, $aNotTranslated, $aOK);
  295. }
  296. public static function Dump()
  297. {
  298. MyHelpers::var_dump_html(self::$m_aData);
  299. }
  300. // Obsolete: only used by the setup/compiler which replaces this method invocation by its own handler !!
  301. // sLanguageCode: Code identifying the language i.e. FR-FR
  302. // sEnglishLanguageDesc: Description of the language code, in English. i.e. French (France)
  303. // sLocalizedLanguageDesc: Description of the language code, in its own language. i.e. Français (France)
  304. // aEntries: Hash array of dictionnary entries
  305. // ~~ or ~* can be used to indicate entries still to be translated.
  306. public static function Add($sLanguageCode, $sEnglishLanguageDesc, $sLocalizedLanguageDesc, $aEntries)
  307. {
  308. if (!array_key_exists($sLanguageCode, self::$m_aLanguages))
  309. {
  310. self::$m_aLanguages[$sLanguageCode] = array('description' => $sEnglishLanguageDesc, 'localized_description' => $sLocalizedLanguageDesc);
  311. self::$m_aData[$sLanguageCode] = array();
  312. }
  313. foreach($aEntries as $sCode => $sValue)
  314. {
  315. self::$m_aData[$sLanguageCode][$sCode] = self::FilterString($sValue);
  316. }
  317. }
  318. }
  319. ?>