/** * Translate the content of a file with Google Translate API. * * @return The automatic translation. */ public function translate() { // We must check if the file exist. // For example, when we start a translation, save it, and then open it from work in progress module, the path don't exist and we must use the fallback path for translation $originalContent = is_file($this->full_path) ? file_get_contents($this->full_path) : file_get_contents($this->full_path_fallback); // We search for new line caracters and mark it ! (Google API delete new line) $originalContent = str_replace("\n", "[@]", $originalContent); $lang = AccountManager::getInstance()->vcsLang; $translation = false; $gt = new Gtranslate(); $gt->setRequestType('curl'); $translation = $gt->translate('en', $lang, $originalContent); // Replace new line mark $translation = str_replace("[@]", "\n", $translation); // Few substitutions $translation = str_replace("&", "&", $translation); $translation = str_replace("& ", "&", $translation); $translation = str_replace("'", "'", $translation); $translation = str_replace(""", '"', $translation); $translation = str_replace("<", '<', $translation); $translation = str_replace(">", '>', $translation); // CLeanUp entities. Google return it like this : & Reftitle.parameters;. We convert it like this : &reftitle.parameters; $translation = preg_replace_callback("/(&)\\s(.)(.[^;]*?)(;)/s", create_function('$matches', 'return $matches[1].strtolower($matches[2]).$matches[3].$matches[4];'), $translation); // We remove extra space after :: operator $translation = preg_replace("/(\\w+)(::)(\\s)(\\w+)/s", "\$1\$2\$4", $translation); // We delete space into tab like this </ b> $translation = preg_replace("/(<\\/\\s(\\w+[^>]*)>)/s", "</\$2>", $translation); // We delete space just after an open tag, and just before a close tag, like this <b> foo </b> $translation = preg_replace("/(<(\\w+[^>]*)>)(\\s?)(.[^>]*?)(\\s?)(<\\/(\\2)>)/s", "<\$2>\$4</\$7>", $translation); return $translation; }
/** * Get the translation from a given string using Google Translate API */ public function getGGTranslation() { if (!AccountManager::getInstance()->isLogged()) { return JsonResponseBuilder::failure(); } $str = $this->getRequestVariable('str'); $lang = AccountManager::getInstance()->vcsLang; $translation = false; $str = str_replace("\n", "[@]", $str); $gt = new Gtranslate(); $gt->setRequestType('curl'); $translation = $gt->translate('en', $lang, $str); // Replace new line mark $translation = str_replace("[@]", "<br>", $translation); // Few substitutions $translation = str_replace("&", "&", $translation); $translation = str_replace("& ", "&", $translation); $translation = str_replace("'", "'", $translation); $translation = str_replace(""", '"', $translation); $translation = str_replace("<", '<', $translation); $translation = str_replace(">", '>', $translation); return JsonResponseBuilder::success(array('translation' => $translation)); }