You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

l10n.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @author Jakob Sack
  7. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  8. * @copyright 2013 Jakob Sack
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  12. * License as published by the Free Software Foundation; either
  13. * version 3 of the License, or any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public
  21. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. /**
  25. * This class is for i18n and l10n
  26. */
  27. class OC_L10N implements \OCP\IL10N {
  28. /**
  29. * cache
  30. */
  31. protected static $cache = array();
  32. /**
  33. * The best language
  34. */
  35. protected static $language = '';
  36. /**
  37. * App of this object
  38. */
  39. protected $app;
  40. /**
  41. * Language of this object
  42. */
  43. protected $lang;
  44. /**
  45. * Translations
  46. */
  47. private $translations = array();
  48. /**
  49. * Plural forms (string)
  50. */
  51. private $plural_form_string = 'nplurals=2; plural=(n != 1);';
  52. /**
  53. * Plural forms (function)
  54. */
  55. private $plural_form_function = null;
  56. /**
  57. * Localization
  58. */
  59. private $localizations = array(
  60. 'jsdate' => 'dd.mm.yy',
  61. 'date' => '%d.%m.%Y',
  62. 'datetime' => '%d.%m.%Y %H:%M:%S',
  63. 'time' => '%H:%M:%S',
  64. 'firstday' => 0);
  65. /**
  66. * get an L10N instance
  67. * @param string $app
  68. * @param string|null $lang
  69. * @return \OC_L10N
  70. */
  71. public static function get($app, $lang=null) {
  72. if (is_null($lang)) {
  73. return OC::$server->getL10N($app);
  74. } else {
  75. return new \OC_L10N($app, $lang);
  76. }
  77. }
  78. /**
  79. * @brief The constructor
  80. * @param string $app app requesting l10n
  81. * @param string $lang default: null Language
  82. *
  83. * If language is not set, the constructor tries to find the right
  84. * language.
  85. */
  86. public function __construct($app, $lang = null) {
  87. $this->app = $app;
  88. $this->lang = $lang;
  89. }
  90. /**
  91. * @param string $transFile
  92. */
  93. public function load($transFile) {
  94. $this->app = true;
  95. include $transFile;
  96. if(isset($TRANSLATIONS) && is_array($TRANSLATIONS)) {
  97. $this->translations = $TRANSLATIONS;
  98. }
  99. if(isset($PLURAL_FORMS)) {
  100. $this->plural_form_string = $PLURAL_FORMS;
  101. }
  102. }
  103. protected function init() {
  104. if ($this->app === true) {
  105. return;
  106. }
  107. $app = OC_App::cleanAppId($this->app);
  108. $lang = str_replace(array('\0', '/', '\\', '..'), '', $this->lang);
  109. $this->app = true;
  110. // Find the right language
  111. if(is_null($lang) || $lang == '') {
  112. $lang = self::findLanguage($app);
  113. }
  114. // Use cache if possible
  115. if(array_key_exists($app.'::'.$lang, self::$cache)) {
  116. $this->translations = self::$cache[$app.'::'.$lang]['t'];
  117. $this->localizations = self::$cache[$app.'::'.$lang]['l'];
  118. }
  119. else{
  120. $i18ndir = self::findI18nDir($app);
  121. // Localization is in /l10n, Texts are in $i18ndir
  122. // (Just no need to define date/time format etc. twice)
  123. if((OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/core/l10n/')
  124. || OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/lib/l10n/')
  125. || OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/settings')
  126. || OC_Helper::isSubDirectory($i18ndir.$lang.'.php', OC_App::getAppPath($app).'/l10n/')
  127. )
  128. && file_exists($i18ndir.$lang.'.php')) {
  129. // Include the file, save the data from $CONFIG
  130. $transFile = strip_tags($i18ndir).strip_tags($lang).'.php';
  131. include $transFile;
  132. if(isset($TRANSLATIONS) && is_array($TRANSLATIONS)) {
  133. $this->translations = $TRANSLATIONS;
  134. //merge with translations from theme
  135. $theme = OC_Config::getValue( "theme" );
  136. if (!is_null($theme)) {
  137. $transFile = OC::$SERVERROOT.'/themes/'.$theme.substr($transFile, strlen(OC::$SERVERROOT));
  138. if (file_exists($transFile)) {
  139. include $transFile;
  140. if (isset($TRANSLATIONS) && is_array($TRANSLATIONS)) {
  141. $this->translations = array_merge($this->translations, $TRANSLATIONS);
  142. }
  143. }
  144. }
  145. }
  146. if(isset($PLURAL_FORMS)) {
  147. $this->plural_form_string = $PLURAL_FORMS;
  148. }
  149. }
  150. if(file_exists(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php') && OC_Helper::isSubDirectory(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php', OC::$SERVERROOT.'/core/l10n/')) {
  151. // Include the file, save the data from $CONFIG
  152. include OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php';
  153. if(isset($LOCALIZATIONS) && is_array($LOCALIZATIONS)) {
  154. $this->localizations = array_merge($this->localizations, $LOCALIZATIONS);
  155. }
  156. }
  157. self::$cache[$app.'::'.$lang]['t'] = $this->translations;
  158. self::$cache[$app.'::'.$lang]['l'] = $this->localizations;
  159. }
  160. }
  161. /**
  162. * @brief Creates a function that The constructor
  163. *
  164. * If language is not set, the constructor tries to find the right
  165. * language.
  166. *
  167. * Parts of the code is copied from Habari:
  168. * https://github.com/habari/system/blob/master/classes/locale.php
  169. * @param $string string
  170. * @return string
  171. */
  172. protected function createPluralFormFunction($string){
  173. if(preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
  174. // sanitize
  175. $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
  176. $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
  177. $body = str_replace(
  178. array( 'plural', 'n', '$n$plurals', ),
  179. array( '$plural', '$n', '$nplurals', ),
  180. 'nplurals='. $nplurals . '; plural=' . $plural
  181. );
  182. // add parents
  183. // important since PHP's ternary evaluates from left to right
  184. $body .= ';';
  185. $res = '';
  186. $p = 0;
  187. for($i = 0; $i < strlen($body); $i++) {
  188. $ch = $body[$i];
  189. switch ( $ch ) {
  190. case '?':
  191. $res .= ' ? (';
  192. $p++;
  193. break;
  194. case ':':
  195. $res .= ') : (';
  196. break;
  197. case ';':
  198. $res .= str_repeat( ')', $p ) . ';';
  199. $p = 0;
  200. break;
  201. default:
  202. $res .= $ch;
  203. }
  204. }
  205. $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
  206. return create_function('$n', $body);
  207. }
  208. else {
  209. // default: one plural form for all cases but n==1 (english)
  210. return create_function(
  211. '$n',
  212. '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
  213. );
  214. }
  215. }
  216. /**
  217. * @brief Translating
  218. * @param string $text The text we need a translation for
  219. * @param array $parameters default:array() Parameters for sprintf
  220. * @return \OC_L10N_String Translation or the same text
  221. *
  222. * Returns the translation. If no translation is found, $text will be
  223. * returned.
  224. */
  225. public function t($text, $parameters = array()) {
  226. return new OC_L10N_String($this, $text, $parameters);
  227. }
  228. /**
  229. * @brief Translating
  230. * @param string $text_singular the string to translate for exactly one object
  231. * @param string $text_plural the string to translate for n objects
  232. * @param integer $count Number of objects
  233. * @param array $parameters default:array() Parameters for sprintf
  234. * @return \OC_L10N_String Translation or the same text
  235. *
  236. * Returns the translation. If no translation is found, $text will be
  237. * returned. %n will be replaced with the number of objects.
  238. *
  239. * The correct plural is determined by the plural_forms-function
  240. * provided by the po file.
  241. *
  242. */
  243. public function n($text_singular, $text_plural, $count, $parameters = array()) {
  244. $this->init();
  245. $identifier = "_${text_singular}_::_${text_plural}_";
  246. if( array_key_exists($identifier, $this->translations)) {
  247. return new OC_L10N_String( $this, $identifier, $parameters, $count );
  248. }else{
  249. if($count === 1) {
  250. return new OC_L10N_String($this, $text_singular, $parameters, $count);
  251. }else{
  252. return new OC_L10N_String($this, $text_plural, $parameters, $count);
  253. }
  254. }
  255. }
  256. /**
  257. * @brief getTranslations
  258. * @return array Fetch all translations
  259. *
  260. * Returns an associative array with all translations
  261. */
  262. public function getTranslations() {
  263. $this->init();
  264. return $this->translations;
  265. }
  266. /**
  267. * @brief getPluralFormString
  268. * @return string containing the gettext "Plural-Forms"-string
  269. *
  270. * Returns a string like "nplurals=2; plural=(n != 1);"
  271. */
  272. public function getPluralFormString() {
  273. $this->init();
  274. return $this->plural_form_string;
  275. }
  276. /**
  277. * @brief getPluralFormFunction
  278. * @return string the plural form function
  279. *
  280. * returned function accepts the argument $n
  281. */
  282. public function getPluralFormFunction() {
  283. $this->init();
  284. if(is_null($this->plural_form_function)) {
  285. $this->plural_form_function = $this->createPluralFormFunction($this->plural_form_string);
  286. }
  287. return $this->plural_form_function;
  288. }
  289. /**
  290. * @brief get localizations
  291. * @return array Fetch all localizations
  292. *
  293. * Returns an associative array with all localizations
  294. */
  295. public function getLocalizations() {
  296. $this->init();
  297. return $this->localizations;
  298. }
  299. /**
  300. * @brief Localization
  301. * @param string $type Type of localization
  302. * @param array|int|string $data parameters for this localization
  303. * @return String or false
  304. *
  305. * Returns the localized data.
  306. *
  307. * Implemented types:
  308. * - date
  309. * - Creates a date
  310. * - l10n-field: date
  311. * - params: timestamp (int/string)
  312. * - datetime
  313. * - Creates date and time
  314. * - l10n-field: datetime
  315. * - params: timestamp (int/string)
  316. * - time
  317. * - Creates a time
  318. * - l10n-field: time
  319. * - params: timestamp (int/string)
  320. */
  321. public function l($type, $data) {
  322. $this->init();
  323. switch($type) {
  324. // If you add something don't forget to add it to $localizations
  325. // at the top of the page
  326. case 'date':
  327. case 'datetime':
  328. case 'time':
  329. if($data instanceof DateTime) {
  330. return $data->format($this->localizations[$type]);
  331. } elseif(is_string($data) && !is_numeric($data)) {
  332. $data = strtotime($data);
  333. }
  334. $locales = array(self::findLanguage());
  335. if (strlen($locales[0]) == 2) {
  336. $locales[] = $locales[0].'_'.strtoupper($locales[0]);
  337. }
  338. setlocale(LC_TIME, $locales);
  339. $format = $this->localizations[$type];
  340. // Check for Windows to find and replace the %e modifier correctly
  341. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
  342. $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
  343. }
  344. return strftime($format, $data);
  345. break;
  346. case 'firstday':
  347. case 'jsdate':
  348. return $this->localizations[$type];
  349. default:
  350. return false;
  351. }
  352. }
  353. /**
  354. * @brief Choose a language
  355. * @param array $text Associative Array with possible strings
  356. * @return String
  357. *
  358. * $text is an array 'de' => 'hallo welt', 'en' => 'hello world', ...
  359. *
  360. * This function is useful to avoid loading thousands of files if only one
  361. * simple string is needed, for example in appinfo.php
  362. */
  363. public static function selectLanguage($text) {
  364. $lang = self::findLanguage(array_keys($text));
  365. return $text[$lang];
  366. }
  367. /**
  368. * The given language is forced to be used while executing the current request
  369. * @param string $lang
  370. */
  371. public static function forceLanguage($lang) {
  372. self::$language = $lang;
  373. }
  374. /**
  375. * @brief find the best language
  376. * @param array|string $app details below
  377. * @return string language
  378. *
  379. * If $app is an array, ownCloud assumes that these are the available
  380. * languages. Otherwise ownCloud tries to find the files in the l10n
  381. * folder.
  382. *
  383. * If nothing works it returns 'en'
  384. */
  385. public static function findLanguage($app = null) {
  386. if(!is_array($app) && self::$language != '') {
  387. return self::$language;
  388. }
  389. if(OC_User::getUser() && OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang')) {
  390. $lang = OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang');
  391. self::$language = $lang;
  392. if(is_array($app)) {
  393. $available = $app;
  394. $lang_exists = array_search($lang, $available) !== false;
  395. } else {
  396. $lang_exists = self::languageExists($app, $lang);
  397. }
  398. if($lang_exists) {
  399. return $lang;
  400. }
  401. }
  402. $default_language = OC_Config::getValue('default_language', false);
  403. if($default_language !== false) {
  404. return $default_language;
  405. }
  406. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  407. if(is_array($app)) {
  408. $available = $app;
  409. } else {
  410. $available = self::findAvailableLanguages($app);
  411. }
  412. // E.g. make sure that 'de' is before 'de_DE'.
  413. sort($available);
  414. $preferences = preg_split('/,\s*/', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  415. foreach($preferences as $preference) {
  416. list($preferred_language) = explode(';', $preference);
  417. $preferred_language = str_replace('-', '_', $preferred_language);
  418. foreach($available as $available_language) {
  419. if ($preferred_language === strtolower($available_language)) {
  420. if (is_null($app)) {
  421. self::$language = $available_language;
  422. }
  423. return $available_language;
  424. }
  425. }
  426. foreach($available as $available_language) {
  427. if (substr($preferred_language, 0, 2) === $available_language) {
  428. if (is_null($app)) {
  429. self::$language = $available_language;
  430. }
  431. return $available_language;
  432. }
  433. }
  434. }
  435. }
  436. // Last try: English
  437. return 'en';
  438. }
  439. /**
  440. * @brief find the l10n directory
  441. * @param string $app App that needs to be translated
  442. * @return directory
  443. */
  444. protected static function findI18nDir($app) {
  445. // find the i18n dir
  446. $i18ndir = OC::$SERVERROOT.'/core/l10n/';
  447. if($app != '') {
  448. // Check if the app is in the app folder
  449. if(file_exists(OC_App::getAppPath($app).'/l10n/')) {
  450. $i18ndir = OC_App::getAppPath($app).'/l10n/';
  451. }
  452. else{
  453. $i18ndir = OC::$SERVERROOT.'/'.$app.'/l10n/';
  454. }
  455. }
  456. return $i18ndir;
  457. }
  458. /**
  459. * @brief find all available languages for an app
  460. * @param string $app App that needs to be translated
  461. * @return array an array of available languages
  462. */
  463. public static function findAvailableLanguages($app=null) {
  464. $available=array('en');//english is always available
  465. $dir = self::findI18nDir($app);
  466. if(is_dir($dir)) {
  467. $files=scandir($dir);
  468. foreach($files as $file) {
  469. if(substr($file, -4, 4) === '.php' && substr($file, 0, 4) !== 'l10n') {
  470. $i = substr($file, 0, -4);
  471. $available[] = $i;
  472. }
  473. }
  474. }
  475. return $available;
  476. }
  477. /**
  478. * @param string $app
  479. * @param string $lang
  480. * @return bool
  481. */
  482. public static function languageExists($app, $lang) {
  483. if ($lang == 'en') {//english is always available
  484. return true;
  485. }
  486. $dir = self::findI18nDir($app);
  487. if(is_dir($dir)) {
  488. return file_exists($dir.'/'.$lang.'.php');
  489. }
  490. return false;
  491. }
  492. }