dolibarr  18.0.6
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  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <https://www.gnu.org/licenses/>.
18  */
19 
30 class Translate
31 {
32  public $dir; // Directories that contains /langs subdirectory
33 
34  public $defaultlang; // Current language for current user
35  public $shortlang; // Short language for current user
36  public $charset_output = 'UTF-8'; // Codage used by "trans" method outputs
37 
38  public $tab_translate = array(); // Array of all translations key=>value
39  private $_tab_loaded = array(); // Array to store result after loading each language file
40 
41  public $cache_labels = array(); // Cache for labels return by getLabelFromKey method
42  public $cache_currencies = array(); // Cache to store currency symbols
43  private $cache_currencies_all_loaded = false;
44  public $origlang;
45  public $error;
46  public $errors = array();
47 
48 
55  public function __construct($dir, $conf)
56  {
57  if (!empty($conf->file->character_set_client)) {
58  $this->charset_output = $conf->file->character_set_client; // If charset output is forced
59  }
60  if ($dir) {
61  $this->dir = array($dir);
62  } else {
63  $this->dir = $conf->file->dol_document_root;
64  }
65  }
66 
67 
74  public function setDefaultLang($srclang = 'en_US')
75  {
76  global $conf;
77 
78  //dol_syslog(get_class($this)."::setDefaultLang srclang=".$srclang,LOG_DEBUG);
79 
80  // If a module ask to force a priority on langs directories (to use its own lang files)
81  if (!empty($conf->global->MAIN_FORCELANGDIR)) {
82  $more = array();
83  $i = 0;
84  foreach ($conf->file->dol_document_root as $dir) {
85  $newdir = $dir . $conf->global->MAIN_FORCELANGDIR; // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
86  if (!in_array($newdir, $this->dir)) {
87  $more['module_' . $i] = $newdir;
88  $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
89  }
90  }
91  $this->dir = array_merge($more, $this->dir); // Forced dir ($more) are before standard dirs ($this->dir)
92  }
93 
94  $this->origlang = $srclang;
95 
96  if (empty($srclang) || $srclang == 'auto') {
97  // $_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
98  $langpref = empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? '' : $_SERVER['HTTP_ACCEPT_LANGUAGE'];
99  $langpref = preg_replace("/;([^,]*)/i", "", $langpref); // Remove the 'q=x.y,' part
100  $langpref = str_replace("-", "_", $langpref);
101  $langlist = preg_split("/[;,]/", $langpref);
102  $codetouse = preg_replace('/[^_a-zA-Z]/', '', $langlist[0]);
103  } else {
104  $codetouse = $srclang;
105  }
106 
107  // We redefine $srclang
108  $langpart = explode("_", $codetouse);
109  //print "Short code before _ : ".$langpart[0].' / Short code after _ : '.$langpart[1].'<br>';
110  if (!empty($langpart[1])) { // If it's for a codetouse that is a long code xx_YY
111  // Array force long code from first part, even if long code is defined
112  $longforshort = array('ar' => 'ar_SA');
113  $longforshortexcep = array('ar_EG');
114  if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep)) {
115  $srclang = $longforshort[strtolower($langpart[0])];
116  } elseif (!is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser
117  $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[1]);
118  $longforlong = array('no_nb' => 'nb_NO');
119  if (isset($longforlong[strtolower($srclang)])) {
120  $srclang = $longforlong[strtolower($srclang)];
121  }
122  } else {
123  $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
124  }
125  } else { // If it's for a codetouse that is a short code xx
126  // Array to convert short lang code into long code.
127  $longforshort = array(
128  'am' => 'am_ET', 'ar' => 'ar_SA', 'bn' => 'bn_DB', 'el' => 'el_GR', 'ca' => 'ca_ES', 'cs' => 'cs_CZ', 'en' => 'en_US', 'fa' => 'fa_IR',
129  'gl' => 'gl_ES', 'he' => 'he_IL', 'hi' => 'hi_IN', 'ja' => 'ja_JP',
130  'ka' => 'ka_GE', 'km' => 'km_KH', 'kn' => 'kn_IN', 'ko' => 'ko_KR', 'lo' => 'lo_LA', 'nb' => 'nb_NO', 'no' => 'nb_NO', 'ne' => 'ne_NP',
131  'sl' => 'sl_SI', 'sq' => 'sq_AL', 'sr' => 'sr_RS', 'sv' => 'sv_SE', 'uk' => 'uk_UA', 'vi' => 'vi_VN', 'zh' => 'zh_CN'
132  );
133  if (isset($longforshort[strtolower($langpart[0])])) {
134  $srclang = $longforshort[strtolower($langpart[0])];
135  } elseif (!empty($langpart[0])) {
136  $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
137  } else {
138  $srclang = 'en_US';
139  }
140  }
141 
142  $this->defaultlang = $srclang;
143  $this->shortlang = substr($srclang, 0, 2);
144  //print 'this->defaultlang='.$this->defaultlang;
145  }
146 
147 
155  public function getDefaultLang($mode = 0)
156  {
157  if (empty($mode)) {
158  return $this->defaultlang;
159  } else {
160  return substr($this->defaultlang, 0, 2);
161  }
162  }
163 
164 
171  public function loadLangs($domains)
172  {
173  $loaded = 0;
174  foreach ($domains as $domain) {
175  $result = $this->load($domain);
176  if ($result > 0) {
177  $loaded = $result;
178  } elseif ($result < 0) {
179  return $result;
180  }
181  }
182  return $loaded;
183  }
184 
206  public function load($domain, $alt = 0, $stopafterdirection = 0, $forcelangdir = '', $loadfromfileonly = 0, $forceloadifalreadynotfound = 0)
207  {
208  global $conf, $db;
209 
210  //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
211 
212  // Check parameters
213  if (empty($domain)) {
214  dol_print_error('', get_class($this) . "::Load ErrorWrongParameters");
215  return -1;
216  }
217  if ($this->defaultlang === 'none_NONE') {
218  return 0; // Special language code to not translate keys
219  }
220 
221 
222  // Load $this->tab_translate[] from database
223  if (empty($loadfromfileonly) && count($this->tab_translate) == 0) {
224  $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database.
225  }
226 
227 
228  $newdomain = $domain;
229  $modulename = '';
230 
231  // Search if a module directory name is provided into lang file name
232  $regs = array();
233  if (preg_match('/^([^@]+)@([^@]+)$/i', $domain, $regs)) {
234  $newdomain = $regs[1];
235  $modulename = $regs[2];
236  }
237 
238  // Check cache
239  if (
240  !empty($this->_tab_loaded[$newdomain])
241  && ($this->_tab_loaded[$newdomain] != 2 || empty($forceloadifalreadynotfound))
242  ) { // File already loaded and found and not forced for this domain
243  //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
244  return 0;
245  }
246 
247  $fileread = 0;
248  $langofdir = (empty($forcelangdir) ? $this->defaultlang : $forcelangdir);
249 
250  // Redefine alt
251  $langarray = explode('_', $langofdir);
252  if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) {
253  $alt = 1;
254  }
255  if ($alt < 2 && strtolower($langofdir) == 'en_us') {
256  $alt = 2;
257  }
258 
259  if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
260  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);
261  return -1;
262  }
263 
264  foreach ($this->dir as $searchdir) {
265  // Directory of translation files
266  $file_lang = $searchdir . ($modulename ? '/' . $modulename : '') . "/langs/" . $langofdir . "/" . $newdomain . ".lang";
267  $file_lang_osencoded = dol_osencode($file_lang);
268 
269  //$filelangexists = is_file($file_lang_osencoded);
270  $filelangexists = @is_file($file_lang_osencoded); // avoid [php:warn]
271 
272  //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);
273  //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";
274 
275  if ($filelangexists) {
276  // TODO Move cache read out of loop on dirs or at least filelangexists
277  $found = false;
278 
279  // Enable caching of lang file in memory (not by default)
280  $usecachekey = '';
281  // Using a memcached server
282  if (isModEnabled('memcached') && !empty($conf->global->MEMCACHED_SERVER)) {
283  $usecachekey = $newdomain . '_' . $langofdir . '_' . md5($file_lang); // Should not contains special chars
284  } elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
285  // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
286  $usecachekey = $newdomain;
287  }
288 
289  if ($usecachekey) {
290  //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
291  //global $aaa; $aaa+=1;
292  //print $aaa." ".$usecachekey."\n";
293  require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
294  $tmparray = dol_getcache($usecachekey);
295  if (is_array($tmparray) && count($tmparray)) {
296  $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.
297  //print $newdomain."\n";
298  //var_dump($this->tab_translate);
299  if ($alt == 2) {
300  $fileread = 1;
301  }
302  $found = true; // Found in dolibarr PHP cache
303  }
304  }
305 
306  if (!$found) {
307  if ($fp = @fopen($file_lang, "rt")) {
308  if ($usecachekey) {
309  $tabtranslatedomain = array(); // To save lang content in cache
310  }
311 
317  while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n\r]")) {
318  if (isset($line[1])) {
319  list($key, $value) = $line;
320  //if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."<br>";
321  //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>";
322  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)
323  if ($key == 'DIRECTION') { // This is to declare direction of language
324  if ($alt < 2 || empty($this->tab_translate[$key])) { // We load direction only for primary files or if not yet loaded
325  $this->tab_translate[$key] = $value;
326  if ($stopafterdirection) {
327  break; // We do not save tab if we stop after DIRECTION
328  } elseif ($usecachekey) {
329  $tabtranslatedomain[$key] = $value;
330  }
331  }
332  } elseif ($key[0] == '#') {
333  continue;
334  } else {
335  // Convert some strings: Parse and render carriage returns. Also, change '\\s' into '\s' because transifex sync pull the string '\s' into string '\\s'
336  $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
337  if ($usecachekey) {
338  $tabtranslatedomain[$key] = $value;
339  } // To save lang content in cache
340  }
341  }
342  }
343  }
344  fclose($fp);
345  $fileread = 1;
346 
347  // TODO Move cache write out of loop on dirs
348  // To save lang content for usecachekey into cache
349  if ($usecachekey && count($tabtranslatedomain)) {
350  $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
351  if ($ressetcache < 0) {
352  $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
353  dol_syslog($error, LOG_ERR);
354  }
355  }
356 
357  if (empty($conf->global->MAIN_FORCELANGDIR)) {
358  break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
359  }
360  }
361  }
362  }
363  }
364 
365  // Now we complete with next file (fr_CA->fr_FR, es_MX->ex_ES, ...)
366  if ($alt == 0) {
367  // This function MUST NOT contains call to syslog
368  //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
369  $langofdir = strtolower($langarray[0]) . '_' . strtoupper($langarray[0]);
370  if ($langofdir == 'el_EL') {
371  $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR'
372  }
373  if ($langofdir == 'ar_AR') {
374  $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
375  }
376  $this->load($domain, $alt + 1, $stopafterdirection, $langofdir);
377  }
378 
379  // Now we complete with reference file (en_US)
380  if ($alt == 1) {
381  // This function MUST NOT contains call to syslog
382  //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
383  $langofdir = 'en_US';
384  $this->load($domain, $alt + 1, $stopafterdirection, $langofdir);
385  }
386 
387  // We are in the pass of the reference file. No more files to scan to complete.
388  if ($alt == 2) {
389  if ($fileread) {
390  $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded
391  }
392 
393  if (empty($this->_tab_loaded[$newdomain])) {
394  $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
395  }
396  }
397 
398  // This part is deprecated and replaced with table llx_overwrite_trans
399  // Kept for backward compatibility.
400  if (empty($loadfromfileonly)) {
401  $overwritekey = 'MAIN_OVERWRITE_TRANS_' . $this->defaultlang;
402  if (!empty($conf->global->$overwritekey)) { // Overwrite translation with key1:newstring1,key2:newstring2
403  // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
404  $tmparray = explode(',', $conf->global->$overwritekey);
405  foreach ($tmparray as $tmp) {
406  $tmparray2 = explode(':', $tmp);
407  if (!empty($tmparray2[1])) {
408  $this->tab_translate[$tmparray2[0]] = $tmparray2[1];
409  }
410  }
411  }
412  }
413 
414  // Check to be sure that SeparatorDecimal differs from SeparatorThousand
415  if (
416  !empty($this->tab_translate["SeparatorDecimal"]) && !empty($this->tab_translate["SeparatorThousand"])
417  && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]
418  ) {
419  $this->tab_translate["SeparatorThousand"] = '';
420  }
421 
422  return 1;
423  }
424 
437  public function loadFromDatabase($db)
438  {
439  global $conf;
440 
441  $domain = 'database';
442 
443  // Check parameters
444  if (empty($db)) {
445  return 0; // Database handler can't be used
446  }
447 
448  //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
449 
450  $newdomain = $domain;
451 
452  // Check cache
453  if (!empty($this->_tab_loaded[$newdomain])) { // File already loaded for this domain 'database'
454  //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
455  return 0;
456  }
457 
458  $this->_tab_loaded[$newdomain] = 1; // We want to be sure this function is called once only for domain 'database'
459 
460  $fileread = 0;
461  $langofdir = $this->defaultlang;
462 
463  if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
464  dol_syslog("Error: " . get_class($this) . "::loadFromDatabase was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
465  return -1;
466  }
467 
468  // TODO Move cache read out of loop on dirs or at least filelangexists
469  $found = false;
470 
471  // Enable caching of lang file in memory (not by default)
472  $usecachekey = '';
473  // Using a memcached server
474  if (isModEnabled('memcached') && !empty($conf->global->MEMCACHED_SERVER)) {
475  $usecachekey = $newdomain . '_' . $langofdir; // Should not contains special chars
476  } elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
477  // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
478  $usecachekey = $newdomain;
479  }
480 
481  if ($usecachekey) {
482  //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
483  //global $aaa; $aaa+=1;
484  //print $aaa." ".$usecachekey."\n";
485  require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
486  $tmparray = dol_getcache($usecachekey);
487  if (is_array($tmparray) && count($tmparray)) {
488  $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.
489  //print $newdomain."\n";
490  //var_dump($this->tab_translate);
491  $fileread = 1;
492  $found = true; // Found in dolibarr PHP cache
493  }
494  }
495 
496  if (!$found && !empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) {
497  // Overwrite translation with database read
498  $sql = "SELECT transkey, transvalue FROM ".$db->prefix()."overwrite_trans where (lang='".$db->escape($this->defaultlang)."' OR lang IS NULL)";
499  $sql .= " AND entity IN (0, ".getEntity('overwrite_trans').")";
500  $sql .= $db->order("lang", "DESC");
501 
502  $resql = $db->query($sql);
503 
504  if ($resql) {
505  $num = $db->num_rows($resql);
506  if ($num) {
507  if ($usecachekey) {
508  $tabtranslatedomain = array(); // To save lang content in cache
509  }
510 
511  $i = 0;
512  while ($i < $num) { // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
513  $obj = $db->fetch_object($resql);
514 
515  $key = $obj->transkey;
516  $value = $obj->transvalue;
517 
518  //print "Domain=$domain, found a string for $tab[0] with value $tab[1]<br>";
519  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)
520  // Convert some strings: Parse and render carriage returns. Also, change '\\s' int '\s' because transifex sync pull the string '\s' into string '\\s'
521  $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
522 
523  if ($usecachekey) {
524  $tabtranslatedomain[$key] = $value; // To save lang content in cache
525  }
526  }
527 
528  $i++;
529  }
530 
531  $fileread = 1;
532 
533  // TODO Move cache write out of loop on dirs
534  // To save lang content for usecachekey into cache
535  if ($usecachekey && count($tabtranslatedomain)) {
536  $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
537  if ($ressetcache < 0) {
538  $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
539  dol_syslog($error, LOG_ERR);
540  }
541  }
542  }
543  } else {
544  dol_print_error($db);
545  }
546  }
547 
548  if ($fileread) {
549  $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
550  }
551 
552  if (empty($this->_tab_loaded[$newdomain])) {
553  $this->_tab_loaded[$newdomain] = 2; // Mark this case as not found (no lines found for language)
554  }
555 
556  return 1;
557  }
558 
565  public function isLoaded($domain)
566  {
567  return $this->_tab_loaded[$domain];
568  }
569 
581  private function getTradFromKey($key)
582  {
583  global $conf, $db;
584 
585  if (!is_string($key)) {
586  //xdebug_print_function_stack('ErrorBadValueForParamNotAString');
587  return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly.
588  }
589 
590  $newstr = $key;
591  $reg = array();
592  if (preg_match('/^Civility([0-9A-Z]+)$/i', $key, $reg)) {
593  $newstr = $this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label');
594  } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg)) {
595  $newstr = $this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label');
596  } elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i', $key, $reg)) {
597  $newstr = $this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle');
598  } elseif (preg_match('/^PaymentType(?:Short)?([0-9A-Z]+)$/i', $key, $reg)) {
599  $newstr = $this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1);
600  } elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i', $key, $reg)) {
601  $newstr = $this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label');
602  } elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i', $key, $reg)) {
603  // TODO OrderSourceX must be replaced with content of table llx_c_input_reason or llx_c_input_method
604  //$newstr=$this->getLabelFromKey($db,$reg[1],'llx_c_input_reason','code','label');
605  }
606 
607  /* Disabled. There is too many cases where translation of $newstr is not defined is normal (like when output with setEventMessage an already translated string)
608  if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2)
609  {
610  dol_syslog(__METHOD__." MAIN_FEATURES_LEVEL=DEVELOP: missing translation for key '".$newstr."' in ".$_SERVER["PHP_SELF"], LOG_DEBUG);
611  }*/
612 
613  return $newstr;
614  }
615 
616 
630  public function trans($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $maxsize = 0)
631  {
632  global $conf;
633 
634  if (!empty($this->tab_translate[$key])) { // Translation is available
635  $str = $this->tab_translate[$key];
636 
637  // Make some string replacement after translation
638  $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
639  if (!empty($conf->global->$replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
640  $tmparray = explode(';', $conf->global->$replacekey);
641  foreach ($tmparray as $tmp) {
642  $tmparray2 = explode(':', $tmp);
643  $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
644  }
645  }
646 
647  // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities because
648  // we want to keep '"' '<b>' '</b>' '<strong' '</strong>' '<a ' '</a>' '<br>' '< ' '<span' '</span>' that are reliable HTML tags inside translation strings.
649  $str = str_replace(
650  array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<strong>', '</strong>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'), // We accept '< ' but not '<'. We can accept however '>'
651  array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__tagb__', '__tagbend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
652  $str
653  );
654 
655  if (strpos($key, 'Format') !== 0) {
656  try {
657  $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
658  } catch (Exception $e) {
659  // No exception managed
660  }
661  }
662 
663  // Crypt string into HTML
664  $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
665 
666  // Restore reliable HTML tags into original translation string
667  $str = str_replace(
668  array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
669  array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'),
670  $str
671  );
672 
673  if ($maxsize) {
674  $str = dol_trunc($str, $maxsize);
675  }
676 
677  return $str;
678  } else { // Translation is not available
679  //if ($key[0] == '$') { return dol_eval($key, 1, 1, '1'); }
680  return $this->getTradFromKey($key);
681  }
682  }
683 
684 
699  public function transnoentities($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
700  {
701  return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5));
702  }
703 
704 
720  public function transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
721  {
722  global $conf;
723 
724  if (!empty($this->tab_translate[$key])) { // Translation is available
725  $str = $this->tab_translate[$key];
726 
727  // Make some string replacement after translation
728  $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
729  if (!empty($conf->global->$replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
730  $tmparray = explode(';', $conf->global->$replacekey);
731  foreach ($tmparray as $tmp) {
732  $tmparray2 = explode(':', $tmp);
733  $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
734  }
735  }
736 
737  if (!preg_match('/^Format/', $key)) {
738  //print $str;
739  $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
740  }
741 
742  return $str;
743  } else {
744  /*if ($key[0] == '$') {
745  return dol_eval($key, 1, 1, '1');
746  }*/
747  return $this->getTradFromKey($key);
748  }
749  }
750 
751 
760  public function transcountry($str, $countrycode)
761  {
762  if (!empty($this->tab_translate["$str$countrycode"])) {
763  return $this->trans("$str$countrycode");
764  } else {
765  return $this->trans($str);
766  }
767  }
768 
769 
778  public function transcountrynoentities($str, $countrycode)
779  {
780  if (!empty($this->tab_translate["$str$countrycode"])) {
781  return $this->transnoentities("$str$countrycode");
782  } else {
783  return $this->transnoentities($str);
784  }
785  }
786 
787 
795  public function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
796  {
797  if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') {
798  $str = utf8_encode($str);
799  }
800  if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') {
801  $str = utf8_decode(str_replace('€', chr(128), $str));
802  // TODO Replace with iconv("UTF-8", "ISO-8859-1", str_replace('€', chr(128), $str)); ?
803  }
804  return $str;
805  }
806 
807 
808  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
818  public function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0, $mainlangonly = 0)
819  {
820  // phpcs:enable
821  global $conf;
822 
823  $this->load("languages");
824 
825  // We scan directory langs to detect available languages
826  $handle = opendir($langdir . "/langs");
827  $langs_available = array();
828  while ($dir = trim(readdir($handle))) {
829  $regs = array();
830  if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
831  // We must keep only main languages
832  if ($mainlangonly) {
833  $arrayofspecialmainlanguages = array(
834  'en' => 'en_US',
835  'am' => 'am_ET',
836  'ar' => 'ar_SA',
837  'bn' => 'bn_DB',
838  'bs' => 'bs_BA',
839  'ca' => 'ca_ES',
840  'cs' => 'cs_CZ',
841  'da' => 'da_DK',
842  'et' => 'et_EE',
843  'el' => 'el_GR',
844  'eu' => 'eu_ES',
845  'fa' => 'fa_IR',
846  'he' => 'he_IL',
847  'ka' => 'ka_GE',
848  'km' => 'km_KH',
849  'kn' => 'kn_IN',
850  'ko' => 'ko_KR',
851  'ja' => 'ja_JP',
852  'lo' => 'lo_LA',
853  'nb' => 'nb_NO',
854  'sq' => 'sq_AL',
855  'sr' => 'sr_RS',
856  'sv' => 'sv_SE',
857  'sl' => 'sl_SI',
858  'uk' => 'uk_UA',
859  'vi' => 'vi_VN',
860  'zh' => 'zh_CN'
861  );
862  if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
863  continue;
864  }
865  }
866  // We must keep only languages into MAIN_LANGUAGES_ALLOWED
867  if (!empty($conf->global->MAIN_LANGUAGES_ALLOWED) && !in_array($dir, explode(',', $conf->global->MAIN_LANGUAGES_ALLOWED))) {
868  continue;
869  }
870 
871  if ($usecode == 2) {
872  $langs_available[$dir] = $dir;
873  }
874 
875  if ($usecode == 1 || !empty($conf->global->MAIN_SHOW_LANGUAGE_CODE)) {
876  $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
877  } else {
878  $langs_available[$dir] = $this->trans('Language_' . $dir);
879  }
880  if ($mainlangonly) {
881  $langs_available[$dir] = str_replace(' (United States)', '', $langs_available[$dir]);
882  }
883  }
884  }
885  return $langs_available;
886  }
887 
888 
889  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
897  public function file_exists($filename, $searchalt = 0)
898  {
899  // phpcs:enable
900  // Test si fichier dans repertoire de la langue
901  foreach ($this->dir as $searchdir) {
902  if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename))) {
903  return true;
904  }
905 
906  if ($searchalt) {
907  // Test si fichier dans repertoire de la langue alternative
908  if ($this->defaultlang != "en_US") {
909  $filenamealt = $searchdir . "/langs/en_US/" . $filename;
910  }
911  //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
912  if (is_readable(dol_osencode($filenamealt))) {
913  return true;
914  }
915  }
916  }
917 
918  return false;
919  }
920 
921 
933  public function getLabelFromNumber($number, $isamount = '')
934  {
935  global $conf;
936 
937  $newnumber = $number;
938 
939  $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
940  foreach ($dirsubstitutions as $reldir) {
941  $dir = dol_buildpath($reldir, 0);
942  $newdir = dol_osencode($dir);
943 
944  // Check if directory exists
945  if (!is_dir($newdir)) {
946  continue; // We must not use dol_is_dir here, function may not be loaded
947  }
948 
949  $fonc = 'numberwords';
950  if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
951  include_once $newdir . '/functions_' . $fonc . '.lib.php';
952  if (function_exists('numberwords_getLabelFromNumber')) {
953  $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
954  break;
955  }
956  }
957  }
958 
959  return $newnumber;
960  }
961 
962 
978  public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
979  {
980  // If key empty
981  if ($key == '') {
982  return '';
983  }
984  // Test should be useless because the 3 variables are never set from user input but we keep it in case of.
985  if (preg_match('/[^0-9A-Z_]/i', $tablename) || preg_match('/[^0-9A-Z_]/i', $fieldkey) || preg_match('/[^0-9A-Z_]/i', $fieldlabel)) {
986  $this->error = 'Bad value for parameter tablename, fieldkey or fieldlabel';
987  return -1;
988  }
989 
990  //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
991 
992  // Check if a translation is available (Note: this can call getTradFromKey that can call getLabelFromKey)
993  $tmp = $this->transnoentitiesnoconv($key);
994  if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
995  return $tmp; // Found in language array
996  }
997 
998  // Check in cache
999  if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
1000  return $this->cache_labels[$tablename][$key]; // Found in cache
1001  }
1002 
1003  // Not found in loaded language file nor in cache. So we will take the label into database.
1004  $sql = "SELECT " . $fieldlabel . " as label";
1005  $sql .= " FROM " . $db->prefix() . $tablename;
1006  $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
1007  if ($filteronentity) {
1008  $sql .= " AND entity IN (" . getEntity($tablename) . ')';
1009  }
1010  dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
1011  $resql = $db->query($sql);
1012  if ($resql) {
1013  $obj = $db->fetch_object($resql);
1014  if ($obj) {
1015  $this->cache_labels[$tablename][$key] = $obj->label;
1016  } else {
1017  $this->cache_labels[$tablename][$key] = $key;
1018  }
1019 
1020  $db->free($resql);
1021  return $this->cache_labels[$tablename][$key];
1022  } else {
1023  $this->error = $db->lasterror();
1024  return -1;
1025  }
1026  }
1027 
1028 
1038  public function getCurrencyAmount($currency_code, $amount)
1039  {
1040  $symbol = $this->getCurrencySymbol($currency_code);
1041 
1042  if (in_array($currency_code, array('USD'))) {
1043  return $symbol . $amount;
1044  } else {
1045  return $amount . $symbol;
1046  }
1047  }
1048 
1057  public function getCurrencySymbol($currency_code, $forceloadall = 0)
1058  {
1059  $currency_sign = ''; // By default return iso code
1060 
1061  if (function_exists("mb_convert_encoding")) {
1062  $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
1063 
1064  if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) {
1065  foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
1066  $currency_sign .= mb_convert_encoding("&#" . $unicode . ";", "UTF-8", 'HTML-ENTITIES');
1067  }
1068  }
1069  }
1070 
1071  return ($currency_sign ? $currency_sign : $currency_code);
1072  }
1073 
1080  public function loadCacheCurrencies($currency_code)
1081  {
1082  global $db;
1083 
1084  if ($this->cache_currencies_all_loaded) {
1085  return 0; // Cache already loaded for all
1086  }
1087  if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
1088  return 0; // Cache already loaded for the currency
1089  }
1090 
1091  $sql = "SELECT code_iso, label, unicode";
1092  $sql .= " FROM " . $db->prefix() . "c_currencies";
1093  $sql .= " WHERE active = 1";
1094  if (!empty($currency_code)) {
1095  $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
1096  }
1097  //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
1098 
1099  dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
1100  $resql = $db->query($sql);
1101  if ($resql) {
1102  $this->load("dict");
1103  $label = array();
1104  if (!empty($currency_code)) {
1105  foreach ($this->cache_currencies as $key => $val) {
1106  $label[$key] = $val['label']; // Label in already loaded cache
1107  }
1108  }
1109 
1110  $num = $db->num_rows($resql);
1111  $i = 0;
1112  while ($i < $num) {
1113  $obj = $db->fetch_object($resql);
1114  if ($obj) {
1115  // If a translation exists, we use it lese we use the default label
1116  $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 : ''));
1117  $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode((empty($obj->unicode) ? '' : $obj->unicode), true);
1118  $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
1119  }
1120  $i++;
1121  }
1122  if (empty($currency_code)) {
1123  $this->cache_currencies_all_loaded = true;
1124  }
1125  //print count($label).' '.count($this->cache_currencies);
1126 
1127  // Resort cache
1128  array_multisort($label, SORT_ASC, $this->cache_currencies);
1129  //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
1130  return $num;
1131  } else {
1132  dol_print_error($db);
1133  return -1;
1134  }
1135  }
1136 
1137  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1145  {
1146  // phpcs:enable
1147  $substitutionarray = array();
1148 
1149  foreach ($this->tab_translate as $code => $label) {
1150  $substitutionarray['lang_' . $code] = $label;
1151  $substitutionarray['__(' . $code . ')__'] = $label;
1152  }
1153 
1154  return $substitutionarray;
1155  }
1156 }
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.
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.
load($domain, $alt=0, $stopafterdirection=0, $forcelangdir='', $loadfromfileonly=0, $forceloadifalreadynotfound=0)
Load translation key-value for a particular file, into a memory array.
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 parametre 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.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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.
isModEnabled($module)
Is Dolibarr module enabled.
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.
Definition: memory.lib.php:68
dol_getcache($memoryid)
Read a memory area shared by all users, all sessions on server.
Definition: memory.lib.php:140