#!/usr/bin/php
<?php

// Call Google Translate API
function translate($text, $from, $to) {
    $key = "AIzaSyD5sFp2R2IMtDVWdu-4X-TptJCSod0chVc";
    $url = sprintf("https://www.googleapis.com/language/translate/v2?"
        ."key=%s&source=%s&target=%s&q=%s", $key, $from, $to, urlencode($text));

    if( ($response = @file_get_contents($url)) === false ) {
        die("Got negative response from Google Translate server.\n"
            ."Check your internet connection and make sure that you "
            ."entered valid language codes.\n");
    }

    $response = json_decode($response, true);

    return $response["data"]["translations"][0]["translatedText"];
}

// Parse input
if( $argc != 3 ) {
    echo sprintf("Usage: %s FROM TO\n", $argv[0]);

    if( $argc > 1 && $argv[1] == "--help" ) {
        echo "FROM is the input language, TO is the language to translate to.\n"
            ."Both languages should be entered as a 2-character long code.\n";
    }

    exit;
}

list($from, $to) = array_slice($argv, 1);
$lang_format = "/^[a-z]{2}$/i";

if( !preg_match($lang_format, $from) || !preg_match($lang_format, $to) )
    die("A language should be specified as two characters.\n");

// Show parsed input
printf("Input language:  %s\nOutput language: %s\n",
       $from = strtolower($from), $to = strtolower($to));

// Read input
$handle = fopen("php://stdin", "r");

echo "\nEnter the text that you want to translate (use ctrl-D to "
    ."end the program).\n\nTranslate: ";

while( ($read = fgets($handle)) !== false )
    printf("Translation: %s\n\nTranslate: ", translate($read, $from, $to));

fclose($handle);

?>
