translate.class.php 44 KB

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