dolibarr 21.0.3
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 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
33{
37 public $dir;
38
42 public $defaultlang;
43
47 public $shortlang;
48
52 public $charset_output = 'UTF-8';
53
54
58 public $tab_translate = array();
59
63 private $_tab_loaded = array();
64
68 public $cache_labels = array();
69
73 public $cache_currencies = array();
74
79 private $cache_currencies_all_loaded = false;
80
84 public $origlang;
85
90 public $error;
91
95 public $errors = array();
96
97
104 public function __construct($dir, $conf)
105 {
106 if (!empty($conf->file->character_set_client)) {
107 $this->charset_output = $conf->file->character_set_client; // If charset output is forced
108 }
109 if ($dir) {
110 $this->dir = array($dir);
111 } else {
112 $this->dir = $conf->file->dol_document_root;
113 }
114 }
115
116
123 public function setDefaultLang($srclang = 'en_US')
124 {
125 global $conf;
126
127 //dol_syslog(get_class($this)."::setDefaultLang srclang=".$srclang,LOG_DEBUG);
128
129 // If a module ask to force a priority on langs directories (to use its own lang files)
130 if (getDolGlobalString('MAIN_FORCELANGDIR')) {
131 $more = array();
132 $i = 0;
133 foreach ($conf->file->dol_document_root as $dir) {
134 $newdir = $dir . getDolGlobalString('MAIN_FORCELANGDIR'); // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
135 if (!in_array($newdir, $this->dir)) {
136 $more['module_' . $i] = $newdir;
137 $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
138 }
139 }
140 $this->dir = array_merge($more, $this->dir); // Forced dir ($more) are before standard dirs ($this->dir)
141 }
142
143 $this->origlang = $srclang;
144
145 if (empty($srclang) || $srclang == 'auto') {
146 // $_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
147 $langpref = empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? '' : $_SERVER['HTTP_ACCEPT_LANGUAGE'];
148 $langpref = preg_replace("/;([^,]*)/i", "", $langpref); // Remove the 'q=x.y,' part
149 $langpref = str_replace("-", "_", $langpref);
150 $langlist = preg_split("/[;,]/", $langpref);
151 $codetouse = preg_replace('/[^_a-zA-Z]/', '', $langlist[0]);
152 } else {
153 $codetouse = $srclang;
154 }
155
156 // We redefine $srclang
157 $langpart = explode("_", $codetouse);
158 //print "Short code before _ : ".$langpart[0].' / Short code after _ : '.$langpart[1].'<br>';
159 if (!empty($langpart[1])) { // If it's for a codetouse that is a long code xx_YY
160 // Array force long code from first part, even if long code is defined
161 $longforshort = array('ar' => 'ar_SA');
162 $longforshortexcep = array('ar_EG');
163 if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep)) {
164 $srclang = $longforshort[strtolower($langpart[0])];
165 } elseif (!is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser
166 $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[1]);
167 $longforlong = array('no_nb' => 'nb_NO');
168 if (isset($longforlong[strtolower($srclang)])) {
169 $srclang = $longforlong[strtolower($srclang)];
170 }
171 } else {
172 $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
173 }
174 } else { // If it's for a codetouse that is a short code xx
175 // Array to convert short lang code into long code.
176 $longforshort = array(
177 'am' => 'am_ET', 'ar' => 'ar_SA', 'bn' => 'bn_DB', 'el' => 'el_GR', 'ca' => 'ca_ES', 'cs' => 'cs_CZ', 'en' => 'en_US', 'fa' => 'fa_IR',
178 'gl' => 'gl_ES', 'he' => 'he_IL', 'hi' => 'hi_IN', 'ja' => 'ja_JP',
179 'ka' => 'ka_GE', 'km' => 'km_KH', 'kn' => 'kn_IN', 'ko' => 'ko_KR', 'lo' => 'lo_LA', 'nb' => 'nb_NO', 'no' => 'nb_NO', 'ne' => 'ne_NP',
180 'sl' => 'sl_SI', 'sq' => 'sq_AL', 'sr' => 'sr_RS', 'sv' => 'sv_SE', 'uk' => 'uk_UA', 'vi' => 'vi_VN', 'zh' => 'zh_CN'
181 );
182 if (isset($longforshort[strtolower($langpart[0])])) {
183 $srclang = $longforshort[strtolower($langpart[0])];
184 } elseif (!empty($langpart[0])) {
185 $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
186 } else {
187 $srclang = 'en_US';
188 }
189 }
190
191 $this->defaultlang = $srclang;
192 $this->shortlang = substr($srclang, 0, 2);
193 //print 'this->defaultlang='.$this->defaultlang;
194 }
195
196
204 public function getDefaultLang($mode = 0)
205 {
206 if (empty($mode)) {
207 return $this->defaultlang;
208 } else {
209 return substr($this->defaultlang, 0, 2);
210 }
211 }
212
213
220 public function loadLangs($domains)
221 {
222 $loaded = 0;
223 foreach ($domains as $domain) {
224 $result = $this->load($domain);
225 if ($result > 0) {
226 $loaded = $result;
227 } elseif ($result < 0) {
228 return $result;
229 }
230 }
231 return $loaded;
232 }
233
257 public function load($domain, $alt = 0, $stopafterdirection = 0, $forcelangdir = '', $loadfromfileonly = 0, $forceloadifalreadynotfound = 0, &$tabtranslatedomain = [], $langkey = '')
258 {
259 global $conf, $db;
260
261 //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
262
263 // Check parameters
264 if (empty($domain)) {
265 dol_print_error(null, get_class($this) . "::Load ErrorWrongParameters");
266 return -1;
267 }
268 if ($this->defaultlang === 'none_NONE') {
269 return 0; // Special language code to not translate keys
270 }
271
272
273 // Load $this->tab_translate[] from database
274 if (empty($loadfromfileonly) && count($this->tab_translate) == 0) {
275 $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database.
276 }
277
278
279 $newdomain = $domain;
280 $modulename = '';
281
282 // Search if a module directory name is provided into lang file name
283 $regs = array();
284 if (preg_match('/^([^@]+)@([^@]+)$/i', $domain, $regs)) {
285 $newdomain = (string) $regs[1];
286 $modulename = (string) $regs[2];
287 }
288
289 // Check cache
290 if (
291 !empty($this->_tab_loaded[$newdomain])
292 && ($this->_tab_loaded[$newdomain] != 2 || empty($forceloadifalreadynotfound))
293 ) { // File already loaded and found and not forced for this domain
294 //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
295 return 0;
296 }
297
298 $fileread = 0;
299 $langofdir = (empty($forcelangdir) ? $this->defaultlang : $forcelangdir);
300 $langkey = (empty($langkey) ? $langofdir : $langkey);
301
302 // Redefine alt
303 $langarray = explode('_', $langofdir);
304 if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) {
305 $alt = 1;
306 }
307 if ($alt < 2 && strtolower($langofdir) == 'en_us') {
308 $alt = 2;
309 }
310
311 if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
312 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);
313 return -1;
314 }
315
316 $usecachekey = '';
317 foreach ($this->dir as $searchdir) {
318 // Directory of translation files
319 $file_lang = $searchdir . ($modulename ? '/' . $modulename : '') . "/langs/" . $langofdir . "/" . $newdomain . ".lang";
320 $file_lang_osencoded = dol_osencode($file_lang);
321
322 //$filelangexists = is_file($file_lang_osencoded);
323 $filelangexists = @is_file($file_lang_osencoded); // avoid [php:warn]
324
325 //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);
326 //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";
327
328 if ($filelangexists) {
329 // TODO Move cache read out of loop on dirs or at least filelangexists
330 $found = false;
331
332 // Enable caching of lang file in memory (not by default)
333 $usecachekey = '';
334 // Using a memcached server
335 if (isModEnabled('memcached') && getDolGlobalString('MEMCACHED_SERVER')) {
336 $usecachekey = $newdomain . '_' . $langkey . '_' . md5($file_lang); // Should not contains special chars
337 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) {
338 // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
339 $usecachekey = $newdomain;
340 }
341
342 if ($usecachekey) {
343 //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
344 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
345 $tmparray = dol_getcache($usecachekey);
346 if (is_array($tmparray) && count($tmparray)) {
347 $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.
348 if ($alt == 2) {
349 $fileread = 1;
350 }
351 $found = true; // Found in dolibarr PHP cache
352 }
353 }
354
355 if (!$found) {
356 if ($fp = @fopen($file_lang, "rt")) {
357 // $tabtranslatedomain = array(); // To save lang content in cache when enabled (commented because initial = argument to function)
358
364 while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n\r]")) {
365 if (isset($line[1])) {
366 list($key, $value) = $line;
367 //if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."<br>";
368 //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>";
369 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)
370 if ($key == 'DIRECTION') { // This is to declare direction of language
371 if ($alt < 2 || empty($this->tab_translate[$key])) { // We load direction only for primary files or if not yet loaded
372 $this->tab_translate[$key] = $value;
373 if ($stopafterdirection) {
374 break; // We do not save tab if we stop after DIRECTION
375 } elseif ($usecachekey) {
376 $tabtranslatedomain[$key] = $value;
377 }
378 }
379 } elseif ($key[0] == '#') {
380 continue;
381 } else {
382 // Convert some strings: Parse and render carriage returns. Also, change '\\s' into '\s' because transifex sync pull the string '\s' into string '\\s'
383 $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
384 if ($usecachekey) {
385 $tabtranslatedomain[$key] = $value;
386 } // To save lang content in cache
387 }
388 }
389 }
390 }
391 fclose($fp);
392 $fileread = 1;
393
394 if (!getDolGlobalString('MAIN_FORCELANGDIR')) {
395 break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
396 }
397 }
398 }
399 }
400 }
401
402 // Now we complete with next file (fr_CA->fr_FR, es_MX->ex_ES, ...)
403 if ($alt == 0) {
404 // This function MUST NOT contains call to syslog
405 //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
406 $langofdir = strtolower($langarray[0]) . '_' . strtoupper($langarray[0]);
407 if ($langofdir == 'el_EL') {
408 $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR'
409 }
410 if ($langofdir == 'ar_AR') {
411 $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
412 }
413 $this->load($domain, $alt + 1, $stopafterdirection, $langofdir, 0, 0, $tabtranslatedomain, $langkey);
414 }
415
416 // Now we complete with reference file (en_US)
417 if ($alt == 1) {
418 // This function MUST NOT contains call to syslog
419 //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
420 $langofdir = 'en_US';
421 $this->load($domain, $alt + 1, $stopafterdirection, $langofdir, 0, 0, $tabtranslatedomain, $langkey);
422 }
423
424 // We are in the pass of the reference file. No more files to scan to complete.
425 if ($alt == 2) {
426 if ($fileread) {
427 $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded
428 }
429
430 if (empty($this->_tab_loaded[$newdomain])) {
431 $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
432 }
433 }
434
435 // This part is deprecated and replaced with table llx_overwrite_trans
436 // Kept for backward compatibility.
437 if (empty($loadfromfileonly)) {
438 $overwritekey = 'MAIN_OVERWRITE_TRANS_' . $this->defaultlang;
439 if (getDolGlobalString($overwritekey)) { // Overwrite translation with key1:newstring1,key2:newstring2
440 // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
441 $tmparray = explode(',', getDolGlobalString($overwritekey));
442 foreach ($tmparray as $tmp) {
443 $tmparray2 = explode(':', $tmp);
444 if (!empty($tmparray2[1])) {
445 $this->tab_translate[$tmparray2[0]] = $tmparray2[1];
446 }
447 }
448 }
449 }
450
451 // To save lang content for usecachekey into cache
452 if ($usecachekey && count($tabtranslatedomain)) {
453 $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
454 if ($ressetcache < 0) {
455 $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
456 dol_syslog($error, LOG_ERR);
457 }
458 }
459
460 // Check to be sure that SeparatorDecimal differs from SeparatorThousand
461 if (
462 !empty($this->tab_translate["SeparatorDecimal"]) && !empty($this->tab_translate["SeparatorThousand"])
463 && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]
464 ) {
465 $this->tab_translate["SeparatorThousand"] = '';
466 }
467
468 return 1;
469 }
470
483 public function loadFromDatabase($db)
484 {
485 global $conf;
486
487 $domain = 'database';
488
489 // Check parameters
490 if (empty($db)) {
491 return 0; // Database handler can't be used
492 }
493
494 //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
495
496 $newdomain = $domain;
497
498 // Check cache
499 if (!empty($this->_tab_loaded[$newdomain])) { // File already loaded for this domain 'database'
500 //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
501 return 0;
502 }
503
504 $this->_tab_loaded[$newdomain] = 2; // Preset the load as loaded and make sure this function is called once only for $newdomain='database'
505
506 $fileread = 0;
507 $langofdir = $this->defaultlang;
508
509 if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
510 dol_syslog("Error: " . get_class($this) . "::loadFromDatabase was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
511 return -1;
512 }
513
514 // TODO Move cache read out of loop on dirs or at least filelangexists
515 $found = false;
516
517 // Enable caching of lang file in memory (not by default)
518 $usecachekey = '';
519 // Using a memcached server
520 if (isModEnabled('memcached') && getDolGlobalString('MEMCACHED_SERVER')) {
521 $usecachekey = $newdomain . '_' . $langofdir; // Should not contains special chars
522 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) {
523 // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
524 $usecachekey = $newdomain;
525 }
526
527 if ($usecachekey) {
528 //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
529 //global $aaa; $aaa+=1;
530 //print $aaa." ".$usecachekey."\n";
531 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
532 $tmparray = dol_getcache($usecachekey);
533 if (is_array($tmparray) && count($tmparray)) {
534 $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.
535 //print $newdomain."\n";
536 //var_dump($this->tab_translate);
537 $fileread = 1;
538 $found = true; // Found in dolibarr PHP cache
539 }
540 }
541
542 if (!$found && getDolGlobalString('MAIN_ENABLE_OVERWRITE_TRANSLATION')) {
543 // Overwrite translation with database read
544 $sql = "SELECT transkey, transvalue FROM ".$db->prefix()."overwrite_trans where (lang='".$db->escape($this->defaultlang)."' OR lang IS NULL)";
545 $sql .= " AND entity IN (0, ".getEntity('overwrite_trans').")";
546 $sql .= $db->order("lang", "DESC");
547
548 $resql = $db->query($sql);
549
550 if ($resql) {
551 $num = $db->num_rows($resql);
552 if ($num) {
553 $tabtranslatedomain = array(); // To save lang content in cache (when enabled)
554
555 $i = 0;
556 while ($i < $num) { // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
557 $obj = $db->fetch_object($resql);
558
559 $key = $obj->transkey;
560 $value = $obj->transvalue;
561
562 //print "Domain=$domain, found a string for $tab[0] with value $tab[1]<br>";
563 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)
564 // Convert some strings: Parse and render carriage returns. Also, change '\\s' int '\s' because transifex sync pull the string '\s' into string '\\s'
565 $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
566
567 if ($usecachekey) {
568 $tabtranslatedomain[$key] = $value; // To save lang content in cache
569 }
570 }
571
572 $i++;
573 }
574
575 $fileread = 1;
576
577 // TODO Move cache write out of loop on dirs
578 // To save lang content for usecachekey into cache
579 if ($usecachekey && count($tabtranslatedomain)) {
580 $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
581 if ($ressetcache < 0) {
582 $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
583 dol_syslog($error, LOG_ERR);
584 }
585 }
586 }
587 } else {
588 dol_print_error($db);
589 }
590 }
591
592 if ($fileread) {
593 $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
594 }
595
596 return 1;
597 }
598
605 public function isLoaded($domain)
606 {
607 return $this->_tab_loaded[$domain];
608 }
609
621 private function getTradFromKey($key)
622 {
623 global $db;
624
625 if (!is_string($key)) {
626 //xdebug_print_function_stack('ErrorBadValueForParamNotAString');
627 return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly.
628 }
629
630 $newstr = $key;
631 $reg = array();
632 if (preg_match('/^Civility([0-9A-Z_]+)$/i', $key, $reg)) {
633 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label');
634 } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg)) {
635 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label');
636 } elseif (preg_match('/^SendingMethod([0-9A-Z_]+)$/i', $key, $reg)) {
637 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle');
638 } elseif (preg_match('/^PaymentType(?:Short)?([0-9A-Z_]+)$/i', $key, $reg)) {
639 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1);
640 } elseif (preg_match('/^OppStatus([0-9A-Z_]+)$/i', $key, $reg)) {
641 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label');
642 } elseif (preg_match('/^OrderSource([0-9A-Z_]+)$/i', $key, $reg)) {
643 // TODO OrderSourceX must be replaced with content of table llx_c_input_reason or llx_c_input_method
644 //$newstr=$this->getLabelFromKey($db,$reg[1],'llx_c_input_reason','code','label');
645 }
646
647 /* Disabled. There is too many cases where translation of $newstr is not defined is normal (like when output with setEventMessage an already translated string)
648 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2)
649 {
650 dol_syslog(__METHOD__." MAIN_FEATURES_LEVEL=DEVELOP: missing translation for key '".$newstr."' in ".$_SERVER["PHP_SELF"], LOG_DEBUG);
651 }*/
652
653 return $newstr;
654 }
655
656
670 public function trans($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $maxsize = 0)
671 {
672 if (!empty($this->tab_translate[$key])) { // Translation is available
673 $str = $this->tab_translate[$key];
674
675 // Make some string replacement after translation
676 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
677 if (getDolGlobalString($replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
678 $tmparray = explode(';', getDolGlobalString($replacekey));
679 foreach ($tmparray as $tmp) {
680 $tmparray2 = explode(':', $tmp);
681 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
682 }
683 }
684
685
686 $str = preg_replace('/([^%])%([^%0sdmYIMpHSBb])/', '\1__percent_with_bad_specifier__\2', $str);
687
688 if (strpos($key, 'Format') !== 0) {
689 try {
690 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
691 $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
692 // Note: the catch ValueError is possible only when php min will be 8.1
693 } catch (Exception $e) {
694 // No exception managed
695 }
696 }
697
698 $str = str_replace('__percent_with_bad_specifier__', '%', $str);
699
700
701 // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities because
702 // we want to keep '"' '<b>' '</b>' '<u>' '</u>' '<i>' '</i>' '<center> '</center>' '<strong' '</strong>' '<a ' '</a>' '<br>' '<span' '</span>' '< ' that are reliable HTML tags inside translation strings.
703 $str = str_replace(
704 array('"', '<b>', '</b>', '<u>', '</u>', '<i>', '</i>', '<center>', '</center>', '<strong>', '</strong>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'), // We accept '< ' but not '<'. We can accept however '>'
705 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__tagb__', '__tagbend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
706 $str
707 );
708
709 // Encode string into HTML
710 $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
711
712 // Restore reliable HTML tags into original translation string
713 $str = str_replace(
714 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
715 array('"', '<b>', '</b>', '<u>', '</u>', '<i>', '</i>', '<center>', '</center>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'),
716 $str
717 );
718
719 // Remove dangerous sequence we should never have. Not needed into a translated response.
720 // %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.
721 $str = str_replace(array('%27', '&#39'), '', $str);
722
723 if ($maxsize) {
724 $str = dol_trunc($str, $maxsize);
725 }
726
727 return $str;
728 } else { // Translation is not available
729 return $this->getTradFromKey($key);
730 }
731 }
732
733
748 public function transnoentities($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
749 {
750 return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5));
751 }
752
753
769 public function tr($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
770 {
771 return $this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5);
772 }
773
789 public function transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
790 {
791 if (!empty($this->tab_translate[$key])) { // Translation is available
792 $str = $this->tab_translate[$key];
793
794 // Make some string replacement after translation
795 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
796 if (getDolGlobalString($replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
797 $tmparray = explode(';', getDolGlobalString($replacekey));
798 foreach ($tmparray as $tmp) {
799 $tmparray2 = explode(':', $tmp);
800 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
801 }
802 }
803
804 $str = preg_replace('/([^%])%([^%0sdmYIMpHSBb])/', '\1__percent_with_bad_specifier__\2', $str);
805
806 if (!preg_match('/^Format/', $key)) {
807 try {
808 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
809 $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
810 // Note: the catch ValueError is possible only when php min will be 8.1
811 } catch (Exception $e) {
812 // No exception managed.
813 }
814 }
815
816 $str = str_replace('__percent_with_bad_specifier__', '%', $str);
817
818 // Remove dangerous sequence we should never have. Not needed into a translated response.
819 // %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.
820 $str = str_replace(array('%27', '&#39'), '', $str);
821
822 return $str;
823 } else {
824 return $this->getTradFromKey($key);
825 }
826 }
827
828
837 public function transcountry($str, $countrycode)
838 {
839 $strLocaleKey = $str.$countrycode;
840 if (!empty($this->tab_translate[$strLocaleKey])) {
841 return $this->trans($strLocaleKey);
842 } else {
843 return $this->trans($str);
844 }
845 }
846
847
856 public function transcountrynoentities($str, $countrycode)
857 {
858 $strLocaleKey = $str.$countrycode;
859 if (!empty($this->tab_translate[$strLocaleKey])) {
860 return $this->transnoentities($strLocaleKey);
861 } else {
862 return $this->transnoentities($str);
863 }
864 }
865
866
875 public function convToOutputCharset($str, $pagecodefrom = 'UTF-8', $pagecodeto = '')
876 {
877 if (empty($pagecodeto)) {
878 $pagecodeto = $this->charset_output;
879 }
880
881 if ($pagecodefrom == 'ISO-8859-1' && $pagecodeto == 'UTF-8') {
882 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
883 }
884 if ($pagecodefrom == 'UTF-8' && $pagecodeto == 'ISO-8859-1') {
885 $str = mb_convert_encoding(str_replace('€', chr(128), $str), 'ISO-8859-1');
886 // TODO Replace with iconv("UTF-8", "ISO-8859-1", str_replace('€', chr(128), $str)); ?
887 }
888 return $str;
889 }
890
891
892 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
902 public function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0, $mainlangonly = 0)
903 {
904 // phpcs:enable
905 $this->load("languages");
906
907 // We scan directory langs to detect available languages
908 $handle = opendir($langdir . "/langs");
909 $langs_available = array();
910 while ($dir = trim(readdir($handle))) {
911 $regs = array();
912 if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
913 // We must keep only main languages
914 if ($mainlangonly) {
915 $arrayofspecialmainlanguages = array(
916 'en' => 'en_US',
917 'am' => 'am_ET',
918 'ar' => 'ar_SA',
919 'bn' => 'bn_DB',
920 'bs' => 'bs_BA',
921 'ca' => 'ca_ES',
922 'cs' => 'cs_CZ',
923 'da' => 'da_DK',
924 'et' => 'et_EE',
925 'el' => 'el_GR',
926 'eu' => 'eu_ES',
927 'fa' => 'fa_IR',
928 'he' => 'he_IL',
929 'ka' => 'ka_GE',
930 'km' => 'km_KH',
931 'kn' => 'kn_IN',
932 'ko' => 'ko_KR',
933 'ja' => 'ja_JP',
934 'lo' => 'lo_LA',
935 'nb' => 'nb_NO',
936 'sq' => 'sq_AL',
937 'sr' => 'sr_RS',
938 'sv' => 'sv_SE',
939 'sl' => 'sl_SI',
940 'uk' => 'uk_UA',
941 'vi' => 'vi_VN',
942 'zh' => 'zh_CN'
943 );
944 if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
945 continue;
946 }
947 }
948 // We must keep only languages into MAIN_LANGUAGES_ALLOWED
949 if (getDolGlobalString('MAIN_LANGUAGES_ALLOWED') && !in_array($dir, explode(',', getDolGlobalString('MAIN_LANGUAGES_ALLOWED')))) {
950 continue;
951 }
952
953 if ($usecode == 2) {
954 $langs_available[$dir] = $dir;
955 }
956
957 if ($usecode == 1 || getDolGlobalString('MAIN_SHOW_LANGUAGE_CODE')) {
958 $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
959 } else {
960 $langs_available[$dir] = $this->trans('Language_' . $dir);
961 }
962 if ($mainlangonly) {
963 $langs_available[$dir] = str_replace(' (United States)', '', $langs_available[$dir]);
964 }
965 }
966 }
967 return $langs_available;
968 }
969
970
971 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
979 public function file_exists($filename, $searchalt = 0)
980 {
981 // phpcs:enable
982 // Test si fichier dans repertoire de la langue
983 foreach ($this->dir as $searchdir) {
984 if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename))) {
985 return true;
986 }
987
988 if ($searchalt) {
989 $filenamealt = null;
990 // Test si fichier dans repertoire de la langue alternative
991 if ($this->defaultlang != "en_US") {
992 $filenamealt = $searchdir . "/langs/en_US/" . $filename;
993 }
994 //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
995 if ($filenamealt !== null && is_readable(dol_osencode($filenamealt))) {
996 return true;
997 }
998 }
999 }
1000
1001 return false;
1002 }
1003
1004
1016 public function getLabelFromNumber($number, $isamount = '')
1017 {
1018 global $conf;
1019
1020 $newnumber = $number;
1021
1022 $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
1023 foreach ($dirsubstitutions as $reldir) {
1024 $dir = dol_buildpath($reldir, 0);
1025 $newdir = dol_osencode($dir);
1026
1027 // Check if directory exists
1028 if (!is_dir($newdir)) {
1029 continue; // We must not use dol_is_dir here, function may not be loaded
1030 }
1031
1032 $fonc = 'numberwords';
1033 if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
1034 include_once $newdir . '/functions_' . $fonc . '.lib.php';
1035 if (function_exists('numberwords_getLabelFromNumber')) {
1036 $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
1037 break;
1038 }
1039 }
1040 }
1041
1042 return $newnumber;
1043 }
1044
1045
1061 public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
1062 {
1063 // If key empty
1064 if ($key == '') {
1065 return '';
1066 }
1067 // Test should be useless because the 3 variables are never set from user input but we keep it in case of.
1068 if (preg_match('/[^0-9A-Z_]/i', $tablename) || preg_match('/[^0-9A-Z_]/i', $fieldkey) || preg_match('/[^0-9A-Z_]/i', $fieldlabel)) {
1069 $this->error = 'Bad value for parameter tablename, fieldkey or fieldlabel';
1070 return -1;
1071 }
1072
1073 //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
1074
1075 // Check if a translation is available (Note: this can call getTradFromKey that can call getLabelFromKey)
1076 $tmp = $this->transnoentitiesnoconv($key);
1077 if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
1078 return $tmp; // Found in language array
1079 }
1080
1081 // Check in cache
1082 if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
1083 return $this->cache_labels[$tablename][$key]; // Found in cache
1084 }
1085
1086 // Not found in loaded language file nor in cache. So we will take the label into database.
1087 $sql = "SELECT " . $fieldlabel . " as label";
1088 $sql .= " FROM " . $db->prefix() . $tablename;
1089 $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
1090 if ($filteronentity) {
1091 $sql .= " AND entity IN (" . getEntity($tablename) . ')';
1092 }
1093 dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
1094 $resql = $db->query($sql);
1095 if ($resql) {
1096 $obj = $db->fetch_object($resql);
1097 if ($obj) {
1098 $this->cache_labels[$tablename][$key] = (string) $obj->label;
1099 } else {
1100 $this->cache_labels[$tablename][$key] = $key;
1101 }
1102
1103 $db->free($resql);
1104 return $this->cache_labels[$tablename][$key];
1105 } else {
1106 $this->error = $db->lasterror();
1107 return -1;
1108 }
1109 }
1110
1111
1121 public function getCurrencyAmount($currency_code, $amount)
1122 {
1123 $symbol = $this->getCurrencySymbol($currency_code);
1124
1125 if (in_array($currency_code, array('USD'))) {
1126 return $symbol . $amount;
1127 } else {
1128 return $amount . $symbol;
1129 }
1130 }
1131
1140 public function getCurrencySymbol($currency_code, $forceloadall = 0)
1141 {
1142 $currency_sign = ''; // By default return iso code
1143
1144 if (function_exists("mb_convert_encoding")) {
1145 $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
1146
1147 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
1148 foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
1149 $currency_sign .= mb_convert_encoding("&#" . $unicode . ";", "UTF-8", 'HTML-ENTITIES');
1150 }
1151 }
1152 }
1153
1154 return ($currency_sign ? $currency_sign : $currency_code);
1155 }
1156
1163 public function loadCacheCurrencies($currency_code)
1164 {
1165 global $db;
1166
1167 if ($this->cache_currencies_all_loaded) {
1168 return 0; // Cache already loaded for all
1169 }
1170 if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
1171 return 0; // Cache already loaded for the currency
1172 }
1173
1174 $sql = "SELECT code_iso, label, unicode";
1175 $sql .= " FROM " . $db->prefix() . "c_currencies";
1176 $sql .= " WHERE active = 1";
1177 if (!empty($currency_code)) {
1178 $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
1179 }
1180 //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
1181
1182 dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
1183 $resql = $db->query($sql);
1184 if ($resql) {
1185 $this->load("dict");
1186 $label = array();
1187 if (!empty($currency_code)) {
1188 foreach ($this->cache_currencies as $key => $val) {
1189 $label[$key] = $val['label']; // Label in already loaded cache
1190 }
1191 }
1192
1193 $num = $db->num_rows($resql);
1194 $i = 0;
1195 while ($i < $num) {
1196 $obj = $db->fetch_object($resql);
1197 if ($obj) {
1198 // If a translation exists, we use it lese we use the default label
1199 $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 : ''));
1200 $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode((empty($obj->unicode) ? '' : $obj->unicode), true); // @phan-suppress-current-line PhanTypeMismatchProperty
1201 $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
1202 }
1203 $i++;
1204 }
1205 if (empty($currency_code)) {
1206 $this->cache_currencies_all_loaded = true;
1207 }
1208 //print count($label).' '.count($this->cache_currencies);
1209
1210 // Resort cache
1211 array_multisort($label, SORT_ASC, $this->cache_currencies);
1212 //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
1213 return $num;
1214 } else {
1215 dol_print_error($db);
1216 return -1;
1217 }
1218 }
1219
1220 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1228 {
1229 // phpcs:enable
1230 $substitutionarray = array();
1231
1232 foreach ($this->tab_translate as $code => $label) {
1233 $substitutionarray['lang_' . $code] = $label;
1234 $substitutionarray['__(' . $code . ')__'] = $label;
1235 }
1236
1237 return $substitutionarray;
1238 }
1239}
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.
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.
tr($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...
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
dol_setcache($memoryid, $data, $expire=0, $filecache=0)
Save data into a memory area shared by all users, all sessions on server.
dol_getcache($memoryid, $filecache=0)
Read a memory area shared by all users, all sessions on server.