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.

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