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 = $regs[1];
285 $modulename = $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 if ($usecachekey) {
357 // $tabtranslatedomain = array(); // To save lang content in cache
358 }
359
365 while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n\r]")) {
366 if (isset($line[1])) {
367 list($key, $value) = $line;
368 //if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."<br>";
369 //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>";
370 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)
371 if ($key == 'DIRECTION') { // This is to declare direction of language
372 if ($alt < 2 || empty($this->tab_translate[$key])) { // We load direction only for primary files or if not yet loaded
373 $this->tab_translate[$key] = $value;
374 if ($stopafterdirection) {
375 break; // We do not save tab if we stop after DIRECTION
376 } elseif ($usecachekey) {
377 $tabtranslatedomain[$key] = $value;
378 }
379 }
380 } elseif ($key[0] == '#') {
381 continue;
382 } else {
383 // Convert some strings: Parse and render carriage returns. Also, change '\\s' into '\s' because transifex sync pull the string '\s' into string '\\s'
384 $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
385 if ($usecachekey) {
386 $tabtranslatedomain[$key] = $value;
387 } // To save lang content in cache
388 }
389 }
390 }
391 }
392 fclose($fp);
393 $fileread = 1;
394
395 if (!getDolGlobalString('MAIN_FORCELANGDIR')) {
396 break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
397 }
398 }
399 }
400 }
401 }
402
403 // Now we complete with next file (fr_CA->fr_FR, es_MX->ex_ES, ...)
404 if ($alt == 0) {
405 // This function MUST NOT contains call to syslog
406 //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
407 $langofdir = strtolower($langarray[0]) . '_' . strtoupper($langarray[0]);
408 if ($langofdir == 'el_EL') {
409 $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR'
410 }
411 if ($langofdir == 'ar_AR') {
412 $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
413 }
414 $this->load($domain, $alt + 1, $stopafterdirection, $langofdir, 0, 0, $tabtranslatedomain, $langkey);
415 }
416
417 // Now we complete with reference file (en_US)
418 if ($alt == 1) {
419 // This function MUST NOT contains call to syslog
420 //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
421 $langofdir = 'en_US';
422 $this->load($domain, $alt + 1, $stopafterdirection, $langofdir, 0, 0, $tabtranslatedomain, $langkey);
423 }
424
425 // We are in the pass of the reference file. No more files to scan to complete.
426 if ($alt == 2) {
427 if ($fileread) {
428 $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded
429 }
430
431 if (empty($this->_tab_loaded[$newdomain])) {
432 $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
433 }
434 }
435
436 // This part is deprecated and replaced with table llx_overwrite_trans
437 // Kept for backward compatibility.
438 if (empty($loadfromfileonly)) {
439 $overwritekey = 'MAIN_OVERWRITE_TRANS_' . $this->defaultlang;
440 if (getDolGlobalString($overwritekey)) { // Overwrite translation with key1:newstring1,key2:newstring2
441 // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
442 $tmparray = explode(',', getDolGlobalString($overwritekey));
443 foreach ($tmparray as $tmp) {
444 $tmparray2 = explode(':', $tmp);
445 if (!empty($tmparray2[1])) {
446 $this->tab_translate[$tmparray2[0]] = $tmparray2[1];
447 }
448 }
449 }
450 }
451
452 // To save lang content for usecachekey into cache
453 if ($usecachekey && count($tabtranslatedomain)) {
454 $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
455 if ($ressetcache < 0) {
456 $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
457 dol_syslog($error, LOG_ERR);
458 }
459 }
460
461 // Check to be sure that SeparatorDecimal differs from SeparatorThousand
462 if (
463 !empty($this->tab_translate["SeparatorDecimal"]) && !empty($this->tab_translate["SeparatorThousand"])
464 && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]
465 ) {
466 $this->tab_translate["SeparatorThousand"] = '';
467 }
468
469 return 1;
470 }
471
484 public function loadFromDatabase($db)
485 {
486 global $conf;
487
488 $domain = 'database';
489
490 // Check parameters
491 if (empty($db)) {
492 return 0; // Database handler can't be used
493 }
494
495 //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
496
497 $newdomain = $domain;
498
499 // Check cache
500 if (!empty($this->_tab_loaded[$newdomain])) { // File already loaded for this domain 'database'
501 //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
502 return 0;
503 }
504
505 $this->_tab_loaded[$newdomain] = 1; // We want to be sure this function is called once only for domain 'database'
506
507 $fileread = 0;
508 $langofdir = $this->defaultlang;
509
510 if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
511 dol_syslog("Error: " . get_class($this) . "::loadFromDatabase was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
512 return -1;
513 }
514
515 // TODO Move cache read out of loop on dirs or at least filelangexists
516 $found = false;
517
518 // Enable caching of lang file in memory (not by default)
519 $usecachekey = '';
520 // Using a memcached server
521 if (isModEnabled('memcached') && getDolGlobalString('MEMCACHED_SERVER')) {
522 $usecachekey = $newdomain . '_' . $langofdir; // Should not contains special chars
523 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) {
524 // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
525 $usecachekey = $newdomain;
526 }
527
528 if ($usecachekey) {
529 //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
530 //global $aaa; $aaa+=1;
531 //print $aaa." ".$usecachekey."\n";
532 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
533 $tmparray = dol_getcache($usecachekey);
534 if (is_array($tmparray) && count($tmparray)) {
535 $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.
536 //print $newdomain."\n";
537 //var_dump($this->tab_translate);
538 $fileread = 1;
539 $found = true; // Found in dolibarr PHP cache
540 }
541 }
542
543 if (!$found && getDolGlobalString('MAIN_ENABLE_OVERWRITE_TRANSLATION')) {
544 // Overwrite translation with database read
545 $sql = "SELECT transkey, transvalue FROM ".$db->prefix()."overwrite_trans where (lang='".$db->escape($this->defaultlang)."' OR lang IS NULL)";
546 $sql .= " AND entity IN (0, ".getEntity('overwrite_trans').")";
547 $sql .= $db->order("lang", "DESC");
548
549 $resql = $db->query($sql);
550
551 if ($resql) {
552 $num = $db->num_rows($resql);
553 if ($num) {
554 if ($usecachekey) {
555 $tabtranslatedomain = array(); // To save lang content in cache
556 }
557
558 $i = 0;
559 while ($i < $num) { // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
560 $obj = $db->fetch_object($resql);
561
562 $key = $obj->transkey;
563 $value = $obj->transvalue;
564
565 //print "Domain=$domain, found a string for $tab[0] with value $tab[1]<br>";
566 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)
567 // Convert some strings: Parse and render carriage returns. Also, change '\\s' int '\s' because transifex sync pull the string '\s' into string '\\s'
568 $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
569
570 if ($usecachekey) {
571 $tabtranslatedomain[$key] = $value; // To save lang content in cache
572 }
573 }
574
575 $i++;
576 }
577
578 $fileread = 1;
579
580 // TODO Move cache write out of loop on dirs
581 // To save lang content for usecachekey into cache
582 if ($usecachekey && count($tabtranslatedomain)) {
583 $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
584 if ($ressetcache < 0) {
585 $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
586 dol_syslog($error, LOG_ERR);
587 }
588 }
589 }
590 } else {
591 dol_print_error($db);
592 }
593 }
594
595 if ($fileread) {
596 $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
597 }
598
599 if (empty($this->_tab_loaded[$newdomain])) {
600 $this->_tab_loaded[$newdomain] = 2; // Mark this case as not found (no lines found for language)
601 }
602
603 return 1;
604 }
605
612 public function isLoaded($domain)
613 {
614 return $this->_tab_loaded[$domain];
615 }
616
628 private function getTradFromKey($key)
629 {
630 global $db;
631
632 if (!is_string($key)) {
633 //xdebug_print_function_stack('ErrorBadValueForParamNotAString');
634 return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly.
635 }
636
637 $newstr = $key;
638 $reg = array();
639 if (preg_match('/^Civility([0-9A-Z]+)$/i', $key, $reg)) {
640 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label');
641 } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg)) {
642 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label');
643 } elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i', $key, $reg)) {
644 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle');
645 } elseif (preg_match('/^PaymentType(?:Short)?([0-9A-Z]+)$/i', $key, $reg)) {
646 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1);
647 } elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i', $key, $reg)) {
648 $newstr = $this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label');
649 } elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i', $key, $reg)) {
650 // TODO OrderSourceX must be replaced with content of table llx_c_input_reason or llx_c_input_method
651 //$newstr=$this->getLabelFromKey($db,$reg[1],'llx_c_input_reason','code','label');
652 }
653
654 /* Disabled. There is too many cases where translation of $newstr is not defined is normal (like when output with setEventMessage an already translated string)
655 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2)
656 {
657 dol_syslog(__METHOD__." MAIN_FEATURES_LEVEL=DEVELOP: missing translation for key '".$newstr."' in ".$_SERVER["PHP_SELF"], LOG_DEBUG);
658 }*/
659
660 return $newstr;
661 }
662
663
677 public function trans($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $maxsize = 0)
678 {
679 if (!empty($this->tab_translate[$key])) { // Translation is available
680 $str = $this->tab_translate[$key];
681
682 // Make some string replacement after translation
683 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
684 if (getDolGlobalString($replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
685 $tmparray = explode(';', getDolGlobalString($replacekey));
686 foreach ($tmparray as $tmp) {
687 $tmparray2 = explode(':', $tmp);
688 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
689 }
690 }
691
692 // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities because
693 // we want to keep '"' '<b>' '</b>' '<strong' '</strong>' '<a ' '</a>' '<br>' '< ' '<span' '</span>' that are reliable HTML tags inside translation strings.
694 $str = str_replace(
695 array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<strong>', '</strong>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'), // We accept '< ' but not '<'. We can accept however '>'
696 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__tagb__', '__tagbend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
697 $str
698 );
699
700 if (strpos($key, 'Format') !== 0) {
701 try {
702 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
703 $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
704 } catch (Exception $e) {
705 // No exception managed
706 }
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 transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
770 {
771 global $conf;
772
773 if (!empty($this->tab_translate[$key])) { // Translation is available
774 $str = $this->tab_translate[$key];
775
776 // Make some string replacement after translation
777 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
778 if (getDolGlobalString($replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
779 $tmparray = explode(';', getDolGlobalString($replacekey));
780 foreach ($tmparray as $tmp) {
781 $tmparray2 = explode(':', $tmp);
782 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
783 }
784 }
785
786 if (!preg_match('/^Format/', $key)) {
787 //print $str;
788 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
789 $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
790 }
791
792 // Remove dangerous sequence we should never have. Not needed into a translated response.
793 // %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.
794 $str = str_replace(array('%27', '&#39'), '', $str);
795
796 return $str;
797 } else {
798 return $this->getTradFromKey($key);
799 }
800 }
801
802
811 public function transcountry($str, $countrycode)
812 {
813 $strLocaleKey = $str.$countrycode;
814 if (!empty($this->tab_translate[$strLocaleKey])) {
815 return $this->trans($strLocaleKey);
816 } else {
817 return $this->trans($str);
818 }
819 }
820
821
830 public function transcountrynoentities($str, $countrycode)
831 {
832 $strLocaleKey = $str.$countrycode;
833 if (!empty($this->tab_translate[$strLocaleKey])) {
834 return $this->transnoentities($strLocaleKey);
835 } else {
836 return $this->transnoentities($str);
837 }
838 }
839
840
848 public function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
849 {
850 if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') {
851 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
852 }
853 if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') {
854 $str = mb_convert_encoding(str_replace('€', chr(128), $str), 'ISO-8859-1');
855 // TODO Replace with iconv("UTF-8", "ISO-8859-1", str_replace('€', chr(128), $str)); ?
856 }
857 return $str;
858 }
859
860
861 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
871 public function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0, $mainlangonly = 0)
872 {
873 // phpcs:enable
874 global $conf;
875
876 $this->load("languages");
877
878 // We scan directory langs to detect available languages
879 $handle = opendir($langdir . "/langs");
880 $langs_available = array();
881 while ($dir = trim(readdir($handle))) {
882 $regs = array();
883 if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
884 // We must keep only main languages
885 if ($mainlangonly) {
886 $arrayofspecialmainlanguages = array(
887 'en' => 'en_US',
888 'am' => 'am_ET',
889 'ar' => 'ar_SA',
890 'bn' => 'bn_DB',
891 'bs' => 'bs_BA',
892 'ca' => 'ca_ES',
893 'cs' => 'cs_CZ',
894 'da' => 'da_DK',
895 'et' => 'et_EE',
896 'el' => 'el_GR',
897 'eu' => 'eu_ES',
898 'fa' => 'fa_IR',
899 'he' => 'he_IL',
900 'ka' => 'ka_GE',
901 'km' => 'km_KH',
902 'kn' => 'kn_IN',
903 'ko' => 'ko_KR',
904 'ja' => 'ja_JP',
905 'lo' => 'lo_LA',
906 'nb' => 'nb_NO',
907 'sq' => 'sq_AL',
908 'sr' => 'sr_RS',
909 'sv' => 'sv_SE',
910 'sl' => 'sl_SI',
911 'uk' => 'uk_UA',
912 'vi' => 'vi_VN',
913 'zh' => 'zh_CN'
914 );
915 if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
916 continue;
917 }
918 }
919 // We must keep only languages into MAIN_LANGUAGES_ALLOWED
920 if (getDolGlobalString('MAIN_LANGUAGES_ALLOWED') && !in_array($dir, explode(',', getDolGlobalString('MAIN_LANGUAGES_ALLOWED')))) {
921 continue;
922 }
923
924 if ($usecode == 2) {
925 $langs_available[$dir] = $dir;
926 }
927
928 if ($usecode == 1 || getDolGlobalString('MAIN_SHOW_LANGUAGE_CODE')) {
929 $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
930 } else {
931 $langs_available[$dir] = $this->trans('Language_' . $dir);
932 }
933 if ($mainlangonly) {
934 $langs_available[$dir] = str_replace(' (United States)', '', $langs_available[$dir]);
935 }
936 }
937 }
938 return $langs_available;
939 }
940
941
942 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
950 public function file_exists($filename, $searchalt = 0)
951 {
952 // phpcs:enable
953 // Test si fichier dans repertoire de la langue
954 foreach ($this->dir as $searchdir) {
955 if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename))) {
956 return true;
957 }
958
959 if ($searchalt) {
960 // Test si fichier dans repertoire de la langue alternative
961 if ($this->defaultlang != "en_US") {
962 $filenamealt = $searchdir . "/langs/en_US/" . $filename;
963 }
964 //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
965 if (is_readable(dol_osencode($filenamealt))) {
966 return true;
967 }
968 }
969 }
970
971 return false;
972 }
973
974
986 public function getLabelFromNumber($number, $isamount = '')
987 {
988 global $conf;
989
990 $newnumber = $number;
991
992 $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
993 foreach ($dirsubstitutions as $reldir) {
994 $dir = dol_buildpath($reldir, 0);
995 $newdir = dol_osencode($dir);
996
997 // Check if directory exists
998 if (!is_dir($newdir)) {
999 continue; // We must not use dol_is_dir here, function may not be loaded
1000 }
1001
1002 $fonc = 'numberwords';
1003 if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
1004 include_once $newdir . '/functions_' . $fonc . '.lib.php';
1005 if (function_exists('numberwords_getLabelFromNumber')) {
1006 $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
1007 break;
1008 }
1009 }
1010 }
1011
1012 return $newnumber;
1013 }
1014
1015
1031 public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
1032 {
1033 // If key empty
1034 if ($key == '') {
1035 return '';
1036 }
1037 // Test should be useless because the 3 variables are never set from user input but we keep it in case of.
1038 if (preg_match('/[^0-9A-Z_]/i', $tablename) || preg_match('/[^0-9A-Z_]/i', $fieldkey) || preg_match('/[^0-9A-Z_]/i', $fieldlabel)) {
1039 $this->error = 'Bad value for parameter tablename, fieldkey or fieldlabel';
1040 return -1;
1041 }
1042
1043 //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
1044
1045 // Check if a translation is available (Note: this can call getTradFromKey that can call getLabelFromKey)
1046 $tmp = $this->transnoentitiesnoconv($key);
1047 if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
1048 return $tmp; // Found in language array
1049 }
1050
1051 // Check in cache
1052 if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
1053 return $this->cache_labels[$tablename][$key]; // Found in cache
1054 }
1055
1056 // Not found in loaded language file nor in cache. So we will take the label into database.
1057 $sql = "SELECT " . $fieldlabel . " as label";
1058 $sql .= " FROM " . $db->prefix() . $tablename;
1059 $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
1060 if ($filteronentity) {
1061 $sql .= " AND entity IN (" . getEntity($tablename) . ')';
1062 }
1063 dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
1064 $resql = $db->query($sql);
1065 if ($resql) {
1066 $obj = $db->fetch_object($resql);
1067 if ($obj) {
1068 $this->cache_labels[$tablename][$key] = $obj->label;
1069 } else {
1070 $this->cache_labels[$tablename][$key] = $key;
1071 }
1072
1073 $db->free($resql);
1074 return $this->cache_labels[$tablename][$key];
1075 } else {
1076 $this->error = $db->lasterror();
1077 return -1;
1078 }
1079 }
1080
1081
1091 public function getCurrencyAmount($currency_code, $amount)
1092 {
1093 $symbol = $this->getCurrencySymbol($currency_code);
1094
1095 if (in_array($currency_code, array('USD'))) {
1096 return $symbol . $amount;
1097 } else {
1098 return $amount . $symbol;
1099 }
1100 }
1101
1110 public function getCurrencySymbol($currency_code, $forceloadall = 0)
1111 {
1112 $currency_sign = ''; // By default return iso code
1113
1114 if (function_exists("mb_convert_encoding")) {
1115 $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
1116
1117 if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) {
1118 foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
1119 $currency_sign .= mb_convert_encoding("&#" . $unicode . ";", "UTF-8", 'HTML-ENTITIES');
1120 }
1121 }
1122 }
1123
1124 return ($currency_sign ? $currency_sign : $currency_code);
1125 }
1126
1133 public function loadCacheCurrencies($currency_code)
1134 {
1135 global $db;
1136
1137 if ($this->cache_currencies_all_loaded) {
1138 return 0; // Cache already loaded for all
1139 }
1140 if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
1141 return 0; // Cache already loaded for the currency
1142 }
1143
1144 $sql = "SELECT code_iso, label, unicode";
1145 $sql .= " FROM " . $db->prefix() . "c_currencies";
1146 $sql .= " WHERE active = 1";
1147 if (!empty($currency_code)) {
1148 $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
1149 }
1150 //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
1151
1152 dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
1153 $resql = $db->query($sql);
1154 if ($resql) {
1155 $this->load("dict");
1156 $label = array();
1157 if (!empty($currency_code)) {
1158 foreach ($this->cache_currencies as $key => $val) {
1159 $label[$key] = $val['label']; // Label in already loaded cache
1160 }
1161 }
1162
1163 $num = $db->num_rows($resql);
1164 $i = 0;
1165 while ($i < $num) {
1166 $obj = $db->fetch_object($resql);
1167 if ($obj) {
1168 // If a translation exists, we use it lese we use the default label
1169 $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 : ''));
1170 $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode((empty($obj->unicode) ? '' : $obj->unicode), true);
1171 $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
1172 }
1173 $i++;
1174 }
1175 if (empty($currency_code)) {
1176 $this->cache_currencies_all_loaded = true;
1177 }
1178 //print count($label).' '.count($this->cache_currencies);
1179
1180 // Resort cache
1181 array_multisort($label, SORT_ASC, $this->cache_currencies);
1182 //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
1183 return $num;
1184 } else {
1185 dol_print_error($db);
1186 return -1;
1187 }
1188 }
1189
1190 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1198 {
1199 // phpcs:enable
1200 $substitutionarray = array();
1201
1202 foreach ($this->tab_translate as $code => $label) {
1203 $substitutionarray['lang_' . $code] = $label;
1204 $substitutionarray['__(' . $code . ')__'] = $label;
1205 }
1206
1207 return $substitutionarray;
1208 }
1209}
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.
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.
convToOutputCharset($str, $pagecodefrom='UTF-8')
Convert a string into output charset (this->charset_output that should be defined to conf->file->char...
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 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.