PageRenderTime 42ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/core/class/translate.class.php

https://github.com/asterix14/dolibarr
PHP | 674 lines | 360 code | 88 blank | 226 comment | 127 complexity | 7afba52859702429d0539828e923e2b9 MD5 | raw file
Possible License(s): LGPL-2.0
  1. <?php
  2. /* Copyright (C) 2001 Eric Seigne <erics@rycks.com>
  3. * Copyright (C) 2004-2010 Destailleur Laurent <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2010 Regis Houssin <regis@dolibarr.fr>
  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 2 of the License, or
  9. * any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/core/class/translate.class.php
  21. * \ingroup core
  22. * \brief File for Tanslate class
  23. * \author Eric Seigne
  24. * \author Laurent Destailleur
  25. */
  26. /**
  27. * \class Translate
  28. * \brief Class to manage translations
  29. */
  30. class Translate {
  31. var $dir; // Directories that contains /langs subdirectory
  32. var $defaultlang; // Current language for current user
  33. var $direction = 'ltr'; // Left to right or Right to left
  34. var $charset_inputfile=array(); // To store charset encoding used for language
  35. var $charset_output='UTF-8'; // Codage used by "trans" method outputs
  36. var $tab_translate=array(); // Array of all translations key=>value
  37. var $tab_loaded=array(); // Array to store result after loading each language file
  38. var $cache_labels=array(); // Cache for labels return by trans method
  39. /**
  40. * Constructor
  41. *
  42. * @param dir Force directory that contains /langs subdirectory (value is sometine '..' like into install/* pages or support/* pages).
  43. * @param conf Object with Dolibarr configuration
  44. */
  45. function Translate($dir = "",$conf)
  46. {
  47. if (! empty($conf->file->character_set_client)) $this->charset_output=$conf->file->character_set_client; // If charset output is forced
  48. if ($dir) $this->dir=array($dir);
  49. else $this->dir=$conf->file->dol_document_root;
  50. }
  51. /**
  52. * Set accessor for this->defaultlang
  53. *
  54. * @param srclang Language to use
  55. */
  56. function setDefaultLang($srclang='fr_FR')
  57. {
  58. global $conf;
  59. //dol_syslog("Translate::setDefaultLang srclang=".$srclang,LOG_DEBUG);
  60. // If a module ask to force a priority on langs directories (to use its own lang files)
  61. if (! empty($conf->global->MAIN_FORCELANGDIR))
  62. {
  63. $more=array();
  64. $i=0;
  65. foreach($conf->file->dol_document_root as $dir)
  66. {
  67. $newdir=$dir.$conf->global->MAIN_FORCELANGDIR;
  68. if (! in_array($newdir,$this->dir))
  69. {
  70. $more['module_'.$i]=$newdir; $i++;
  71. }
  72. }
  73. $this->dir=array_merge($more,$this->dir);
  74. }
  75. $this->origlang=$srclang;
  76. if (empty($srclang) || $srclang == 'auto')
  77. {
  78. $langpref=$_SERVER['HTTP_ACCEPT_LANGUAGE'];
  79. $langpref=preg_replace("/;([^,]*)/i","",$langpref);
  80. $langpref=str_replace("-","_",$langpref);
  81. $langlist=preg_split("/[;,]/",$langpref);
  82. $codetouse=$langlist[0];
  83. }
  84. else $codetouse=$srclang;
  85. // We redefine $srclang
  86. $langpart=explode("_",$codetouse);
  87. //print "Short before _ : ".$langpart[0].'/ Short after _ : '.$langpart[1].'<br>';
  88. if (isset($langpart[1])) // If it's for a codetouse that is a long code xx_YY
  89. {
  90. // Array force long code from first part, even if long code is defined
  91. $longforshort=array('ar'=>'ar_SA');
  92. if (isset($longforshort[strtolower($langpart[0])])) $srclang=$longforshort[strtolower($langpart[0])];
  93. else {
  94. $srclang=strtolower($langpart[0])."_".strtoupper($langpart[1]);
  95. $longforlong=array('no_nb'=>'nb_NO');
  96. if (isset($longforlong[strtolower($srclang)])) $srclang=$longforlong[strtolower($srclang)];
  97. }
  98. }
  99. else { // If it's for a codetouse that is a short code xx
  100. // Array to convert short lang code into long code.
  101. $longforshort=array('ar'=>'ar_SA', 'el'=>'el_GR', 'ca'=>'ca_ES', 'en'=>'en_US', 'nb'=>'nb_NO', 'no'=>'nb_NO');
  102. if (isset($longforshort[strtolower($langpart[0])])) $srclang=$longforshort[strtolower($langpart[0])];
  103. else $srclang=strtolower($langpart[0])."_".strtoupper($langpart[0]);
  104. }
  105. $this->defaultlang=$srclang;
  106. //print $this->defaultlang;
  107. }
  108. /**
  109. * Return active language code for current user
  110. * It's an accessor for this->defaultlang
  111. *
  112. * @param mode 0=Long language code, 1=Short language code
  113. * @return string Language code used (en_US, en_AU, fr_FR, ...)
  114. */
  115. function getDefaultLang($mode=0)
  116. {
  117. if (empty($mode)) return $this->defaultlang;
  118. else return substr($this->defaultlang,0,2);
  119. }
  120. /**
  121. * Load translation key-value for a particular file, into a memory array.
  122. * If data for file already loaded, do nothing.
  123. * All data in translation array are stored in UTF-8 format.
  124. * tab_loaded is completed with $domain key.
  125. * Value for hash are: 1:Loaded from disk, 2:Not found, 3:Loaded from cache
  126. *
  127. * @param string $domain File name to load (.lang file). Must be "file" or "file@module" for module language files:
  128. * If $domain is "file@module" instead of "file" then we look for module lang file
  129. * in htdocs/custom/modules/mymodule/langs/code_CODE/file.lang
  130. * then in htdocs/module/langs/code_CODE/file.lang instead of htdocs/langs/code_CODE/file.lang
  131. * @param string $alt 0 (try xx_ZZ then 1), 1 (try xx_XX then 2), 2 (try en_US or fr_FR or es_ES)
  132. * @param int $stopafterdirection Stop when the DIRECTION tag is found (optimize speed)
  133. * @param int $forcelangdir To force a different lang directory
  134. * @return int <0 if KO, 0 if already loaded, >0 if OK
  135. */
  136. function Load($domain,$alt=0,$stopafterdirection=0,$forcelangdir='')
  137. {
  138. global $conf;
  139. //var_dump($this->dir);exit;
  140. // Check parameters
  141. if (empty($domain))
  142. {
  143. dol_print_error('',"Translate::Load ErrorWrongParameters");
  144. exit;
  145. }
  146. //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
  147. $newdomain = $domain;
  148. $modulename = '';
  149. // Search if a module directory name is provided into lang file name
  150. if (preg_match('/^([^@]+)@([^@]+)$/i',$domain,$regs))
  151. {
  152. $newdomain = $regs[1];
  153. $modulename = $regs[2];
  154. }
  155. // Check cache
  156. if (! empty($this->tab_loaded[$newdomain])) // File already loaded for this domain
  157. {
  158. //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
  159. return 0;
  160. }
  161. $fileread=0;
  162. $langofdir=(empty($forcelangdir)?$this->defaultlang:$forcelangdir);
  163. // Redefine alt
  164. $langarray=explode('_',$langofdir);
  165. if ($alt < 1 && strtolower($langarray[0]) == strtolower($langarray[1])) $alt=1;
  166. if ($alt < 2 && (strtolower($langofdir) == 'en_us' || strtolower($langofdir) == 'fr_fr' || strtolower($langofdir) == 'es_es')) $alt=2;
  167. foreach($this->dir as $keydir => $searchdir)
  168. {
  169. // Directory of translation files
  170. $file_lang = $searchdir.($modulename?'/'.$modulename:'')."/langs/".$langofdir."/".$newdomain.".lang";
  171. $file_lang_osencoded=dol_osencode($file_lang);
  172. $filelangexists=is_file($file_lang_osencoded);
  173. //dol_syslog('Translate::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' file_lang='.$file_lang." => filelangexists=".$filelangexists);
  174. if ($filelangexists)
  175. {
  176. // TODO Move cache read out of loop on dirs
  177. $found=false;
  178. // Enable caching of lang file in memory (not by default)
  179. $usecachekey='';
  180. // Using a memcached server
  181. if (! empty($conf->memcached->enabled) && ! empty($conf->global->MEMCACHED_SERVER))
  182. {
  183. $usecachekey=$newdomain.'_'.$langofdir.'_'.md5($file_lang); // Should not contains special chars
  184. }
  185. // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
  186. else if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02))
  187. {
  188. $usecachekey=$newdomain;
  189. }
  190. if ($usecachekey)
  191. {
  192. //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
  193. require_once(DOL_DOCUMENT_ROOT ."/core/lib/memory.lib.php");
  194. $tmparray=dol_getcache($usecachekey);
  195. if (is_array($tmparray) && count($tmparray))
  196. {
  197. $this->tab_translate=array_merge($tmparray,$this->tab_translate); // Already found values tab_translate overwrites duplicates
  198. //print $newdomain."\n";
  199. //var_dump($this->tab_translate);
  200. if ($alt == 2) $fileread=1;
  201. $found=true; // Found in dolibarr PHP cache
  202. }
  203. }
  204. if (! $found)
  205. {
  206. if ($fp = @fopen($file_lang,"rt"))
  207. {
  208. if ($usecachekey) $tabtranslatedomain=array(); // To save lang content in cache
  209. while ($line = fgets($fp,4096)) // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
  210. {
  211. if ($line[0] != "\n" && $line[0] != " " && $line[0] != "#")
  212. {
  213. $tab=explode('=',$line,2);
  214. $key=trim($tab[0]);
  215. //print "Domain=$domain, found a string for $tab[0] with value $tab[1]<br>";
  216. if (empty($this->tab_translate[$key]) && isset($tab[1]))
  217. {
  218. $value=trim(preg_replace('/\\n/',"\n",$tab[1]));
  219. if ($key == 'DIRECTION') // This is to declare direction of language
  220. {
  221. if ($alt < 2 || empty($this->tab_translate[$key])) // We load direction only for primary files or if not yet loaded
  222. {
  223. $this->tab_translate[$key]=$value;
  224. if ($stopafterdirection) break; // We do not save tab if we stop after DIRECTION
  225. else if ($usecachekey) $tabtranslatedomain[$key]=$value;
  226. }
  227. }
  228. else
  229. {
  230. // On stocke toujours dans le tableau Tab en UTF-8
  231. //if (! empty($this->charset_inputfile[$newdomain]) && $this->charset_inputfile[$newdomain] == 'ISO-8859-1') $value=utf8_encode($value);
  232. $this->tab_translate[$key]=$value;
  233. if ($usecachekey) $tabtranslatedomain[$key]=$value; // To save lang content in cache
  234. }
  235. }
  236. }
  237. }
  238. fclose($fp);
  239. $fileread=1;
  240. // TODO Move cache write out of loop on dirs
  241. // To save lang content for usecachekey into cache
  242. if ($usecachekey && count($tabtranslatedomain))
  243. {
  244. $ressetcache=dol_setcache($usecachekey,$tabtranslatedomain);
  245. if ($ressetcache < 0)
  246. {
  247. $error='Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache;
  248. dol_syslog($error, LOG_ERR);
  249. }
  250. }
  251. //exit;
  252. if (empty($conf->global->MAIN_FORCELANGDIR)) break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
  253. }
  254. }
  255. }
  256. }
  257. // Now we complete with next file
  258. if ($alt == 0)
  259. {
  260. // This function MUST NOT contains call to syslog
  261. //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
  262. $langofdir=strtolower($langarray[0]).'_'.strtoupper($langarray[0]);
  263. $this->load($domain,$alt+1,$stopafterdirection,$langofdir);
  264. }
  265. // Now we complete with reference en_US/fr_FR/es_ES file
  266. if ($alt == 1)
  267. {
  268. // This function MUST NOT contains call to syslog
  269. //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
  270. $langofdir='en_US';
  271. if (preg_match('/^fr/i',$langarray[0])) $langofdir='fr_FR';
  272. if (preg_match('/^es/i',$langarray[0])) $langofdir='es_ES';
  273. $this->load($domain,$alt+1,$stopafterdirection,$langofdir);
  274. }
  275. if ($alt == 2)
  276. {
  277. if ($fileread) $this->tab_loaded[$newdomain]=1; // Set domain file as loaded
  278. if (empty($this->tab_loaded[$newdomain])) $this->tab_loaded[$newdomain]=2; // Marque ce fichier comme non trouve
  279. }
  280. // Check to be sure that SeparatorDecimal differs from SeparatorThousand
  281. if (! empty($this->tab_translate["SeparatorDecimal"]) && ! empty($this->tab_translate["SeparatorThousand"])
  282. && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]) $this->tab_translate["SeparatorThousand"]='';
  283. return 1;
  284. }
  285. /**
  286. * Return translated value of key. Search in lang file, then into database.
  287. * If not found, return key.
  288. * WARNING: To avoid infinite loop (getLabelFromKey->transnoentities->getTradFromKey), getLabelFromKey must
  289. * not be called with same value than input.
  290. *
  291. * @param key
  292. * @return string
  293. */
  294. function getTradFromKey($key)
  295. {
  296. global $db;
  297. $newstr=$key;
  298. if (preg_match('/^CurrencySing([A-Z][A-Z][A-Z])$/i',$key,$reg))
  299. {
  300. $newstr=$this->getLabelFromKey($db,$reg[1],'c_currencies','code_iso','labelsing');
  301. }
  302. else if (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i',$key,$reg))
  303. {
  304. $newstr=$this->getLabelFromKey($db,$reg[1],'c_currencies','code_iso','label');
  305. }
  306. else if (preg_match('/^SendingMethod([0-9A-Z]+)$/i',$key,$reg))
  307. {
  308. $newstr=$this->getLabelFromKey($db,$reg[1],'c_shipment_mode','code','libelle');
  309. }
  310. else if (preg_match('/^PaymentTypeShort([0-9A-Z]+)$/i',$key,$reg))
  311. {
  312. $newstr=$this->getLabelFromKey($db,$reg[1],'c_paiement','code','libelle');
  313. }
  314. else if (preg_match('/^Civility([0-9A-Z]+)$/i',$key,$reg))
  315. {
  316. $newstr=$this->getLabelFromKey($db,$reg[1],'c_civilite','code','civilite');
  317. }
  318. else if (preg_match('/^OrderSource([0-9A-Z]+)$/i',$key,$reg))
  319. {
  320. // TODO Add a table for OrderSourceX
  321. //$newstr=$this->getLabelFromKey($db,$reg[1],'c_ordersource','code','label');
  322. }
  323. return $newstr;
  324. }
  325. /**
  326. * Return text translated of text received as parameter (and encode it into HTML)
  327. * Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
  328. * et si toujours pas trouve, il est retourne tel quel
  329. * Les parametres de cette methode peuvent contenir de balises HTML.
  330. *
  331. * @param key cle de chaine a traduire
  332. * @param param1 chaine de param1
  333. * @param param2 chaine de param2
  334. * @param param3 chaine de param3
  335. * @param param4 chaine de param4
  336. * @param maxsize taille max
  337. * @return string Chaine traduite et code en HTML
  338. */
  339. function trans($key, $param1='', $param2='', $param3='', $param4='', $maxsize=0)
  340. {
  341. if (! empty($this->tab_translate[$key])) // Translation is available
  342. {
  343. $str=$this->tab_translate[$key];
  344. if (! preg_match('/^Format/',$key)) $str=sprintf($str,$param1,$param2,$param3,$param4); // Replace %s and %d except for FormatXXX strings.
  345. if ($maxsize) $str=dol_trunc($str,$maxsize);
  346. // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities
  347. $str=str_replace(array('<','>','"',),array('__lt__','__gt__','__quot__'),$str);
  348. $str=$this->convToOutputCharset($str); // Convert string to $this->charset_output
  349. // Crypt string into HTML
  350. // $str est une chaine stockee en memoire au format $this->charset_output
  351. $str=htmlentities($str,ENT_QUOTES,$this->charset_output);
  352. // Restore HTML tags
  353. $str=str_replace(array('__lt__','__gt__','__quot__'),array('<','>','"',),$str);
  354. return $str;
  355. }
  356. else // Translation is not available
  357. {
  358. $str=$this->getTradFromKey($key);
  359. return $this->convToOutputCharset($str);
  360. }
  361. }
  362. /**
  363. * Return translated value of a text string
  364. * Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
  365. * et si toujours pas trouve, il est retourne tel quel.
  366. * Parameters of this method must not contains any HTML tags.
  367. *
  368. * @param key key of string to translate
  369. * @param param1 chaine de param1
  370. * @param param2 chaine de param2
  371. * @param param3 chaine de param3
  372. * @param param4 chaine de param4
  373. * @return string chaine traduite
  374. */
  375. function transnoentities($key, $param1='', $param2='', $param3='', $param4='')
  376. {
  377. if (! empty($this->tab_translate[$key]))
  378. {
  379. // Si la traduction est disponible
  380. $newstr=sprintf($this->tab_translate[$key],$param1,$param2,$param3,$param4);
  381. }
  382. else
  383. {
  384. $newstr=$this->getTradFromKey($key);
  385. }
  386. return $this->convToOutputCharset($newstr);
  387. }
  388. /**
  389. * Return translated value of a text string
  390. * Si il n'y a pas de correspondance pour ce texte, on cherche dans fichier alternatif
  391. * et si toujours pas trouve, il est retourne tel quel.
  392. * No convert to encoding charset of lang object is done.
  393. * Parameters of this method must not contains any HTML tags.
  394. *
  395. * @param key key of string to translate
  396. * @param param1 chaine de param1
  397. * @param param2 chaine de param1
  398. * @param param3 chaine de param1
  399. * @param param4 chaine de param1
  400. * @return string chaine traduite
  401. */
  402. function transnoentitiesnoconv($key, $param1='', $param2='', $param3='', $param4='')
  403. {
  404. if (! empty($this->tab_translate[$key]))
  405. {
  406. // Si la traduction est disponible
  407. $newstr=sprintf($this->tab_translate[$key],$param1,$param2,$param3,$param4);
  408. }
  409. else
  410. {
  411. $newstr=$this->getTradFromKey($key);
  412. }
  413. return $newstr;
  414. }
  415. /**
  416. * Return translation of a key depending on country
  417. *
  418. * @param str string root to translate
  419. * @param countrycode country code (FR, ...)
  420. * @return string translated string
  421. */
  422. function transcountry($str, $countrycode)
  423. {
  424. if ($this->tab_translate["$str$countrycode"]) return $this->trans("$str$countrycode");
  425. else return $this->trans($str);
  426. }
  427. /**
  428. * Retourne la version traduite du texte passe en parametre complete du code pays
  429. *
  430. * @param str string root to translate
  431. * @param countrycode country code (FR, ...)
  432. * @return string translated string
  433. */
  434. function transcountrynoentities($str, $countrycode)
  435. {
  436. if ($this->tab_translate["$str$countrycode"]) return $this->transnoentities("$str$countrycode");
  437. else return $this->transnoentities($str);
  438. }
  439. /**
  440. * Convert a string into output charset (this->charset_output that should be defined to conf->file->character_set_client)
  441. *
  442. * @param str String to convert
  443. * @param pagecodefrom Page code of src string
  444. * @return string Converted string
  445. */
  446. function convToOutputCharset($str,$pagecodefrom='UTF-8')
  447. {
  448. if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') $str=utf8_encode($str);
  449. if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') $str=utf8_decode(str_replace('€',chr(128),$str));
  450. return $str;
  451. }
  452. /**
  453. * Return list of all available languages
  454. *
  455. * @param langdir Directory to scan
  456. * @param maxlength Max length for each value in combo box (will be truncated)
  457. * @param usecode Show code instead of country name for language variant
  458. * @return array List of languages
  459. */
  460. function get_available_languages($langdir=DOL_DOCUMENT_ROOT,$maxlength=0,$usecode=0)
  461. {
  462. global $conf;
  463. // We scan directory langs to detect available languages
  464. $handle=opendir($langdir."/langs");
  465. $langs_available=array();
  466. while ($dir = trim(readdir($handle)))
  467. {
  468. if (preg_match('/^[a-z]+_[A-Z]+/i',$dir))
  469. {
  470. $this->load("languages");
  471. if ($usecode || ! empty($conf->global->MAIN_SHOW_LANGUAGE_CODE))
  472. {
  473. $langs_available[$dir] = $dir.': '.dol_trunc($this->trans('Language_'.$dir),$maxlength);
  474. }
  475. else
  476. {
  477. $langs_available[$dir] = $this->trans('Language_'.$dir);
  478. }
  479. }
  480. }
  481. return $langs_available;
  482. }
  483. /**
  484. * Return if a filename $filename exists for current language (or alternate language)
  485. *
  486. * @param filename Language filename to search
  487. * @param searchalt Search also alernate language file
  488. * @return boolean true if exists and readable
  489. */
  490. function file_exists($filename,$searchalt=0)
  491. {
  492. // Test si fichier dans repertoire de la langue
  493. foreach($this->dir as $searchdir)
  494. {
  495. if (is_readable(dol_osencode($searchdir."/langs/".$this->defaultlang."/".$filename))) return true;
  496. if ($searchalt)
  497. {
  498. // Test si fichier dans repertoire de la langue alternative
  499. if ($this->defaultlang != "en_US") $filenamealt = $searchdir."/langs/en_US/".$filename;
  500. else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
  501. if (is_readable(dol_osencode($filenamealt))) return true;
  502. }
  503. }
  504. return false;
  505. }
  506. /**
  507. * Return full text translated to language label for a key. Store key-label in a cache.
  508. * This function need module "numberwords" to be installed. If not it will return
  509. * same number (this module is not provided by default as it use non GPL source code).
  510. *
  511. * @param number Number to encode in full text
  512. * @param isamount 1=It's an amount, 0=it's just a number
  513. * @return string Label translated in UTF8 (but without entities)
  514. * 10 if setDefaultLang was en_US => ten
  515. * 123 if setDefaultLang was fr_FR => cent vingt trois
  516. */
  517. function getLabelFromNumber($number,$isamount=0)
  518. {
  519. global $conf;
  520. /*
  521. $outlang=$this->defaultlang; // Output language we want
  522. $outlangarray=explode('_',$outlang,2);
  523. // If lang is xx_XX, then we use xx
  524. if (strtolower($outlangarray[0]) == strtolower($outlangarray[1])) $outlang=$outlangarray[0];
  525. */
  526. $newnumber=$number;
  527. foreach ($conf->file->dol_document_root as $dirroot)
  528. {
  529. $dir=$dirroot."/core/modules/substitutions";
  530. $fonc='numberwords';
  531. if (file_exists($dir.'/functions_'.$fonc.'.lib.php'))
  532. {
  533. include_once($dir.'/functions_'.$fonc.'.lib.php');
  534. $newnumber=numberwords_getLabelFromNumber($this,$number,$isamount);
  535. break;
  536. }
  537. }
  538. return $newnumber;
  539. }
  540. /**
  541. * Return a label for a key. Store key-label into cache variable $this->cache_labels to save SQL requests to get labels.
  542. * This function can be used to get label in database but more often to get code from key id.
  543. *
  544. * @param db Database handler
  545. * @param key Key to get label (key in language file)
  546. * @param tablename Table name without prefix
  547. * @param fieldkey Field for key
  548. * @param fieldlabel Field for label
  549. * @return string Label in UTF8 (but without entities)
  550. */
  551. function getLabelFromKey($db,$key,$tablename,$fieldkey,$fieldlabel)
  552. {
  553. // If key empty
  554. if ($key == '') return '';
  555. // Check in language array
  556. if ($this->transnoentities($key) != $key)
  557. {
  558. return $this->transnoentities($key); // Found in language array
  559. }
  560. // Check in cache
  561. if (isset($this->cache_labels[$tablename][$key])) // Can be defined to 0 or ''
  562. {
  563. return $this->cache_labels[$tablename][$key]; // Found in cache
  564. }
  565. $sql = "SELECT ".$fieldlabel." as label";
  566. $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
  567. $sql.= " WHERE ".$fieldkey." = '".$key."'";
  568. dol_syslog('Translate::getLabelFromKey sql='.$sql,LOG_DEBUG);
  569. $resql = $db->query($sql);
  570. if ($resql)
  571. {
  572. $obj = $db->fetch_object($resql);
  573. if ($obj) $this->cache_labels[$tablename][$key]=$obj->label;
  574. else $this->cache_labels[$tablename][$key]=$key;
  575. $db->free($resql);
  576. return $this->cache_labels[$tablename][$key];
  577. }
  578. else
  579. {
  580. $this->error=$db->lasterror();
  581. dol_syslog("Translate::getLabelFromKey error=".$this->error,LOG_ERR);
  582. return -1;
  583. }
  584. }
  585. }
  586. ?>