BxDolLanguages.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. define('BX_DOL_LANGUAGE_DEFAULT', 'en');
  10. define('BX_DOL_LANGUAGE_DIRECTION_LTR', 'LTR');
  11. define('BX_DOL_LANGUAGE_DIRECTION_RTL', 'RTL');
  12. define('BX_DOL_LANGUAGE_CATEGORY_SYSTEM', 1);
  13. define('BX_DOL_LANGUAGE_CATEGORY_CUSTOM', 2);
  14. class BxDolLanguages extends BxDolFactory implements iBxDolSingleton
  15. {
  16. protected $oDb;
  17. protected $sCurrentLanguage;
  18. protected function __construct()
  19. {
  20. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  21. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  22. parent::__construct();
  23. $this->oDb = BxDolLanguagesQuery::getInstance();
  24. }
  25. /**
  26. * Prevent cloning the instance
  27. */
  28. public function __clone()
  29. {
  30. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  31. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  32. }
  33. /**
  34. * Get singleton instance of the class
  35. */
  36. static function getInstance()
  37. {
  38. if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  39. $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolLanguages();
  40. $GLOBALS['bxDolClasses'][__CLASS__]->init();
  41. }
  42. return $GLOBALS['bxDolClasses'][__CLASS__];
  43. }
  44. function getCurrentLangName($bSetCookie = true)
  45. {
  46. $sLang = '';
  47. if(!$sLang && !empty($_GET['lang']))
  48. $sLang = $this->tryToGetLang($_GET['lang'], $bSetCookie);
  49. if(!$sLang && !empty($_POST['lang']))
  50. $sLang = $this->tryToGetLang($_POST['lang'], $bSetCookie);
  51. if(!$sLang && !empty($_COOKIE['lang']))
  52. $sLang = $this->tryToGetLang($_COOKIE['lang']);
  53. if(!$sLang && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
  54. $sLang = $this->tryToGetLang($_SERVER['HTTP_ACCEPT_LANGUAGE']);
  55. if(!$sLang)
  56. $sLang = $this->tryToGetLang(getParam('lang_default'));
  57. if(!$sLang)
  58. $sLang = $this->tryToGetLang(BX_DOL_LANGUAGE_DEFAULT);
  59. $sLocale = $this->getLangCountryCode($sLang);
  60. if (!$sLocale)
  61. $sLocale = $sLang . '_' . strtoupper($sLang);
  62. setlocale(LC_TIME,
  63. $sLocale . '.utf-8',
  64. $sLocale . '.utf8',
  65. $sLang . '.utf-8',
  66. $sLang . '.utf8',
  67. $sLang);
  68. return $sLang;
  69. }
  70. function getCurrentLangId()
  71. {
  72. return $this->getLangId($this->getCurrentLanguage());
  73. }
  74. function getLangId($sLang)
  75. {
  76. return $this->oDb->getLanguageId($sLang);
  77. }
  78. function getLangName($iLangId)
  79. {
  80. return $this->oDb->getLanguageName($iLangId);
  81. }
  82. function getLangFlag($sLang = '')
  83. {
  84. if (!$sLang)
  85. $sLang = $this->getCurrentLanguage();
  86. return $this->oDb->getLanguageFlag($sLang);
  87. }
  88. function getLangDirection($sLang = '')
  89. {
  90. if (!$sLang)
  91. $sLang = $this->getCurrentLanguage();
  92. return strtoupper($this->oDb->getLanguageDirection($sLang));
  93. }
  94. function getLangCountryCode($sLang = '')
  95. {
  96. if (!$sLang)
  97. $sLang = $this->getCurrentLanguage();
  98. return $this->oDb->getLangCountryCode($sLang);
  99. }
  100. function getDefaultLangName()
  101. {
  102. return getParam('lang_default');
  103. }
  104. function getLanguages($bIdAsKey = false, $bActiveOnly = false)
  105. {
  106. return $this->oDb->getLanguages($bIdAsKey, $bActiveOnly);
  107. }
  108. function getLanguagesExt($bIdAsKey = false, $bActiveOnly = false)
  109. {
  110. $aParams = array('type' => 'all_key_' . ($bIdAsKey ? 'id' : 'name'));
  111. if($bActiveOnly)
  112. $aParams['enabled'] = 1;
  113. $aResults = array();
  114. $this->oDb->getLanguagesBy($aParams, $aResults, false);
  115. return $aResults;
  116. }
  117. function getLanguageCategory($sName)
  118. {
  119. $iId = 0;
  120. $this->oDb->getCategoriesBy(array('type' => 'id_by_name', 'value' => $sName), $iId);
  121. return (int)$iId;
  122. }
  123. /**
  124. * It tries to match current language with provided languages array, if nothing is found $sFallbackLanguage is returned.
  125. * @param $aLangs - array of languages, example: array('ru' => 1, 'kg' => 1);
  126. * @param $sFallbackLanguage - language to return of nothis is found
  127. * @return language code string
  128. */
  129. function detectLanguageFromArray($aLangs, $sFallbackLanguage = 'en', $bLowercase = false)
  130. {
  131. if (isset($aLangs[$GLOBALS['sCurrentLanguage']])) {
  132. return $GLOBALS['sCurrentLanguage'];
  133. }
  134. elseif ($sLangCountry = $this->getLangCountryCode()) {
  135. if ($bLowercase)
  136. $sLangCountry = strtolower($sLangCountry);
  137. if (isset($aLangs[$sLangCountry]))
  138. return $sLangCountry;
  139. $sLangCountry = str_replace('_', '-', $sLangCountry);
  140. if (isset($aLangs[$sLangCountry]))
  141. return $sLangCountry;
  142. }
  143. return $sFallbackLanguage;
  144. }
  145. /**
  146. * Get current language.
  147. */
  148. function getCurrentLanguage()
  149. {
  150. return $GLOBALS['sCurrentLanguage'];
  151. }
  152. function _t()
  153. {
  154. global $LANG;
  155. $key = func_get_arg(0);
  156. if(isset($LANG[$key])) {
  157. $str = $LANG[$key];
  158. if(($iNumArgs = func_num_args()) > 1)
  159. for($i = 1; $i < $iNumArgs; $i++)
  160. $str = str_replace('{' . ($i - 1) . '}', func_get_arg($i), $str);
  161. return $str;
  162. } else
  163. return $key;
  164. }
  165. function _t_err()
  166. {
  167. return MsgBox(call_user_func_array(array($this, '_t'), func_get_args()));
  168. }
  169. function _t_action()
  170. {
  171. return MsgBox(call_user_func_array(array($this, '_t'), func_get_args()));
  172. }
  173. function _t_ext($key, $args)
  174. {
  175. global $LANG;
  176. if(isset($LANG[$key])) {
  177. $str = $LANG[$key];
  178. if(!is_array($args))
  179. return str_replace('{0}', $args, $str);
  180. foreach ($args as $key => $val)
  181. $str = str_replace('{'.$key.'}', $val, $str);
  182. return $str;
  183. } else
  184. return $key;
  185. }
  186. function _t_format_size ($iSize)
  187. {
  188. $a = array (
  189. 1024 => '_sys_format_size_b',
  190. 1024*1024 => '_sys_format_size_kb',
  191. 1024*1024*1024 => '_sys_format_size_mb',
  192. 1024*1024*1024*1024 => '_sys_format_size_gb',
  193. 1024*1024*1024*1024*1024 => '_sys_format_size_tb',
  194. );
  195. foreach($a as $i => $sKey)
  196. if($iSize < $i)
  197. return $this->_t($sKey, round($iSize / ($i / 1024), 1));
  198. return $this->_t('_sys_format_size_b', 0);
  199. }
  200. function _t_format_duration ($iTime)
  201. {
  202. $iTime = (int)$iTime;
  203. $sFormat = '%M:%S';
  204. if($iTime > 3600)
  205. $sFormat = '%H:' . $sFormat;
  206. return strftime($sFormat, $iTime);
  207. }
  208. function _t_format_currency ($fPrice)
  209. {
  210. return $this->_t('_sys_currency', getParam('currency_sign'), sprintf("%.2f", (float)$fPrice));
  211. }
  212. function _t_format_extensions ($mixedExtensions)
  213. {
  214. if (!is_array($mixedExtensions))
  215. $a = explode(',', $mixedExtensions);
  216. else
  217. $a = $mixedExtensions;
  218. if (!$a)
  219. return '';
  220. return '.' . implode(', .', $a);
  221. }
  222. protected function init()
  223. {
  224. /**
  225. * Trying to initialize default language.
  226. */
  227. $GLOBALS['sCurrentLanguage'] = $GLOBALS['bxDolClasses'][__CLASS__]->getCurrentLangName(false);
  228. if($GLOBALS['sCurrentLanguage'] != '') {
  229. $sPath = BX_DIRECTORY_PATH_CACHE . 'lang-' . $GLOBALS['sCurrentLanguage'] . '.php';
  230. if(!file_exists($sPath))
  231. BxDolStudioLanguagesUtils::getInstance()->compileLanguage();
  232. require($sPath);
  233. if($this->getLangDirection($GLOBALS['sCurrentLanguage']) == BX_DOL_LANGUAGE_DIRECTION_RTL)
  234. BxDolTemplate::getInstance()->addCss('rtl.css');
  235. }
  236. $GLOBALS['bxDolClasses'][__CLASS__]->getCurrentLangName(true);
  237. if(isset($_GET['lang'])) {
  238. if(BxDolPermalinks::getInstance()->redirectIfNecessary(array('lang')))
  239. exit;
  240. }
  241. }
  242. protected function tryToGetLang($sLangs, $bSetCookie = false)
  243. {
  244. $sLangs = trim($sLangs);
  245. if(!$sLangs)
  246. return '';
  247. $sLangs = preg_replace( '/[^a-zA-Z0-9,;-]/m', '', $sLangs ); // we do not need 'q=0.3'. we are using live queue :)
  248. $sLangs = strtolower($sLangs);
  249. if(!$sLangs)
  250. return '';
  251. $aLangs = explode(',', $sLangs); // ru,en-us;q=0.7,en;q=0.3 => array( 'ru' , 'en-us;q=0.7' , 'en;q=0.3' );
  252. foreach($aLangs as $sLang) {
  253. if(!$sLang)
  254. continue;
  255. list($sLang) = explode(';', $sLang, 2); // en-us;q=0.7 => en-us
  256. if(!$sLang)
  257. continue;
  258. // check with country
  259. if($this->checkLangExists($sLang)) {
  260. if( $bSetCookie && (!isset($_COOKIE['lang']) || $_COOKIE['lang'] != $sLang) && (!isset($GLOBALS['glLangSet']) || $GLOBALS['glLangSet'] != $sLang)) {
  261. $this->setLangCookie( $sLang );
  262. $GLOBALS['glLangSet'] = $sLang;
  263. }
  264. return $sLang;
  265. }
  266. //drop country
  267. if(strpos($sLang, '-') === false)
  268. continue;
  269. list($sLang, $sCntr) = explode('-', $sLang, 2); // en-us => en
  270. if(!$sLang or !$sCntr)
  271. continue; //no lang or nothing changed
  272. //check again. without country
  273. if($this->checkLangExists($sLang)) {
  274. if($bSetCookie)
  275. $this->setLangCookie($sLang);
  276. return $sLang;
  277. }
  278. }
  279. return '';
  280. }
  281. protected function checkLangExists( $sLang )
  282. {
  283. if(!preg_match('/^[A-Za-z0-9_]+$/', $sLang))
  284. return false;
  285. $iLangId = $this->oDb->getLanguageId($sLang, false);
  286. if(!$iLangId)
  287. return false;
  288. if(file_exists( BX_DIRECTORY_PATH_CACHE . "lang-{$sLang}.php"))
  289. return true;
  290. if(BxDolStudioLanguagesUtils::getInstance()->compileLanguage($iLangId))
  291. return true;
  292. return false;
  293. }
  294. protected function setLangCookie( $sLang )
  295. {
  296. $sLang = bx_process_input($sLang);
  297. if(isLogged()) {
  298. $iLangId = $this->oDb->getLanguageId($sLang, false);
  299. if(!$iLangId)
  300. $iLangId = 0;
  301. $iAccountId = getLoggedId();
  302. $oAccountQuery = BxDolAccountQuery::getInstance();
  303. $oAccountQuery->updateLanguage($iAccountId, $iLangId);
  304. }
  305. setcookie( 'lang', '', time() - 60*60*24, '/' );
  306. setcookie( 'lang', $sLang, time() + 60*60*24*365, '/' );
  307. }
  308. }
  309. if (!function_exists('_t')) {
  310. function _t()
  311. {
  312. return call_user_func_array(array(BxDolLanguages::getInstance(), '_t'), func_get_args());
  313. }
  314. }
  315. function _t_err()
  316. {
  317. return call_user_func_array(array(BxDolLanguages::getInstance(), '_t_err'), func_get_args());
  318. }
  319. function _t_action()
  320. {
  321. return call_user_func_array(array(BxDolLanguages::getInstance(), '_t_action'), func_get_args());
  322. }
  323. function _t_ext($key, $args)
  324. {
  325. return BxDolLanguages::getInstance()->_t_ext($key, $args);
  326. }
  327. function _t_format_size($iSize)
  328. {
  329. return BxDolLanguages::getInstance()->_t_format_size($iSize);
  330. }
  331. function _t_format_duration($iTime)
  332. {
  333. return BxDolLanguages::getInstance()->_t_format_duration($iTime);
  334. }
  335. function _t_format_currency($fPrice)
  336. {
  337. return BxDolLanguages::getInstance()->_t_format_currency($fPrice);
  338. }
  339. function _t_format_extensions($mixedExtensions)
  340. {
  341. return BxDolLanguages::getInstance()->_t_format_extensions($mixedExtensions);
  342. }
  343. function bx_lang_name()
  344. {
  345. return BxDolLanguages::getInstance()->getCurrentLanguage();
  346. }
  347. function bx_lang_direction($sLanguage = '')
  348. {
  349. return BxDolLanguages::getInstance()->getLangDirection($sLanguage);
  350. }
  351. /** @} */