l10n.php 15 KB

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