Passed
Push — master ( 65bdac...4e88da )
by Alxarafe
32:38
created

Langs::load()   F

Complexity

Conditions 57
Paths > 20000

Size

Total Lines 201
Code Lines 101

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 57
eloc 101
nc 25372838
nop 5
dl 0
loc 201
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2018       Alxarafe            <[email protected]>
3
 *
4
 * This program 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
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
16
 */
17
namespace Alixar\Base;
18
19
use Alixar\Helpers\DolUtils;
20
21
class Langs
22
{
23
24
    public $dir;                          // Directories that contains /langs subdirectory
25
    public $defaultlang;                  // Current language for current user
26
    public $charset_output = 'UTF-8';       // Codage used by "trans" method outputs
27
    public $tab_translate = array();        // Array of all translations key=>value
28
    private $_tab_loaded = array();         // Array to store result after loading each language file
29
    public $cache_labels = array();         // Cache for labels return by getLabelFromKey method
30
    public $cache_currencies = array();     // Cache to store currency symbols
31
    private $cache_currencies_all_loaded = false;
32
33
    /**
34
     * 	Constructor
35
     */
36
    function __construct()
37
    {
38
        $dir = DOL_BASE_PATH;
39
        if (!empty($conf->file->character_set_client))
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $conf seems to be never defined.
Loading history...
40
            $this->charset_output = $conf->file->character_set_client; // If charset output is forced
41
        if ($dir)
42
            $this->dir = array($dir);
43
        else
44
            $this->dir = $conf->file->dol_document_root;
45
    }
46
47
    /**
48
     *  Set accessor for this->defaultlang
49
     *
50
     *  @param	string	$srclang     	Language to use. If '' or 'auto', we use browser lang.
51
     *  @return	void
52
     */
53
    function setDefaultLang($srclang = 'en_US')
54
    {
55
        global $conf;
56
57
        //DolUtils::dol_syslog(get_class($this)."::setDefaultLang srclang=".$srclang,LOG_DEBUG);
58
        // If a module ask to force a priority on langs directories (to use its own lang files)
59
        if (!empty($conf->global->MAIN_FORCELANGDIR)) {
60
            $more = array();
61
            $i = 0;
62
            foreach ($conf->file->dol_document_root as $dir) {
63
                $newdir = $dir . $conf->global->MAIN_FORCELANGDIR;    // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
64
                if (!in_array($newdir, $this->dir)) {
65
                    $more['module_' . $i] = $newdir;
66
                    $i++;   // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
67
                }
68
            }
69
            $this->dir = array_merge($more, $this->dir);    // Forced dir ($more) are before standard dirs ($this->dir)
70
        }
71
72
        $this->origlang = $srclang;
73
74
        if (empty($srclang) || $srclang == 'auto') {
75
            $langpref = empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? '' : $_SERVER['HTTP_ACCEPT_LANGUAGE'];
76
            $langpref = preg_replace("/;([^,]*)/i", "", $langpref);
77
            $langpref = str_replace("-", "_", $langpref);
78
            $langlist = preg_split("/[;,]/", $langpref);
79
            $codetouse = $langlist[0];
80
        } else
81
            $codetouse = $srclang;
82
83
        // We redefine $srclang
84
        $langpart = explode("_", $codetouse);
85
        //print "Short code before _ : ".$langpart[0].' / Short code after _ : '.$langpart[1].'<br>';
86
        if (!empty($langpart[1])) { // If it's for a codetouse that is a long code xx_YY
87
            // Array force long code from first part, even if long code is defined
88
            $longforshort = array('ar' => 'ar_SA');
89
            $longforshortexcep = array('ar_EG');
90
            if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep))
91
                $srclang = $longforshort[strtolower($langpart[0])];
92
            else if (!is_numeric($langpart[1])) {  // Second part YY may be a numeric with some Chrome browser
93
                $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[1]);
94
                $longforlong = array('no_nb' => 'nb_NO');
95
                if (isset($longforlong[strtolower($srclang)]))
96
                    $srclang = $longforlong[strtolower($srclang)];
97
            } else
98
                $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
99
        }
100
        else {      // If it's for a codetouse that is a short code xx
101
            // Array to convert short lang code into long code.
102
            $longforshort = array('ar' => 'ar_SA', 'el' => 'el_GR', 'ca' => 'ca_ES', 'en' => 'en_US', 'nb' => 'nb_NO', 'no' => 'nb_NO');
103
            if (isset($longforshort[strtolower($langpart[0])]))
104
                $srclang = $longforshort[strtolower($langpart[0])];
105
            else if (!empty($langpart[0]))
106
                $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
107
            else
108
                $srclang = 'en_US';
109
        }
110
111
        $this->defaultlang = $srclang;
112
        //print 'this->defaultlang='.$this->defaultlang;
113
    }
114
115
    /**
116
     *  Return active language code for current user
117
     * 	It's an accessor for this->defaultlang
118
     *
119
     *  @param	int		$mode       0=Long language code, 1=Short language code (en, fr, es, ...)
120
     *  @return string      		Language code used (en_US, en_AU, fr_FR, ...)
121
     */
122
    function getDefaultLang($mode = 0)
123
    {
124
        if (empty($mode))
125
            return $this->defaultlang;
126
        else
127
            return substr($this->defaultlang, 0, 2);
128
    }
129
130
    /**
131
     *  Load translation files.
132
     *
133
     *  @param	array	$domains      		Array of lang files to load
134
     * 	@return	int							<0 if KO, 0 if already loaded or loading not required, >0 if OK
135
     */
136
    function loadLangs($domains)
137
    {
138
        foreach ($domains as $domain) {
139
            $this->load($domain);
140
        }
141
    }
142
143
    /**
144
     *  Load translation key-value for a particular file, into a memory array.
145
     *  If data for file already loaded, do nothing.
146
     * 	All data in translation array are stored in UTF-8 format.
147
     *  tab_loaded is completed with $domain key.
148
     *  rule "we keep first entry found with we keep last entry found" so it is probably not what you want to do.
149
     *
150
     *  Value for hash are: 1:Loaded from disk, 2:Not found, 3:Loaded from cache
151
     *
152
     *  @param	string	$domain      		File name to load (.lang file). Must be "file" or "[email protected]" for module language files:
153
     * 										If $domain is "[email protected]" instead of "file" then we look for module lang file
154
     * 										in htdocs/custom/modules/mymodule/langs/code_CODE/file.lang
155
     * 										then in htdocs/module/langs/code_CODE/file.lang instead of htdocs/langs/code_CODE/file.lang
156
     *  @param	integer	$alt         		0 (try xx_ZZ then 1), 1 (try xx_XX then 2), 2 (try en_US)
157
     * 	@param	int		$stopafterdirection	Stop when the DIRECTION tag is found (optimize speed)
158
     * 	@param	int		$forcelangdir		To force a different lang directory
159
     *  @param  int     $loadfromfileonly   1=Do not load overwritten translation from file or old conf.
160
     * 	@return	int							<0 if KO, 0 if already loaded or loading not required, >0 if OK
161
     *  @see loadLangs
162
     */
163
    function load($domain, $alt = 0, $stopafterdirection = 0, $forcelangdir = '', $loadfromfileonly = 0)
164
    {
165
        global $conf, $db;
166
167
        //DolUtils::dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
168
        // Check parameters
169
        if (empty($domain)) {
170
            dol_print_error('', get_class($this) . "::Load ErrorWrongParameters");
171
            return -1;
172
        }
173
        if ($this->defaultlang == 'none_NONE')
174
            return 0;    // Special language code to not translate keys
175
176
177
178
179
180
            
181
// Load $this->tab_translate[] from database
182
        if (empty($loadfromfileonly) && count($this->tab_translate) == 0)
183
            $this->loadFromDatabase($db);      // No translation was never loaded yet, so we load database.
184
185
186
        $newdomain = $domain;
187
        $modulename = '';
188
189
        // Search if a module directory name is provided into lang file name
190
        if (preg_match('/^([^@]+)@([^@]+)$/i', $domain, $regs)) {
191
            $newdomain = $regs[1];
192
            $modulename = $regs[2];
193
        }
194
195
        // Check cache
196
        if (!empty($this->_tab_loaded[$newdomain])) { // File already loaded for this domain
197
            //DolUtils::dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
198
            return 0;
199
        }
200
201
        $fileread = 0;
202
        $langofdir = (empty($forcelangdir) ? $this->defaultlang : $forcelangdir);
203
204
        // Redefine alt
205
        $langarray = explode('_', $langofdir);
206
        if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr'))))
207
            $alt = 1;
208
        if ($alt < 2 && strtolower($langofdir) == 'en_us')
209
            $alt = 2;
210
211
        if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
212
            DolUtils::dol_syslog("Error: " . get_class($this) . "::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
213
            return -1;
214
        }
215
216
        foreach ($this->dir as $keydir => $searchdir) {
217
            // Directory of translation files
218
            $file_lang = $searchdir . ($modulename ? '/' . $modulename : '') . "/langs/" . $langofdir . "/" . $newdomain . ".lang";
219
            $file_lang_osencoded = dol_osencode($file_lang);
220
221
            $filelangexists = is_file($file_lang_osencoded);
222
223
            //DolUtils::dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' domain='.$domain.' newdomain='.$newdomain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists);
224
            //print 'Try to read for alt='.$alt.' langofdir='.$langofdir.' domain='.$domain.' newdomain='.$newdomain.' modulename='.$modulename.' this->_tab_loaded[newdomain]='.$this->_tab_loaded[$newdomain].' file_lang='.$file_lang." => filelangexists=".$filelangexists."\n";
225
226
            if ($filelangexists) {
227
                // TODO Move cache read out of loop on dirs or at least filelangexists
228
                $found = false;
229
230
                // Enable caching of lang file in memory (not by default)
231
                $usecachekey = '';
232
                // Using a memcached server
233
                if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER)) {
234
                    $usecachekey = $newdomain . '_' . $langofdir . '_' . md5($file_lang);    // Should not contains special chars
235
                }
236
                // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
237
                else if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
238
                    $usecachekey = $newdomain;
239
                }
240
241
                if ($usecachekey) {
242
                    //DolUtils::dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
243
                    //global $aaa; $aaa+=1;
244
                    //print $aaa." ".$usecachekey."\n";
245
                    require_once DOL_BASE_PATH . '/core/lib/memory.lib.php';
246
                    $tmparray = dol_getcache($usecachekey);
247
                    if (is_array($tmparray) && count($tmparray)) {
248
                        $this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a value already exists into tab_translate, value into tmparaay is not added.
249
                        //print $newdomain."\n";
250
                        //var_dump($this->tab_translate);
251
                        if ($alt == 2)
252
                            $fileread = 1;
253
                        $found = true;      // Found in dolibarr PHP cache
254
                    }
255
                }
256
257
                if (!$found) {
258
                    if ($fp = @fopen($file_lang, "rt")) {
259
                        if ($usecachekey)
260
                            $tabtranslatedomain = array(); // To save lang content in cache
261
262
                        /**
263
                         * Read each lines until a '=' (with any combination of spaces around it)
264
                         * and split the rest until a line feed.
265
                         * This is more efficient than fgets + explode + trim by a factor of ~2.
266
                         */
267
                        while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n]")) {
268
                            if (isset($line[1])) {
269
                                list($key, $value) = $line;
270
                                //if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."<br>";
271
                                //if ($key == 'Order') print "Domain=$domain, found a string for key=$key=$tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."<br>";
272
                                if (empty($this->tab_translate[$key])) { // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries)
273
                                    $value = preg_replace('/\\n/', "\n", $value); // Parse and render carriage returns
274
                                    if ($key == 'DIRECTION') { // This is to declare direction of language
275
                                        if ($alt < 2 || empty($this->tab_translate[$key])) { // We load direction only for primary files or if not yet loaded
276
                                            $this->tab_translate[$key] = $value;
277
                                            if ($stopafterdirection) {
278
                                                break; // We do not save tab if we stop after DIRECTION
279
                                            } elseif ($usecachekey) {
280
                                                $tabtranslatedomain[$key] = $value;
281
                                            }
282
                                        }
283
                                    } elseif ($key[0] == '#') {
284
                                        continue;
285
                                    } else {
286
                                        $this->tab_translate[$key] = $value;
287
                                        //if ($domain == 'orders') print "$tab[0] value $value<br>";
288
                                        if ($usecachekey) {
289
                                            $tabtranslatedomain[$key] = $value;
290
                                        } // To save lang content in cache
291
                                    }
292
                                }
293
                            }
294
                        }
295
                        fclose($fp);
296
                        $fileread = 1;
297
298
                        // TODO Move cache write out of loop on dirs
299
                        // To save lang content for usecachekey into cache
300
                        if ($usecachekey && count($tabtranslatedomain)) {
301
                            $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
302
                            if ($ressetcache < 0) {
303
                                $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
304
                                DolUtils::dol_syslog($error, LOG_ERR);
305
                            }
306
                        }
307
308
                        if (empty($conf->global->MAIN_FORCELANGDIR))
309
                            break;  // Break loop on each root dir. If a module has forced dir, we do not stop loop.
310
                    }
311
                }
312
            }
313
        }
314
315
        // Now we complete with next file (fr_CA->fr_FR, es_MX->ex_ES, ...)
316
        if ($alt == 0) {
317
            // This function MUST NOT contains call to syslog
318
            //DolUtils::dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
319
            $langofdir = strtolower($langarray[0]) . '_' . strtoupper($langarray[0]);
320
            if ($langofdir == 'el_EL')
321
                $langofdir = 'el_GR';                     // main parent for el_CY is not 'el_EL' but 'el_GR'
322
            if ($langofdir == 'ar_AR')
323
                $langofdir = 'ar_SA';                     // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
324
            $this->load($domain, $alt + 1, $stopafterdirection, $langofdir);
325
        }
326
327
        // Now we complete with reference file (en_US)
328
        if ($alt == 1) {
329
            // This function MUST NOT contains call to syslog
330
            //DolUtils::dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
331
            $langofdir = 'en_US';
332
            $this->load($domain, $alt + 1, $stopafterdirection, $langofdir);
333
        }
334
335
        // We are in the pass of the reference file. No more files to scan to complete.
336
        if ($alt == 2) {
337
            if ($fileread)
338
                $this->_tab_loaded[$newdomain] = 1;        // Set domain file as found so loaded
339
340
            if (empty($this->_tab_loaded[$newdomain]))
341
                $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
342
        }
343
344
        // This part is deprecated and replaced with table llx_overwrite_trans
345
        // Kept for backward compatibility.
346
        if (empty($loadfromfileonly)) {
347
            $overwritekey = 'MAIN_OVERWRITE_TRANS_' . $this->defaultlang;
348
            if (!empty($conf->global->$overwritekey)) {    // Overwrite translation with key1:newstring1,key2:newstring2
349
                // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
350
                $tmparray = explode(',', $conf->global->$overwritekey);
351
                foreach ($tmparray as $tmp) {
352
                    $tmparray2 = explode(':', $tmp);
353
                    if (!empty($tmparray2[1]))
354
                        $this->tab_translate[$tmparray2[0]] = $tmparray2[1];
355
                }
356
            }
357
        }
358
359
        // Check to be sure that SeparatorDecimal differs from SeparatorThousand
360
        if (!empty($this->tab_translate["SeparatorDecimal"]) && !empty($this->tab_translate["SeparatorThousand"]) && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"])
361
            $this->tab_translate["SeparatorThousand"] = '';
362
363
        return 1;
364
    }
365
366
    /**
367
     *  Load translation key-value from database into a memory array.
368
     *  If data already loaded, do nothing.
369
     * 	All data in translation array are stored in UTF-8 format.
370
     *  tab_loaded is completed with $domain key.
371
     *  rule "we keep first entry found with we keep last entry found" so it is probably not what you want to do.
372
     *
373
     *  Value for hash are: 1:Loaded from disk, 2:Not found, 3:Loaded from cache
374
     *
375
     *  @param  Database    $db             Database handler
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\Database was not found. Did you mean Database? If so, make sure to prefix the type with \.
Loading history...
376
     * 	@return	int							<0 if KO, 0 if already loaded or loading not required, >0 if OK
377
     */
378
    function loadFromDatabase($db)
379
    {
380
        global $conf;
381
382
        $domain = 'database';
383
384
        // Check parameters
385
        if (empty($db))
386
            return 0;    // Database handler can't be used
387
388
389
390
391
            
392
            
393
//DolUtils::dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
394
395
        $newdomain = $domain;
396
397
        // Check cache
398
        if (!empty($this->_tab_loaded[$newdomain])) { // File already loaded for this domain 'database'
399
            //DolUtils::dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
400
            return 0;
401
        }
402
403
        $this->_tab_loaded[$newdomain] = 1;   // We want to be sure this function is called once only for domain 'database'
404
405
        $fileread = 0;
406
        $langofdir = $this->defaultlang;
407
408
        if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
409
            DolUtils::dol_syslog("Error: " . get_class($this) . "::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
410
            return -1;
411
        }
412
413
        // TODO Move cache read out of loop on dirs or at least filelangexists
414
        $found = false;
415
416
        // Enable caching of lang file in memory (not by default)
417
        $usecachekey = '';
418
        // Using a memcached server
419
        if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER)) {
420
            $usecachekey = $newdomain . '_' . $langofdir;    // Should not contains special chars
421
        }
422
        // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
423
        else if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
424
            $usecachekey = $newdomain;
425
        }
426
427
        if ($usecachekey) {
428
            //DolUtils::dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
429
            //global $aaa; $aaa+=1;
430
            //print $aaa." ".$usecachekey."\n";
431
            require_once DOL_BASE_PATH . '/core/lib/memory.lib.php';
432
            $tmparray = dol_getcache($usecachekey);
433
            if (is_array($tmparray) && count($tmparray)) {
434
                $this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a valuer already exists into tab_translate, value into tmparaay is not added.
435
                //print $newdomain."\n";
436
                //var_dump($this->tab_translate);
437
                $fileread = 1;
438
                $found = true;      // Found in dolibarr PHP cache
439
            }
440
        }
441
442
        if (!$found && !empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) {
443
            // Overwrite translation with database read
444
            $sql = "SELECT transkey, transvalue FROM " . MAIN_DB_PREFIX . "overwrite_trans where lang='" . $db->escape($this->defaultlang) . "'";
445
            $resql = $db->query($sql);
446
447
            if ($resql) {
448
                $num = $db->num_rows($resql);
449
                if ($num) {
450
                    if ($usecachekey)
451
                        $tabtranslatedomain = array(); // To save lang content in cache
452
453
                    $i = 0;
454
                    while ($i < $num) { // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
455
                        $obj = $db->fetch_object($resql);
456
457
                        $key = $obj->transkey;
458
                        $value = $obj->transvalue;
459
460
                        //print "Domain=$domain, found a string for $tab[0] with value $tab[1]<br>";
461
                        if (empty($this->tab_translate[$key])) {    // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries)
462
                            $value = trim(preg_replace('/\\n/', "\n", $value));
463
464
                            $this->tab_translate[$key] = $value;
465
                            if ($usecachekey)
466
                                $tabtranslatedomain[$key] = $value; // To save lang content in cache
467
                        }
468
469
                        $i++;
470
                    }
471
472
                    $fileread = 1;
473
474
                    // TODO Move cache write out of loop on dirs
475
                    // To save lang content for usecachekey into cache
476
                    if ($usecachekey && count($tabtranslatedomain)) {
477
                        $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
478
                        if ($ressetcache < 0) {
479
                            $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
480
                            DolUtils::dol_syslog($error, LOG_ERR);
481
                        }
482
                    }
483
                }
484
            } else {
485
                dol_print_error($db);
486
            }
487
        }
488
489
        if ($fileread)
490
            $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
491
492
        if (empty($this->_tab_loaded[$newdomain]))
493
            $this->_tab_loaded[$newdomain] = 2;           // Marque ce cas comme non trouve (no lines found for language)
494
495
        return 1;
496
    }
497
498
    /**
499
     * Return translated value of key for special keys ("Currency...", "Civility...", ...).
500
     * Search in lang file, then into database. Key must be any complete entry into lang file: CurrencyEUR, ...
501
     * If not found, return key.
502
     * The string return is not formated (translated with transnoentitiesnoconv)
503
     * NOTE: To avoid infinite loop (getLabelFromKey->transnoentities->getTradFromKey), if you modify this function,
504
     * check that getLabelFromKey is not called with same value than input.
505
     *
506
     * @param	string		$key		Key to translate
507
     * @return 	string					Translated string (translated with transnoentitiesnoconv)
508
     */
509
    private function getTradFromKey($key)
510
    {
511
        global $conf, $db;
512
513
        if (!is_string($key))
514
            return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly.
515
516
        $newstr = $key;
517
        if (preg_match('/^Civility([0-9A-Z]+)$/i', $key, $reg)) {
518
            $newstr = $this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label');
519
        } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg)) {
520
            $newstr = $this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label');
521
        } elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i', $key, $reg)) {
522
            $newstr = $this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle');
523
        } elseif (preg_match('/^PaymentTypeShort([0-9A-Z]+)$/i', $key, $reg)) {
524
            $newstr = $this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1);
525
        } elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i', $key, $reg)) {
526
            $newstr = $this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label');
527
        } elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i', $key, $reg)) {
528
            // TODO OrderSourceX must be replaced with content of table llx_c_input_reason or llx_c_input_method
529
            //$newstr=$this->getLabelFromKey($db,$reg[1],'c_ordersource','code','label');
530
        }
531
532
        /* Disabled. There is too many cases where translation of $newstr is not defined is normal (like when output with setEventMessage an already translated string)
533
          if (! empty($conf->global->MAIN_FEATURES_LEVEL) && $conf->global->MAIN_FEATURES_LEVEL >= 2)
534
          {
535
          DolUtils::dol_syslog(__METHOD__." MAIN_FEATURES_LEVEL=DEVELOP: missing translation for key '".$newstr."' in ".$_SERVER["PHP_SELF"], LOG_DEBUG);
536
          } */
537
538
        return $newstr;
539
    }
540
541
    /**
542
     *  Return text translated of text received as parameter (and encode it into HTML)
543
     *              Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
544
     *              et si toujours pas trouve, il est retourne tel quel
545
     *              Les parametres de cette methode peuvent contenir de balises HTML.
546
     *
547
     *  @param	string	$key        Key to translate
548
     *  @param  string	$param1     chaine de param1
549
     *  @param  string	$param2     chaine de param2
550
     *  @param  string	$param3     chaine de param3
551
     *  @param  string	$param4     chaine de param4
552
     * 	@param	int		$maxsize	Max length of text
553
     *  @return string      		Translated string (encoded into HTML entities and UTF8)
554
     */
555
    function trans($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $maxsize = 0)
556
    {
557
        global $conf;
558
559
        if (!empty($this->tab_translate[$key])) { // Translation is available
560
            $str = $this->tab_translate[$key];
561
562
            // Make some string replacement after translation
563
            $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
564
            if (!empty($conf->global->$replacekey)) {    // Replacement translation variable with string1:newstring1;string2:newstring2
565
                $tmparray = explode(';', $conf->global->$replacekey);
566
                foreach ($tmparray as $tmp) {
567
                    $tmparray2 = explode(':', $tmp);
568
                    $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
569
                }
570
            }
571
572
            if (!preg_match('/^Format/', $key)) {
573
                //print $str;
574
                $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
575
            }
576
577
            if ($maxsize)
578
                $str = dol_trunc($str, $maxsize);
579
580
            // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities
581
            $str = str_replace(array('<', '>', '"',), array('__lt__', '__gt__', '__quot__'), $str);
582
583
            // Crypt string into HTML
584
            $str = htmlentities($str, ENT_COMPAT, $this->charset_output); // Do not convert simple quotes in translation (strings in html are enmbraced by "). Use dol_escape_htmltag around text in HTML content
585
            // Restore HTML tags
586
            $str = str_replace(array('__lt__', '__gt__', '__quot__'), array('<', '>', '"',), $str);
587
588
            return $str;
589
        }
590
        else {        // Translation is not available
591
            //if ($key[0] == '$') { return dol_eval($key,1); }
592
            return $this->getTradFromKey($key);
593
        }
594
    }
595
596
    /**
597
     *  Return translated value of a text string
598
     *               Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
599
     *               et si toujours pas trouve, il est retourne tel quel.
600
     *               Parameters of this method must not contains any HTML tags.
601
     *
602
     *  @param	string	$key        Key to translate
603
     *  @param  string	$param1     chaine de param1
604
     *  @param  string	$param2     chaine de param2
605
     *  @param  string	$param3     chaine de param3
606
     *  @param  string	$param4     chaine de param4
607
     *  @param  string	$param5     chaine de param5
608
     *  @return string      		Translated string (encoded into UTF8)
609
     */
610
    function transnoentities($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
611
    {
612
        return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5));
613
    }
614
615
    /**
616
     *  Return translated value of a text string
617
     *               Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
618
     *               et si toujours pas trouve, il est retourne tel quel.
619
     *               No convert to encoding charset of lang object is done.
620
     *               Parameters of this method must not contains any HTML tags.
621
     *
622
     *  @param	string	$key        Key to translate
623
     *  @param  string	$param1     chaine de param1
624
     *  @param  string	$param2     chaine de param2
625
     *  @param  string	$param3     chaine de param3
626
     *  @param  string	$param4     chaine de param4
627
     *  @param  string	$param5     chaine de param5
628
     *  @return string      		Translated string
629
     */
630
    function transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
631
    {
632
        global $conf;
633
634
        if (!empty($this->tab_translate[$key])) { // Translation is available
635
            $str = $this->tab_translate[$key];
636
637
            // Make some string replacement after translation
638
            $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
639
            if (!empty($conf->global->$replacekey)) {    // Replacement translation variable with string1:newstring1;string2:newstring2
640
                $tmparray = explode(';', $conf->global->$replacekey);
641
                foreach ($tmparray as $tmp) {
642
                    $tmparray2 = explode(':', $tmp);
643
                    $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
644
                }
645
            }
646
647
            if (!preg_match('/^Format/', $key)) {
648
                //print $str;
649
                $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
650
            }
651
652
            return $str;
653
        } else {
654
            if ($key[0] == '$') {
655
                return dol_eval($key, 1);
656
            }
657
            return $this->getTradFromKey($key);
658
        }
659
    }
660
661
    /**
662
     *  Return translation of a key depending on country
663
     *
664
     *  @param	string	$str            string root to translate
665
     *  @param  string	$countrycode    country code (FR, ...)
666
     *  @return	string         			translated string
667
     */
668
    function transcountry($str, $countrycode)
669
    {
670
        if ($this->tab_translate["$str$countrycode"])
671
            return $this->trans("$str$countrycode");
672
        else
673
            return $this->trans($str);
674
    }
675
676
    /**
677
     *  Retourne la version traduite du texte passe en parametre complete du code pays
678
     *
679
     *  @param	string	$str            string root to translate
680
     *  @param  string	$countrycode    country code (FR, ...)
681
     *  @return string         			translated string
682
     */
683
    function transcountrynoentities($str, $countrycode)
684
    {
685
        if ($this->tab_translate["$str$countrycode"])
686
            return $this->transnoentities("$str$countrycode");
687
        else
688
            return $this->transnoentities($str);
689
    }
690
691
    /**
692
     *  Convert a string into output charset (this->charset_output that should be defined to conf->file->character_set_client)
693
     *
694
     *  @param	string	$str            String to convert
695
     *  @param	string	$pagecodefrom	Page code of src string
696
     *  @return string         			Converted string
697
     */
698
    function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
699
    {
700
        if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8')
701
            $str = utf8_encode($str);
702
        if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1')
703
            $str = utf8_decode(str_replace('€', chr(128), $str));
704
        return $str;
705
    }
706
707
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
708
    /**
709
     *  Return list of all available languages
710
     *
711
     * 	@param	string	$langdir		Directory to scan
712
     *  @param  integer	$maxlength   	Max length for each value in combo box (will be truncated)
713
     *  @param	int		$usecode		1=Show code instead of country name for language variant, 2=Show only code
714
     *  @return array     				List of languages
715
     */
716
    function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0)
717
    {
718
        // phpcs:enable
719
        global $conf;
720
721
        if ($langdir == DOL_DOCUMENT_ROOT) {
722
            $langdir = DOL_BASE_PATH;
723
        }
724
725
        // We scan directory langs to detect available languages
726
        $handle = opendir($langdir . "/langs");
727
        $langs_available = array();
728
        while ($dir = trim(readdir($handle))) {
729
            if (preg_match('/^[a-z]+_[A-Z]+/i', $dir)) {
730
                $this->load("languages");
731
732
                if ($usecode == 2) {
733
                    $langs_available[$dir] = $dir;
734
                }
735
                if ($usecode == 1 || !empty($conf->global->MAIN_SHOW_LANGUAGE_CODE)) {
736
                    $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
737
                } else {
738
                    $langs_available[$dir] = $this->trans('Language_' . $dir);
739
                }
740
            }
741
        }
742
        return $langs_available;
743
    }
744
745
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
746
    /**
747
     *  Return if a filename $filename exists for current language (or alternate language)
748
     *
749
     *  @param	string	$filename       Language filename to search
750
     *  @param  integer	$searchalt      Search also alernate language file
751
     *  @return boolean         		true if exists and readable
752
     */
753
    function file_exists($filename, $searchalt = 0)
754
    {
755
        // phpcs:enable
756
        // Test si fichier dans repertoire de la langue
757
        foreach ($this->dir as $searchdir) {
758
            if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename)))
759
                return true;
760
761
            if ($searchalt) {
762
                // Test si fichier dans repertoire de la langue alternative
763
                if ($this->defaultlang != "en_US")
764
                    $filenamealt = $searchdir . "/langs/en_US/" . $filename;
765
                //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
766
                if (is_readable(dol_osencode($filenamealt)))
767
                    return true;
768
            }
769
        }
770
771
        return false;
772
    }
773
774
    /**
775
     *      Return full text translated to language label for a key. Store key-label in a cache.
776
     *      This function need module "numberwords" to be installed. If not it will return
777
     *      same number (this module is not provided by default as it use non GPL source code).
778
     *
779
     * 		@param	int		$number		Number to encode in full text
780
     * 		@param	int		$isamount	1=It's an amount, 0=it's just a number
781
     *      @return string				Label translated in UTF8 (but without entities)
782
     * 									10 if setDefaultLang was en_US => ten
783
     * 									123 if setDefaultLang was fr_FR => cent vingt trois
784
     */
785
    function getLabelFromNumber($number, $isamount = 0)
786
    {
787
        global $conf;
788
789
        $newnumber = $number;
790
791
        $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
792
        foreach ($dirsubstitutions as $reldir) {
793
            $dir = dol_buildpath($reldir, 0);
794
            $newdir = dol_osencode($dir);
795
796
            // Check if directory exists
797
            if (!is_dir($newdir))
798
                continue; // We must not use dol_is_dir here, function may not be loaded
799
800
            $fonc = 'numberwords';
801
            if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
802
                include_once $newdir . '/functions_' . $fonc . '.lib.php';
803
                $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
0 ignored issues
show
Bug introduced by alxarafe
The function numberwords_getLabelFromNumber was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

803
                $newnumber = /** @scrutinizer ignore-call */ numberwords_getLabelFromNumber($this, $number, $isamount);
Loading history...
804
                break;
805
            }
806
        }
807
808
        return $newnumber;
809
    }
810
811
    /**
812
     *      Return a label for a key.
813
     *      Search into translation array, then into cache, then if still not found, search into database.
814
     *      Store key-label found into cache variable $this->cache_labels to save SQL requests to get labels.
815
     *
816
     * 		@param	DoliDB	$db				Database handler
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
817
     * 		@param	string	$key			Translation key to get label (key in language file)
818
     * 		@param	string	$tablename		Table name without prefix
819
     * 		@param	string	$fieldkey		Field for key
820
     * 		@param	string	$fieldlabel		Field for label
821
     *      @param	string	$keyforselect	Use another value than the translation key for the where into select
822
     *      @param  int		$filteronentity	Use a filter on entity
823
     *      @return string					Label in UTF8 (but without entities)
824
     *      @see dol_getIdFromCode
825
     */
826
    function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
827
    {
828
        // If key empty
829
        if ($key == '')
830
            return '';
831
832
        //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
833
        // Check if a translation is available (this can call getTradFromKey)
834
        $tmp = $this->transnoentitiesnoconv($key);
835
        if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
836
            return $tmp;    // Found in language array
837
        }
838
839
        // Check in cache
840
        if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
841
            return $this->cache_labels[$tablename][$key];   // Found in cache
842
        }
843
844
        $sql = "SELECT " . $fieldlabel . " as label";
845
        $sql .= " FROM " . MAIN_DB_PREFIX . $tablename;
846
        $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
847
        if ($filteronentity)
848
            $sql .= " AND entity IN (" . getEntity($tablename) . ')';
849
        DolUtils::dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
850
        $resql = $db->query($sql);
851
        if ($resql) {
852
            $obj = $db->fetch_object($resql);
853
            if ($obj)
854
                $this->cache_labels[$tablename][$key] = $obj->label;
855
            else
856
                $this->cache_labels[$tablename][$key] = $key;
857
858
            $db->free($resql);
859
            return $this->cache_labels[$tablename][$key];
860
        }
861
        else {
862
            $this->error = $db->lasterror();
863
            return -1;
864
        }
865
    }
866
867
    /**
868
     * 	Return a currency code into its symbol
869
     *
870
     *  @param	string	$currency_code		Currency Code
871
     *  @param	string	$amount				If not '', show currency + amount according to langs ($10, 10€).
872
     *  @return	string						Amount + Currency symbol encoded into UTF8
873
     *  @deprecated							Use method price to output a price
874
     *  @see price()
875
     */
876
    function getCurrencyAmount($currency_code, $amount)
877
    {
878
        $symbol = $this->getCurrencySymbol($currency_code);
879
880
        if (in_array($currency_code, array('USD')))
881
            return $symbol . $amount;
882
        else
883
            return $amount . $symbol;
884
    }
885
886
    /**
887
     * 	Return a currency code into its symbol.
888
     *  If mb_convert_encoding is not available, return currency code.
889
     *
890
     *  @param	string	$currency_code		Currency code
891
     *  @param	integer	$forceloadall		1=Force to load all currencies into cache. We know we need to use all of them. By default read and cache only required currency.
892
     *  @return	string						Currency symbol encoded into UTF8
893
     */
894
    function getCurrencySymbol($currency_code, $forceloadall = 0)
895
    {
896
        $currency_sign = ''; // By default return iso code
897
898
        if (function_exists("mb_convert_encoding")) {
899
            $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
900
901
            if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) {
902
                foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
903
                    $currency_sign .= mb_convert_encoding("&#{$unicode};", "UTF-8", 'HTML-ENTITIES');
904
                }
905
            }
906
        }
907
908
        return ($currency_sign ? $currency_sign : $currency_code);
909
    }
910
911
    /**
912
     *  Load into the cache this->cache_currencies, all currencies
913
     *
914
     * 	@param	string	$currency_code		Get only currency. Get all if ''.
915
     *  @return int             			Nb of loaded lines, 0 if already loaded, <0 if KO
916
     */
917
    public function loadCacheCurrencies($currency_code)
918
    {
919
        global $db;
920
921
        if ($this->cache_currencies_all_loaded)
922
            return 0;                                           // Cache already loaded for all
923
        if (!empty($currency_code) && isset($this->cache_currencies[$currency_code]))
924
            return 0;    // Cache already loaded for the currency
925
926
        $sql = "SELECT code_iso, label, unicode";
927
        $sql .= " FROM " . MAIN_DB_PREFIX . "c_currencies";
928
        $sql .= " WHERE active = 1";
929
        if (!empty($currency_code))
930
            $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
931
        //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
932
933
        DolUtils::dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
934
        $resql = $db->query($sql);
935
        if ($resql) {
936
            $this->load("dict");
937
            $label = array();
938
            if (!empty($currency_code))
939
                foreach ($this->cache_currencies as $key => $val)
940
                    $label[$key] = $val['label']; // Label in already loaded cache
941
942
                $num = $db->num_rows($resql);
943
            $i = 0;
944
            while ($i < $num) {
945
                $obj = $db->fetch_object($resql);
946
947
                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
948
                $this->cache_currencies[$obj->code_iso]['label'] = ($obj->code_iso && $this->trans("Currency" . $obj->code_iso) != "Currency" . $obj->code_iso ? $this->trans("Currency" . $obj->code_iso) : ($obj->label != '-' ? $obj->label : ''));
949
                $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode($obj->unicode, true);
950
                $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
951
                $i++;
952
            }
953
            if (empty($currency_code))
954
                $this->cache_currencies_all_loaded = true;
955
            //print count($label).' '.count($this->cache_currencies);
956
            // Resort cache
957
            array_multisort($label, SORT_ASC, $this->cache_currencies);
958
            //var_dump($this->cache_currencies);	$this->cache_currencies is now sorted onto label
959
            return $num;
960
        }
961
        else {
962
            dol_print_error($db);
963
            return -1;
964
        }
965
    }
966
967
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
968
    /**
969
     * Return an array with content of all loaded translation keys (found into this->tab_translate) so
970
     * we get a substitution array we can use for substitutions (for mail or ODT generation for example)
971
     *
972
     * @return array	Array of translation keys lang_key => string_translation_loaded
973
     */
974
    function get_translations_for_substitutions()
975
    {
976
        // phpcs:enable
977
        $substitutionarray = array();
978
979
        foreach ($this->tab_translate as $code => $label) {
980
            $substitutionarray['lang_' . $code] = $label;
981
            $substitutionarray['__(' . $code . ')__'] = $label;
982
        }
983
984
        return $substitutionarray;
985
    }
986
}
987