Skip to content

Instantly share code, notes, and snippets.

@marcolino
Last active December 24, 2015 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcolino/6830343 to your computer and use it in GitHub Desktop.
Save marcolino/6830343 to your computer and use it in GitHub Desktop.
Contribution to i18next project to auto-translate missing entries
<?php
#
# i18next
#
# This script can be used to auto-translate missing keys when using
# "sendMissing: true" option in i18next.
# It should be placed - renamed as "index.php" - inside each of locales
# subdirs (say: 'locales/it/index.php', 'locales/es/index.php', ...).
# A sample of i18n config options could be:
# i18n.init({
# sendMissing: true, // set this to false in production
# resPostPath: 'locales/__lng__/',
# sendMissingTo: 'current',
# postAsync: true,
# }, function() {
# $("body").i18n();
# });
#
# Notes:
# JSON translations files shoul be writable by web server user
# (example: "chown www-data locales/*/translation.json")
#
# Of course automatic translations MUST be revised by a human...
#
$from = 'en'; // source language is always English, by definition
$to = basename(dirname(__FILE__)); // destination language is the name of parent directory where this script resides
$jsonTranslationsFile = "./translation.json"; // JSON translation file
// open the the JSON translations file
if (($handle = fopen($jsonTranslationsFile, "c+")) === FALSE) {
$e = error_get_last();
error("can't open [$to] translations file!" . " " . $e["message"]);
}
if (flock($handle, LOCK_EX)) { // lock file and return with error if unable to lock
$size = filesize($jsonTranslationsFile);
if ($size > 0) { // some translation already exists
$jsonTranslations = fread($handle, filesize($jsonTranslationsFile)); # translations JSON
$translations = json_decode($jsonTranslations, true); # array from translations
} else {
$translations = array(); // empty array
}
// usually we have only one key in the request, but loop on all parameters to be on the safe side...
foreach ($_REQUEST as $key) {
$key = urldecode($key);
if (!array_key_exists($key, $translations)) { // check key isn't present, yet (it shouldn't be...)
$value = translate($key, $from, $to); // translate key
$translations[$key] = $value; // add translated key to translations
}
}
ksort($translations, SORT_STRING | SORT_FLAG_CASE); // sort translations keys to produce a sorted file...
$jsonTranslations = json_encode($translations, JSON_PRETTY_PRINT);
ftruncate($handle, 0); // truncate file
rewind($handle); // rewind file handle
if (fwrite($handle, $jsonTranslations) === FALSE) {
error("can't write to [$to] translations file!");
}
flock($handle, LOCK_UN); // unlock file
} else {
error("can't lock to read [$to] translations file!");
}
// close file
fclose($handle);
terminate($translations);
# translate a word with Google service
function translate($word, $from, $to) {
$word = urlencode($word);
$url = "http://translate.google.com/translate_a/t?client=t&text=".$word."&hl=".$from."&sl=".$from."&tl=".$to."&ie=UTF-8&oe=UTF-8&multires=1&otf=1&ssel=3&tsel=3&sc=1";
$result = curl($url);
$result = explode('"', $result);
$translation = $result[1];
return $translation;
}
function curl($url, $params = array(), $isCookieSet = false) {
if (!$isCookieSet) {
// create a cookie file
$curlCookieFile = tempnam("/tmp", "CURLCOOKIE");
// visit the page to set the cookie properly
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $curlCookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
}
$str = ''; $str_arr= array();
foreach ($params as $key => $value) {
$str_arr[] = urlencode($key) . "=" . urlencode($value);
}
if (!empty($str_arr))
$str = '?' . implode('&', $str_arr);
// visit the cookie page
$Url = $url . $str;
$ch = curl_init($Url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $curlCookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
return $output;
}
function terminate($data) {
jsonOut($data);
exit(0);
}
function error($msg) {
$lastError = error_get_last();
if ($lastError["message"]) {
$msg .= " (" . $lastError["message"] . ")";
}
jsonOut(["error" => $msg]);
exit(-1);
}
function jsonOut($msg) {
header('Content-type: application/json');
print json_encode($msg);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment