<?php
/**
 * Proxy della REST API di Google TTS
 * @package SCREENREADER::plugins::system
 * @subpackage screenreader
 * @subpackage libraries
 * @subpackage tts
 * @author Joomla! Extensions Store
 * @copyright (C) 2015 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html  
 */
ini_set ( 'display_errors', false );
// Joomla Init
define ( '_JEXEC', 1 );
defined ( '_JEXEC' ) or die ();
define ( 'JPATH_BASE', realpath ( '../../../../../../' ) );

if (file_exists(JPATH_BASE . '/defines.php')) {
	include_once JPATH_BASE . '/defines.php';
}

if (!defined('_JDEFINES')) {
	require_once JPATH_BASE.'/includes/defines.php';
}

require_once (JPATH_BASE . '/includes/framework.php');
$app = JFactory::getApplication ( 'site' );

// testo
$text = preg_replace ( "/[" . PHP_EOL . "]+/", " ", ($GLOBALS['_' . strtoupper('get')] ['text']) );
// lingua
$lang = ($GLOBALS['_' . strtoupper('get')] ['lang']);
// security token same domain
$token = ($GLOBALS['_' . strtoupper('get')] ['token']);
// engine token if used by the engine
$engineToken = ($GLOBALS['_' . strtoupper('get')] ['engine_token']);

if(!function_exists('curl_version')) {
	exit();
}

if ($token === md5 ( $_SERVER ['HTTP_HOST'] )) {
	// Random user agents DB
	$userAgents = array (
			"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0",
			"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0",
			"Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0",
			"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0",
			"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
			"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36",
			"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36",
			"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2224.3 Safari/537.36",
			"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2224.3 Safari/537.36",
			"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A",
			"Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25",
			"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko",
			"Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko",
			"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)",
			"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)",
			"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)",
			"Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)"
		);
	$ua = $userAgents [rand ( 0, count ( $userAgents ) - 1 )];
	
	// Mapped language to code
	$mappedLangCode = array (
			'ar-AR' => 'leila22k',
			'ar-AE' => 'leila22k',
			'ar-AA' => 'leila22k',
			'ar' => 'leila22k',
			'en-US' => 'karen22k',
			'en-GB' => 'graham22k',
			'en' => 'graham22k',
			'fr-FR' => 'alice22k',
			'fr' => 'alice22k',
			'de-DE' => 'andreas22k',
			'de' => 'andreas22k',
			'es-ES' => 'maria22k',
			'es' => 'maria22k',
			'it-IT' => 'fabiana22k',
			'it' => 'fabiana22k',
			'nl-BE' => 'daan22k',
			'nl-NL' => 'daan22k',
			'nl' => 'daan22k',
			'ca-ES' => 'laia22k',
			'ca' => 'laia22k',
			'cs-CZ' => 'eliska22k',
			'cs' => 'eliska22k',
			'da-DK' => 'mette22k',
			'da' => 'mette22k',
			'el-GR' => 'dimitris22k',
			'el' => 'dimitris22k',
			'ja-JP' => 'sakura22k',
			'ja' => 'sakura22k',
			'ko-KR' => 'minji22k',
			'ko' => 'minji22k',
			'nb-NO' => 'bente22k',
			'nb' => 'bente22k',
			'pl-PL' => 'ania22k',
			'pl' => 'ania22k',
			'pt-PT' => 'celia22k',
			'pt-BR' => 'celia22k',
			'pt' => 'celia22k',
			'ru-RU' => 'alyona22k',
			'ru' =>'alyona22k',
			'sv-FI' => 'sanna22k',
			'sv-SE' => 'sanna22k',
			'sv' => 'sanna22k',
			'tr-TR' => 'ipek22k',
			'tr' => 'ipek22k'
	);
	
	if(array_key_exists($lang, $mappedLangCode)) {
		$langSelectedVoice = $mappedLangCode[$lang];
	} else {
		$langSelectedVoice = 'graham22k';
	}
	
	$plugin = JPluginHelper::getPlugin('system', 'screenreader');
	$pluginParams = json_decode($plugin->params);
	$main_account_login = (isset($pluginParams->virtualspeaker_account_login) && $pluginParams->virtualspeaker_account_login) ? $pluginParams->virtualspeaker_account_login : 'EVAL_VAAS'; // Expires on 2017/09/23
	$application_login = (isset($pluginParams->virtualspeaker_application_login) && $pluginParams->virtualspeaker_application_login) ? $pluginParams->virtualspeaker_application_login : 'EVAL_9385684';
	$application_password = (isset($pluginParams->virtualspeaker_application_password) && $pluginParams->virtualspeaker_application_password) ? $pluginParams->virtualspeaker_application_password : 'qyhxyl0k';
		
	// Make the first POST form request and get the HTML page including the MP3 link
	$qs = array (
			'prot_vers' => '2',
			'cl_env' => 'PHP_APACHE_2.2.3_LINUX_SUSE',
			'cl_vers' => '1-30',
			'cl_login' => $main_account_login,
			'cl_app' => $application_login,
			'cl_pwd' => $application_password,
			'req_type' => '',
			'req_snd_id' => '',
			'req_voice' => $langSelectedVoice,
			'req_text' => $text,
			'req_vol' => '',
			'req_spd' => '',
			'req_vct' => '',
			'req_eq1' => '',
			'req_eq2' => '',
			'req_eq3' => '',
			'req_eq4' => '',
			'req_snd_type' => '',
			'req_snd_ext' => '',
			'req_snd_kbps' => '',
			'req_alt_snd_type' => '',
			'req_alt_snd_ext' => '',
			'req_alt_snd_kbps' => '',
			'req_wp' => '',
			'req_bp' => '',
			'req_mp' => '',
			'req_comment' => '',
			'req_start_time' => '',
			'req_timeout' => '',
			'req_asw_type' => '',
			'req_asw_as_alt_snd' => '',
			'req_err_as_id3' => '',
			'req_echo' => '' 
	);
	
	// Remote POST using sockets or CURL lib
	$ch = curl_init();
	$url = "http://vaas.acapela-group.com/Services/Synthesizer";
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $qs);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	
	
	// execute post
	$HTTPResponse = new stdClass();
	$HTTPResponse->body = curl_exec ($ch);
	
	// close the connection
	curl_close ($ch);
	
	if($HTTPResponse->body) {
		$varNvalue = explode('&', $HTTPResponse->body);
		foreach ($varNvalue as $entry) {
			$parts = explode('=', $entry);
			if (!empty($parts[1]) && $parts[0] == 'snd_url') {
				$mp3BinaryFile = urldecode($parts[1]);   //those fields have been url encoded by the service for transportation
			}
		}
	}
		
	// Now scrape the javascript var for the Mp3 file generated
	// Found a valid Mp3 file to play?
	$binaryString = null;
	$download_size = 0;
	if($mp3BinaryFile) {
		$opts = array(
				'http'=>array(
						'method'=>"GET",
						'header'=>"Accept-language: en\r\n" .
								  "Host: http://www.acapela-vaas.com\r\n" .
								  "Cache-Control: no-cache\r\n" .
								  "Connection: keep-alive\r\n" .
								  "Pragma: no-cache\r\n" .
								  "Range: bytes=0-\r\n" .
								  "User-Agent: $ua\r\n" .
								  "Accept: */*\r\n" .
								  "Referer: http://www.acapela-vaas.com\r\n" .
								  "Accept-Language: en-US,en;q=0.8,de;q=0.6,es;q=0.4,fr;q=0.2,it;q=0.2,ru;q=0.2,ja;q=0.2,el;q=0.2,sk;q=0.2,nl;q=0.2,ar;q=0.2,sv;q=0.2'"
				)
		);
		$context = stream_context_create($opts);
		$binaryString = file_get_contents ($mp3BinaryFile, false, $context );
		
		// If fopen is not enabled, fallback on the socket HTTP GET
		if(!$binaryString) {
			$socketHeadersArray = array(
					"Accept-language" => "en",
					"Cache-Control" => "no-cache",
					"Connection" => "keep-alive",
					"Pragma" => "no-cache",
					"Range" => "bytes=0-",
					"User-Agent" => $ua,
					"Accept" => "*/*",
					"Referer" => "http://www.acapela-vaas.com",
					"Accept-Language" => "en-US,en;q=0.8,de;q=0.6,es;q=0.4,fr;q=0.2,it;q=0.2,ru;q=0.2,ja;q=0.2,el;q=0.2,sk;q=0.2,nl;q=0.2,ar;q=0.2,sv;q=0.2");
			require_once '../http/http.php';
			$HTTPClient = new jscrHttp ();
			$binaryString = $HTTPClient->get($mp3BinaryFile, $socketHeadersArray)->body;
		}
		
		$download_size = strlen ( $binaryString );
	}
	
	// send the headers
	header ( "Pragma: public" ); // purge the browser cache
	header ( "Expires: 0" ); // ...
	header ( "Cache-Control:" ); // ...
	header ( "Cache-Control: public" ); // ...
	header ( "Content-Description: File Transfer" ); //
	header ( "Content-Type: audio/mpeg" ); // file type
	header ( "Content-Disposition: attachment; filename=tts.mp3" );
	header ( "Content-Transfer-Encoding: binary" ); // transfer method
	header ( "Content-Length: $download_size" ); // download length
	
	echo $binaryString;
}
exit ();