translate.class.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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 ".MAIN_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), if you modify this function,
  485. * check that getLabelFromKey is not called with same value than input.
  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('/^PaymentTypeShort([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],'c_ordersource','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 (! empty($conf->global->MAIN_FEATURES_LEVEL) && $conf->global->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. $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
  556. }
  557. // Crypt string into HTML
  558. $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
  559. // Restore reliable HTML tags into original translation string
  560. $str = str_replace(
  561. array('__quot__', '__tagb__', '__tagbend__', '__tagu__', '__taguend__', '__tagi__', '__tagiend__', '__tagcenter__', '__tagcenterend__', '__taga__', '__tagaend__', '__tagbr__', '__tagspan__', '__tagspanend__', '__ltspace__', '__gt__'),
  562. array('"', '<b>', '</b>', '<u>', '</u>', '<i', '</i>', '<center>', '</center>', '<a ', '</a>', '<br>', '<span', '</span>', '< ', '>'),
  563. $str
  564. );
  565. if ($maxsize) {
  566. $str = dol_trunc($str, $maxsize);
  567. }
  568. return $str;
  569. } else { // Translation is not available
  570. //if ($key[0] == '$') { return dol_eval($key,1); }
  571. return $this->getTradFromKey($key);
  572. }
  573. }
  574. /**
  575. * Return translated value of a text string
  576. * If there is no match for this text, we look in alternative file and if still not found
  577. * it is returned as is.
  578. * Parameters of this method must not contain any HTML tags.
  579. *
  580. * @param string $key Key to translate
  581. * @param string $param1 chaine de param1
  582. * @param string $param2 chaine de param2
  583. * @param string $param3 chaine de param3
  584. * @param string $param4 chaine de param4
  585. * @param string $param5 chaine de param5
  586. * @return string Translated string (encoded into UTF8)
  587. */
  588. public function transnoentities($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
  589. {
  590. return $this->convToOutputCharset($this->transnoentitiesnoconv($key, $param1, $param2, $param3, $param4, $param5));
  591. }
  592. /**
  593. * Return translated value of a text string
  594. * If there is no match for this text, we look in alternative file and if still not found,
  595. * it is returned as is.
  596. * No conversion to encoding charset of lang object is done.
  597. * Parameters of this method must not contains any HTML tags.
  598. *
  599. * @param string $key Key to translate
  600. * @param string $param1 chaine de param1
  601. * @param string $param2 chaine de param2
  602. * @param string $param3 chaine de param3
  603. * @param string $param4 chaine de param4
  604. * @param string $param5 chaine de param5
  605. * @return string Translated string
  606. */
  607. public function transnoentitiesnoconv($key, $param1 = '', $param2 = '', $param3 = '', $param4 = '', $param5 = '')
  608. {
  609. global $conf;
  610. if (!empty($this->tab_translate[$key])) { // Translation is available
  611. $str = $this->tab_translate[$key];
  612. // Make some string replacement after translation
  613. $replacekey = 'MAIN_REPLACE_TRANS_'.$this->defaultlang;
  614. if (!empty($conf->global->$replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
  615. $tmparray = explode(';', $conf->global->$replacekey);
  616. foreach ($tmparray as $tmp) {
  617. $tmparray2 = explode(':', $tmp);
  618. $str = preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str);
  619. }
  620. }
  621. if (!preg_match('/^Format/', $key)) {
  622. //print $str;
  623. $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
  624. }
  625. return $str;
  626. } else {
  627. if ($key[0] == '$') {
  628. return dol_eval($key, 1);
  629. }
  630. return $this->getTradFromKey($key);
  631. }
  632. }
  633. /**
  634. * Return translation of a key depending on country
  635. *
  636. * @param string $str string root to translate
  637. * @param string $countrycode country code (FR, ...)
  638. * @return string translated string
  639. * @see transcountrynoentities(), picto_from_langcode()
  640. */
  641. public function transcountry($str, $countrycode)
  642. {
  643. if (!empty($this->tab_translate["$str$countrycode"])) {
  644. return $this->trans("$str$countrycode");
  645. } else {
  646. return $this->trans($str);
  647. }
  648. }
  649. /**
  650. * Retourne la version traduite du texte passe en parametre complete du code pays
  651. *
  652. * @param string $str string root to translate
  653. * @param string $countrycode country code (FR, ...)
  654. * @return string translated string
  655. * @see transcountry(), picto_from_langcode()
  656. */
  657. public function transcountrynoentities($str, $countrycode)
  658. {
  659. if (!empty($this->tab_translate["$str$countrycode"])) {
  660. return $this->transnoentities("$str$countrycode");
  661. } else {
  662. return $this->transnoentities($str);
  663. }
  664. }
  665. /**
  666. * Convert a string into output charset (this->charset_output that should be defined to conf->file->character_set_client)
  667. *
  668. * @param string $str String to convert
  669. * @param string $pagecodefrom Page code of src string
  670. * @return string Converted string
  671. */
  672. public function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
  673. {
  674. if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') {
  675. $str = utf8_encode($str);
  676. }
  677. if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') {
  678. $str = utf8_decode(str_replace('€', chr(128), $str));
  679. }
  680. return $str;
  681. }
  682. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  683. /**
  684. * Return list of all available languages
  685. *
  686. * @param string $langdir Directory to scan
  687. * @param integer $maxlength Max length for each value in combo box (will be truncated)
  688. * @param int $usecode 1=Show code instead of country name for language variant, 2=Show only code
  689. * @param int $mainlangonly 1=Show only main languages ('fr_FR' no' fr_BE', 'es_ES' not 'es_MX', ...)
  690. * @return array List of languages
  691. */
  692. public function get_available_languages($langdir = DOL_DOCUMENT_ROOT, $maxlength = 0, $usecode = 0, $mainlangonly = 0)
  693. {
  694. // phpcs:enable
  695. global $conf;
  696. $this->load("languages");
  697. // We scan directory langs to detect available languages
  698. $handle = opendir($langdir."/langs");
  699. $langs_available = array();
  700. while ($dir = trim(readdir($handle))) {
  701. $regs = array();
  702. if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
  703. // We must keep only main languages
  704. if ($mainlangonly) {
  705. $arrayofspecialmainlanguages = array(
  706. 'en'=>'en_US',
  707. 'am'=>'am_ET',
  708. 'ar'=>'ar_SA',
  709. 'bn'=>'bn_DB',
  710. 'bs'=>'bs_BA',
  711. 'ca'=>'ca_ES',
  712. 'cs'=>'cs_CZ',
  713. 'da'=>'da_DK',
  714. 'et'=>'et_EE',
  715. 'el'=>'el_GR',
  716. 'eu'=>'eu_ES',
  717. 'fa'=>'fa_IR',
  718. 'he'=>'he_IL',
  719. 'ka'=>'ka_GE',
  720. 'km'=>'km_KH',
  721. 'kn'=>'kn_IN',
  722. 'ko'=>'ko_KR',
  723. 'ja'=>'ja_JP',
  724. 'lo'=>'lo_LA',
  725. 'nb'=>'nb_NO',
  726. 'fa'=>'fa_IR',
  727. 'sq'=>'sq_AL',
  728. 'sr'=>'sr_RS',
  729. 'sv'=>'sv_SE',
  730. 'sl'=>'sl_SI',
  731. 'uk'=>'uk_UA',
  732. 'vi'=>'vi_VN',
  733. 'zh'=>'zh_CN'
  734. );
  735. if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
  736. continue;
  737. }
  738. }
  739. // We must keep only languages into MAIN_LANGUAGES_ALLOWED
  740. if (!empty($conf->global->MAIN_LANGUAGES_ALLOWED) && !in_array($dir, explode(',', $conf->global->MAIN_LANGUAGES_ALLOWED))) {
  741. continue;
  742. }
  743. if ($usecode == 2) {
  744. $langs_available[$dir] = $dir;
  745. }
  746. if ($usecode == 1 || !empty($conf->global->MAIN_SHOW_LANGUAGE_CODE)) {
  747. $langs_available[$dir] = $dir.': '.dol_trunc($this->trans('Language_'.$dir), $maxlength);
  748. } else {
  749. $langs_available[$dir] = $this->trans('Language_'.$dir);
  750. }
  751. if ($mainlangonly) {
  752. $langs_available[$dir] = str_replace(' (United States)', '', $langs_available[$dir]);
  753. }
  754. }
  755. }
  756. return $langs_available;
  757. }
  758. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  759. /**
  760. * Return if a filename $filename exists for current language (or alternate language)
  761. *
  762. * @param string $filename Language filename to search
  763. * @param integer $searchalt Search also alernate language file
  764. * @return boolean true if exists and readable
  765. */
  766. public function file_exists($filename, $searchalt = 0)
  767. {
  768. // phpcs:enable
  769. // Test si fichier dans repertoire de la langue
  770. foreach ($this->dir as $searchdir) {
  771. if (is_readable(dol_osencode($searchdir."/langs/".$this->defaultlang."/".$filename))) {
  772. return true;
  773. }
  774. if ($searchalt) {
  775. // Test si fichier dans repertoire de la langue alternative
  776. if ($this->defaultlang != "en_US") {
  777. $filenamealt = $searchdir."/langs/en_US/".$filename;
  778. }
  779. //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
  780. if (is_readable(dol_osencode($filenamealt))) {
  781. return true;
  782. }
  783. }
  784. }
  785. return false;
  786. }
  787. /**
  788. * Return full text translated to language label for a key. Store key-label in a cache.
  789. * This function need module "numberwords" to be installed. If not it will return
  790. * same number (this module is not provided by default as it use non GPL source code).
  791. *
  792. * @param int $number Number to encode in full text
  793. * @param string $isamount ''=it's just a number, '1'=It's an amount (default currency), 'currencycode'=It's an amount (foreign currency)
  794. * @return string Label translated in UTF8 (but without entities)
  795. * 10 if setDefaultLang was en_US => ten
  796. * 123 if setDefaultLang was fr_FR => cent vingt trois
  797. */
  798. public function getLabelFromNumber($number, $isamount = '')
  799. {
  800. global $conf;
  801. $newnumber = $number;
  802. $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
  803. foreach ($dirsubstitutions as $reldir) {
  804. $dir = dol_buildpath($reldir, 0);
  805. $newdir = dol_osencode($dir);
  806. // Check if directory exists
  807. if (!is_dir($newdir)) {
  808. continue; // We must not use dol_is_dir here, function may not be loaded
  809. }
  810. $fonc = 'numberwords';
  811. if (file_exists($newdir.'/functions_'.$fonc.'.lib.php')) {
  812. include_once $newdir.'/functions_'.$fonc.'.lib.php';
  813. $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
  814. break;
  815. }
  816. }
  817. return $newnumber;
  818. }
  819. /**
  820. * Return a label for a key.
  821. * Search into translation array, then into cache, then if still not found, search into database.
  822. * Store key-label found into cache variable $this->cache_labels to save SQL requests to get labels.
  823. *
  824. * @param DoliDB $db Database handler
  825. * @param string $key Translation key to get label (key in language file)
  826. * @param string $tablename Table name without prefix
  827. * @param string $fieldkey Field for key
  828. * @param string $fieldlabel Field for label
  829. * @param string $keyforselect Use another value than the translation key for the where into select
  830. * @param int $filteronentity Use a filter on entity
  831. * @return string Label in UTF8 (but without entities)
  832. * @see dol_getIdFromCode()
  833. */
  834. public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
  835. {
  836. // If key empty
  837. if ($key == '') {
  838. return '';
  839. }
  840. //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
  841. // Check if a translation is available (this can call getTradFromKey)
  842. $tmp = $this->transnoentitiesnoconv($key);
  843. if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
  844. return $tmp; // Found in language array
  845. }
  846. // Check in cache
  847. if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
  848. return $this->cache_labels[$tablename][$key]; // Found in cache
  849. }
  850. $sql = "SELECT ".$fieldlabel." as label";
  851. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  852. $sql .= " WHERE ".$fieldkey." = '".$db->escape($keyforselect ? $keyforselect : $key)."'";
  853. if ($filteronentity) {
  854. $sql .= " AND entity IN (".getEntity($tablename).')';
  855. }
  856. dol_syslog(get_class($this).'::getLabelFromKey', LOG_DEBUG);
  857. $resql = $db->query($sql);
  858. if ($resql) {
  859. $obj = $db->fetch_object($resql);
  860. if ($obj) {
  861. $this->cache_labels[$tablename][$key] = $obj->label;
  862. } else {
  863. $this->cache_labels[$tablename][$key] = $key;
  864. }
  865. $db->free($resql);
  866. return $this->cache_labels[$tablename][$key];
  867. } else {
  868. $this->error = $db->lasterror();
  869. return -1;
  870. }
  871. }
  872. /**
  873. * Return a currency code into its symbol
  874. *
  875. * @param string $currency_code Currency Code
  876. * @param string $amount If not '', show currency + amount according to langs ($10, 10€).
  877. * @return string Amount + Currency symbol encoded into UTF8
  878. * @deprecated Use method price to output a price
  879. * @see price()
  880. */
  881. public function getCurrencyAmount($currency_code, $amount)
  882. {
  883. $symbol = $this->getCurrencySymbol($currency_code);
  884. if (in_array($currency_code, array('USD'))) {
  885. return $symbol.$amount;
  886. } else {
  887. return $amount.$symbol;
  888. }
  889. }
  890. /**
  891. * Return a currency code into its symbol.
  892. * If mb_convert_encoding is not available, return currency code.
  893. *
  894. * @param string $currency_code Currency code
  895. * @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.
  896. * @return string Currency symbol encoded into UTF8
  897. */
  898. public function getCurrencySymbol($currency_code, $forceloadall = 0)
  899. {
  900. $currency_sign = ''; // By default return iso code
  901. if (function_exists("mb_convert_encoding")) {
  902. $this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
  903. if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) {
  904. foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
  905. $currency_sign .= mb_convert_encoding("&#{$unicode};", "UTF-8", 'HTML-ENTITIES');
  906. }
  907. }
  908. }
  909. return ($currency_sign ? $currency_sign : $currency_code);
  910. }
  911. /**
  912. * Load into the cache this->cache_currencies, all currencies
  913. *
  914. * @param string $currency_code Get only currency. Get all if ''.
  915. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  916. */
  917. public function loadCacheCurrencies($currency_code)
  918. {
  919. global $db;
  920. if ($this->cache_currencies_all_loaded) {
  921. return 0; // Cache already loaded for all
  922. }
  923. if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
  924. return 0; // Cache already loaded for the currency
  925. }
  926. $sql = "SELECT code_iso, label, unicode";
  927. $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies";
  928. $sql .= " WHERE active = 1";
  929. if (!empty($currency_code)) {
  930. $sql .= " AND code_iso = '".$db->escape($currency_code)."'";
  931. }
  932. //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
  933. dol_syslog(get_class($this).'::loadCacheCurrencies', LOG_DEBUG);
  934. $resql = $db->query($sql);
  935. if ($resql) {
  936. $this->load("dict");
  937. $label = array();
  938. if (!empty($currency_code)) {
  939. foreach ($this->cache_currencies as $key => $val) {
  940. $label[$key] = $val['label']; // Label in already loaded cache
  941. }
  942. }
  943. $num = $db->num_rows($resql);
  944. $i = 0;
  945. while ($i < $num) {
  946. $obj = $db->fetch_object($resql);
  947. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  948. $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 : ''));
  949. $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode($obj->unicode, true);
  950. $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
  951. $i++;
  952. }
  953. if (empty($currency_code)) {
  954. $this->cache_currencies_all_loaded = true;
  955. }
  956. //print count($label).' '.count($this->cache_currencies);
  957. // Resort cache
  958. array_multisort($label, SORT_ASC, $this->cache_currencies);
  959. //var_dump($this->cache_currencies); $this->cache_currencies is now sorted onto label
  960. return $num;
  961. } else {
  962. dol_print_error($db);
  963. return -1;
  964. }
  965. }
  966. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  967. /**
  968. * Return an array with content of all loaded translation keys (found into this->tab_translate) so
  969. * we get a substitution array we can use for substitutions (for mail or ODT generation for example)
  970. *
  971. * @return array Array of translation keys lang_key => string_translation_loaded
  972. */
  973. public function get_translations_for_substitutions()
  974. {
  975. // phpcs:enable
  976. $substitutionarray = array();
  977. foreach ($this->tab_translate as $code => $label) {
  978. $substitutionarray['lang_'.$code] = $label;
  979. $substitutionarray['__('.$code.')__'] = $label;
  980. }
  981. return $substitutionarray;
  982. }
  983. }