dolibarr 20.0.0
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 (!empty($conf->global->$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 global $conf;
680
681 if (!empty($this->tab_translate[$key])) { // Translation is available
682 $str = $this->tab_translate[$key];
683
684 // Make some string replacement after translation
685 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
686 if (!empty($conf->global->$replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
687 $tmparray = explode(';', getDolGlobalString($replacekey));
688 foreach ($tmparray as $tmp) {
689 $tmparray2 = explode(':', $tmp);
690 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
691 }
692 }
693
694 // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities because
695 // we want to keep '"' '<b>' '</b>' '<strong' '</strong>' '<a ' '</a>' '<br>' '< ' '<span' '</span>' that are reliable HTML tags inside translation strings.
696 $str = str_replace(
697 array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<strong>', '</strong>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'), // We accept '< ' but not '<'. We can accept however '>'
698 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__tagb__', '__tagbend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
699 $str
700 );
701
702 if (strpos($key, 'Format') !== 0) {
703 try {
704 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
705 $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
706 } catch (Exception $e) {
707 // No exception managed
708 }
709 }
710
711 // Encode string into HTML
712 $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
713
714 // Restore reliable HTML tags into original translation string
715 $str = str_replace(
716 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
717 array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'),
718 $str
719 );
720
721 // Remove dangerous sequence we should never have. Not needed into a translated response.
722 // %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.
723 $str = str_replace(array('%27', '&#39'), '', $str);
724
725 if ($maxsize) {
726 $str = dol_trunc($str, $maxsize);
727 }
728
729 return $str;
730 } else { // Translation is not available
731 return $this->getTradFromKey($key);
732 }
733 }
734
735
750 public function transnoentities($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
751 {
752 return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5));
753 }
754
755
771 public function transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
772 {
773 global $conf;
774
775 if (!empty($this->tab_translate[$key])) { // Translation is available
776 $str = $this->tab_translate[$key];
777
778 // Make some string replacement after translation
779 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
780 if (!empty($conf->global->$replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
781 $tmparray = explode(';', getDolGlobalString($replacekey));
782 foreach ($tmparray as $tmp) {
783 $tmparray2 = explode(':', $tmp);
784 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
785 }
786 }
787
788 if (!preg_match('/^Format/', $key)) {
789 //print $str;
790 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
791 $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
792 }
793
794 // Remove dangerous sequence we should never have. Not needed into a translated response.
795 // %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.
796 $str = str_replace(array('%27', '&#39'), '', $str);
797
798 return $str;
799 } else {
800 return $this->getTradFromKey($key);
801 }
802 }
803
804
813 public function transcountry($str, $countrycode)
814 {
815 $strLocaleKey = $str.$countrycode;
816 if (!empty($this->tab_translate[$strLocaleKey])) {
817 return $this->trans($strLocaleKey);
818 } else {
819 return $this->trans($str);
820 }
821 }
822
823
832 public function transcountrynoentities($str, $countrycode)
833 {
834 $strLocaleKey = $str.$countrycode;
835 if (!empty($this->tab_translate[$strLocaleKey])) {
836 return $this->transnoentities($strLocaleKey);
837 } else {
838 return $this->transnoentities($str);
839 }
840 }
841
842
850 public function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
851 {
852 if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') {
853 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
854 }
855 if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') {
856 $str = mb_convert_encoding(str_replace('€', chr(128), $str), 'ISO-8859-1');
857 // TODO Replace with iconv("UTF-8", "ISO-8859-1", str_replace('€', chr(128), $str)); ?
858 }
859 return $str;
860 }
861
862
863 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
873 public function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0, $mainlangonly = 0)
874 {
875 // phpcs:enable
876 global $conf;
877
878 $this->load("languages");
879
880 // We scan directory langs to detect available languages
881 $handle = opendir($langdir . "/langs");
882 $langs_available = array();
883 while ($dir = trim(readdir($handle))) {
884 $regs = array();
885 if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
886 // We must keep only main languages
887 if ($mainlangonly) {
888 $arrayofspecialmainlanguages = array(
889 'en' => 'en_US',
890 'am' => 'am_ET',
891 'ar' => 'ar_SA',
892 'bn' => 'bn_DB',
893 'bs' => 'bs_BA',
894 'ca' => 'ca_ES',
895 'cs' => 'cs_CZ',
896 'da' => 'da_DK',
897 'et' => 'et_EE',
898 'el' => 'el_GR',
899 'eu' => 'eu_ES',
900 'fa' => 'fa_IR',
901 'he' => 'he_IL',
902 'ka' => 'ka_GE',
903 'km' => 'km_KH',
904 'kn' => 'kn_IN',
905 'ko' => 'ko_KR',
906 'ja' => 'ja_JP',
907 'lo' => 'lo_LA',
908 'nb' => 'nb_NO',
909 'sq' => 'sq_AL',
910 'sr' => 'sr_RS',
911 'sv' => 'sv_SE',
912 'sl' => 'sl_SI',
913 'uk' => 'uk_UA',
914 'vi' => 'vi_VN',
915 'zh' => 'zh_CN'
916 );
917 if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
918 continue;
919 }
920 }
921 // We must keep only languages into MAIN_LANGUAGES_ALLOWED
922 if (getDolGlobalString('MAIN_LANGUAGES_ALLOWED') && !in_array($dir, explode(',', getDolGlobalString('MAIN_LANGUAGES_ALLOWED')))) {
923 continue;
924 }
925
926 if ($usecode == 2) {
927 $langs_available[$dir] = $dir;
928 }
929
930 if ($usecode == 1 || getDolGlobalString('MAIN_SHOW_LANGUAGE_CODE')) {
931 $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
932 } else {
933 $langs_available[$dir] = $this->trans('Language_' . $dir);
934 }
935 if ($mainlangonly) {
936 $langs_available[$dir] = str_replace(' (United States)', '', $langs_available[$dir]);
937 }
938 }
939 }
940 return $langs_available;
941 }
942
943
944 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
952 public function file_exists($filename, $searchalt = 0)
953 {
954 // phpcs:enable
955 // Test si fichier dans repertoire de la langue
956 foreach ($this->dir as $searchdir) {
957 if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename))) {
958 return true;
959 }
960
961 if ($searchalt) {
962 // Test si fichier dans repertoire de la langue alternative
963 if ($this->defaultlang != "en_US") {
964 $filenamealt = $searchdir . "/langs/en_US/" . $filename;
965 }
966 //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
967 if (is_readable(dol_osencode($filenamealt))) {
968 return true;
969 }
970 }
971 }
972
973 return false;
974 }
975
976
988 public function getLabelFromNumber($number, $isamount = '')
989 {
990 global $conf;
991
992 $newnumber = $number;
993
994 $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
995 foreach ($dirsubstitutions as $reldir) {
996 $dir = dol_buildpath($reldir, 0);
997 $newdir = dol_osencode($dir);
998
999 // Check if directory exists
1000 if (!is_dir($newdir)) {
1001 continue; // We must not use dol_is_dir here, function may not be loaded
1002 }
1003
1004 $fonc = 'numberwords';
1005 if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
1006 include_once $newdir . '/functions_' . $fonc . '.lib.php';
1007 if (function_exists('numberwords_getLabelFromNumber')) {
1008 $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
1009 break;
1010 }
1011 }
1012 }
1013
1014 return $newnumber;
1015 }
1016
1017
1033 public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
1034 {
1035 // If key empty
1036 if ($key == '') {
1037 return '';
1038 }
1039 // Test should be useless because the 3 variables are never set from user input but we keep it in case of.
1040 if (preg_match('/[^0-9A-Z_]/i', $tablename) || preg_match('/[^0-9A-Z_]/i', $fieldkey) || preg_match('/[^0-9A-Z_]/i', $fieldlabel)) {
1041 $this->error = 'Bad value for parameter tablename, fieldkey or fieldlabel';
1042 return -1;
1043 }
1044
1045 //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
1046
1047 // Check if a translation is available (Note: this can call getTradFromKey that can call getLabelFromKey)
1048 $tmp = $this->transnoentitiesnoconv($key);
1049 if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
1050 return $tmp; // Found in language array
1051 }
1052
1053 // Check in cache
1054 if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
1055 return $this->cache_labels[$tablename][$key]; // Found in cache
1056 }
1057
1058 // Not found in loaded language file nor in cache. So we will take the label into database.
1059 $sql = "SELECT " . $fieldlabel . " as label";
1060 $sql .= " FROM " . $db->prefix() . $tablename;
1061 $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
1062 if ($filteronentity) {
1063 $sql .= " AND entity IN (" . getEntity($tablename) . ')';
1064 }
1065 dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
1066 $resql = $db->query($sql);
1067 if ($resql) {
1068 $obj = $db->fetch_object($resql);
1069 if ($obj) {
1070 $this->cache_labels[$tablename][$key] = $obj->label;
1071 } else {
1072 $this->cache_labels[$tablename][$key] = $key;
1073 }
1074
1075 $db->free($resql);
1076 return $this->cache_labels[$tablename][$key];
1077 } else {
1078 $this->error = $db->lasterror();
1079 return -1;
1080 }
1081 }
1082
1083
1093 public function getCurrencyAmount($currency_code, $amount)
1094 {
1095 $symbol = $this->getCurrencySymbol($currency_code);
1096
1097 if (in_array($currency_code, array('USD'))) {
1098 return $symbol . $amount;
1099 } else {
1100 return $amount . $symbol;
1101 }
1102 }
1103
1112 public function getCurrencySymbol($currency_code, $forceloadall = 0)
1113 {
1114 $currency_sign = ''; // By default return iso code
1115
1116 if (function_exists("mb_convert_encoding")) {
1117 $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
1118
1119 if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) {
1120 foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
1121 $currency_sign .= mb_convert_encoding("&#" . $unicode . ";", "UTF-8", 'HTML-ENTITIES');
1122 }
1123 }
1124 }
1125
1126 return ($currency_sign ? $currency_sign : $currency_code);
1127 }
1128
1135 public function loadCacheCurrencies($currency_code)
1136 {
1137 global $db;
1138
1139 if ($this->cache_currencies_all_loaded) {
1140 return 0; // Cache already loaded for all
1141 }
1142 if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
1143 return 0; // Cache already loaded for the currency
1144 }
1145
1146 $sql = "SELECT code_iso, label, unicode";
1147 $sql .= " FROM " . $db->prefix() . "c_currencies";
1148 $sql .= " WHERE active = 1";
1149 if (!empty($currency_code)) {
1150 $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
1151 }
1152 //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
1153
1154 dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
1155 $resql = $db->query($sql);
1156 if ($resql) {
1157 $this->load("dict");
1158 $label = array();
1159 if (!empty($currency_code)) {
1160 foreach ($this->cache_currencies as $key => $val) {
1161 $label[$key] = $val['label']; // Label in already loaded cache
1162 }
1163 }
1164
1165 $num = $db->num_rows($resql);
1166 $i = 0;
1167 while ($i < $num) {
1168 $obj = $db->fetch_object($resql);
1169 if ($obj) {
1170 // If a translation exists, we use it lese we use the default label
1171 $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 : ''));
1172 $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode((empty($obj->unicode) ? '' : $obj->unicode), true);
1173 $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
1174 }
1175 $i++;
1176 }
1177 if (empty($currency_code)) {
1178 $this->cache_currencies_all_loaded = true;
1179 }
1180 //print count($label).' '.count($this->cache_currencies);
1181
1182 // Resort cache
1183 array_multisort($label, SORT_ASC, $this->cache_currencies);
1184 //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
1185 return $num;
1186 } else {
1187 dol_print_error($db);
1188 return -1;
1189 }
1190 }
1191
1192 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1200 {
1201 // phpcs:enable
1202 $substitutionarray = array();
1203
1204 foreach ($this->tab_translate as $code => $label) {
1205 $substitutionarray['lang_' . $code] = $label;
1206 $substitutionarray['__(' . $code . ')__'] = $label;
1207 }
1208
1209 return $substitutionarray;
1210 }
1211}
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.