<?php
/**
 * Site Export Plugin
 * 
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     i-net software <tools@inetsoftware.de>
 * @author     Gerry Weissbach <gweissbach@inetsoftware.de>
 */

// must be run within Dokuwiki
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');

require_once(DOKU_PLUGIN.'action.php');

class action_plugin_translator extends DokuWiki_Action_Plugin {

	var $functions = null;		// Helper
	
	function getInfo(){
        return array_merge(confToHash(dirname(__FILE__).'/info.txt'), array(
				'name' => 'Translator (Action Component)',
		));
    }

	/**
	* Register Plugin in DW
	**/
	function register(&$controller) {
		$controller->register_hook('DOKUWIKI_STARTED', 'BEFORE', $this, 'export_action');
		$controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_google_translation');
	}

	/**
	* Export via calling URL
	**/
	function export_action( &$event ) {
		global $INFO;
					
		if (	(empty($_REQUEST['export_language'])
				|| empty($_REQUEST['Category'])
				|| empty($_REQUEST['Language'])
				|| empty($_REQUEST['Version'])
				|| empty($INFO['userinfo'])) && empty($_REQUEST['fn']) ) return;
		
		// check Database
		if ( !$functions =& plugin_load('helper', 'translator') ) {
			print $this->lang['helpermissing'];
			return false;
		}
		
		$functions->init_database();
		
		// Handle prior Requests
		if ( !empty($_REQUEST['fn']) ) {
			$functions->_handleRequest($_REQUEST['fn']);
			return;
		}
		
		$Category = trim($_REQUEST['Category']);
		$Language = trim($_REQUEST['Language']);
		$Version = trim($_REQUEST['Version']);
		$Encode = empty($_REQUEST['NoEncode']);
		if ( ($CategoryArray = $functions->_getCategoryFromName($Category)) === false ) {
			return;
		}
		
		if ( $Language != 'export all' && !in_array( $Language, $functions->_getAvailableLanguages($Category) ) ) {
			msg($functions->_messageReplacer('CategoryNotSupportedInLanguage', array($Category, $Language)), -1);
		}
		
		list($CategoryID, $CategoryFileName) = $CategoryArray;
		
		if ( $Language != 'export all' ) { $Language = array($Language); }
		else { $Language = $functions->_getAvailableLanguages($CategoryID, $Version); }
		
		if ( count($Language) > 1 ) {
			require_once(DOKU_INC . "inc/ZipLib.class.php");
			$zipFile = new ZipLib();
		}
		
		foreach ( $Language as $exportLang ) {
		
			$fileName = str_replace("(.*?)", ( $exportLang == $this->getConf('default_language') ? "" : "_$exportLang" ), $CategoryFileName);
			
			$data = $functions->_getTranslation($CategoryID, $Version, $exportLang);
			
			foreach( array_keys($data) as $key ) {
				$data[$key] = str_replace("\\\\", "\\", $data[$key]);
				$data[$key] = str_replace("\\\"", "\"", $data[$key]);
				$data[$key] = str_replace("\\'", "'", $data[$key]);
				$data[$key] = stripslashes($key) .'=' . $data[$key]; //( $Encode ? $functions->_stringEncode($data[$key]) : $data[$key]);
			}
			
			if ( count($Language) > 1 ) {
				$zipFile->add_File(implode("\r\n", array_values($data)), $fileName );
			}
		}

		if ( count($Language) == 1 ) {
			$functions->_sendLanguageFile(array_values($data), $fileName);
		} else {
			$fileName = str_replace("(.*?)", "_all", $CategoryFileName) . ".zip";
			$functions->_sendLanguageFile(array(), $fileName);
			print $zipFile->get_file();
		}
		
		exit();
	}
	
	function ajax_google_translation(&$event) {
		
		if ( $event->data != '_google_translation' ) {
			return;
		}
		
		// check Database
		if ( !$functions =& plugin_load('helper', 'translator') ) {
			return false;
		}
		
		$functions->init_database();

		$url = 'http://ajax.googleapis.com/ajax/services/language/translate';
		$data = array(
			'v' => '1.0',
			'langpair' => 'en|' . $_REQUEST['translation'],
			'q' => stripslashes(str_replace('\n', '%%%%', $functions->_getMasterKeyIDFromName(intval($_REQUEST['key']), intval($_REQUEST['category']), true, false)))
		);
		
		$http = new DokuHTTPClient();
		//$http->debug = true;
		
		$response = $http->post($url, $data);
		if ( empty($response) ) {
			exit();
		}
		
		include_once(DOKU_INC . 'inc/JSON.php');
		$json = new JSON();
		$value = $json->decode($response);
		print preg_replace("/\*?%{4}\s*/", "\n", urldecode($value->responseData->translatedText));
		
		exit();
	}
}