translate.class.php 44 KB

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