autotranslator.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. /* Copyright (C) 2009-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file dev/translation/langAutoParser.class.php
  19. * \ingroup dev
  20. * \brief This file is an example for a command line script
  21. */
  22. /**
  23. * Class to parse language files and translate them
  24. * This is a language automatic translator parser for Dolibarr
  25. */
  26. class autoTranslator
  27. {
  28. private $_translatedFiles = array();
  29. private $_destlang = '';
  30. private $_refLang = '';
  31. private $_langDir = '';
  32. private $_limittofile = '';
  33. private $_time;
  34. private $_time_end;
  35. private $_outputpagecode = 'UTF-8';
  36. private $_apikey;
  37. //private $_outputpagecode = 'ISO-8859-1';
  38. const DIR_SEPARATOR = '/';
  39. /**
  40. * Constructor
  41. *
  42. * @param string $_destlang Destination lang
  43. * @param string $_refLang Ref lang
  44. * @param string $_langDir Dir lang
  45. * @param string $_limittofile Limit to file
  46. * @param string $_apikey Api key
  47. * @return void
  48. */
  49. function __construct($_destlang, $_refLang, $_langDir, $_limittofile, $_apikey)
  50. {
  51. // Set enviorment variables
  52. $this->_destlang = $_destlang;
  53. $this->_refLang = $_refLang;
  54. $this->_langDir = $_langDir.self::DIR_SEPARATOR;
  55. $this->_time = date('Y-m-d H:i:s');
  56. $this->_limittofile = $_limittofile;
  57. $this->_apikey = $_apikey;
  58. // Translate
  59. //ini_set('default_charset','UTF-8');
  60. ini_set('default_charset',$this->_outputpagecode);
  61. $this->parseRefLangTranslationFiles();
  62. }
  63. /**
  64. * Parse file
  65. *
  66. * @return void
  67. */
  68. private function parseRefLangTranslationFiles()
  69. {
  70. $files = $this->getTranslationFilesArray($this->_refLang);
  71. $counter = 1;
  72. foreach($files as $file)
  73. {
  74. if ($this->_limittofile && $this->_limittofile != $file) continue;
  75. $counter++;
  76. $fileContent = null;
  77. $refPath = $this->_langDir.$this->_refLang.self::DIR_SEPARATOR.$file;
  78. $fileContent = file($refPath,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
  79. print "Processing file " . $file . ", with ".count($fileContent)." lines<br>\n";
  80. // Define target dirs
  81. $targetlangs=array($this->_destlang);
  82. if ($this->_destlang == 'all')
  83. {
  84. $targetlangs=array();
  85. // If we must process all languages
  86. $arraytmp=dol_dir_list($this->_langDir,'directories',0);
  87. foreach($arraytmp as $dirtmp)
  88. {
  89. if ($dirtmp['name'] === $this->_refLang) continue; // We discard source language
  90. $tmppart=explode('_',$dirtmp['name']);
  91. if (preg_match('/^en/i',$dirtmp['name'])) continue; // We discard en_* languages
  92. if (preg_match('/^fr/i',$dirtmp['name'])) continue; // We discard fr_* languages
  93. if (preg_match('/^es/i',$dirtmp['name'])) continue; // We discard es_* languages
  94. if (preg_match('/ca_ES/i',$dirtmp['name'])) continue; // We discard es_CA language
  95. if (preg_match('/pt_BR/i',$dirtmp['name'])) continue; // We discard pt_BR language
  96. if (preg_match('/nl_BE/i',$dirtmp['name'])) continue; // We discard nl_BE language
  97. if (preg_match('/^\./i',$dirtmp['name'])) continue; // We discard files .*
  98. if (preg_match('/^CVS/i',$dirtmp['name'])) continue; // We discard CVS
  99. $targetlangs[]=$dirtmp['name'];
  100. }
  101. //var_dump($targetlangs);
  102. }
  103. // Process translation of source file for each target languages
  104. foreach($targetlangs as $my_destlang)
  105. {
  106. $this->_translatedFiles = array();
  107. $destPath = $this->_langDir.$my_destlang.self::DIR_SEPARATOR.$file;
  108. // Check destination file presence
  109. if (! file_exists($destPath))
  110. {
  111. // No file present, we generate file
  112. echo "File not found: " . $destPath . ". We generate it.<br>\n";
  113. $this->createTranslationFile($destPath,$my_destlang);
  114. }
  115. else
  116. {
  117. echo "Updating file: " . $destPath . "<br>\n";
  118. }
  119. // Translate lines
  120. $fileContentDest = file($destPath,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
  121. $newlines=0;
  122. foreach($fileContent as $line){
  123. $key = $this->getLineKey($line);
  124. $value = $this->getLineValue($line);
  125. if ($key && $value)
  126. {
  127. $newlines+=$this->translateFileLine($fileContentDest,$file,$key,$value,$my_destlang);
  128. }
  129. }
  130. $this->updateTranslationFile($destPath,$file,$my_destlang);
  131. echo "New translated lines: " . $newlines . "<br>\n";
  132. //if ($counter ==3) die('fim');
  133. }
  134. }
  135. }
  136. /**
  137. * Update file with new translations
  138. *
  139. * @param string $destPath Target path
  140. * @param string $file File
  141. * @param string $my_destlang Target language code
  142. * @return void
  143. */
  144. private function updateTranslationFile($destPath, $file, $my_destlang)
  145. {
  146. $this->_time_end = date('Y-m-d H:i:s');
  147. if (isset($this->_translatedFiles[$file]) && count($this->_translatedFiles[$file])>0)
  148. {
  149. $fp = fopen($destPath, 'a');
  150. fwrite($fp, "\n");
  151. fwrite($fp, "\n");
  152. fwrite($fp, "// START - Lines generated via autotranslator.php tool (".$this->_time.").\n");
  153. fwrite($fp, "// Reference language: ".$this->_refLang." -> ".$my_destlang."\n");
  154. foreach( $this->_translatedFiles[$file] as $line) {
  155. fwrite($fp, $line . "\n");
  156. }
  157. fwrite($fp, "// STOP - Lines generated via autotranslator.php tool (".$this->_time_end.").\n");
  158. fclose($fp);
  159. }
  160. return;
  161. }
  162. /**
  163. * Create a new translation file
  164. *
  165. * @param string $path Path
  166. * @param string $my_destlang Target language code
  167. * @return void
  168. */
  169. private function createTranslationFile($path, $my_destlang)
  170. {
  171. $fp = fopen($path, 'w+');
  172. fwrite($fp, "/*\n");
  173. fwrite($fp, " * Language code: {$my_destlang}\n");
  174. fwrite($fp, " * Automatic generated via autotranslator.php tool\n");
  175. fwrite($fp, " * Generation date " . $this->_time. "\n");
  176. fwrite($fp, " */\n");
  177. fclose($fp);
  178. return;
  179. }
  180. /**
  181. * Put in array _translatedFiles[$file], line of a new tranlated pair
  182. *
  183. * @param string $content Existing content of dest file
  184. * @param string $file Target file name translated (xxxx.lang)
  185. * @param string $key Key to translate
  186. * @param string $value Existing value in source file
  187. * @param string $my_destlang Language code (ie: fr_FR)
  188. * @return int 0=Nothing translated, 1=Record translated
  189. */
  190. private function translateFileLine($content, $file, $key, $value, $my_destlang)
  191. {
  192. //print "key =".$key."\n";
  193. foreach( $content as $line ) {
  194. $destKey = $this->getLineKey($line);
  195. $destValue = $this->getLineValue($line);
  196. // If translated return
  197. //print "destKey=".$destKey."\n";
  198. if ( trim($destKey) == trim($key) )
  199. { // Found already existing translation (key already exits in dest file)
  200. return 0;
  201. }
  202. }
  203. if ($key == 'CHARSET') $val=$this->_outputpagecode;
  204. elseif (preg_match('/^Format/',$key)) $val=$value;
  205. elseif ($value=='-') $val=$value;
  206. else
  207. {
  208. // If not translated then translate
  209. if ($this->_outputpagecode == 'UTF-8') $val=$this->translateTexts(array($value),substr($this->_refLang,0,2),substr($my_destlang,0,2));
  210. else $val=utf8_decode($this->translateTexts(array($value),substr($this->_refLang,0,2),substr($my_destlang,0,2)));
  211. }
  212. $val=trim($val);
  213. if (empty($val)) return 0;
  214. $this->_translatedFiles[$file][] = $key . '=' . $val ;
  215. return 1;
  216. }
  217. /**
  218. * getLineKey
  219. *
  220. * @param string $line Line found into file
  221. * @return string Key
  222. */
  223. private function getLineKey($line)
  224. {
  225. $arraykey = explode('=',$line,2);
  226. return trim($arraykey[0]);
  227. }
  228. /**
  229. * getLineValue
  230. *
  231. * @param string $line Line found into file
  232. * @return string Value
  233. */
  234. private function getLineValue($line)
  235. {
  236. $arraykey = explode('=',$line,2);
  237. return trim(isset($arraykey[1])?$arraykey[1]:'');
  238. }
  239. /**
  240. * getTranslationFilesArray
  241. *
  242. * @param string $lang Language code
  243. * @return array Array
  244. */
  245. private function getTranslationFilesArray($lang)
  246. {
  247. $dir = new DirectoryIterator($this->_langDir.$lang);
  248. while($dir->valid()) {
  249. if(!$dir->isDot() && $dir->isFile() && ! preg_match('/^\./',$dir->getFilename())) {
  250. $files[] = $dir->getFilename();
  251. }
  252. $dir->next();
  253. }
  254. return $files;
  255. }
  256. /**
  257. * Return translation of a value
  258. *
  259. * @param array $src_texts Array with one value
  260. * @param string $src_lang Language code source (us, fr, it, ...)
  261. * @param string $dest_lang Language code target (es, de, ...)
  262. * @return string Value translated
  263. */
  264. private function translateTexts($src_texts, $src_lang, $dest_lang)
  265. {
  266. // We want to be sure that src_lang and dest_lang are using 2 chars only
  267. $tmp=explode('_',$src_lang);
  268. if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $src_lang=$tmp[0];
  269. $tmp=explode('_',$dest_lang);
  270. if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $dest_lang=$tmp[0];
  271. //setting language pair
  272. $lang_pair = $src_lang.'|'.$dest_lang;
  273. $src_text_to_translate=preg_replace('/%s/','SSSSS',implode('',$src_texts));
  274. $src_text_to_translate=preg_replace('/'.preg_quote('\n\n').'/',' NNNNN ',$src_text_to_translate);
  275. // Define GET URL v1
  276. //$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($src_text_to_translate)."&langpair=".urlencode($lang_pair);
  277. // Example: http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=Setup%20area&langpair=en_US|fr_FR
  278. // Define GET URL v2
  279. $url = "https://www.googleapis.com/language/translate/v2?key=".$this->_apikey."&q=".urlencode($src_text_to_translate)."&source=".urlencode($src_lang)."&target=".urlencode($dest_lang);
  280. // Example: https://www.googleapis.com/language/translate/v2?key=_apikey&q=Setup%20area&source=en_US&target=fr_FR
  281. // Send request
  282. //print "Url to translate: ".$url."\n";
  283. if (! function_exists("curl_init"))
  284. {
  285. print "Error, your PHP does not support curl functions.\n";
  286. die();
  287. }
  288. $ch = curl_init();
  289. curl_setopt($ch, CURLOPT_URL, $url);
  290. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  291. curl_setopt($ch, CURLOPT_REFERER, "Mozilla");
  292. $body = curl_exec($ch);
  293. curl_close($ch);
  294. //sleep(1); // This is to avoid to overload server.
  295. // now, process the JSON string
  296. $json = json_decode($body, true);
  297. if ((! empty($json['responseStatus']) && $json['responseStatus'] != 200)
  298. || count($json['data']['translations']) == 0)
  299. {
  300. print "Error: ".$json['responseStatus']." ".$url."\n";
  301. return false;
  302. }
  303. $rep=$json['data']['translations'][0]['translatedText'];
  304. $rep=preg_replace('/SSSSS/i','%s',$rep);
  305. $rep=preg_replace('/NNNNN/i','\n\n',$rep);
  306. $rep=preg_replace('/&#39;/i','\'',$rep);
  307. //print "OK ".join('',$src_texts).' => '.$rep."\n";
  308. return $rep;
  309. }
  310. }