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 cache stores list of available translations */
52
* Create new instance of string manager
54
* @param string $otherroot location of downloaded lang packs - usually $CFG->dataroot/lang
55
* @param string $localroot usually the same as $otherroot
56
* @param array $translist limit list of visible translations
58
public function __construct($otherroot, $localroot, $translist) {
59
$this->otherroot = $otherroot;
60
$this->localroot = $localroot;
62
$this->translist = array_combine($translist, $translist);
64
$this->translist = array();
67
if ($this->get_revision() > 0) {
68
// We can use a proper cache, establish the cache using the 'String cache' definition.
69
$this->cache = cache::make('core', 'string');
70
$this->menucache = cache::make('core', 'langmenu');
72
// We only want a cache for the length of the request, create a static cache.
77
$this->cache = cache::make_from_params(cache_store::MODE_REQUEST, 'core', 'string', array(), $options);
78
$this->menucache = cache::make_from_params(cache_store::MODE_REQUEST, 'core', 'langmenu', 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.'_'.$this->get_key_suffix();
118
$cachedstring = $this->cache->get($cachekey);
119
if (!$disablecache and !$disablelocal) {
120
if ($cachedstring !== false) {
121
return $cachedstring;
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");
139
// And then corresponding local if present and allowed.
140
if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
141
include("$this->localroot/en_local/$file.php");
143
// Now loop through all langs in correct order.
144
$deps = $this->get_language_dependencies($lang);
145
foreach ($deps as $dep) {
146
// The main lang string location.
147
if (file_exists("$this->otherroot/$dep/$file.php")) {
148
include("$this->otherroot/$dep/$file.php");
150
if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
151
include("$this->localroot/{$dep}_local/$file.php");
156
if (!$location = core_component::get_plugin_directory($plugintype, $pluginname) or !is_dir($location)) {
159
if ($plugintype === 'mod') {
163
$file = $plugintype . '_' . $pluginname;
166
// First load English pack.
167
if (!file_exists("$location/lang/en/$file.php")) {
168
// English pack does not exist, so do not try to load anything else.
171
include("$location/lang/en/$file.php");
173
// And then corresponding local english if present.
174
if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
175
include("$this->localroot/en_local/$file.php");
178
// Now loop through all langs in correct order.
179
$deps = $this->get_language_dependencies($lang);
180
foreach ($deps as $dep) {
181
// Legacy location - used by contrib only.
182
if (file_exists("$location/lang/$dep/$file.php")) {
183
include("$location/lang/$dep/$file.php");
185
// The main lang string location.
186
if (file_exists("$this->otherroot/$dep/$file.php")) {
187
include("$this->otherroot/$dep/$file.php");
189
// Local customisations.
190
if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
191
include("$this->localroot/{$dep}_local/$file.php");
196
// We do not want any extra strings from other languages - everything must be in en lang pack.
197
$string = array_intersect_key($string, $enstring);
199
if (!$disablelocal) {
200
// Now we have a list of strings from all possible sources,
201
// cache it in MUC cache if not already there.
202
if ($cachedstring === false) {
203
$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 formatting 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
// Do not rebuild caches here!
279
// Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
280
if (!isset($string[$identifier])) {
281
// The string is still missing - should be fixed by developer.
282
if (debugging('', DEBUG_DEVELOPER)) {
283
list($plugintype, $pluginname) = core_component::normalize_component($component);
284
if ($plugintype === 'core') {
285
$file = "lang/en/{$component}.php";
286
} else if ($plugintype == 'mod') {
287
$file = "mod/{$pluginname}/lang/en/{$pluginname}.php";
289
$path = core_component::get_plugin_directory($plugintype, $pluginname);
290
$file = "{$path}/lang/en/{$plugintype}_{$pluginname}.php";
292
debugging("Invalid get_string() identifier: '{$identifier}' or component '{$component}'. " .
293
"Perhaps you are missing \$string['{$identifier}'] = ''; in {$file}?", DEBUG_DEVELOPER);
295
return "[[$identifier]]";
299
$string = $string[$identifier];
302
// Process array's and objects (except lang_strings).
303
if (is_array($a) or (is_object($a) && !($a instanceof lang_string))) {
307
foreach ($a as $key => $value) {
309
// We do not support numeric keys - sorry!
312
if (is_array($value) or (is_object($value) && !($value instanceof lang_string))) {
313
// We support just string or lang_string as value.
316
$search[] = '{$a->'.$key.'}';
317
$replace[] = (string)$value;
320
$string = str_replace($search, $replace, $string);
323
$string = str_replace('{$a}', (string)$a, $string);
331
* Returns information about the core_string_manager performance.
335
public function get_performance_summary() {
337
'langcountgetstring' => $this->countgetstring,
339
'langcountgetstring' => 'get_string calls',
344
* Returns a localised list of all country names, sorted by localised name.
346
* @param bool $returnall return all or just enabled
347
* @param string $lang moodle translation language, null means use current
348
* @return array two-letter country code => translated name.
350
public function get_list_of_countries($returnall = false, $lang = null) {
353
if ($lang === null) {
354
$lang = current_language();
357
$countries = $this->load_component_strings('core_countries', $lang);
358
core_collator::asort($countries);
359
if (!$returnall and !empty($CFG->allcountrycodes)) {
360
$enabled = explode(',', $CFG->allcountrycodes);
362
foreach ($enabled as $c) {
363
if (isset($countries[$c])) {
364
$return[$c] = $countries[$c];
374
* Returns a localised list of languages, sorted by code keys.
376
* @param string $lang moodle translation language, null means use current
377
* @param string $standard language list standard
378
* - iso6392: three-letter language code (ISO 639-2/T) => translated name
379
* - iso6391: two-letter language code (ISO 639-1) => translated name
380
* @return array language code => translated name
382
public function get_list_of_languages($lang = null, $standard = 'iso6391') {
383
if ($lang === null) {
384
$lang = current_language();
387
if ($standard === 'iso6392') {
388
$langs = $this->load_component_strings('core_iso6392', $lang);
392
} else if ($standard === 'iso6391') {
393
$langs2 = $this->load_component_strings('core_iso6392', $lang);
394
static $mapping = array('aar' => 'aa', 'abk' => 'ab', 'afr' => 'af', 'aka' => 'ak', 'sqi' => 'sq', 'amh' => 'am', 'ara' => 'ar', 'arg' => 'an', 'hye' => 'hy',
395
'asm' => 'as', 'ava' => 'av', 'ave' => 'ae', 'aym' => 'ay', 'aze' => 'az', 'bak' => 'ba', 'bam' => 'bm', 'eus' => 'eu', 'bel' => 'be', 'ben' => 'bn', 'bih' => 'bh',
396
'bis' => 'bi', 'bos' => 'bs', 'bre' => 'br', 'bul' => 'bg', 'mya' => 'my', 'cat' => 'ca', 'cha' => 'ch', 'che' => 'ce', 'zho' => 'zh', 'chu' => 'cu', 'chv' => 'cv',
397
'cor' => 'kw', 'cos' => 'co', 'cre' => 'cr', 'ces' => 'cs', 'dan' => 'da', 'div' => 'dv', 'nld' => 'nl', 'dzo' => 'dz', 'eng' => 'en', 'epo' => 'eo', 'est' => 'et',
398
'ewe' => 'ee', 'fao' => 'fo', 'fij' => 'fj', 'fin' => 'fi', 'fra' => 'fr', 'fry' => 'fy', 'ful' => 'ff', 'kat' => 'ka', 'deu' => 'de', 'gla' => 'gd', 'gle' => 'ga',
399
'glg' => 'gl', 'glv' => 'gv', 'ell' => 'el', 'grn' => 'gn', 'guj' => 'gu', 'hat' => 'ht', 'hau' => 'ha', 'heb' => 'he', 'her' => 'hz', 'hin' => 'hi', 'hmo' => 'ho',
400
'hrv' => 'hr', 'hun' => 'hu', 'ibo' => 'ig', 'isl' => 'is', 'ido' => 'io', 'iii' => 'ii', 'iku' => 'iu', 'ile' => 'ie', 'ina' => 'ia', 'ind' => 'id', 'ipk' => 'ik',
401
'ita' => 'it', 'jav' => 'jv', 'jpn' => 'ja', 'kal' => 'kl', 'kan' => 'kn', 'kas' => 'ks', 'kau' => 'kr', 'kaz' => 'kk', 'khm' => 'km', 'kik' => 'ki', 'kin' => 'rw',
402
'kir' => 'ky', 'kom' => 'kv', 'kon' => 'kg', 'kor' => 'ko', 'kua' => 'kj', 'kur' => 'ku', 'lao' => 'lo', 'lat' => 'la', 'lav' => 'lv', 'lim' => 'li', 'lin' => 'ln',
403
'lit' => 'lt', 'ltz' => 'lb', 'lub' => 'lu', 'lug' => 'lg', 'mkd' => 'mk', 'mah' => 'mh', 'mal' => 'ml', 'mri' => 'mi', 'mar' => 'mr', 'msa' => 'ms', 'mlg' => 'mg',
404
'mlt' => 'mt', 'mon' => 'mn', 'nau' => 'na', 'nav' => 'nv', 'nbl' => 'nr', 'nde' => 'nd', 'ndo' => 'ng', 'nep' => 'ne', 'nno' => 'nn', 'nob' => 'nb', 'nor' => 'no',
405
'nya' => 'ny', 'oci' => 'oc', 'oji' => 'oj', 'ori' => 'or', 'orm' => 'om', 'oss' => 'os', 'pan' => 'pa', 'fas' => 'fa', 'pli' => 'pi', 'pol' => 'pl', 'por' => 'pt',
406
'pus' => 'ps', 'que' => 'qu', 'roh' => 'rm', 'ron' => 'ro', 'run' => 'rn', 'rus' => 'ru', 'sag' => 'sg', 'san' => 'sa', 'sin' => 'si', 'slk' => 'sk', 'slv' => 'sl',
407
'sme' => 'se', 'smo' => 'sm', 'sna' => 'sn', 'snd' => 'sd', 'som' => 'so', 'sot' => 'st', 'spa' => 'es', 'srd' => 'sc', 'srp' => 'sr', 'ssw' => 'ss', 'sun' => 'su',
408
'swa' => 'sw', 'swe' => 'sv', 'tah' => 'ty', 'tam' => 'ta', 'tat' => 'tt', 'tel' => 'te', 'tgk' => 'tg', 'tgl' => 'tl', 'tha' => 'th', 'bod' => 'bo', 'tir' => 'ti',
409
'ton' => 'to', 'tsn' => 'tn', 'tso' => 'ts', 'tuk' => 'tk', 'tur' => 'tr', 'twi' => 'tw', 'uig' => 'ug', 'ukr' => 'uk', 'urd' => 'ur', 'uzb' => 'uz', 'ven' => 've',
410
'vie' => 'vi', 'vol' => 'vo', 'cym' => 'cy', 'wln' => 'wa', 'wol' => 'wo', 'xho' => 'xh', 'yid' => 'yi', 'yor' => 'yo', 'zha' => 'za', 'zul' => 'zu');
412
foreach ($mapping as $c2 => $c1) {
413
$langs1[$c1] = $langs2[$c2];
419
debugging('Unsupported $standard parameter in get_list_of_languages() method: '.$standard);
426
* Checks if the translation exists for the language
428
* @param string $lang moodle translation language code
429
* @param bool $includeall include also disabled translations
430
* @return bool true if exists
432
public function translation_exists($lang, $includeall = true) {
433
$translations = $this->get_list_of_translations($includeall);
434
return isset($translations[$lang]);
438
* Returns localised list of installed translations
440
* @param bool $returnall return all or just enabled
441
* @return array moodle translation code => localised translation name
443
public function get_list_of_translations($returnall = false) {
446
$languages = array();
448
$cachekey = 'list_'.$this->get_key_suffix();
449
$cachedlist = $this->menucache->get($cachekey);
450
if ($cachedlist !== false) {
451
// The cache content is invalid.
452
if ($returnall or empty($this->translist)) {
455
// Return only enabled translations.
456
foreach ($cachedlist as $langcode => $langname) {
457
if (isset($this->translist[$langcode])) {
458
$languages[$langcode] = $langname;
464
// Get all languages available in system.
465
$langdirs = get_list_of_plugins('', 'en', $this->otherroot);
466
$langdirs["$CFG->dirroot/lang/en"] = 'en';
468
// Loop through all langs and get info.
469
foreach ($langdirs as $lang) {
470
if (strrpos($lang, '_local') !== false) {
471
// Just a local tweak of some other lang pack.
474
if (strrpos($lang, '_utf8') !== false) {
475
// Legacy 1.x lang pack.
478
if ($lang !== clean_param($lang, PARAM_SAFEDIR)) {
479
// Invalid lang pack name!
482
$string = $this->load_component_strings('langconfig', $lang);
483
if (!empty($string['thislanguage'])) {
484
$languages[$lang] = $string['thislanguage'].' ('. $lang .')';
488
core_collator::asort($languages);
490
// Cache the list so that it can be used next time.
491
$this->menucache->set($cachekey, $languages);
493
if ($returnall or empty($this->translist)) {
497
$cachedlist = $languages;
499
// Return only enabled translations.
500
$languages = array();
501
foreach ($cachedlist as $langcode => $langname) {
502
if (isset($this->translist[$langcode])) {
503
$languages[$langcode] = $langname;
511
* Returns localised list of currencies.
513
* @param string $lang moodle translation language, null means use current
514
* @return array currency code => localised currency name
516
public function get_list_of_currencies($lang = null) {
517
if ($lang === null) {
518
$lang = current_language();
521
$currencies = $this->load_component_strings('core_currencies', $lang);
528
* Clears both in-memory and on-disk caches
529
* @param bool $phpunitreset true means called from our PHPUnit integration test reset
531
public function reset_caches($phpunitreset = false) {
532
// Clear the on-disk disk with aggregated string files.
533
$this->cache->purge();
534
$this->menucache->purge();
536
if (!$phpunitreset) {
537
// Increment the revision counter.
538
$langrev = get_config('core', 'langrev');
540
if ($langrev !== false and $next <= $langrev and $langrev - $next < 60*60) {
541
// This resolves problems when reset is requested repeatedly within 1s,
542
// the < 1h condition prevents accidental switching to future dates
543
// because we might not recover from it.
546
set_config('langrev', $next);
549
// Lang packs use PHP files in dataroot, it is better to invalidate opcode caches.
550
if (function_exists('opcache_reset')) {
556
* Returns cache key suffix, this enables us to store string + lang menu
557
* caches in local caches on cluster nodes. We can not use prefix because
558
* it would cause problems when creating subdirs in cache file store.
561
protected function get_key_suffix() {
562
$rev = $this->get_revision();
564
// Simple keys do not like minus char.
572
* Returns string revision counter, this is incremented after any string cache reset.
573
* @return int lang string revision counter, -1 if unknown
575
public function get_revision() {
577
if (empty($CFG->langstringcache)) {
580
if (isset($CFG->langrev)) {
581
return (int)$CFG->langrev;
588
* Helper method that recursively loads all parents of the given language.
590
* @see self::get_language_dependencies()
591
* @param string $lang language code
592
* @param array $stack list of parent languages already populated in previous recursive calls
593
* @return array list of all parents of the given language with the $lang itself added as the last element
595
protected function populate_parent_languages($lang, array $stack = array()) {
597
// English does not have a parent language.
598
if ($lang === 'en') {
602
// Prevent circular dependency (and thence the infinitive recursion loop).
603
if (in_array($lang, $stack)) {
607
// Load language configuration and look for the explicit parent language.
608
if (!file_exists("$this->otherroot/$lang/langconfig.php")) {
612
include("$this->otherroot/$lang/langconfig.php");
614
if (empty($string['parentlanguage']) or $string['parentlanguage'] === 'en') {
615
return array_merge(array($lang), $stack);
619
$parentlang = $string['parentlanguage'];
620
return $this->populate_parent_languages($parentlang, array_merge(array($lang), $stack));