dolibarr 21.0.0-alpha
translate.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2001 Eric Seigne <erics@rycks.com>
3 * Copyright (C) 2004-2015 Destailleur Laurent <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2010 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
32{
36 public $dir;
37
41 public $defaultlang;
42
46 public $shortlang;
47
51 public $charset_output = 'UTF-8';
52
53
57 public $tab_translate = array();
58
62 private $_tab_loaded = array();
63
67 public $cache_labels = array();
68
72 public $cache_currencies = array();
73
78 private $cache_currencies_all_loaded = false;
79
83 public $origlang;
84
89 public $error;
90
94 public $errors = array();
95
96
103 public function __construct($dir, $conf)
104 {
105 if (!empty($conf->file->character_set_client)) {
106 $this->charset_output = $conf->file->character_set_client; // If charset output is forced
107 }
108 if ($dir) {
109 $this->dir = array($dir);
110 } else {
111 $this->dir = $conf->file->dol_document_root;
112 }
113 }
114
115
122 public function setDefaultLang($srclang = 'en_US')
123 {
124 global $conf;
125
126 //dol_syslog(get_class($this)."::setDefaultLang srclang=".$srclang,LOG_DEBUG);
127
128 // If a module ask to force a priority on langs directories (to use its own lang files)
129 if (getDolGlobalString('MAIN_FORCELANGDIR')) {
130 $more = array();
131 $i = 0;
132 foreach ($conf->file->dol_document_root as $dir) {
133 $newdir = $dir . getDolGlobalString('MAIN_FORCELANGDIR'); // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
134 if (!in_array($newdir, $this->dir)) {
135 $more['module_' . $i] = $newdir;
136 $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
137 }
138 }
139 $this->dir = array_merge($more, $this->dir); // Forced dir ($more) are before standard dirs ($this->dir)
140 }
141
142 $this->origlang = $srclang;
143
144 if (empty($srclang) || $srclang == 'auto') {
145 // $_SERVER['HTTP_ACCEPT_LANGUAGE'] can be 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7,it;q=0.6' but can contains also malicious content
146 $langpref = empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? '' : $_SERVER['HTTP_ACCEPT_LANGUAGE'];
147 $langpref = preg_replace("/;([^,]*)/i", "", $langpref); // Remove the 'q=x.y,' part
148 $langpref = str_replace("-", "_", $langpref);
149 $langlist = preg_split("/[;,]/", $langpref);
150 $codetouse = preg_replace('/[^_a-zA-Z]/', '', $langlist[0]);
151 } else {
152 $codetouse = $srclang;
153 }
154
155 // We redefine $srclang
156 $langpart = explode("_", $codetouse);
157 //print "Short code before _ : ".$langpart[0].' / Short code after _ : '.$langpart[1].'<br>';
158 if (!empty($langpart[1])) { // If it's for a codetouse that is a long code xx_YY
159 // Array force long code from first part, even if long code is defined
160 $longforshort = array('ar' => 'ar_SA');
161 $longforshortexcep = array('ar_EG');
162 if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep)) {
163 $srclang = $longforshort[strtolower($langpart[0])];
164 } elseif (!is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser
165 $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[1]);
166 $longforlong = array('no_nb' => 'nb_NO');
167 if (isset($longforlong[strtolower($srclang)])) {
168 $srclang = $longforlong[strtolower($srclang)];
169 }
170 } else {
171 $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
172 }
173 } else { // If it's for a codetouse that is a short code xx
174 // Array to convert short lang code into long code.
175 $longforshort = array(
176 'am' => 'am_ET', 'ar' => 'ar_SA', 'bn' => 'bn_DB', 'el' => 'el_GR', 'ca' => 'ca_ES', 'cs' => 'cs_CZ', 'en' => 'en_US', 'fa' => 'fa_IR',
177 'gl' => 'gl_ES', 'he' => 'he_IL', 'hi' => 'hi_IN', 'ja' => 'ja_JP',
178 'ka' => 'ka_GE', 'km' => 'km_KH', 'kn' => 'kn_IN', 'ko' => 'ko_KR', 'lo' => 'lo_LA', 'nb' => 'nb_NO', 'no' => 'nb_NO', 'ne' => 'ne_NP',
179 'sl' => 'sl_SI', 'sq' => 'sq_AL', 'sr' => 'sr_RS', 'sv' => 'sv_SE', 'uk' => 'uk_UA', 'vi' => 'vi_VN', 'zh' => 'zh_CN'
180 );
181 if (isset($longforshort[strtolower($langpart[0])])) {
182 $srclang = $longforshort[strtolower($langpart[0])];
183 } elseif (!empty($langpart[0])) {
184 $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
185 } else {
186 $srclang = 'en_US';
187 }
188 }
189
190 $this->defaultlang = $srclang;
191 $this->shortlang = substr($srclang, 0, 2);
192 //print 'this->defaultlang='.$this->defaultlang;
193 }
194
195
203 public function getDefaultLang($mode = 0)
204 {
205 if (empty($mode)) {
206 return $this->defaultlang;
207 } else {
208 return substr($this->defaultlang, 0, 2);
209 }
210 }
211
212
219 public function loadLangs($domains)
220 {
221 $loaded = 0;
222 foreach ($domains as $domain) {
223 $result = $this->load($domain);
224 if ($result > 0) {
225 $loaded = $result;
226 } elseif ($result < 0) {
227 return $result;
228 }
229 }
230 return $loaded;
231 }
232
256 public function load($domain, $alt = 0, $stopafterdirection = 0, $forcelangdir = '', $loadfromfileonly = 0, $forceloadifalreadynotfound = 0, &$tabtranslatedomain = [], $langkey = '')
257 {
258 global $conf, $db;
259
260 //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
261
262 // Check parameters
263 if (empty($domain)) {
264 dol_print_error(null, get_class($this) . "::Load ErrorWrongParameters");
265 return -1;
266 }
267 if ($this->defaultlang === 'none_NONE') {
268 return 0; // Special language code to not translate keys
269 }
270
271
272 // Load $this->tab_translate[] from database
273 if (empty($loadfromfileonly) && count($this->tab_translate) == 0) {
274 $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database.
275 }
276
277
278 $newdomain = $domain;
279 $modulename = '';
280
281 // Search if a module directory name is provided into lang file name
282 $regs = array();
283 if (preg_match('/^([^@]+)@([^@]+)$/i', $domain, $regs)) {
284 $newdomain = (string) $regs[1];
285 $modulename = (string) $regs[2];
286 }
287
288 // Check cache
289 if (
290 !empty($this->_tab_loaded[$newdomain])
291 && ($this->_tab_loaded[$newdomain] != 2 || empty($forceloadifalreadynotfound))
292 ) { // File already loaded and found and not forced for this domain
293 //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
294 return 0;
295 }
296
297 $fileread = 0;
298 $langofdir = (empty($forcelangdir) ? $this->defaultlang : $forcelangdir);
299 $langkey = (empty($langkey) ? $langofdir : $langkey);
300
301 // Redefine alt
302 $langarray = explode('_', $langofdir);
303 if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) {
304 $alt = 1;
305 }
306 if ($alt < 2 && strtolower($langofdir) == 'en_us') {
307 $alt = 2;
308 }
309
310 if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
311 dol_syslog("Error: " . get_class($this) . "::load was called for domain=" . $domain . " but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
312 return -1;
313 }
314
315 $usecachekey = '';
316 foreach ($this->dir as $searchdir) {
317 // Directory of translation files
318 $file_lang = $searchdir . ($modulename ? '/' . $modulename : '') . "/langs/" . $langofdir . "/" . $newdomain . ".lang";
319 $file_lang_osencoded = dol_osencode($file_lang);
320
321 //$filelangexists = is_file($file_lang_osencoded);
322 $filelangexists = @is_file($file_lang_osencoded); // avoid [php:warn]
323
324 //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);
325 //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";
326
327 if ($filelangexists) {
328 // TODO Move cache read out of loop on dirs or at least filelangexists
329 $found = false;
330
331 // Enable caching of lang file in memory (not by default)
332 $usecachekey = '';
333 // Using a memcached server
334 if (isModEnabled('memcached') && getDolGlobalString('MEMCACHED_SERVER')) {
335 $usecachekey = $newdomain . '_' . $langkey . '_' . md5($file_lang); // Should not contains special chars
336 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) {
337 // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
338 $usecachekey = $newdomain;
339 }
340
341 if ($usecachekey) {
342 //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
343 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
344 $tmparray = dol_getcache($usecachekey);
345 if (is_array($tmparray) && count($tmparray)) {
346 $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.
347 if ($alt == 2) {
348 $fileread = 1;
349 }
350 $found = true; // Found in dolibarr PHP cache
351 }
352 }
353
354 if (!$found) {
355 if ($fp = @fopen($file_lang, "rt")) {
356 // $tabtranslatedomain = array(); // To save lang content in cache when enabled (commented because initial = argument to function)
357
363 while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n\r]")) {
364 if (isset($line[1])) {
365 list($key, $value) = $line;
366 //if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."<br>";
367 //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>";
368 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)
369 if ($key == 'DIRECTION') { // This is to declare direction of language
370 if ($alt < 2 || empty($this->tab_translate[$key])) { // We load direction only for primary files or if not yet loaded
371 $this->tab_translate[$key] = $value;
372 if ($stopafterdirection) {
373 break; // We do not save tab if we stop after DIRECTION
374 } elseif ($usecachekey) {
375 $tabtranslatedomain[$key] = $value;
376 }
377 }
378 } elseif ($key[0] == '#') {
379 continue;
380 } else {
381 // Convert some strings: Parse and render carriage returns. Also, change '\\s' into '\s' because transifex sync pull the string '\s' into string '\\s'
382 $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
383 if ($usecachekey) {
384 $tabtranslatedomain[$key] = $value;
385 } // To save lang content in cache
386 }
387 }
388 }
389 }
390 fclose($fp);
391 $fileread = 1;
392
393 if (!getDolGlobalString('MAIN_FORCELANGDIR')) {
394 break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
395 }
396 }
397 }
398 }
399 }
400
401 // Now we complete with next file (fr_CA->fr_FR, es_MX->ex_ES, ...)
402 if ($alt == 0) {
403 // This function MUST NOT contains call to syslog
404 //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
405 $langofdir = strtolower($langarray[0]) . '_' . strtoupper($langarray[0]);
406 if ($langofdir == 'el_EL') {
407 $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR'
408 }
409 if ($langofdir == 'ar_AR') {
410 $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
411 }
412 $this->load($domain, $alt + 1, $stopafterdirection, $langofdir, 0, 0, $tabtranslatedomain, $langkey);
413 }
414
415 // Now we complete with reference file (en_US)
416 if ($alt == 1) {
417 // This function MUST NOT contains call to syslog
418 //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
419 $langofdir = 'en_US';
420 $this->load($domain, $alt + 1, $stopafterdirection, $langofdir, 0, 0, $tabtranslatedomain, $langkey);
421 }
422
423 // We are in the pass of the reference file. No more files to scan to complete.
424 if ($alt == 2) {
425 if ($fileread) {
426 $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded
427 }
428
429 if (empty($this->_tab_loaded[$newdomain])) {
430 $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
431 }
432 }
433
434 // This part is deprecated and replaced with table llx_overwrite_trans
435 // Kept for backward compatibility.
436 if (empty($loadfromfileonly)) {
437 $overwritekey = 'MAIN_OVERWRITE_TRANS_' . $this->defaultlang;
438 if (getDolGlobalString($overwritekey)) { // Overwrite translation with key1:newstring1,key2:newstring2
439 // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
440 $tmparray = explode(',', getDolGlobalString($overwritekey));
441 foreach ($tmparray as $tmp) {
442 $tmparray2 = explode(':', $tmp);
443 if (!empty($tmparray2[1])) {
444 $this->tab_translate[$tmparray2[0]] = $tmparray2[1];
445 }
446 }
447 }
448 }
449
450 // To save lang content for usecachekey into cache
451 if ($usecachekey && count($tabtranslatedomain)) {
452 $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
453 if ($ressetcache < 0) {
454 $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
455 dol_syslog($error, LOG_ERR);
456 }
457 }
458
459 // Check to be sure that SeparatorDecimal differs from SeparatorThousand
460 if (
461 !empty($this->tab_translate["SeparatorDecimal"]) && !empty($this->tab_translate["SeparatorThousand"])
462 && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]
463 ) {
464 $this->tab_translate["SeparatorThousand"] = '';
465 }
466
467 return 1;
468 }
469
482 public function loadFromDatabase($db)
483 {
484 global $conf;
485
486 $domain = 'database';
487
488 // Check parameters
489 if (empty($db)) {
490 return 0; // Database handler can't be used
491 }
492
493 //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
494
495 $newdomain = $domain;
496
497 // Check cache
498 if (!empty($this->_tab_loaded[$newdomain])) { // File already loaded for this domain 'database'
499 //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
500 return 0;
501 }
502
503 $this->_tab_loaded[$newdomain] = 2; // Preset the load as loaded and make sure this function is called once only for $newdomain='database'
504
505 $fileread = 0;
506 $langofdir = $this->defaultlang;
507
508 if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
509 dol_syslog("Error: " . get_class($this) . "::loadFromDatabase was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
510 return -1;
511 }
512
513 // TODO Move cache read out of loop on dirs or at least filelangexists
514 $found = false;
515
516 // Enable caching of lang file in memory (not by default)
517 $usecachekey = '';
518 // Using a memcached server
519 if (isModEnabled('memcached') && getDolGlobalString('MEMCACHED_SERVER')) {
520 $usecachekey = $newdomain . '_' . $langofdir; // Should not contains special chars
521 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) {
522 // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
523 $usecachekey = $newdomain;
524 }
525
526 if ($usecachekey) {
527 //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
528 //global $aaa; $aaa+=1;
529 //print $aaa." ".$usecachekey."\n";
530 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
531 $tmparray = dol_getcache($usecachekey);
532 if (is_array($tmparray) && count($tmparray)) {
533 $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.
534 //print $newdomain."\n";
535 //var_dump($this->tab_translate);
536 $fileread = 1;
537 $found = true; // Found in dolibarr PHP cache
538 }
539 }
540
541 if (!$found && getDolGlobalString('MAIN_ENABLE_OVERWRITE_TRANSLATION')) {
542 // Overwrite translation with database read
543 $sql = "SELECT transkey, transvalue FROM ".$db->prefix()."overwrite_trans where (lang='".$db->escape($this->defaultlang)."' OR lang IS NULL)";
544 $sql .= " AND entity IN (0, ".getEntity('overwrite_trans').")";
545 $sql .= $db->order("lang", "DESC");
546
547 $resql = $db->query($sql);
548
549 if ($resql) {
550 $num = $db->num_rows($resql);
551 if ($num) {
552 $tabtranslatedomain = array(); // To save lang content in cache (when enabled)
553
554 $i = 0;
555 while ($i < $num) { // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
556 $obj = $db->fetch_object($resql);
557
558 $key = $obj->transkey;
559 $value = $obj->transvalue;
560
561 //print "Domain=$domain, found a string for $tab[0] with value $tab[1]<br>";
562 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)
563 // Convert some strings: Parse and render carriage returns. Also, change '\\s' int '\s' because transifex sync pull the string '\s' into string '\\s'
564 $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
565
566 if ($usecachekey) {
567 $tabtranslatedomain[$key] = $value; // To save lang content in cache
568 }
569 }
570
571 $i++;
572 }
573
574 $fileread = 1;
575
576 // TODO Move cache write out of loop on dirs
577 // To save lang content for usecachekey into cache
578 if ($usecachekey && count($tabtranslatedomain)) {
579 $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
580 if ($ressetcache < 0) {
581 $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
582 dol_syslog($error, LOG_ERR);
583 }
584 }
585 }
586 } else {
587 dol_print_error($db);
588 }
589 }
590
591 if ($fileread) {
592 $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
593 }
594
595 return 1;
596 }
597
604 public function isLoaded($domain)
605 {
606 return $this->_tab_loaded[$domain];
607 }
608
620 private function getTradFromKey($key)
621 {
622 global $db;
623
624 if (!is_string($key)) {
625 //xdebug_print_function_stack('ErrorBadValueForParamNotAString');
626 return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly.
627 }
628
629 $newstr = $key;
630 $reg = array();
631 if (preg_match('/^Civility([0-9A-Z]+)$/i', $key, $reg)) {
632 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label');
633 } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg)) {
634 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label');
635 } elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i', $key, $reg)) {
636 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle');
637 } elseif (preg_match('/^PaymentType(?:Short)?([0-9A-Z]+)$/i', $key, $reg)) {
638 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1);
639 } elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i', $key, $reg)) {
640 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label');
641 } elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i', $key, $reg)) {
642 // TODO OrderSourceX must be replaced with content of table llx_c_input_reason or llx_c_input_method
643 //$newstr=$this->getLabelFromKey($db,$reg[1],'llx_c_input_reason','code','label');
644 }
645
646 /* Disabled. There is too many cases where translation of $newstr is not defined is normal (like when output with setEventMessage an already translated string)
647 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2)
648 {
649 dol_syslog(__METHOD__." MAIN_FEATURES_LEVEL=DEVELOP: missing translation for key '".$newstr."' in ".$_SERVER["PHP_SELF"], LOG_DEBUG);
650 }*/
651
652 return $newstr;
653 }
654
655
669 public function trans($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $maxsize = 0)
670 {
671 if (!empty($this->tab_translate[$key])) { // Translation is available
672 $str = $this->tab_translate[$key];
673
674 // Make some string replacement after translation
675 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
676 if (getDolGlobalString($replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
677 $tmparray = explode(';', getDolGlobalString($replacekey));
678 foreach ($tmparray as $tmp) {
679 $tmparray2 = explode(':', $tmp);
680 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
681 }
682 }
683
684 // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities because
685 // we want to keep '"' '<b>' '</b>' '<strong' '</strong>' '<a ' '</a>' '<br>' '< ' '<span' '</span>' that are reliable HTML tags inside translation strings.
686 $str = str_replace(
687 array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<strong>', '</strong>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'), // We accept '< ' but not '<'. We can accept however '>'
688 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__tagb__', '__tagbend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
689 $str
690 );
691
692 if (strpos($key, 'Format') !== 0) {
693 try {
694 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
695 $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
696 } catch (Exception $e) {
697 // No exception managed
698 }
699 }
700
701 // Encode string into HTML
702 $str = htmlentities($str, ENT_COMPAT, $this->charset_output); // Do not convert simple quotes in translation (strings in html are embraced by "). Use dol_escape_htmltag around text in HTML content
703
704 // Restore reliable HTML tags into original translation string
705 $str = str_replace(
706 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
707 array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'),
708 $str
709 );
710
711 // Remove dangerous sequence we should never have. Not needed into a translated response.
712 // %27 is entity code for ' and is replaced by browser automatically when translation is inside a javascript code called by a click like on a href link.
713 $str = str_replace(array('%27', '&#39'), '', $str);
714
715 if ($maxsize) {
716 $str = dol_trunc($str, $maxsize);
717 }
718
719 return $str;
720 } else { // Translation is not available
721 return $this->getTradFromKey($key);
722 }
723 }
724
725
740 public function transnoentities($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
741 {
742 return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5));
743 }
744
745
761 public function transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
762 {
763 global $conf;
764
765 if (!empty($this->tab_translate[$key])) { // Translation is available
766 $str = $this->tab_translate[$key];
767
768 // Make some string replacement after translation
769 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
770 if (getDolGlobalString($replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
771 $tmparray = explode(';', getDolGlobalString($replacekey));
772 foreach ($tmparray as $tmp) {
773 $tmparray2 = explode(':', $tmp);
774 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
775 }
776 }
777
778 if (!preg_match('/^Format/', $key)) {
779 //print $str;
780 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
781 $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
782 }
783
784 // Remove dangerous sequence we should never have. Not needed into a translated response.
785 // %27 is entity code for ' and is replaced by browser automatically when translation is inside a javascript code called by a click like on a href link.
786 $str = str_replace(array('%27', '&#39'), '', $str);
787
788 return $str;
789 } else {
790 return $this->getTradFromKey($key);
791 }
792 }
793
794
803 public function transcountry($str, $countrycode)
804 {
805 $strLocaleKey = $str.$countrycode;
806 if (!empty($this->tab_translate[$strLocaleKey])) {
807 return $this->trans($strLocaleKey);
808 } else {
809 return $this->trans($str);
810 }
811 }
812
813
822 public function transcountrynoentities($str, $countrycode)
823 {
824 $strLocaleKey = $str.$countrycode;
825 if (!empty($this->tab_translate[$strLocaleKey])) {
826 return $this->transnoentities($strLocaleKey);
827 } else {
828 return $this->transnoentities($str);
829 }
830 }
831
832
841 public function convToOutputCharset($str, $pagecodefrom = 'UTF-8', $pagecodeto = '')
842 {
843 if (empty($pagecodeto)) {
844 $pagecodeto = $this->charset_output;
845 }
846
847 if ($pagecodefrom == 'ISO-8859-1' && $pagecodeto == 'UTF-8') {
848 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
849 }
850 if ($pagecodefrom == 'UTF-8' && $pagecodeto == 'ISO-8859-1') {
851 $str = mb_convert_encoding(str_replace('€', chr(128), $str), 'ISO-8859-1');
852 // TODO Replace with iconv("UTF-8", "ISO-8859-1", str_replace('€', chr(128), $str)); ?
853 }
854 return $str;
855 }
856
857
858 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
868 public function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0, $mainlangonly = 0)
869 {
870 // phpcs:enable
871 $this->load("languages");
872
873 // We scan directory langs to detect available languages
874 $handle = opendir($langdir . "/langs");
875 $langs_available = array();
876 while ($dir = trim(readdir($handle))) {
877 $regs = array();
878 if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
879 // We must keep only main languages
880 if ($mainlangonly) {
881 $arrayofspecialmainlanguages = array(
882 'en' => 'en_US',
883 'am' => 'am_ET',
884 'ar' => 'ar_SA',
885 'bn' => 'bn_DB',
886 'bs' => 'bs_BA',
887 'ca' => 'ca_ES',
888 'cs' => 'cs_CZ',
889 'da' => 'da_DK',
890 'et' => 'et_EE',
891 'el' => 'el_GR',
892 'eu' => 'eu_ES',
893 'fa' => 'fa_IR',
894 'he' => 'he_IL',
895 'ka' => 'ka_GE',
896 'km' => 'km_KH',
897 'kn' => 'kn_IN',
898 'ko' => 'ko_KR',
899 'ja' => 'ja_JP',
900 'lo' => 'lo_LA',
901 'nb' => 'nb_NO',
902 'sq' => 'sq_AL',
903 'sr' => 'sr_RS',
904 'sv' => 'sv_SE',
905 'sl' => 'sl_SI',
906 'uk' => 'uk_UA',
907 'vi' => 'vi_VN',
908 'zh' => 'zh_CN'
909 );
910 if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
911 continue;
912 }
913 }
914 // We must keep only languages into MAIN_LANGUAGES_ALLOWED
915 if (getDolGlobalString('MAIN_LANGUAGES_ALLOWED') && !in_array($dir, explode(',', getDolGlobalString('MAIN_LANGUAGES_ALLOWED')))) {
916 continue;
917 }
918
919 if ($usecode == 2) {
920 $langs_available[$dir] = $dir;
921 }
922
923 if ($usecode == 1 || getDolGlobalString('MAIN_SHOW_LANGUAGE_CODE')) {
924 $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
925 } else {
926 $langs_available[$dir] = $this->trans('Language_' . $dir);
927 }
928 if ($mainlangonly) {
929 $langs_available[$dir] = str_replace(' (United States)', '', $langs_available[$dir]);
930 }
931 }
932 }
933 return $langs_available;
934 }
935
936
937 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
945 public function file_exists($filename, $searchalt = 0)
946 {
947 // phpcs:enable
948 // Test si fichier dans repertoire de la langue
949 foreach ($this->dir as $searchdir) {
950 if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename))) {
951 return true;
952 }
953
954 if ($searchalt) {
955 $filenamealt = null;
956 // Test si fichier dans repertoire de la langue alternative
957 if ($this->defaultlang != "en_US") {
958 $filenamealt = $searchdir . "/langs/en_US/" . $filename;
959 }
960 //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
961 if ($filenamealt !== null && is_readable(dol_osencode($filenamealt))) {
962 return true;
963 }
964 }
965 }
966
967 return false;
968 }
969
970
982 public function getLabelFromNumber($number, $isamount = '')
983 {
984 global $conf;
985
986 $newnumber = $number;
987
988 $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
989 foreach ($dirsubstitutions as $reldir) {
990 $dir = dol_buildpath($reldir, 0);
991 $newdir = dol_osencode($dir);
992
993 // Check if directory exists
994 if (!is_dir($newdir)) {
995 continue; // We must not use dol_is_dir here, function may not be loaded
996 }
997
998 $fonc = 'numberwords';
999 if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
1000 include_once $newdir . '/functions_' . $fonc . '.lib.php';
1001 if (function_exists('numberwords_getLabelFromNumber')) {
1002 $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
1003 break;
1004 }
1005 }
1006 }
1007
1008 return $newnumber;
1009 }
1010
1011
1027 public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
1028 {
1029 // If key empty
1030 if ($key == '') {
1031 return '';
1032 }
1033 // Test should be useless because the 3 variables are never set from user input but we keep it in case of.
1034 if (preg_match('/[^0-9A-Z_]/i', $tablename) || preg_match('/[^0-9A-Z_]/i', $fieldkey) || preg_match('/[^0-9A-Z_]/i', $fieldlabel)) {
1035 $this->error = 'Bad value for parameter tablename, fieldkey or fieldlabel';
1036 return -1;
1037 }
1038
1039 //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
1040
1041 // Check if a translation is available (Note: this can call getTradFromKey that can call getLabelFromKey)
1042 $tmp = $this->transnoentitiesnoconv($key);
1043 if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
1044 return $tmp; // Found in language array
1045 }
1046
1047 // Check in cache
1048 if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
1049 return $this->cache_labels[$tablename][$key]; // Found in cache
1050 }
1051
1052 // Not found in loaded language file nor in cache. So we will take the label into database.
1053 $sql = "SELECT " . $fieldlabel . " as label";
1054 $sql .= " FROM " . $db->prefix() . $tablename;
1055 $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
1056 if ($filteronentity) {
1057 $sql .= " AND entity IN (" . getEntity($tablename) . ')';
1058 }
1059 dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
1060 $resql = $db->query($sql);
1061 if ($resql) {
1062 $obj = $db->fetch_object($resql);
1063 if ($obj) {
1064 $this->cache_labels[$tablename][$key] = (string) $obj->label;
1065 } else {
1066 $this->cache_labels[$tablename][$key] = $key;
1067 }
1068
1069 $db->free($resql);
1070 return $this->cache_labels[$tablename][$key];
1071 } else {
1072 $this->error = $db->lasterror();
1073 return -1;
1074 }
1075 }
1076
1077
1087 public function getCurrencyAmount($currency_code, $amount)
1088 {
1089 $symbol = $this->getCurrencySymbol($currency_code);
1090
1091 if (in_array($currency_code, array('USD'))) {
1092 return $symbol . $amount;
1093 } else {
1094 return $amount . $symbol;
1095 }
1096 }
1097
1106 public function getCurrencySymbol($currency_code, $forceloadall = 0)
1107 {
1108 $currency_sign = ''; // By default return iso code
1109
1110 if (function_exists("mb_convert_encoding")) {
1111 $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
1112
1113 if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) { // @phan-suppress-current-line PhanTypeMismatchProperty
1114 foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
1115 $currency_sign .= mb_convert_encoding("&#" . $unicode . ";", "UTF-8", 'HTML-ENTITIES');
1116 }
1117 }
1118 }
1119
1120 return ($currency_sign ? $currency_sign : $currency_code);
1121 }
1122
1129 public function loadCacheCurrencies($currency_code)
1130 {
1131 global $db;
1132
1133 if ($this->cache_currencies_all_loaded) {
1134 return 0; // Cache already loaded for all
1135 }
1136 if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
1137 return 0; // Cache already loaded for the currency
1138 }
1139
1140 $sql = "SELECT code_iso, label, unicode";
1141 $sql .= " FROM " . $db->prefix() . "c_currencies";
1142 $sql .= " WHERE active = 1";
1143 if (!empty($currency_code)) {
1144 $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
1145 }
1146 //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
1147
1148 dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
1149 $resql = $db->query($sql);
1150 if ($resql) {
1151 $this->load("dict");
1152 $label = array();
1153 if (!empty($currency_code)) {
1154 foreach ($this->cache_currencies as $key => $val) {
1155 $label[$key] = $val['label']; // Label in already loaded cache
1156 }
1157 }
1158
1159 $num = $db->num_rows($resql);
1160 $i = 0;
1161 while ($i < $num) {
1162 $obj = $db->fetch_object($resql);
1163 if ($obj) {
1164 // If a translation exists, we use it lese we use the default label
1165 $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 : ''));
1166 $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode((empty($obj->unicode) ? '' : $obj->unicode), true); // @phan-suppress-current-line PhanTypeMismatchProperty
1167 $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
1168 }
1169 $i++;
1170 }
1171 if (empty($currency_code)) {
1172 $this->cache_currencies_all_loaded = true;
1173 }
1174 //print count($label).' '.count($this->cache_currencies);
1175
1176 // Resort cache
1177 array_multisort($label, SORT_ASC, $this->cache_currencies);
1178 //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
1179 return $num;
1180 } else {
1181 dol_print_error($db);
1182 return -1;
1183 }
1184 }
1185
1186 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1194 {
1195 // phpcs:enable
1196 $substitutionarray = array();
1197
1198 foreach ($this->tab_translate as $code => $label) {
1199 $substitutionarray['lang_' . $code] = $label;
1200 $substitutionarray['__(' . $code . ')__'] = $label;
1201 }
1202
1203 return $substitutionarray;
1204 }
1205}
Class to manage translations.
transnoentities($key, $param1='', $param2='', $param3='', $param4='', $param5='')
Return translated value of a text string If there is no match for this text, we look in alternative f...
transnoentitiesnoconv($key, $param1='', $param2='', $param3='', $param4='', $param5='')
Return translated value of a text string If there is no match for this text, we look in alternative f...
getTradFromKey($key)
Return translated value of key for special keys ("Currency...", "Civility...", ......
getLabelFromNumber($number, $isamount='')
Return full text translated to language label for a key.
getCurrencyAmount($currency_code, $amount)
Return a currency code into its symbol.
get_translations_for_substitutions()
Return an array with content of all loaded translation keys (found into this->tab_translate) so we ge...
getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect='', $filteronentity=0)
Return a label for a key.
load($domain, $alt=0, $stopafterdirection=0, $forcelangdir='', $loadfromfileonly=0, $forceloadifalreadynotfound=0, &$tabtranslatedomain=[], $langkey='')
Load translation key-value for a particular file, into a memory array.
get_available_languages($langdir=DOL_DOCUMENT_ROOT, $maxlength=0, $usecode=0, $mainlangonly=0)
Return list of all available languages.
loadCacheCurrencies($currency_code)
Load into the cache this->cache_currencies, all currencies.
convToOutputCharset($str, $pagecodefrom='UTF-8', $pagecodeto='')
Convert a string into output charset (this->charset_output that should be defined to conf->file->char...
setDefaultLang($srclang='en_US')
Set accessor for this->defaultlang.
file_exists($filename, $searchalt=0)
Return if a filename $filename exists for current language (or alternate language)
transcountry($str, $countrycode)
Return translation of a key depending on country.
isLoaded($domain)
Get information with result of loading data for domain.
trans($key, $param1='', $param2='', $param3='', $param4='', $maxsize=0)
Return text translated of text received as parameter (and encode it into HTML) If there is no match f...
transcountrynoentities($str, $countrycode)
Retourne la version traduite du texte passe en parameter complete du code pays.
getCurrencySymbol($currency_code, $forceloadall=0)
Return a currency code into its symbol.
loadLangs($domains)
Load translation files.
loadFromDatabase($db)
Load translation key-value from database into a memory array.
getDefaultLang($mode=0)
Return active language code for current user It's an accessor for this->defaultlang.
__construct($dir, $conf)
Constructor.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_setcache($memoryid, $data, $expire=0)
Save data into a memory area shared by all users, all sessions on server.
dol_getcache($memoryid)
Read a memory area shared by all users, all sessions on server.