<?php
/*
* @package		Comércio BR
* @copyright	2014
* @site			http://comerciobr.com
* @license		http://www.gnu.org/licenses/gpl-2.0.html
*
* @Donate		1G3xTNh512PRDbfoEoeWWacigVVR9tYHAp Bitcoin
* @Donate		LXjsKahtNEmtZCQPXyRnw7c7mU4iKJbYWJ Litcoin
* @Donate		DFLaTxkhVeA84juzLBmxL8uRA1A7KJGnbL DogeCoin
*/

if(!function_exists('file_put_contents'))
{
    function file_put_contents($filename, $data)
	{
        $f = @fopen($filename, 'w');
        if(!$f)
		{
            return false;
        }
		else
		{
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

if(!function_exists('file_get_contents'))
{
	function file_get_contents($filename)
	{
		if(!file_exists($filename))
		{
			return false;
		}

		$fhandle = fopen($filename, "r");
		$fcontents = fread($fhandle, filesize($filename));
		fclose($fhandle);	
		
		return $fcontents;
	}
}


class Translator
{
	private $load;
	private $db;
	private $config;
	private $language;
	private $request;
	private $files = array();
	private $dirsScan = array();
	private $data = array('result' => false, 'success' => false, 'errors' => false);
	public function __construct($registry)
	{
		$this->load = $registry->get("load");
		$this->db = $registry->get("db");
		$this->config = $registry->get("config");
		$this->language = $registry->get("language");
		$this->language->load('module/translator');
		$this->request = $registry->get("request");
		
		$dirOc = str_ireplace('system/', '', DIR_SYSTEM);
		$this->dirsScan[] = DIR_LANGUAGE;
		$this->dirsScan[] = "{$dirOc}/vqmod/xml/";
		
		if(!defined('HTTP_CATALOG'))
		{ // CATALOG
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template'))
			{
				$template = DIR_TEMPLATE . $this->config->get('config_template') . '/template/';
			}
			else
			{
				$template = DIR_TEMPLATE . 'default/template';
			}

			$this->dirsScan[] = $template;
		}


		//$this->dirsScan = array("{$dirOc}/vqmod/xml/", $this->template, DIR_LANGUAGE);
	}

	public function run()
	{
		if(isset($this->request->post['find']))
		{
			$find = $this->request->post['find'];
			$this->find($find);
			$this->data["success"] = is_array($this->data["result"]);
		}
		
		if(isset($this->request->post['text_from']) && isset($this->request->post['text_destination']) && isset($this->request->post['files']))
		{
			$text_from = $this->request->post['text_from'];
			$text_destination = $this->request->post['text_destination'];
			$files = $this->request->post['files'];
			
			$this->traduzir($text_from, $text_destination, $files);			
		}

		echo json_encode($this->data);
	}

	private function traduzir($text_from, $text_destination, $files)
	{
		$text_destination = str_replace("'", "\'", $text_destination);
		$text_destination = html_entity_decode($text_destination);
		foreach($files as $file)
		{
			if(file_exists($file))
			{
				if($this->config->get('translator_backup_files') && !file_exists("{$file}.translator.bak"))
				{
					$file_name_bak = "{$file}.translator.bak";
					copy($file, $file_name_bak);
				}
				
				$text_file = file_get_contents($file);
				$new_text = str_ireplace($text_from, $text_destination, $text_file);
				file_put_contents($file, $new_text);
				$this->data["success"] = true;
			}
			else
			{
				$this->data["errors"] = sprintf($this->language->get('error_file_not_found'), $file);
			}
		}
	}

	private function find($string)
	{
		$this->scan();
		if(count($this->files))
		{
			foreach($this->files as $file)
			{
				$h = fopen($file, "r");
				if ($h)
				{
					// Read file line-by-line
					$line = 0;
					while (($buffer = fgets($h)) !== false)
					{
						$line++;
						if (stripos($buffer, $string) !== false)
						{
							$this->data["result"][] = array('file' => $file, 'line' => $line);
							break;
						}
					}
				}
				fclose($h);
			}
		}

		if(is_array($this->data["result"]))
		{
			$this->data["success"] = true;
		}
		else
		{
			$this->data["errors"][] = sprintf($this->language->get('error_not_found'), $string);
		}	
	}
	
	private function scan()
	{
		foreach($this->dirsScan as $dirScan)
		{
			$this->files = array_merge($this->files, $this->listIn($dirScan, $dirScan));
		}
		
		foreach($this->files as $key => $file)
		{
			if(!preg_match('#(\.php|\.tpl|\.xml)$#i', $file))
			{
				unset($this->files[$key]);
			}
		}
	}
	
	private function listIn($dir, $prefix = '', $filesDirsIgnore = array())
	{
		$dir = rtrim($dir, '\\/');
		$result = array();

		foreach (scandir($dir) as $f)
		{
			if($f !== '.' and $f !== '..')
			{
				if(in_array($f, $filesDirsIgnore))
				{
					continue;
				}
				
				if(is_dir("$dir/$f"))
				{
					$result = array_merge($result, $this->listIn("$dir/$f", "$prefix$f/"));
				}
				else
				{
					$result[] = $prefix.$f;
				}
			}
		}

		return $result;
	}
}
?>