<?php
/**
 * Translating language with Google API
 * @author gabe@fijiwebdesign.com
 * @version $Id$
 * @license - Share-Alike 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)
 *
 * Google requires attribution for their Language API, please see: http://code.google.com/apis/ajaxlanguage/documentation/#Branding
 *
 */
class gtranslate {
    var $path;
    function translate($text, $from='', $to='en') {
        $url='http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='.rawurlencode($text).'&langpair='.rawurlencode($from.'|'.$to);
        $response=file_get_contents($url,null,stream_context_create(array('http'=>array('method'=>"GET",'header'=>"Referer: http://".$_SERVER['HTTP_HOST']."/\r\n"))));
        if (preg_match("/{\"translatedText\":\"([^\"]+)\"/i", $response, $matches)) {return self::_unescapeUTF8EscapeSeq($matches[1]);}
        return false;
    }
    function _unescapeUTF8EscapeSeq($str) {
        return preg_replace_callback("/\\\u([0-9a-f]{4})/i", create_function('$matches', 'return gtranslate::_bin2utf8(hexdec($matches[1]));'), $str);
    }
    function _bin2utf8($bin) {
        if ($bin <= 0x7F) return chr($bin);
        else if ($bin >= 0x80 && $bin <= 0x7FF) return pack("C*", 0xC0 | $bin >> 6, 0x80 | $bin & 0x3F);
        else if ($bin >= 0x800 && $bin <= 0xFFF) return pack("C*", 0xE0 | $bin >> 11, 0x80 | $bin >> 6 & 0x3F, 0x80 | $bin & 0x3F);
        else if ($bin >= 0x10000 && $bin <= 0x10FFFF) return pack("C*", 0xE0 | $bin >> 17, 0x80 | $bin >> 12 & 0x3F, 0x80 | $bin >> 6& 0x3F, 0x80 | $bin & 0x3F);
    }
    function get_extensions() {
        $languages_ext=file($this->path."languages.ini");
        $ret_val=array();
        foreach($languages_ext as $key=>$data) {
            $da=explode('=',$data);
            $ret_val[trim($da[1])]=trim($da[0]);
            $ret_val[$key]=trim($da[1]).'=>'.trim($da[0]);
        }
        return $ret_val;
    }
}

$obj=new gtranslate();
$lan=$obj->get_extensions();
$chk=$obj->translate('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 'en', 'hi');
/*** example usage
// we need the page treated as utf-8, otherwise the encoding will be mangled
header('Content-Type: text/html; charset=utf-8');
// require google language api class
require_once('google.translator.php');
// translate text
$text = 'Welcome to my website.';
$trans_text = gtranslate::translate($text, 'en', 'it'); //Google_Translate_API
if ($trans_text !== false) {
        echo $trans_text;
}
*/
?>