dolibarr 21.0.0-beta
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 // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities because
686 // we want to keep '"' '<b>' '</b>' '<strong' '</strong>' '<a ' '</a>' '<br>' '< ' '<span' '</span>' that are reliable HTML tags inside translation strings.
687 $str = str_replace(
688 array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<strong>', '</strong>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'), // We accept '< ' but not '<'. We can accept however '>'
689 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__tagb__', '__tagbend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
690 $str
691 );
692
693 if (strpos($key, 'Format') !== 0) {
694 try {
695 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
696 $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
697 } catch (Exception $e) {
698 // No exception managed
699 }
700 }
701
702 // Encode string into HTML
703 $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
704
705 // Restore reliable HTML tags into original translation string
706 $str = str_replace(
707 array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
708 array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'),
709 $str
710 );
711
712 // Remove dangerous sequence we should never have. Not needed into a translated response.
713 // %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.
714 $str = str_replace(array('%27', '&#39'), '', $str);
715
716 if ($maxsize) {
717 $str = dol_trunc($str, $maxsize);
718 }
719
720 return $str;
721 } else { // Translation is not available
722 return $this->getTradFromKey($key);
723 }
724 }
725
726
741 public function transnoentities($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
742 {
743 return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5));
744 }
745
746
762 public function transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
763 {
764 global $conf;
765
766 if (!empty($this->tab_translate[$key])) { // Translation is available
767 $str = $this->tab_translate[$key];
768
769 // Make some string replacement after translation
770 $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
771 if (getDolGlobalString($replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
772 $tmparray = explode(';', getDolGlobalString($replacekey));
773 foreach ($tmparray as $tmp) {
774 $tmparray2 = explode(':', $tmp);
775 $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
776 }
777 }
778
779 if (!preg_match('/^Format/', $key)) {
780 //print $str;
781 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
782 $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
783 }
784
785 // Remove dangerous sequence we should never have. Not needed into a translated response.
786 // %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.
787 $str = str_replace(array('%27', '&#39'), '', $str);
788
789 return $str;
790 } else {
791 return $this->getTradFromKey($key);
792 }
793 }
794
795
804 public function transcountry($str, $countrycode)
805 {
806 $strLocaleKey = $str.$countrycode;
807 if (!empty($this->tab_translate[$strLocaleKey])) {
808 return $this->trans($strLocaleKey);
809 } else {
810 return $this->trans($str);
811 }
812 }
813
814
823 public function transcountrynoentities($str, $countrycode)
824 {
825 $strLocaleKey = $str.$countrycode;
826 if (!empty($this->tab_translate[$strLocaleKey])) {
827 return $this->transnoentities($strLocaleKey);
828 } else {
829 return $this->transnoentities($str);
830 }
831 }
832
833
842 public function convToOutputCharset($str, $pagecodefrom = 'UTF-8', $pagecodeto = '')
843 {
844 if (empty($pagecodeto)) {
845 $pagecodeto = $this->charset_output;
846 }
847
848 if ($pagecodefrom == 'ISO-8859-1' && $pagecodeto == 'UTF-8') {
849 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
850 }
851 if ($pagecodefrom == 'UTF-8' && $pagecodeto == 'ISO-8859-1') {
852 $str = mb_convert_encoding(str_replace('€', chr(128), $str), 'ISO-8859-1');
853 // TODO Replace with iconv("UTF-8", "ISO-8859-1", str_replace('€', chr(128), $str)); ?
854 }
855 return $str;
856 }
857
858
859 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
869 public function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0, $mainlangonly = 0)
870 {
871 // phpcs:enable
872 $this->load("languages");
873
874 // We scan directory langs to detect available languages
875 $handle = opendir($langdir . "/langs");
876 $langs_available = array();
877 while ($dir = trim(readdir($handle))) {
878 $regs = array();
879 if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
880 // We must keep only main languages
881 if ($mainlangonly) {
882 $arrayofspecialmainlanguages = array(
883 'en' => 'en_US',
884 'am' => 'am_ET',
885 'ar' => 'ar_SA',
886 'bn' => 'bn_DB',
887 'bs' => 'bs_BA',
888 'ca' => 'ca_ES',
889 'cs' => 'cs_CZ',
890 'da' => 'da_DK',
891 'et' => 'et_EE',
892 'el' => 'el_GR',
893 'eu' => 'eu_ES',
894 'fa' => 'fa_IR',
895 'he' => 'he_IL',
896 'ka' => 'ka_GE',
897 'km' => 'km_KH',
898 'kn' => 'kn_IN',
899 'ko' => 'ko_KR',
900 'ja' => 'ja_JP',
901 'lo' => 'lo_LA',
902 'nb' => 'nb_NO',
903 'sq' => 'sq_AL',
904 'sr' => 'sr_RS',
905 'sv' => 'sv_SE',
906 'sl' => 'sl_SI',
907 'uk' => 'uk_UA',
908 'vi' => 'vi_VN',
909 'zh' => 'zh_CN'
910 );
911 if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
912 continue;
913 }
914 }
915 // We must keep only languages into MAIN_LANGUAGES_ALLOWED
916 if (getDolGlobalString('MAIN_LANGUAGES_ALLOWED') && !in_array($dir, explode(',', getDolGlobalString('MAIN_LANGUAGES_ALLOWED')))) {
917 continue;
918 }
919
920 if ($usecode == 2) {
921 $langs_available[$dir] = $dir;
922 }
923
924 if ($usecode == 1 || getDolGlobalString('MAIN_SHOW_LANGUAGE_CODE')) {
925 $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
926 } else {
927 $langs_available[$dir] = $this->trans('Language_' . $dir);
928 }
929 if ($mainlangonly) {
930 $langs_available[$dir] = str_replace(' (United States)', '', $langs_available[$dir]);
931 }
932 }
933 }
934 return $langs_available;
935 }
936
937
938 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
946 public function file_exists($filename, $searchalt = 0)
947 {
948 // phpcs:enable
949 // Test si fichier dans repertoire de la langue
950 foreach ($this->dir as $searchdir) {
951 if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename))) {
952 return true;
953 }
954
955 if ($searchalt) {
956 $filenamealt = null;
957 // Test si fichier dans repertoire de la langue alternative
958 if ($this->defaultlang != "en_US") {
959 $filenamealt = $searchdir . "/langs/en_US/" . $filename;
960 }
961 //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
962 if ($filenamealt !== null && is_readable(dol_osencode($filenamealt))) {
963 return true;
964 }
965 }
966 }
967
968 return false;
969 }
970
971
983 public function getLabelFromNumber($number, $isamount = '')
984 {
985 global $conf;
986
987 $newnumber = $number;
988
989 $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
990 foreach ($dirsubstitutions as $reldir) {
991 $dir = dol_buildpath($reldir, 0);
992 $newdir = dol_osencode($dir);
993
994 // Check if directory exists
995 if (!is_dir($newdir)) {
996 continue; // We must not use dol_is_dir here, function may not be loaded
997 }
998
999 $fonc = 'numberwords';
1000 if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
1001 include_once $newdir . '/functions_' . $fonc . '.lib.php';
1002 if (function_exists('numberwords_getLabelFromNumber')) {
1003 $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
1004 break;
1005 }
1006 }
1007 }
1008
1009 return $newnumber;
1010 }
1011
1012
1028 public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
1029 {
1030 // If key empty
1031 if ($key == '') {
1032 return '';
1033 }
1034 // Test should be useless because the 3 variables are never set from user input but we keep it in case of.
1035 if (preg_match('/[^0-9A-Z_]/i', $tablename) || preg_match('/[^0-9A-Z_]/i', $fieldkey) || preg_match('/[^0-9A-Z_]/i', $fieldlabel)) {
1036 $this->error = 'Bad value for parameter tablename, fieldkey or fieldlabel';
1037 return -1;
1038 }
1039
1040 //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
1041
1042 // Check if a translation is available (Note: this can call getTradFromKey that can call getLabelFromKey)
1043 $tmp = $this->transnoentitiesnoconv($key);
1044 if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
1045 return $tmp; // Found in language array
1046 }
1047
1048 // Check in cache
1049 if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
1050 return $this->cache_labels[$tablename][$key]; // Found in cache
1051 }
1052
1053 // Not found in loaded language file nor in cache. So we will take the label into database.
1054 $sql = "SELECT " . $fieldlabel . " as label";
1055 $sql .= " FROM " . $db->prefix() . $tablename;
1056 $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
1057 if ($filteronentity) {
1058 $sql .= " AND entity IN (" . getEntity($tablename) . ')';
1059 }
1060 dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
1061 $resql = $db->query($sql);
1062 if ($resql) {
1063 $obj = $db->fetch_object($resql);
1064 if ($obj) {
1065 $this->cache_labels[$tablename][$key] = (string) $obj->label;
1066 } else {
1067 $this->cache_labels[$tablename][$key] = $key;
1068 }
1069
1070 $db->free($resql);
1071 return $this->cache_labels[$tablename][$key];
1072 } else {
1073 $this->error = $db->lasterror();
1074 return -1;
1075 }
1076 }
1077
1078
1088 public function getCurrencyAmount($currency_code, $amount)
1089 {
1090 $symbol = $this->getCurrencySymbol($currency_code);
1091
1092 if (in_array($currency_code, array('USD'))) {
1093 return $symbol . $amount;
1094 } else {
1095 return $amount . $symbol;
1096 }
1097 }
1098
1107 public function getCurrencySymbol($currency_code, $forceloadall = 0)
1108 {
1109 $currency_sign = ''; // By default return iso code
1110
1111 if (function_exists("mb_convert_encoding")) {
1112 $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
1113
1114 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
1115 foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
1116 $currency_sign .= mb_convert_encoding("&#" . $unicode . ";", "UTF-8", 'HTML-ENTITIES');
1117 }
1118 }
1119 }
1120
1121 return ($currency_sign ? $currency_sign : $currency_code);
1122 }
1123
1130 public function loadCacheCurrencies($currency_code)
1131 {
1132 global $db;
1133
1134 if ($this->cache_currencies_all_loaded) {
1135 return 0; // Cache already loaded for all
1136 }
1137 if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
1138 return 0; // Cache already loaded for the currency
1139 }
1140
1141 $sql = "SELECT code_iso, label, unicode";
1142 $sql .= " FROM " . $db->prefix() . "c_currencies";
1143 $sql .= " WHERE active = 1";
1144 if (!empty($currency_code)) {
1145 $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
1146 }
1147 //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
1148
1149 dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
1150 $resql = $db->query($sql);
1151 if ($resql) {
1152 $this->load("dict");
1153 $label = array();
1154 if (!empty($currency_code)) {
1155 foreach ($this->cache_currencies as $key => $val) {
1156 $label[$key] = $val['label']; // Label in already loaded cache
1157 }
1158 }
1159
1160 $num = $db->num_rows($resql);
1161 $i = 0;
1162 while ($i < $num) {
1163 $obj = $db->fetch_object($resql);
1164 if ($obj) {
1165 // If a translation exists, we use it lese we use the default label
1166 $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 : ''));
1167 $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode((empty($obj->unicode) ? '' : $obj->unicode), true); // @phan-suppress-current-line PhanTypeMismatchProperty
1168 $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
1169 }
1170 $i++;
1171 }
1172 if (empty($currency_code)) {
1173 $this->cache_currencies_all_loaded = true;
1174 }
1175 //print count($label).' '.count($this->cache_currencies);
1176
1177 // Resort cache
1178 array_multisort($label, SORT_ASC, $this->cache_currencies);
1179 //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
1180 return $num;
1181 } else {
1182 dol_print_error($db);
1183 return -1;
1184 }
1185 }
1186
1187 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1195 {
1196 // phpcs:enable
1197 $substitutionarray = array();
1198
1199 foreach ($this->tab_translate as $code => $label) {
1200 $substitutionarray['lang_' . $code] = $label;
1201 $substitutionarray['__(' . $code . ')__'] = $label;
1202 }
1203
1204 return $substitutionarray;
1205 }
1206}
Class to manage translations.
transnoentities($key, $param1='', $param2='', $param3='', $param4='', $param5='')
Return translated value of a text string If there is no match for this text, we look in alternative f...
transnoentitiesnoconv($key, $param1='', $param2='', $param3='', $param4='', $param5='')
Return translated value of a text string If there is no match for this text, we look in alternative f...
getTradFromKey($key)
Return translated value of key for special keys ("Currency...", "Civility...", ......
getLabelFromNumber($number, $isamount='')
Return full text translated to language label for a key.
getCurrencyAmount($currency_code, $amount)
Return a currency code into its symbol.
get_translations_for_substitutions()
Return an array with content of all loaded translation keys (found into this->tab_translate) so we ge...
getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect='', $filteronentity=0)
Return a label for a key.
load($domain, $alt=0, $stopafterdirection=0, $forcelangdir='', $loadfromfileonly=0, $forceloadifalreadynotfound=0, &$tabtranslatedomain=[], $langkey='')
Load translation key-value for a particular file, into a memory array.
get_available_languages($langdir=DOL_DOCUMENT_ROOT, $maxlength=0, $usecode=0, $mainlangonly=0)
Return list of all available languages.
loadCacheCurrencies($currency_code)
Load into the cache this->cache_currencies, all currencies.
convToOutputCharset($str, $pagecodefrom='UTF-8', $pagecodeto='')
Convert a string into output charset (this->charset_output that should be defined to conf->file->char...
setDefaultLang($srclang='en_US')
Set accessor for this->defaultlang.
file_exists($filename, $searchalt=0)
Return if a filename $filename exists for current language (or alternate language)
transcountry($str, $countrycode)
Return translation of a key depending on country.
isLoaded($domain)
Get information with result of loading data for domain.
trans($key, $param1='', $param2='', $param3='', $param4='', $maxsize=0)
Return text translated of text received as parameter (and encode it into HTML) If there is no match f...
transcountrynoentities($str, $countrycode)
Retourne la version traduite du texte passe en parameter complete du code pays.
getCurrencySymbol($currency_code, $forceloadall=0)
Return a currency code into its symbol.
loadLangs($domains)
Load translation files.
loadFromDatabase($db)
Load translation key-value from database into a memory array.
getDefaultLang($mode=0)
Return active language code for current user It's an accessor for this->defaultlang.
__construct($dir, $conf)
Constructor.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
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)
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.