2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Standard string manager.
21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
29 * Standard string_manager implementation
31 * Implements string_manager with getting and printing localised strings
34 * @copyright 2010 Petr Skoda {@link http://skodak.org}
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class core_string_manager_standard implements core_string_manager {
38 /** @var string location of all packs except 'en' */
40 /** @var string location of all lang pack local modifications */
42 /** @var cache lang string cache - it will be optimised more later */
44 /** @var int get_string() counter */
45 protected $countgetstring = 0;
46 /** @var bool use disk cache */
48 /** @var array limit list of translations */
50 /** @var string location of a file that caches the list of available translations */
54 * Create new instance of string manager
56 * @param string $otherroot location of downlaoded lang packs - usually $CFG->dataroot/lang
57 * @param string $localroot usually the same as $otherroot
58 * @param bool $usecache use disk cache
59 * @param array $translist limit list of visible translations
60 * @param string $menucache the location of a file that caches the list of available translations
62 public function __construct($otherroot, $localroot, $usecache, $translist, $menucache) {
63 $this->otherroot = $otherroot;
64 $this->localroot = $localroot;
65 $this->usecache = $usecache;
66 $this->translist = $translist;
67 $this->menucache = $menucache;
69 if ($this->usecache) {
70 // We can use a proper cache, establish the cache using the 'String cache' definition.
71 $this->cache = cache::make('core', 'string');
73 // We only want a cache for the length of the request, create a static cache.
78 $this->cache = cache::make_from_params(cache_store::MODE_REQUEST, 'core', 'string', array(), $options);
83 * Returns list of all explicit parent languages for the given language.
85 * English (en) is considered as the top implicit parent of all language packs
86 * and is not included in the returned list. The language itself is appended to the
87 * end of the list. The method is aware of circular dependency risk.
89 * @see self::populate_parent_languages()
90 * @param string $lang the code of the language
91 * @return array all explicit parent languages with the lang itself appended
93 public function get_language_dependencies($lang) {
94 return $this->populate_parent_languages($lang);
98 * Load all strings for one component
100 * @param string $component The module the string is associated with
101 * @param string $lang
102 * @param bool $disablecache Do not use caches, force fetching the strings from sources
103 * @param bool $disablelocal Do not use customized strings in xx_local language packs
104 * @return array of all string for given component and lang
106 public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false) {
109 list($plugintype, $pluginname) = core_component::normalize_component($component);
110 if ($plugintype == 'core' and is_null($pluginname)) {
113 $component = $plugintype . '_' . $pluginname;
116 $cachekey = $lang.'_'.$component;
118 if (!$disablecache and !$disablelocal) {
119 $string = $this->cache->get($cachekey);
125 // No cache found - let us merge all possible sources of the strings.
126 if ($plugintype === 'core') {
128 if ($file === null) {
132 // First load english pack.
133 if (!file_exists("$CFG->dirroot/lang/en/$file.php")) {
136 include("$CFG->dirroot/lang/en/$file.php");
137 $originalkeys = array_keys($string);
138 $originalkeys = array_flip($originalkeys);
140 // And then corresponding local if present and allowed.
141 if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
142 include("$this->localroot/en_local/$file.php");
144 // Now loop through all langs in correct order.
145 $deps = $this->get_language_dependencies($lang);
146 foreach ($deps as $dep) {
147 // The main lang string location.
148 if (file_exists("$this->otherroot/$dep/$file.php")) {
149 include("$this->otherroot/$dep/$file.php");
151 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
152 include("$this->localroot/{$dep}_local/$file.php");
157 if (!$location = core_component::get_plugin_directory($plugintype, $pluginname) or !is_dir($location)) {
160 if ($plugintype === 'mod') {
164 $file = $plugintype . '_' . $pluginname;
167 // First load English pack.
168 if (!file_exists("$location/lang/en/$file.php")) {
169 // English pack does not exist, so do not try to load anything else.
172 include("$location/lang/en/$file.php");
173 $originalkeys = array_keys($string);
174 $originalkeys = array_flip($originalkeys);
175 // And then corresponding local english if present.
176 if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
177 include("$this->localroot/en_local/$file.php");
180 // Now loop through all langs in correct order.
181 $deps = $this->get_language_dependencies($lang);
182 foreach ($deps as $dep) {
183 // Legacy location - used by contrib only.
184 if (file_exists("$location/lang/$dep/$file.php")) {
185 include("$location/lang/$dep/$file.php");
187 // The main lang string location.
188 if (file_exists("$this->otherroot/$dep/$file.php")) {
189 include("$this->otherroot/$dep/$file.php");
191 // Local customisations.
192 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
193 include("$this->localroot/{$dep}_local/$file.php");
198 // We do not want any extra strings from other languages - everything must be in en lang pack.
199 $string = array_intersect_key($string, $originalkeys);
201 if (!$disablelocal) {
202 // Now we have a list of strings from all possible sources. put it into both in-memory and on-disk
203 // caches so we do not need to do all this merging and dependencies resolving again.
204 $this->cache->set($cachekey, $string);
210 * Does the string actually exist?
212 * get_string() is throwing debug warnings, sometimes we do not want them
213 * or we want to display better explanation of the problem.
214 * Note: Use with care!
216 * @param string $identifier The identifier of the string to search for
217 * @param string $component The module the string is associated with
218 * @return boot true if exists
220 public function string_exists($identifier, $component) {
221 $lang = current_language();
222 $string = $this->load_component_strings($component, $lang);
223 return isset($string[$identifier]);
227 * Get String returns a requested string
229 * @param string $identifier The identifier of the string to search for
230 * @param string $component The module the string is associated with
231 * @param string|object|array $a An object, string or number that can be used
232 * within translation strings
233 * @param string $lang moodle translation language, null means use current
234 * @return string The String !
236 public function get_string($identifier, $component = '', $a = null, $lang = null) {
237 $this->countgetstring++;
238 // There are very many uses of these time formating strings without the 'langconfig' component,
239 // it would not be reasonable to expect that all of them would be converted during 2.0 migration.
240 static $langconfigstrs = array(
242 'strftimedatefullshort' => 1,
243 'strftimedateshort' => 1,
244 'strftimedatetime' => 1,
245 'strftimedatetimeshort' => 1,
246 'strftimedaydate' => 1,
247 'strftimedaydatetime' => 1,
248 'strftimedayshort' => 1,
249 'strftimedaytime' => 1,
250 'strftimemonthyear' => 1,
251 'strftimerecent' => 1,
252 'strftimerecentfull' => 1,
253 'strftimetime' => 1);
255 if (empty($component)) {
256 if (isset($langconfigstrs[$identifier])) {
257 $component = 'langconfig';
259 $component = 'moodle';
263 if ($lang === null) {
264 $lang = current_language();
267 $string = $this->load_component_strings($component, $lang);
269 if (!isset($string[$identifier])) {
270 if ($component === 'pix' or $component === 'core_pix') {
271 // This component contains only alt tags for emoticons, not all of them are supposed to be defined.
274 if ($identifier === 'parentlanguage' and ($component === 'langconfig' or $component === 'core_langconfig')) {
275 // Identifier parentlanguage is a special string, undefined means use English if not defined.
278 if ($this->usecache) {
279 // Maybe the on-disk cache is dirty - let the last attempt be to find the string in original sources,
280 // do NOT write the results to disk cache because it may end up in race conditions see MDL-31904.
281 $this->usecache = false;
282 $string = $this->load_component_strings($component, $lang, true);
283 $this->usecache = true;
285 if (!isset($string[$identifier])) {
286 // The string is still missing - should be fixed by developer.
287 list($plugintype, $pluginname) = core_component::normalize_component($component);
288 if ($plugintype == 'core') {
289 $file = "lang/en/{$component}.php";
290 } else if ($plugintype == 'mod') {
291 $file = "mod/{$pluginname}/lang/en/{$pluginname}.php";
293 $path = core_component::get_plugin_directory($plugintype, $pluginname);
294 $file = "{$path}/lang/en/{$plugintype}_{$pluginname}.php";
296 debugging("Invalid get_string() identifier: '{$identifier}' or component '{$component}'. " .
297 "Perhaps you are missing \$string['{$identifier}'] = ''; in {$file}?", DEBUG_DEVELOPER);
298 return "[[$identifier]]";
302 $string = $string[$identifier];
305 // Process array's and objects (except lang_strings).
306 if (is_array($a) or (is_object($a) && !($a instanceof lang_string))) {
310 foreach ($a as $key => $value) {
312 // We do not support numeric keys - sorry!
315 if (is_array($value) or (is_object($value) && !($value instanceof lang_string))) {
316 // We support just string or lang_string as value.
319 $search[] = '{$a->'.$key.'}';
320 $replace[] = (string)$value;
323 $string = str_replace($search, $replace, $string);
326 $string = str_replace('{$a}', (string)$a, $string);
334 * Returns information about the string_manager performance.
338 public function get_performance_summary() {
340 'langcountgetstring' => $this->countgetstring,
342 'langcountgetstring' => 'get_string calls',
347 * Returns a localised list of all country names, sorted by localised name.
349 * @param bool $returnall return all or just enabled
350 * @param string $lang moodle translation language, null means use current
351 * @return array two-letter country code => translated name.
353 public function get_list_of_countries($returnall = false, $lang = null) {
356 if ($lang === null) {
357 $lang = current_language();
360 $countries = $this->load_component_strings('core_countries', $lang);
361 core_collator::asort($countries);
362 if (!$returnall and !empty($CFG->allcountrycodes)) {
363 $enabled = explode(',', $CFG->allcountrycodes);
365 foreach ($enabled as $c) {
366 if (isset($countries[$c])) {
367 $return[$c] = $countries[$c];
377 * Returns a localised list of languages, sorted by code keys.
379 * @param string $lang moodle translation language, null means use current
380 * @param string $standard language list standard
381 * - iso6392: three-letter language code (ISO 639-2/T) => translated name
382 * - iso6391: two-letter langauge code (ISO 639-1) => translated name
383 * @return array language code => translated name
385 public function get_list_of_languages($lang = null, $standard = 'iso6391') {
386 if ($lang === null) {
387 $lang = current_language();
390 if ($standard === 'iso6392') {
391 $langs = $this->load_component_strings('core_iso6392', $lang);
395 } else if ($standard === 'iso6391') {
396 $langs2 = $this->load_component_strings('core_iso6392', $lang);
397 static $mapping = array('aar' => 'aa', 'abk' => 'ab', 'afr' => 'af', 'aka' => 'ak', 'sqi' => 'sq', 'amh' => 'am', 'ara' => 'ar', 'arg' => 'an', 'hye' => 'hy',
398 'asm' => 'as', 'ava' => 'av', 'ave' => 'ae', 'aym' => 'ay', 'aze' => 'az', 'bak' => 'ba', 'bam' => 'bm', 'eus' => 'eu', 'bel' => 'be', 'ben' => 'bn', 'bih' => 'bh',
399 'bis' => 'bi', 'bos' => 'bs', 'bre' => 'br', 'bul' => 'bg', 'mya' => 'my', 'cat' => 'ca', 'cha' => 'ch', 'che' => 'ce', 'zho' => 'zh', 'chu' => 'cu', 'chv' => 'cv',
400 'cor' => 'kw', 'cos' => 'co', 'cre' => 'cr', 'ces' => 'cs', 'dan' => 'da', 'div' => 'dv', 'nld' => 'nl', 'dzo' => 'dz', 'eng' => 'en', 'epo' => 'eo', 'est' => 'et',
401 'ewe' => 'ee', 'fao' => 'fo', 'fij' => 'fj', 'fin' => 'fi', 'fra' => 'fr', 'fry' => 'fy', 'ful' => 'ff', 'kat' => 'ka', 'deu' => 'de', 'gla' => 'gd', 'gle' => 'ga',
402 'glg' => 'gl', 'glv' => 'gv', 'ell' => 'el', 'grn' => 'gn', 'guj' => 'gu', 'hat' => 'ht', 'hau' => 'ha', 'heb' => 'he', 'her' => 'hz', 'hin' => 'hi', 'hmo' => 'ho',
403 'hrv' => 'hr', 'hun' => 'hu', 'ibo' => 'ig', 'isl' => 'is', 'ido' => 'io', 'iii' => 'ii', 'iku' => 'iu', 'ile' => 'ie', 'ina' => 'ia', 'ind' => 'id', 'ipk' => 'ik',
404 'ita' => 'it', 'jav' => 'jv', 'jpn' => 'ja', 'kal' => 'kl', 'kan' => 'kn', 'kas' => 'ks', 'kau' => 'kr', 'kaz' => 'kk', 'khm' => 'km', 'kik' => 'ki', 'kin' => 'rw',
405 'kir' => 'ky', 'kom' => 'kv', 'kon' => 'kg', 'kor' => 'ko', 'kua' => 'kj', 'kur' => 'ku', 'lao' => 'lo', 'lat' => 'la', 'lav' => 'lv', 'lim' => 'li', 'lin' => 'ln',
406 'lit' => 'lt', 'ltz' => 'lb', 'lub' => 'lu', 'lug' => 'lg', 'mkd' => 'mk', 'mah' => 'mh', 'mal' => 'ml', 'mri' => 'mi', 'mar' => 'mr', 'msa' => 'ms', 'mlg' => 'mg',
407 'mlt' => 'mt', 'mon' => 'mn', 'nau' => 'na', 'nav' => 'nv', 'nbl' => 'nr', 'nde' => 'nd', 'ndo' => 'ng', 'nep' => 'ne', 'nno' => 'nn', 'nob' => 'nb', 'nor' => 'no',
408 'nya' => 'ny', 'oci' => 'oc', 'oji' => 'oj', 'ori' => 'or', 'orm' => 'om', 'oss' => 'os', 'pan' => 'pa', 'fas' => 'fa', 'pli' => 'pi', 'pol' => 'pl', 'por' => 'pt',
409 'pus' => 'ps', 'que' => 'qu', 'roh' => 'rm', 'ron' => 'ro', 'run' => 'rn', 'rus' => 'ru', 'sag' => 'sg', 'san' => 'sa', 'sin' => 'si', 'slk' => 'sk', 'slv' => 'sl',
410 'sme' => 'se', 'smo' => 'sm', 'sna' => 'sn', 'snd' => 'sd', 'som' => 'so', 'sot' => 'st', 'spa' => 'es', 'srd' => 'sc', 'srp' => 'sr', 'ssw' => 'ss', 'sun' => 'su',
411 'swa' => 'sw', 'swe' => 'sv', 'tah' => 'ty', 'tam' => 'ta', 'tat' => 'tt', 'tel' => 'te', 'tgk' => 'tg', 'tgl' => 'tl', 'tha' => 'th', 'bod' => 'bo', 'tir' => 'ti',
412 'ton' => 'to', 'tsn' => 'tn', 'tso' => 'ts', 'tuk' => 'tk', 'tur' => 'tr', 'twi' => 'tw', 'uig' => 'ug', 'ukr' => 'uk', 'urd' => 'ur', 'uzb' => 'uz', 'ven' => 've',
413 'vie' => 'vi', 'vol' => 'vo', 'cym' => 'cy', 'wln' => 'wa', 'wol' => 'wo', 'xho' => 'xh', 'yid' => 'yi', 'yor' => 'yo', 'zha' => 'za', 'zul' => 'zu');
415 foreach ($mapping as $c2 => $c1) {
416 $langs1[$c1] = $langs2[$c2];
422 debugging('Unsupported $standard parameter in get_list_of_languages() method: '.$standard);
429 * Checks if the translation exists for the language
431 * @param string $lang moodle translation language code
432 * @param bool $includeall include also disabled translations
433 * @return bool true if exists
435 public function translation_exists($lang, $includeall = true) {
437 if (strpos($lang, '_local') !== false) {
438 // Local packs are not real translations.
441 if (!$includeall and !empty($this->translist)) {
442 if (!in_array($lang, $this->translist)) {
446 if ($lang === 'en') {
447 // Part of distribution.
450 return file_exists("$this->otherroot/$lang/langconfig.php");
454 * Returns localised list of installed translations
456 * @param bool $returnall return all or just enabled
457 * @return array moodle translation code => localised translation name
459 public function get_list_of_translations($returnall = false) {
462 $languages = array();
464 if (!empty($CFG->langcache) and is_readable($this->menucache)) {
465 // Try to re-use the cached list of all available languages.
466 $cachedlist = json_decode(file_get_contents($this->menucache), true);
468 if (is_array($cachedlist) and !empty($cachedlist)) {
469 // The cache file is restored correctly.
471 if (!$returnall and !empty($this->translist)) {
472 // Return just enabled translations.
473 foreach ($cachedlist as $langcode => $langname) {
474 if (in_array($langcode, $this->translist)) {
475 $languages[$langcode] = $langname;
481 // Return all translations.
487 // The cached list of languages is not available, let us populate the list.
488 if (!$returnall and !empty($this->translist)) {
489 // Return only some translations.
490 foreach ($this->translist as $lang) {
491 $lang = trim($lang); // Just trim spaces to be a bit more permissive.
492 if (strstr($lang, '_local') !== false) {
495 if (strstr($lang, '_utf8') !== false) {
498 if ($lang !== 'en' and !file_exists("$this->otherroot/$lang/langconfig.php")) {
499 // Some broken or missing lang - can not switch to it anyway.
502 $string = $this->load_component_strings('langconfig', $lang);
503 if (!empty($string['thislanguage'])) {
504 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
510 // Return all languages available in system.
511 $langdirs = get_list_of_plugins('', '', $this->otherroot);
513 $langdirs = array_merge($langdirs, array("$CFG->dirroot/lang/en" => 'en'));
516 // Loop through all langs and get info.
517 foreach ($langdirs as $lang) {
518 if (strstr($lang, '_local') !== false) {
521 if (strstr($lang, '_utf8') !== false) {
524 $string = $this->load_component_strings('langconfig', $lang);
525 if (!empty($string['thislanguage'])) {
526 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
531 if (!empty($CFG->langcache) and !empty($this->menucache)) {
532 // Cache the list so that it can be used next time.
533 core_collator::asort($languages);
534 check_dir_exists(dirname($this->menucache), true, true);
535 file_put_contents($this->menucache, json_encode($languages));
536 @chmod($this->menucache, $CFG->filepermissions);
540 core_collator::asort($languages);
546 * Returns localised list of currencies.
548 * @param string $lang moodle translation language, null means use current
549 * @return array currency code => localised currency name
551 public function get_list_of_currencies($lang = null) {
552 if ($lang === null) {
553 $lang = current_language();
556 $currencies = $this->load_component_strings('core_currencies', $lang);
563 * Clears both in-memory and on-disk caches
564 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
566 public function reset_caches($phpunitreset = false) {
568 require_once("$CFG->libdir/filelib.php");
570 // Clear the on-disk disk with aggregated string files.
571 $this->cache->purge();
573 if (!$phpunitreset) {
574 // Increment the revision counter.
575 $langrev = get_config('core', 'langrev');
577 if ($langrev !== false and $next <= $langrev and $langrev - $next < 60*60) {
578 // This resolves problems when reset is requested repeatedly within 1s,
579 // the < 1h condition prevents accidental switching to future dates
580 // because we might not recover from it.
583 set_config('langrev', $next);
586 // Clear the cache containing the list of available translations
587 // and re-populate it again.
588 fulldelete($this->menucache);
589 $this->get_list_of_translations(true);
591 // Lang packs use PHP files in dataroot, it is better to invalidate opcode caches.
592 if (function_exists('opcache_reset')) {
598 * Returns string revision counter, this is incremented after any string cache reset.
599 * @return int lang string revision counter, -1 if unknown
601 public function get_revision() {
603 if (isset($CFG->langrev)) {
604 return (int)$CFG->langrev;
610 // End of external API.
613 * Helper method that recursively loads all parents of the given language.
615 * @see self::get_language_dependencies()
616 * @param string $lang language code
617 * @param array $stack list of parent languages already populated in previous recursive calls
618 * @return array list of all parents of the given language with the $lang itself added as the last element
620 protected function populate_parent_languages($lang, array $stack = array()) {
622 // English does not have a parent language.
623 if ($lang === 'en') {
627 // Prevent circular dependency (and thence the infinitive recursion loop).
628 if (in_array($lang, $stack)) {
632 // Load language configuration and look for the explicit parent language.
633 if (!file_exists("$this->otherroot/$lang/langconfig.php")) {
637 include("$this->otherroot/$lang/langconfig.php");
639 if (empty($string['parentlanguage']) or $string['parentlanguage'] === 'en') {
641 return array_merge(array($lang), $stack);
644 $parentlang = $string['parentlanguage'];
646 return $this->populate_parent_languages($parentlang, array_merge(array($lang), $stack));