l10n.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 $app string
  68. * @param $lang string|null
  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 $app string app requesting l10n
  81. * @param $lang string default: null Language
  82. * @returns OC_L10N-Object
  83. *
  84. * If language is not set, the constructor tries to find the right
  85. * language.
  86. */
  87. public function __construct($app, $lang = null) {
  88. $this->app = $app;
  89. $this->lang = $lang;
  90. }
  91. public function load($transFile) {
  92. $this->app = true;
  93. include $transFile;
  94. if(isset($TRANSLATIONS) && is_array($TRANSLATIONS)) {
  95. $this->translations = $TRANSLATIONS;
  96. }
  97. if(isset($PLURAL_FORMS)) {
  98. $this->plural_form_string = $PLURAL_FORMS;
  99. }
  100. }
  101. protected function init() {
  102. if ($this->app === true) {
  103. return;
  104. }
  105. $app = OC_App::cleanAppId($this->app);
  106. $lang = $this->lang;
  107. $this->app = true;
  108. // Find the right language
  109. if(is_null($lang) || $lang == '') {
  110. $lang = self::findLanguage($app);
  111. }
  112. // Use cache if possible
  113. if(array_key_exists($app.'::'.$lang, self::$cache)) {
  114. $this->translations = self::$cache[$app.'::'.$lang]['t'];
  115. $this->localizations = self::$cache[$app.'::'.$lang]['l'];
  116. }
  117. else{
  118. $i18ndir = self::findI18nDir($app);
  119. // Localization is in /l10n, Texts are in $i18ndir
  120. // (Just no need to define date/time format etc. twice)
  121. if((OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC_App::getAppPath($app).'/l10n/')
  122. || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/core/l10n/')
  123. || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/lib/l10n/')
  124. || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/settings')
  125. )
  126. && file_exists($i18ndir.$lang.'.php')) {
  127. // Include the file, save the data from $CONFIG
  128. $transFile = strip_tags($i18ndir).strip_tags($lang).'.php';
  129. include $transFile;
  130. if(isset($TRANSLATIONS) && is_array($TRANSLATIONS)) {
  131. $this->translations = $TRANSLATIONS;
  132. //merge with translations from theme
  133. $theme = OC_Config::getValue( "theme" );
  134. if (!is_null($theme)) {
  135. $transFile = OC::$SERVERROOT.'/themes/'.$theme.substr($transFile, strlen(OC::$SERVERROOT));
  136. if (file_exists($transFile)) {
  137. include $transFile;
  138. if (isset($TRANSLATIONS) && is_array($TRANSLATIONS)) {
  139. $this->translations = array_merge($this->translations, $TRANSLATIONS);
  140. }
  141. }
  142. }
  143. }
  144. if(isset($PLURAL_FORMS)) {
  145. $this->plural_form_string = $PLURAL_FORMS;
  146. }
  147. }
  148. if(file_exists(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php')) {
  149. // Include the file, save the data from $CONFIG
  150. include OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php';
  151. if(isset($LOCALIZATIONS) && is_array($LOCALIZATIONS)) {
  152. $this->localizations = array_merge($this->localizations, $LOCALIZATIONS);
  153. }
  154. }
  155. self::$cache[$app.'::'.$lang]['t'] = $this->translations;
  156. self::$cache[$app.'::'.$lang]['l'] = $this->localizations;
  157. }
  158. }
  159. /**
  160. * @brief Creates a function that The constructor
  161. *
  162. * If language is not set, the constructor tries to find the right
  163. * language.
  164. *
  165. * Parts of the code is copied from Habari:
  166. * https://github.com/habari/system/blob/master/classes/locale.php
  167. * @param $string string
  168. * @return string
  169. */
  170. protected function createPluralFormFunction($string){
  171. if(preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
  172. // sanitize
  173. $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
  174. $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
  175. $body = str_replace(
  176. array( 'plural', 'n', '$n$plurals', ),
  177. array( '$plural', '$n', '$nplurals', ),
  178. 'nplurals='. $nplurals . '; plural=' . $plural
  179. );
  180. // add parents
  181. // important since PHP's ternary evaluates from left to right
  182. $body .= ';';
  183. $res = '';
  184. $p = 0;
  185. for($i = 0; $i < strlen($body); $i++) {
  186. $ch = $body[$i];
  187. switch ( $ch ) {
  188. case '?':
  189. $res .= ' ? (';
  190. $p++;
  191. break;
  192. case ':':
  193. $res .= ') : (';
  194. break;
  195. case ';':
  196. $res .= str_repeat( ')', $p ) . ';';
  197. $p = 0;
  198. break;
  199. default:
  200. $res .= $ch;
  201. }
  202. }
  203. $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
  204. return create_function('$n', $body);
  205. }
  206. else {
  207. // default: one plural form for all cases but n==1 (english)
  208. return create_function(
  209. '$n',
  210. '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
  211. );
  212. }
  213. }
  214. /**
  215. * @brief Translating
  216. * @param $text String The text we need a translation for
  217. * @param array $parameters default:array() Parameters for sprintf
  218. * @return \OC_L10N_String Translation or the same text
  219. *
  220. * Returns the translation. If no translation is found, $text will be
  221. * returned.
  222. */
  223. public function t($text, $parameters = array()) {
  224. return new OC_L10N_String($this, $text, $parameters);
  225. }
  226. /**
  227. * @brief Translating
  228. * @param $text_singular String the string to translate for exactly one object
  229. * @param $text_plural String the string to translate for n objects
  230. * @param $count Integer Number of objects
  231. * @param array $parameters default:array() Parameters for sprintf
  232. * @return \OC_L10N_String Translation or the same text
  233. *
  234. * Returns the translation. If no translation is found, $text will be
  235. * returned. %n will be replaced with the number of objects.
  236. *
  237. * The correct plural is determined by the plural_forms-function
  238. * provided by the po file.
  239. *
  240. */
  241. public function n($text_singular, $text_plural, $count, $parameters = array()) {
  242. $this->init();
  243. $identifier = "_${text_singular}__${text_plural}_";
  244. if( array_key_exists($identifier, $this->translations)) {
  245. return new OC_L10N_String( $this, $identifier, $parameters, $count );
  246. }
  247. else{
  248. if($count === 1) {
  249. return new OC_L10N_String($this, $text_singular, $parameters, $count);
  250. }
  251. else{
  252. return new OC_L10N_String($this, $text_plural, $parameters, $count);
  253. }
  254. }
  255. }
  256. /**
  257. * @brief Translating
  258. * @param $textArray The text array we need a translation for
  259. * @returns Translation or the same text
  260. *
  261. * Returns the translation. If no translation is found, $textArray will be
  262. * returned.
  263. *
  264. *
  265. * @deprecated deprecated since ownCloud version 5.0
  266. * This method will probably be removed with ownCloud 6.0
  267. *
  268. *
  269. */
  270. public function tA($textArray) {
  271. OC_Log::write('core', 'DEPRECATED: the method tA is deprecated and will be removed soon.', OC_Log::WARN);
  272. $result = array();
  273. foreach($textArray as $key => $text) {
  274. $result[$key] = (string)$this->t($text);
  275. }
  276. return $result;
  277. }
  278. /**
  279. * @brief getTranslations
  280. * @returns Fetch all translations
  281. *
  282. * Returns an associative array with all translations
  283. */
  284. public function getTranslations() {
  285. $this->init();
  286. return $this->translations;
  287. }
  288. /**
  289. * @brief getPluralFormString
  290. * @returns string containing the gettext "Plural-Forms"-string
  291. *
  292. * Returns a string like "nplurals=2; plural=(n != 1);"
  293. */
  294. public function getPluralFormString() {
  295. $this->init();
  296. return $this->plural_form_string;
  297. }
  298. /**
  299. * @brief getPluralFormFunction
  300. * @returns string the plural form function
  301. *
  302. * returned function accepts the argument $n
  303. */
  304. public function getPluralFormFunction() {
  305. $this->init();
  306. if(is_null($this->plural_form_function)) {
  307. $this->plural_form_function = $this->createPluralFormFunction($this->plural_form_string);
  308. }
  309. return $this->plural_form_function;
  310. }
  311. /**
  312. * @brief get localizations
  313. * @returns Fetch all localizations
  314. *
  315. * Returns an associative array with all localizations
  316. */
  317. public function getLocalizations() {
  318. $this->init();
  319. return $this->localizations;
  320. }
  321. /**
  322. * @brief Localization
  323. * @param $type Type of localization
  324. * @param $params parameters for this localization
  325. * @returns String or false
  326. *
  327. * Returns the localized data.
  328. *
  329. * Implemented types:
  330. * - date
  331. * - Creates a date
  332. * - l10n-field: date
  333. * - params: timestamp (int/string)
  334. * - datetime
  335. * - Creates date and time
  336. * - l10n-field: datetime
  337. * - params: timestamp (int/string)
  338. * - time
  339. * - Creates a time
  340. * - l10n-field: time
  341. * - params: timestamp (int/string)
  342. */
  343. public function l($type, $data) {
  344. $this->init();
  345. switch($type) {
  346. // If you add something don't forget to add it to $localizations
  347. // at the top of the page
  348. case 'date':
  349. case 'datetime':
  350. case 'time':
  351. if($data instanceof DateTime) {
  352. return $data->format($this->localizations[$type]);
  353. } elseif(is_string($data) && !is_numeric($data)) {
  354. $data = strtotime($data);
  355. }
  356. $locales = array(self::findLanguage());
  357. if (strlen($locales[0]) == 2) {
  358. $locales[] = $locales[0].'_'.strtoupper($locales[0]);
  359. }
  360. setlocale(LC_TIME, $locales);
  361. $format = $this->localizations[$type];
  362. // Check for Windows to find and replace the %e modifier correctly
  363. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
  364. $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
  365. }
  366. return strftime($format, $data);
  367. break;
  368. case 'firstday':
  369. case 'jsdate':
  370. return $this->localizations[$type];
  371. default:
  372. return false;
  373. }
  374. }
  375. /**
  376. * @brief Choose a language
  377. * @param $texts Associative Array with possible strings
  378. * @returns String
  379. *
  380. * $text is an array 'de' => 'hallo welt', 'en' => 'hello world', ...
  381. *
  382. * This function is useful to avoid loading thousands of files if only one
  383. * simple string is needed, for example in appinfo.php
  384. */
  385. public static function selectLanguage($text) {
  386. $lang = self::findLanguage(array_keys($text));
  387. return $text[$lang];
  388. }
  389. /**
  390. * @brief find the best language
  391. * @param $app Array or string, details below
  392. * @returns string language
  393. *
  394. * If $app is an array, ownCloud assumes that these are the available
  395. * languages. Otherwise ownCloud tries to find the files in the l10n
  396. * folder.
  397. *
  398. * If nothing works it returns 'en'
  399. */
  400. public static function findLanguage($app = null) {
  401. if(!is_array($app) && self::$language != '') {
  402. return self::$language;
  403. }
  404. if(OC_User::getUser() && OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang')) {
  405. $lang = OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang');
  406. self::$language = $lang;
  407. if(is_array($app)) {
  408. $available = $app;
  409. $lang_exists = array_search($lang, $available) !== false;
  410. } else {
  411. $lang_exists = self::languageExists($app, $lang);
  412. }
  413. if($lang_exists) {
  414. return $lang;
  415. }
  416. }
  417. $default_language = OC_Config::getValue('default_language', false);
  418. if($default_language !== false) {
  419. return $default_language;
  420. }
  421. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  422. if(is_array($app)) {
  423. $available = $app;
  424. } else {
  425. $available = self::findAvailableLanguages($app);
  426. }
  427. // E.g. make sure that 'de' is before 'de_DE'.
  428. sort($available);
  429. $preferences = preg_split('/,\s*/', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  430. foreach($preferences as $preference) {
  431. list($preferred_language) = explode(';', $preference);
  432. $preferred_language = str_replace('-', '_', $preferred_language);
  433. foreach($available as $available_language) {
  434. if ($preferred_language === strtolower($available_language)) {
  435. if (is_null($app)) {
  436. self::$language = $available_language;
  437. }
  438. return $available_language;
  439. }
  440. }
  441. foreach($available as $available_language) {
  442. if (substr($preferred_language, 0, 2) === $available_language) {
  443. if (is_null($app)) {
  444. self::$language = $available_language;
  445. }
  446. return $available_language;
  447. }
  448. }
  449. }
  450. }
  451. // Last try: English
  452. return 'en';
  453. }
  454. /**
  455. * @brief find the l10n directory
  456. * @param $app App that needs to be translated
  457. * @returns directory
  458. */
  459. protected static function findI18nDir($app) {
  460. // find the i18n dir
  461. $i18ndir = OC::$SERVERROOT.'/core/l10n/';
  462. if($app != '') {
  463. // Check if the app is in the app folder
  464. if(file_exists(OC_App::getAppPath($app).'/l10n/')) {
  465. $i18ndir = OC_App::getAppPath($app).'/l10n/';
  466. }
  467. else{
  468. $i18ndir = OC::$SERVERROOT.'/'.$app.'/l10n/';
  469. }
  470. }
  471. return $i18ndir;
  472. }
  473. /**
  474. * @brief find all available languages for an app
  475. * @param $app App that needs to be translated
  476. * @returns array an array of available languages
  477. */
  478. public static function findAvailableLanguages($app=null) {
  479. $available=array('en');//english is always available
  480. $dir = self::findI18nDir($app);
  481. if(is_dir($dir)) {
  482. $files=scandir($dir);
  483. foreach($files as $file) {
  484. if(substr($file, -4, 4) === '.php' && substr($file, 0, 4) !== 'l10n') {
  485. $i = substr($file, 0, -4);
  486. $available[] = $i;
  487. }
  488. }
  489. }
  490. return $available;
  491. }
  492. public static function languageExists($app, $lang) {
  493. if ($lang == 'en') {//english is always available
  494. return true;
  495. }
  496. $dir = self::findI18nDir($app);
  497. if(is_dir($dir)) {
  498. return file_exists($dir.'/'.$lang.'.php');
  499. }
  500. return false;
  501. }
  502. }