MDL-41019 improve language caching
[moodle.git] / lib / classes / string_manager_standard.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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.
13 //
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/>.
17 /**
18  * Standard string manager.
19  *
20  * @package    core
21  * @copyright  2010 Petr Skoda {@link http://skodak.org}
22  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 defined('MOODLE_INTERNAL') || die();
28 /**
29  * Standard string_manager implementation
30  *
31  * Implements string_manager with getting and printing localised strings
32  *
33  * @package    core
34  * @copyright  2010 Petr Skoda {@link http://skodak.org}
35  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 class core_string_manager_standard implements core_string_manager {
38     /** @var string location of all packs except 'en' */
39     protected $otherroot;
40     /** @var string location of all lang pack local modifications */
41     protected $localroot;
42     /** @var cache lang string cache - it will be optimised more later */
43     protected $cache;
44     /** @var int get_string() counter */
45     protected $countgetstring = 0;
46     /** @var bool use disk cache */
47     protected $translist;
48     /** @var cache stores list of available translations */
49     protected $menucache;
51     /**
52      * Create new instance of string manager
53      *
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
57      */
58     public function __construct($otherroot, $localroot, $translist) {
59         $this->otherroot    = $otherroot;
60         $this->localroot    = $localroot;
61         if ($translist) {
62             $this->translist = array_combine($translist, $translist);
63         } else {
64             $this->translist = array();
65         }
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');
71         } else {
72             // We only want a cache for the length of the request, create a static cache.
73             $options = array(
74                 'simplekeys' => true,
75                 'simpledata' => true
76             );
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);
79         }
80     }
82     /**
83      * Returns list of all explicit parent languages for the given language.
84      *
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.
88      *
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
92      */
93     public function get_language_dependencies($lang) {
94         return $this->populate_parent_languages($lang);
95     }
97     /**
98      * Load all strings for one component
99      *
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
105      */
106     public function load_component_strings($component, $lang, $disablecache = false, $disablelocal = false) {
107         global $CFG;
109         list($plugintype, $pluginname) = core_component::normalize_component($component);
110         if ($plugintype === 'core' and is_null($pluginname)) {
111             $component = 'core';
112         } else {
113             $component = $plugintype . '_' . $pluginname;
114         }
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;
122             }
123         }
125         // No cache found - let us merge all possible sources of the strings.
126         if ($plugintype === 'core') {
127             $file = $pluginname;
128             if ($file === null) {
129                 $file = 'moodle';
130             }
131             $string = array();
132             // First load english pack.
133             if (!file_exists("$CFG->dirroot/lang/en/$file.php")) {
134                 return array();
135             }
136             include("$CFG->dirroot/lang/en/$file.php");
137             $enstring = $string;
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");
142             }
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");
149                 }
150                 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
151                     include("$this->localroot/{$dep}_local/$file.php");
152                 }
153             }
155         } else {
156             if (!$location = core_component::get_plugin_directory($plugintype, $pluginname) or !is_dir($location)) {
157                 return array();
158             }
159             if ($plugintype === 'mod') {
160                 // Bloody mod hack.
161                 $file = $pluginname;
162             } else {
163                 $file = $plugintype . '_' . $pluginname;
164             }
165             $string = array();
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.
169                 return array();
170             }
171             include("$location/lang/en/$file.php");
172             $enstring = $string;
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");
176             }
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");
184                 }
185                 // The main lang string location.
186                 if (file_exists("$this->otherroot/$dep/$file.php")) {
187                     include("$this->otherroot/$dep/$file.php");
188                 }
189                 // Local customisations.
190                 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
191                     include("$this->localroot/{$dep}_local/$file.php");
192                 }
193             }
194         }
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);
204             }
205         }
206         return $string;
207     }
209     /**
210      * Does the string actually exist?
211      *
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!
215      *
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
219      */
220     public function string_exists($identifier, $component) {
221         $lang = current_language();
222         $string = $this->load_component_strings($component, $lang);
223         return isset($string[$identifier]);
224     }
226     /**
227      * Get String returns a requested string
228      *
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 !
235      */
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(
241             'strftimedate' => 1,
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';
258             } else {
259                 $component = 'moodle';
260             }
261         }
263         if ($lang === null) {
264             $lang = current_language();
265         }
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.
272                 return '';
273             }
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.
276                 return 'en';
277             }
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";
288                     } else {
289                         $path = core_component::get_plugin_directory($plugintype, $pluginname);
290                         $file = "{$path}/lang/en/{$plugintype}_{$pluginname}.php";
291                     }
292                     debugging("Invalid get_string() identifier: '{$identifier}' or component '{$component}'. " .
293                     "Perhaps you are missing \$string['{$identifier}'] = ''; in {$file}?", DEBUG_DEVELOPER);
294                 }
295                 return "[[$identifier]]";
296             }
297         }
299         $string = $string[$identifier];
301         if ($a !== null) {
302             // Process array's and objects (except lang_strings).
303             if (is_array($a) or (is_object($a) && !($a instanceof lang_string))) {
304                 $a = (array)$a;
305                 $search = array();
306                 $replace = array();
307                 foreach ($a as $key => $value) {
308                     if (is_int($key)) {
309                         // We do not support numeric keys - sorry!
310                         continue;
311                     }
312                     if (is_array($value) or (is_object($value) && !($value instanceof lang_string))) {
313                         // We support just string or lang_string as value.
314                         continue;
315                     }
316                     $search[]  = '{$a->'.$key.'}';
317                     $replace[] = (string)$value;
318                 }
319                 if ($search) {
320                     $string = str_replace($search, $replace, $string);
321                 }
322             } else {
323                 $string = str_replace('{$a}', (string)$a, $string);
324             }
325         }
327         return $string;
328     }
330     /**
331      * Returns information about the core_string_manager performance.
332      *
333      * @return array
334      */
335     public function get_performance_summary() {
336         return array(array(
337             'langcountgetstring' => $this->countgetstring,
338         ), array(
339             'langcountgetstring' => 'get_string calls',
340         ));
341     }
343     /**
344      * Returns a localised list of all country names, sorted by localised name.
345      *
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.
349      */
350     public function get_list_of_countries($returnall = false, $lang = null) {
351         global $CFG;
353         if ($lang === null) {
354             $lang = current_language();
355         }
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);
361             $return = array();
362             foreach ($enabled as $c) {
363                 if (isset($countries[$c])) {
364                     $return[$c] = $countries[$c];
365                 }
366             }
367             return $return;
368         }
370         return $countries;
371     }
373     /**
374      * Returns a localised list of languages, sorted by code keys.
375      *
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
381      */
382     public function get_list_of_languages($lang = null, $standard = 'iso6391') {
383         if ($lang === null) {
384             $lang = current_language();
385         }
387         if ($standard === 'iso6392') {
388             $langs = $this->load_component_strings('core_iso6392', $lang);
389             ksort($langs);
390             return $langs;
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');
411             $langs1 = array();
412             foreach ($mapping as $c2 => $c1) {
413                 $langs1[$c1] = $langs2[$c2];
414             }
415             ksort($langs1);
416             return $langs1;
418         } else {
419             debugging('Unsupported $standard parameter in get_list_of_languages() method: '.$standard);
420         }
422         return array();
423     }
425     /**
426      * Checks if the translation exists for the language
427      *
428      * @param string $lang moodle translation language code
429      * @param bool $includeall include also disabled translations
430      * @return bool true if exists
431      */
432     public function translation_exists($lang, $includeall = true) {
433         $translations = $this->get_list_of_translations($includeall);
434         return isset($translations[$lang]);
435     }
437     /**
438      * Returns localised list of installed translations
439      *
440      * @param bool $returnall return all or just enabled
441      * @return array moodle translation code => localised translation name
442      */
443     public function get_list_of_translations($returnall = false) {
444         global $CFG;
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)) {
453                 return $cachedlist;
454             }
455             // Return only enabled translations.
456             foreach ($cachedlist as $langcode => $langname) {
457                 if (isset($this->translist[$langcode])) {
458                     $languages[$langcode] = $langname;
459                 }
460             }
461             return $languages;
462         }
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.
472                 continue;
473             }
474             if (strrpos($lang, '_utf8') !== false) {
475                 // Legacy 1.x lang pack.
476                 continue;
477             }
478             if ($lang !== clean_param($lang, PARAM_SAFEDIR)) {
479                 // Invalid lang pack name!
480                 continue;
481             }
482             $string = $this->load_component_strings('langconfig', $lang);
483             if (!empty($string['thislanguage'])) {
484                 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
485             }
486         }
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)) {
494             return $languages;
495         }
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;
504             }
505         }
507         return $languages;
508     }
510     /**
511      * Returns localised list of currencies.
512      *
513      * @param string $lang moodle translation language, null means use current
514      * @return array currency code => localised currency name
515      */
516     public function get_list_of_currencies($lang = null) {
517         if ($lang === null) {
518             $lang = current_language();
519         }
521         $currencies = $this->load_component_strings('core_currencies', $lang);
522         asort($currencies);
524         return $currencies;
525     }
527     /**
528      * Clears both in-memory and on-disk caches
529      * @param bool $phpunitreset true means called from our PHPUnit integration test reset
530      */
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');
539             $next = time();
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.
544                 $next = $langrev+1;
545             }
546             set_config('langrev', $next);
547         }
549         // Lang packs use PHP files in dataroot, it is better to invalidate opcode caches.
550         if (function_exists('opcache_reset')) {
551             opcache_reset();
552         }
553     }
555     /**
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.
559      * @return string
560      */
561     protected function get_key_suffix() {
562         $rev = $this->get_revision();
563         if ($rev < 0) {
564             // Simple keys do not like minus char.
565             $rev = 0;
566         }
568         return $rev;
569     }
571     /**
572      * Returns string revision counter, this is incremented after any string cache reset.
573      * @return int lang string revision counter, -1 if unknown
574      */
575     public function get_revision() {
576         global $CFG;
577         if (empty($CFG->langstringcache)) {
578             return -1;
579         }
580         if (isset($CFG->langrev)) {
581             return (int)$CFG->langrev;
582         } else {
583             return -1;
584         }
585     }
587     /**
588      * Helper method that recursively loads all parents of the given language.
589      *
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
594      */
595     protected function populate_parent_languages($lang, array $stack = array()) {
597         // English does not have a parent language.
598         if ($lang === 'en') {
599             return $stack;
600         }
602         // Prevent circular dependency (and thence the infinitive recursion loop).
603         if (in_array($lang, $stack)) {
604             return $stack;
605         }
607         // Load language configuration and look for the explicit parent language.
608         if (!file_exists("$this->otherroot/$lang/langconfig.php")) {
609             return $stack;
610         }
611         $string = array();
612         include("$this->otherroot/$lang/langconfig.php");
614         if (empty($string['parentlanguage']) or $string['parentlanguage'] === 'en') {
615             return array_merge(array($lang), $stack);
617         }
619         $parentlang = $string['parentlanguage'];
620         return $this->populate_parent_languages($parentlang, array_merge(array($lang), $stack));
621     }