translate.class.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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@capnetworks.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 <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/core/class/translate.class.php
  21. * \ingroup core
  22. * \brief File for Tanslate class
  23. */
  24. /**
  25. * Class to manage translations
  26. */
  27. class Translate
  28. {
  29. public $dir; // Directories that contains /langs subdirectory
  30. public $defaultlang; // Current language for current user
  31. public $charset_output='UTF-8'; // Codage used by "trans" method outputs
  32. public $tab_translate=array(); // Array of all translations key=>value
  33. private $_tab_loaded=array(); // Array to store result after loading each language file
  34. public $cache_labels=array(); // Cache for labels return by getLabelFromKey method
  35. public $cache_currencies=array(); // Cache to store currency symbols
  36. private $cache_currencies_all_loaded=false;
  37. /**
  38. * Constructor
  39. *
  40. * @param string $dir Force directory that contains /langs subdirectory (value is sometine '..' like into install/* pages or support/* pages).
  41. * @param Conf $conf Object with Dolibarr configuration
  42. */
  43. function __construct($dir,$conf)
  44. {
  45. if (! empty($conf->file->character_set_client)) $this->charset_output=$conf->file->character_set_client; // If charset output is forced
  46. if ($dir) $this->dir=array($dir);
  47. else $this->dir=$conf->file->dol_document_root;
  48. }
  49. /**
  50. * Set accessor for this->defaultlang
  51. *
  52. * @param string $srclang Language to use. If '' or 'auto', we use browser lang.
  53. * @return void
  54. */
  55. function setDefaultLang($srclang='en_US')
  56. {
  57. global $conf;
  58. //dol_syslog(get_class($this)."::setDefaultLang srclang=".$srclang,LOG_DEBUG);
  59. // If a module ask to force a priority on langs directories (to use its own lang files)
  60. if (! empty($conf->global->MAIN_FORCELANGDIR))
  61. {
  62. $more=array();
  63. $i=0;
  64. foreach($conf->file->dol_document_root as $dir)
  65. {
  66. $newdir=$dir.$conf->global->MAIN_FORCELANGDIR; // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
  67. if (! in_array($newdir,$this->dir))
  68. {
  69. $more['module_'.$i]=$newdir; $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
  70. }
  71. }
  72. $this->dir=array_merge($more,$this->dir); // Forced dir ($more) are before standard dirs ($this->dir)
  73. }
  74. $this->origlang=$srclang;
  75. if (empty($srclang) || $srclang == 'auto')
  76. {
  77. $langpref=empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])?'':$_SERVER['HTTP_ACCEPT_LANGUAGE'];
  78. $langpref=preg_replace("/;([^,]*)/i","",$langpref);
  79. $langpref=str_replace("-","_",$langpref);
  80. $langlist=preg_split("/[;,]/",$langpref);
  81. $codetouse=$langlist[0];
  82. }
  83. else $codetouse=$srclang;
  84. // We redefine $srclang
  85. $langpart=explode("_",$codetouse);
  86. //print "Short before _ : ".$langpart[0].'/ Short after _ : '.$langpart[1].'<br>';
  87. if (! empty($langpart[1])) // If it's for a codetouse that is a long code xx_YY
  88. {
  89. // Array force long code from first part, even if long code is defined
  90. $longforshort=array('ar'=>'ar_SA');
  91. if (isset($longforshort[strtolower($langpart[0])])) $srclang=$longforshort[strtolower($langpart[0])];
  92. else if (! is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser
  93. $srclang=strtolower($langpart[0])."_".strtoupper($langpart[1]);
  94. $longforlong=array('no_nb'=>'nb_NO');
  95. if (isset($longforlong[strtolower($srclang)])) $srclang=$longforlong[strtolower($srclang)];
  96. }
  97. else $srclang=strtolower($langpart[0])."_".strtoupper($langpart[0]);
  98. }
  99. else { // If it's for a codetouse that is a short code xx
  100. // Array to convert short lang code into long code.
  101. $longforshort=array('ar'=>'ar_SA', 'el'=>'el_GR', 'ca'=>'ca_ES', 'en'=>'en_US', 'nb'=>'nb_NO', 'no'=>'nb_NO');
  102. if (isset($longforshort[strtolower($langpart[0])])) $srclang=$longforshort[strtolower($langpart[0])];
  103. else if (! empty($langpart[0])) $srclang=strtolower($langpart[0])."_".strtoupper($langpart[0]);
  104. else $srclang='en_US';
  105. }
  106. $this->defaultlang=$srclang;
  107. //print 'this->defaultlang='.$this->defaultlang;
  108. }
  109. /**
  110. * Return active language code for current user
  111. * It's an accessor for this->defaultlang
  112. *
  113. * @param int $mode 0=Long language code, 1=Short language code
  114. * @return string Language code used (en_US, en_AU, fr_FR, ...)
  115. */
  116. function getDefaultLang($mode=0)
  117. {
  118. if (empty($mode)) return $this->defaultlang;
  119. else return substr($this->defaultlang,0,2);
  120. }
  121. /**
  122. * Load translation files.
  123. *
  124. * @param array $domains Array of lang files to load
  125. * @return int <0 if KO, 0 if already loaded or loading not required, >0 if OK
  126. */
  127. function loadLangs($domains)
  128. {
  129. foreach($domains as $domain)
  130. {
  131. $this->load($domain);
  132. }
  133. }
  134. /**
  135. * Load translation key-value for a particular file, into a memory array.
  136. * If data for file already loaded, do nothing.
  137. * All data in translation array are stored in UTF-8 format.
  138. * tab_loaded is completed with $domain key.
  139. * rule "we keep first entry found with we keep last entry found" so it is probably not what you want to do.
  140. *
  141. * Value for hash are: 1:Loaded from disk, 2:Not found, 3:Loaded from cache
  142. *
  143. * @param string $domain File name to load (.lang file). Must be "file" or "file@module" for module language files:
  144. * If $domain is "file@module" instead of "file" then we look for module lang file
  145. * in htdocs/custom/modules/mymodule/langs/code_CODE/file.lang
  146. * then in htdocs/module/langs/code_CODE/file.lang instead of htdocs/langs/code_CODE/file.lang
  147. * @param integer $alt 0 (try xx_ZZ then 1), 1 (try xx_XX then 2), 2 (try en_US)
  148. * @param int $stopafterdirection Stop when the DIRECTION tag is found (optimize speed)
  149. * @param int $forcelangdir To force a different lang directory
  150. * @param int $loadfromfileonly 1=Do not load overwritten translation from file or old conf.
  151. * @return int <0 if KO, 0 if already loaded or loading not required, >0 if OK
  152. * @see loadLangs
  153. */
  154. function load($domain,$alt=0,$stopafterdirection=0,$forcelangdir='',$loadfromfileonly=0)
  155. {
  156. global $conf,$db;
  157. //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
  158. // Check parameters
  159. if (empty($domain))
  160. {
  161. dol_print_error('',get_class($this)."::Load ErrorWrongParameters");
  162. return -1;
  163. }
  164. if ($this->defaultlang == 'none_NONE') return 0; // Special language code to not translate keys
  165. // Load $this->tab_translate[] from database
  166. if (empty($loadfromfileonly) && count($this->tab_translate) == 0) $this->loadFromDatabase($db); // Nothing was loaded yet, so we load database.
  167. $newdomain = $domain;
  168. $modulename = '';
  169. // Search if a module directory name is provided into lang file name
  170. if (preg_match('/^([^@]+)@([^@]+)$/i',$domain,$regs))
  171. {
  172. $newdomain = $regs[1];
  173. $modulename = $regs[2];
  174. }
  175. // Check cache
  176. if (! empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain
  177. {
  178. //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
  179. return 0;
  180. }
  181. $fileread=0;
  182. $langofdir=(empty($forcelangdir)?$this->defaultlang:$forcelangdir);
  183. // Redefine alt
  184. $langarray=explode('_',$langofdir);
  185. if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) $alt=1;
  186. if ($alt < 2 && strtolower($langofdir) == 'en_us') $alt=2;
  187. if (empty($langofdir)) // This may occurs when load is called without setting the language and without providing a value for forcelangdir
  188. {
  189. dol_syslog("Error: ".get_class($this)."::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
  190. return -1;
  191. }
  192. foreach($this->dir as $keydir => $searchdir)
  193. {
  194. // Directory of translation files
  195. $file_lang = $searchdir.($modulename?'/'.$modulename:'')."/langs/".$langofdir."/".$newdomain.".lang";
  196. $file_lang_osencoded=dol_osencode($file_lang);
  197. $filelangexists=is_file($file_lang_osencoded);
  198. //dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' newdomain='.$domain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists);
  199. if ($filelangexists)
  200. {
  201. // TODO Move cache read out of loop on dirs or at least filelangexists
  202. $found=false;
  203. // Enable caching of lang file in memory (not by default)
  204. $usecachekey='';
  205. // Using a memcached server
  206. if (! empty($conf->memcached->enabled) && ! empty($conf->global->MEMCACHED_SERVER))
  207. {
  208. $usecachekey=$newdomain.'_'.$langofdir.'_'.md5($file_lang); // Should not contains special chars
  209. }
  210. // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
  211. else if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02))
  212. {
  213. $usecachekey=$newdomain;
  214. }
  215. if ($usecachekey)
  216. {
  217. //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
  218. //global $aaa; $aaa+=1;
  219. //print $aaa." ".$usecachekey."\n";
  220. require_once DOL_DOCUMENT_ROOT .'/core/lib/memory.lib.php';
  221. $tmparray=dol_getcache($usecachekey);
  222. if (is_array($tmparray) && count($tmparray))
  223. {
  224. $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.
  225. //print $newdomain."\n";
  226. //var_dump($this->tab_translate);
  227. if ($alt == 2) $fileread=1;
  228. $found=true; // Found in dolibarr PHP cache
  229. }
  230. }
  231. if (! $found)
  232. {
  233. if ($fp = @fopen($file_lang,"rt"))
  234. {
  235. if ($usecachekey) $tabtranslatedomain=array(); // To save lang content in cache
  236. /**
  237. * Read each lines until a '=' (with any combination of spaces around it)
  238. * and split the rest until a line feed.
  239. * This is more efficient than fgets + explode + trim by a factor of ~2.
  240. */
  241. while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n]"))
  242. {
  243. if (isset($line[1]))
  244. {
  245. list($key, $value) = $line;
  246. //if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."<br>";
  247. //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>";
  248. if (empty($this->tab_translate[$key]))
  249. { // 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)
  250. $value = preg_replace('/\\n/', "\n", $value); // Parse and render carriage returns
  251. if ($key == 'DIRECTION') { // This is to declare direction of language
  252. if ($alt < 2 || empty($this->tab_translate[$key])) { // We load direction only for primary files or if not yet loaded
  253. $this->tab_translate[$key] = $value;
  254. if ($stopafterdirection) {
  255. break; // We do not save tab if we stop after DIRECTION
  256. } elseif ($usecachekey) {
  257. $tabtranslatedomain[$key] = $value;
  258. }
  259. }
  260. }
  261. elseif ($key[0] == '#')
  262. {
  263. continue;
  264. }
  265. else {
  266. $this->tab_translate[$key] = $value;
  267. //if ($domain == 'orders') print "$tab[0] value $value<br>";
  268. if ($usecachekey) {
  269. $tabtranslatedomain[$key] = $value;
  270. } // To save lang content in cache
  271. }
  272. }
  273. }
  274. }
  275. fclose($fp);
  276. $fileread=1;
  277. // TODO Move cache write out of loop on dirs
  278. // To save lang content for usecachekey into cache
  279. if ($usecachekey && count($tabtranslatedomain))
  280. {
  281. $ressetcache=dol_setcache($usecachekey,$tabtranslatedomain);
  282. if ($ressetcache < 0)
  283. {
  284. $error='Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache;
  285. dol_syslog($error, LOG_ERR);
  286. }
  287. }
  288. if (empty($conf->global->MAIN_FORCELANGDIR)) break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
  289. }
  290. }
  291. }
  292. }
  293. // Now we complete with next file (fr_CA->fr_FR, es_MX->ex_ES, ...)
  294. if ($alt == 0)
  295. {
  296. // This function MUST NOT contains call to syslog
  297. //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
  298. $langofdir=strtolower($langarray[0]).'_'.strtoupper($langarray[0]);
  299. if ($langofdir == 'el_EL') $langofdir = 'el_GR'; // main parent for el_CY is not el_EL but el_GR
  300. $this->load($domain,$alt+1,$stopafterdirection,$langofdir);
  301. }
  302. // Now we complete with reference file (en_US)
  303. if ($alt == 1)
  304. {
  305. // This function MUST NOT contains call to syslog
  306. //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
  307. $langofdir='en_US';
  308. $this->load($domain,$alt+1,$stopafterdirection,$langofdir);
  309. }
  310. // We already are the reference file. No more files to scan to complete.
  311. if ($alt == 2)
  312. {
  313. if ($fileread) $this->_tab_loaded[$newdomain]=1; // Set domain file as loaded
  314. if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain]=2; // Set this file as found
  315. }
  316. // This part is deprecated and replaced with table llx_overwrite_trans
  317. // Kept for backward compatibility.
  318. if (empty($loadfromfileonly))
  319. {
  320. $overwritekey='MAIN_OVERWRITE_TRANS_'.$this->defaultlang;
  321. if (! empty($conf->global->$overwritekey)) // Overwrite translation with key1:newstring1,key2:newstring2
  322. {
  323. // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
  324. $tmparray=explode(',', $conf->global->$overwritekey);
  325. foreach($tmparray as $tmp)
  326. {
  327. $tmparray2=explode(':',$tmp);
  328. if (! empty($tmparray2[1])) $this->tab_translate[$tmparray2[0]]=$tmparray2[1];
  329. }
  330. }
  331. }
  332. // Check to be sure that SeparatorDecimal differs from SeparatorThousand
  333. if (! empty($this->tab_translate["SeparatorDecimal"]) && ! empty($this->tab_translate["SeparatorThousand"])
  334. && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]) $this->tab_translate["SeparatorThousand"]='';
  335. return 1;
  336. }
  337. /**
  338. * Load translation key-value from database into a memory array.
  339. * If data already loaded, do nothing.
  340. * All data in translation array are stored in UTF-8 format.
  341. * tab_loaded is completed with $domain key.
  342. * rule "we keep first entry found with we keep last entry found" so it is probably not what you want to do.
  343. *
  344. * Value for hash are: 1:Loaded from disk, 2:Not found, 3:Loaded from cache
  345. *
  346. * @param Database $db Database handler
  347. * @return int <0 if KO, 0 if already loaded or loading not required, >0 if OK
  348. */
  349. function loadFromDatabase($db)
  350. {
  351. global $conf;
  352. $domain='database';
  353. // Check parameters
  354. if (empty($db)) return 0; // Database handler can't be used
  355. //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
  356. $newdomain = $domain;
  357. $modulename = '';
  358. // Check cache
  359. if (! empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain
  360. {
  361. //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
  362. return 0;
  363. }
  364. $this->_tab_loaded[$newdomain] = 1; // We want to be sure this function is called once only.
  365. $fileread=0;
  366. $langofdir=(empty($forcelangdir)?$this->defaultlang:$forcelangdir);
  367. // Redefine alt
  368. $alt=2;
  369. if (empty($langofdir)) // This may occurs when load is called without setting the language and without providing a value for forcelangdir
  370. {
  371. dol_syslog("Error: ".get_class($this)."::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
  372. return -1;
  373. }
  374. // TODO Move cache read out of loop on dirs or at least filelangexists
  375. $found=false;
  376. // Enable caching of lang file in memory (not by default)
  377. $usecachekey='';
  378. // Using a memcached server
  379. if (! empty($conf->memcached->enabled) && ! empty($conf->global->MEMCACHED_SERVER))
  380. {
  381. $usecachekey=$newdomain.'_'.$langofdir.'_'.md5($file_lang); // Should not contains special chars
  382. }
  383. // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
  384. else if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02))
  385. {
  386. $usecachekey=$newdomain;
  387. }
  388. if ($usecachekey)
  389. {
  390. //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
  391. //global $aaa; $aaa+=1;
  392. //print $aaa." ".$usecachekey."\n";
  393. require_once DOL_DOCUMENT_ROOT .'/core/lib/memory.lib.php';
  394. $tmparray=dol_getcache($usecachekey);
  395. if (is_array($tmparray) && count($tmparray))
  396. {
  397. $this->tab_translate+=$tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a valuer already exists into tab_translate, value into tmparaay is not added.
  398. //print $newdomain."\n";
  399. //var_dump($this->tab_translate);
  400. $fileread=1;
  401. $found=true; // Found in dolibarr PHP cache
  402. }
  403. }
  404. if (! $found && ! empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION))
  405. {
  406. // Overwrite translation with database read
  407. $sql="SELECT transkey, transvalue FROM ".MAIN_DB_PREFIX."overwrite_trans where lang='".$db->escape($this->defaultlang)."'";
  408. $resql=$db->query($sql);
  409. if ($resql)
  410. {
  411. $num = $db->num_rows($resql);
  412. if ($num)
  413. {
  414. if ($usecachekey) $tabtranslatedomain=array(); // To save lang content in cache
  415. $i = 0;
  416. while ($i < $num) // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
  417. {
  418. $obj=$db->fetch_object($resql);
  419. $key=$obj->transkey;
  420. $value=$obj->transvalue;
  421. //print "Domain=$domain, found a string for $tab[0] with value $tab[1]<br>";
  422. 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)
  423. {
  424. $value=trim(preg_replace('/\\n/',"\n",$value));
  425. $this->tab_translate[$key]=$value;
  426. if ($usecachekey) $tabtranslatedomain[$key]=$value; // To save lang content in cache
  427. }
  428. $i++;
  429. }
  430. $fileread=1;
  431. // TODO Move cache write out of loop on dirs
  432. // To save lang content for usecachekey into cache
  433. if ($usecachekey && count($tabtranslatedomain))
  434. {
  435. $ressetcache=dol_setcache($usecachekey,$tabtranslatedomain);
  436. if ($ressetcache < 0)
  437. {
  438. $error='Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache;
  439. dol_syslog($error, LOG_ERR);
  440. }
  441. }
  442. }
  443. }
  444. else
  445. {
  446. dol_print_error($db);
  447. }
  448. }
  449. if ($fileread) $this->_tab_loaded[$newdomain]=1; // Set domain file as loaded
  450. if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain]=2; // Marque ce cas comme non trouve (no lines found for language)
  451. return 1;
  452. }
  453. /**
  454. * Return translated value of key for special keys ("Currency...", "Civility...", ...).
  455. * Search in lang file, then into database. Key must be any complete entry into lang file: CurrencyEUR, ...
  456. * If not found, return key.
  457. * The string return is not formated (translated with transnoentitiesnoconv)
  458. * NOTE: To avoid infinite loop (getLabelFromKey->transnoentities->getTradFromKey), if you modify this function,
  459. * check that getLabelFromKey is not called with same value than input.
  460. *
  461. * @param string $key Key to translate
  462. * @return string Translated string (translated with transnoentitiesnoconv)
  463. */
  464. private function getTradFromKey($key)
  465. {
  466. global $db;
  467. if (! is_string($key)) return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly.
  468. $newstr=$key;
  469. if (preg_match('/^Civility([0-9A-Z]+)$/i',$key,$reg))
  470. {
  471. $newstr=$this->getLabelFromKey($db,$reg[1],'c_civility','code','label');
  472. }
  473. elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i',$key,$reg))
  474. {
  475. $newstr=$this->getLabelFromKey($db,$reg[1],'c_currencies','code_iso','label');
  476. }
  477. elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i',$key,$reg))
  478. {
  479. $newstr=$this->getLabelFromKey($db,$reg[1],'c_shipment_mode','code','libelle');
  480. }
  481. elseif (preg_match('/^PaymentTypeShort([0-9A-Z]+)$/i',$key,$reg))
  482. {
  483. $newstr=$this->getLabelFromKey($db,$reg[1],'c_paiement','code','libelle');
  484. }
  485. elseif (preg_match('/^OppStatusShort([0-9A-Z]+)$/i',$key,$reg))
  486. {
  487. $newstr=$this->getLabelFromKey($db,$reg[1],'c_lead_status','code','label');
  488. }
  489. elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i',$key,$reg))
  490. {
  491. $newstr=$this->getLabelFromKey($db,$reg[1],'c_lead_status','code','label');
  492. }
  493. elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i',$key,$reg))
  494. {
  495. // TODO OrderSourceX must be replaced with content of table llx_c_input_reason or llx_c_input_method
  496. //$newstr=$this->getLabelFromKey($db,$reg[1],'c_ordersource','code','label');
  497. }
  498. return $newstr;
  499. }
  500. /**
  501. * Return text translated of text received as parameter (and encode it into HTML)
  502. * Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
  503. * et si toujours pas trouve, il est retourne tel quel
  504. * Les parametres de cette methode peuvent contenir de balises HTML.
  505. *
  506. * @param string $key Key to translate
  507. * @param string $param1 chaine de param1
  508. * @param string $param2 chaine de param2
  509. * @param string $param3 chaine de param3
  510. * @param string $param4 chaine de param4
  511. * @param int $maxsize Max length of text
  512. * @return string Translated string (encoded into HTML entities and UTF8)
  513. */
  514. function trans($key, $param1='', $param2='', $param3='', $param4='', $maxsize=0)
  515. {
  516. global $conf;
  517. if (! empty($this->tab_translate[$key])) // Translation is available
  518. {
  519. $str=$this->tab_translate[$key];
  520. // Make some string replacement after translation
  521. $replacekey='MAIN_REPLACE_TRANS_'.$this->defaultlang;
  522. if (! empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2
  523. {
  524. $tmparray=explode(';', $conf->global->$replacekey);
  525. foreach($tmparray as $tmp)
  526. {
  527. $tmparray2=explode(':',$tmp);
  528. $str=preg_replace('/'.preg_quote($tmparray2[0]).'/',$tmparray2[1],$str);
  529. }
  530. }
  531. if (! preg_match('/^Format/',$key))
  532. {
  533. //print $str;
  534. $str=sprintf($str,$param1,$param2,$param3,$param4); // Replace %s and %d except for FormatXXX strings.
  535. }
  536. if ($maxsize) $str=dol_trunc($str,$maxsize);
  537. // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities
  538. $str=str_replace(array('<','>','"',),array('__lt__','__gt__','__quot__'),$str);
  539. // Crypt string into HTML
  540. $str=htmlentities($str,ENT_QUOTES,$this->charset_output);
  541. // Restore HTML tags
  542. $str=str_replace(array('__lt__','__gt__','__quot__'),array('<','>','"',),$str);
  543. return $str;
  544. }
  545. else // Translation is not available
  546. {
  547. if ($key[0] == '$') { return dol_eval($key,1); }
  548. return $this->getTradFromKey($key);
  549. }
  550. }
  551. /**
  552. * Return translated value of a text string
  553. * Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
  554. * et si toujours pas trouve, il est retourne tel quel.
  555. * Parameters of this method must not contains any HTML tags.
  556. *
  557. * @param string $key Key to translate
  558. * @param string $param1 chaine de param1
  559. * @param string $param2 chaine de param2
  560. * @param string $param3 chaine de param3
  561. * @param string $param4 chaine de param4
  562. * @return string Translated string (encoded into UTF8)
  563. */
  564. function transnoentities($key, $param1='', $param2='', $param3='', $param4='')
  565. {
  566. return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4));
  567. }
  568. /**
  569. * Return translated value of a text string
  570. * Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
  571. * et si toujours pas trouve, il est retourne tel quel.
  572. * No convert to encoding charset of lang object is done.
  573. * Parameters of this method must not contains any HTML tags.
  574. *
  575. * @param string $key Key to translate
  576. * @param string $param1 chaine de param1
  577. * @param string $param2 chaine de param2
  578. * @param string $param3 chaine de param3
  579. * @param string $param4 chaine de param4
  580. * @return string Translated string
  581. */
  582. function transnoentitiesnoconv($key, $param1='', $param2='', $param3='', $param4='')
  583. {
  584. global $conf;
  585. if (! empty($this->tab_translate[$key])) // Translation is available
  586. {
  587. $str=$this->tab_translate[$key];
  588. // Make some string replacement after translation
  589. $replacekey='MAIN_REPLACE_TRANS_'.$this->defaultlang;
  590. if (! empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2
  591. {
  592. $tmparray=explode(';', $conf->global->$replacekey);
  593. foreach($tmparray as $tmp)
  594. {
  595. $tmparray2=explode(':',$tmp);
  596. $str=preg_replace('/'.preg_quote($tmparray2[0]).'/',$tmparray2[1],$str);
  597. }
  598. }
  599. if (! preg_match('/^Format/',$key))
  600. {
  601. //print $str;
  602. $str=sprintf($str,$param1,$param2,$param3,$param4); // Replace %s and %d except for FormatXXX strings.
  603. }
  604. return $str;
  605. }
  606. else
  607. {
  608. if ($key[0] == '$') { return dol_eval($key,1); }
  609. return $this->getTradFromKey($key);
  610. }
  611. }
  612. /**
  613. * Return translation of a key depending on country
  614. *
  615. * @param string $str string root to translate
  616. * @param string $countrycode country code (FR, ...)
  617. * @return string translated string
  618. */
  619. function transcountry($str, $countrycode)
  620. {
  621. if ($this->tab_translate["$str$countrycode"]) return $this->trans("$str$countrycode");
  622. else return $this->trans($str);
  623. }
  624. /**
  625. * Retourne la version traduite du texte passe en parametre complete du code pays
  626. *
  627. * @param string $str string root to translate
  628. * @param string $countrycode country code (FR, ...)
  629. * @return string translated string
  630. */
  631. function transcountrynoentities($str, $countrycode)
  632. {
  633. if ($this->tab_translate["$str$countrycode"]) return $this->transnoentities("$str$countrycode");
  634. else return $this->transnoentities($str);
  635. }
  636. /**
  637. * Convert a string into output charset (this->charset_output that should be defined to conf->file->character_set_client)
  638. *
  639. * @param string $str String to convert
  640. * @param string $pagecodefrom Page code of src string
  641. * @return string Converted string
  642. */
  643. function convToOutputCharset($str,$pagecodefrom='UTF-8')
  644. {
  645. if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') $str=utf8_encode($str);
  646. if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') $str=utf8_decode(str_replace('€',chr(128),$str));
  647. return $str;
  648. }
  649. /**
  650. * Return list of all available languages
  651. *
  652. * @param string $langdir Directory to scan
  653. * @param integer $maxlength Max length for each value in combo box (will be truncated)
  654. * @param int $usecode 1=Show code instead of country name for language variant, 2=Show only code
  655. * @return array List of languages
  656. */
  657. function get_available_languages($langdir=DOL_DOCUMENT_ROOT,$maxlength=0,$usecode=0)
  658. {
  659. global $conf;
  660. // We scan directory langs to detect available languages
  661. $handle=opendir($langdir."/langs");
  662. $langs_available=array();
  663. while ($dir = trim(readdir($handle)))
  664. {
  665. if (preg_match('/^[a-z]+_[A-Z]+/i',$dir))
  666. {
  667. $this->load("languages");
  668. if ($usecode == 2)
  669. {
  670. $langs_available[$dir] = $dir;
  671. }
  672. if ($usecode == 1 || ! empty($conf->global->MAIN_SHOW_LANGUAGE_CODE))
  673. {
  674. $langs_available[$dir] = $dir.': '.dol_trunc($this->trans('Language_'.$dir),$maxlength);
  675. }
  676. else
  677. {
  678. $langs_available[$dir] = $this->trans('Language_'.$dir);
  679. }
  680. }
  681. }
  682. return $langs_available;
  683. }
  684. /**
  685. * Return if a filename $filename exists for current language (or alternate language)
  686. *
  687. * @param string $filename Language filename to search
  688. * @param integer $searchalt Search also alernate language file
  689. * @return boolean true if exists and readable
  690. */
  691. function file_exists($filename,$searchalt=0)
  692. {
  693. // Test si fichier dans repertoire de la langue
  694. foreach($this->dir as $searchdir)
  695. {
  696. if (is_readable(dol_osencode($searchdir."/langs/".$this->defaultlang."/".$filename))) return true;
  697. if ($searchalt)
  698. {
  699. // Test si fichier dans repertoire de la langue alternative
  700. if ($this->defaultlang != "en_US") $filenamealt = $searchdir."/langs/en_US/".$filename;
  701. //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
  702. if (is_readable(dol_osencode($filenamealt))) return true;
  703. }
  704. }
  705. return false;
  706. }
  707. /**
  708. * Return full text translated to language label for a key. Store key-label in a cache.
  709. * This function need module "numberwords" to be installed. If not it will return
  710. * same number (this module is not provided by default as it use non GPL source code).
  711. *
  712. * @param int $number Number to encode in full text
  713. * @param int $isamount 1=It's an amount, 0=it's just a number
  714. * @return string Label translated in UTF8 (but without entities)
  715. * 10 if setDefaultLang was en_US => ten
  716. * 123 if setDefaultLang was fr_FR => cent vingt trois
  717. */
  718. function getLabelFromNumber($number,$isamount=0)
  719. {
  720. global $conf;
  721. $newnumber=$number;
  722. $dirsubstitutions=array_merge(array(),$conf->modules_parts['substitutions']);
  723. foreach($dirsubstitutions as $reldir)
  724. {
  725. $dir=dol_buildpath($reldir,0);
  726. $newdir=dol_osencode($dir);
  727. // Check if directory exists
  728. if (! is_dir($newdir)) continue; // We must not use dol_is_dir here, function may not be loaded
  729. $fonc='numberwords';
  730. if (file_exists($newdir.'/functions_'.$fonc.'.lib.php'))
  731. {
  732. include_once $newdir.'/functions_'.$fonc.'.lib.php';
  733. $newnumber=numberwords_getLabelFromNumber($this,$number,$isamount);
  734. break;
  735. }
  736. }
  737. return $newnumber;
  738. }
  739. /**
  740. * Return a label for a key.
  741. * Search into translation array, then into cache, then if still not found, search into database.
  742. * Store key-label found into cache variable $this->cache_labels to save SQL requests to get labels.
  743. *
  744. * @param DoliDB $db Database handler
  745. * @param string $key Translation key to get label (key in language file)
  746. * @param string $tablename Table name without prefix
  747. * @param string $fieldkey Field for key
  748. * @param string $fieldlabel Field for label
  749. * @param string $keyforselect Use another value than the translation key for the where into select
  750. * @return string Label in UTF8 (but without entities)
  751. * @see dol_getIdFromCode
  752. */
  753. function getLabelFromKey($db,$key,$tablename,$fieldkey,$fieldlabel,$keyforselect='')
  754. {
  755. // If key empty
  756. if ($key == '') return '';
  757. //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
  758. // Check if a translation is available (this can call getTradFromKey)
  759. $tmp=$this->transnoentitiesnoconv($key);
  760. if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString')
  761. {
  762. return $tmp; // Found in language array
  763. }
  764. // Check in cache
  765. if (isset($this->cache_labels[$tablename][$key])) // Can be defined to 0 or ''
  766. {
  767. return $this->cache_labels[$tablename][$key]; // Found in cache
  768. }
  769. $sql = "SELECT ".$fieldlabel." as label";
  770. $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
  771. $sql.= " WHERE ".$fieldkey." = '".($keyforselect?$keyforselect:$key)."'";
  772. dol_syslog(get_class($this).'::getLabelFromKey', LOG_DEBUG);
  773. $resql = $db->query($sql);
  774. if ($resql)
  775. {
  776. $obj = $db->fetch_object($resql);
  777. if ($obj) $this->cache_labels[$tablename][$key]=$obj->label;
  778. else $this->cache_labels[$tablename][$key]=$key;
  779. $db->free($resql);
  780. return $this->cache_labels[$tablename][$key];
  781. }
  782. else
  783. {
  784. $this->error=$db->lasterror();
  785. return -1;
  786. }
  787. }
  788. /**
  789. * Return a currency code into its symbol
  790. *
  791. * @param string $currency_code Currency Code
  792. * @param string $amount If not '', show currency + amount according to langs ($10, 10€).
  793. * @return string Amount + Currency symbol encoded into UTF8
  794. * @deprecated Use method price to output a price
  795. * @see price()
  796. */
  797. function getCurrencyAmount($currency_code, $amount)
  798. {
  799. $symbol=$this->getCurrencySymbol($currency_code);
  800. if (in_array($currency_code, array('USD'))) return $symbol.$amount;
  801. else return $amount.$symbol;
  802. }
  803. /**
  804. * Return a currency code into its symbol.
  805. * If mb_convert_encoding is not available, return currency code.
  806. *
  807. * @param string $currency_code Currency code
  808. * @param integer $forceloadall 1=Force to load all currencies into cache. We know we need to use all of them. By default read and cache only required currency.
  809. * @return string Currency symbol encoded into UTF8
  810. */
  811. function getCurrencySymbol($currency_code, $forceloadall=0)
  812. {
  813. $currency_sign = ''; // By default return iso code
  814. if (function_exists("mb_convert_encoding"))
  815. {
  816. $this->loadCacheCurrencies($forceloadall?'':$currency_code);
  817. if (isset($this->cache_currencies[$currency_code]) && ! empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode']))
  818. {
  819. foreach($this->cache_currencies[$currency_code]['unicode'] as $unicode)
  820. {
  821. $currency_sign .= mb_convert_encoding("&#{$unicode};", "UTF-8", 'HTML-ENTITIES');
  822. }
  823. }
  824. }
  825. return ($currency_sign?$currency_sign:$currency_code);
  826. }
  827. /**
  828. * Load into the cache this->cache_currencies, all currencies
  829. *
  830. * @param string $currency_code Get only currency. Get all if ''.
  831. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  832. */
  833. public function loadCacheCurrencies($currency_code)
  834. {
  835. global $db;
  836. if ($this->cache_currencies_all_loaded) return 0; // Cache already loaded for all
  837. if (! empty($currency_code) && isset($this->cache_currencies[$currency_code])) return 0; // Cache already loaded for the currency
  838. $sql = "SELECT code_iso, label, unicode";
  839. $sql.= " FROM ".MAIN_DB_PREFIX."c_currencies";
  840. $sql.= " WHERE active = 1";
  841. if (! empty($currency_code)) $sql.=" AND code_iso = '".$currency_code."'";
  842. //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
  843. dol_syslog(get_class($this).'::loadCacheCurrencies', LOG_DEBUG);
  844. $resql = $db->query($sql);
  845. if ($resql)
  846. {
  847. $this->load("dict");
  848. $label=array();
  849. if (! empty($currency_code)) foreach($this->cache_currencies as $key => $val) $label[$key]=$val['label']; // Label in already loaded cache
  850. $num = $db->num_rows($resql);
  851. $i = 0;
  852. while ($i < $num)
  853. {
  854. $obj = $db->fetch_object($resql);
  855. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  856. $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:''));
  857. $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode($obj->unicode, true);
  858. $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
  859. $i++;
  860. }
  861. if (empty($currency_code)) $this->cache_currencies_all_loaded=true;
  862. //print count($label).' '.count($this->cache_currencies);
  863. // Resort cache
  864. array_multisort($label, SORT_ASC, $this->cache_currencies);
  865. //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
  866. return $num;
  867. }
  868. else
  869. {
  870. dol_print_error($db);
  871. return -1;
  872. }
  873. }
  874. /**
  875. * Return an array with content of all loaded translation keys (found into this->tab_translate) so
  876. * we get a substitution array we can use for substitutions (for mail or ODT generation for example)
  877. *
  878. * @return array Array of translation keys lang_key => string_translation_loaded
  879. */
  880. function get_translations_for_substitutions()
  881. {
  882. $substitutionarray = array();
  883. foreach($this->tab_translate as $code => $label) {
  884. $substitutionarray['lang_'.$code] = $label;
  885. }
  886. return $substitutionarray;
  887. }
  888. }