<?php 

class ConvertCodepage {
	
	
	/**
	 * Check for codepage conversion Engine
	 *
	 */
	protected function GetConvertEngine() {
		if (function_exists('iconv')) {
			$recoding_engine = 'iconv';
		} elseif (function_exists('recode_string')) {
			$recoding_engine = 'recode';
		} else {
			$recoding_engine = 'none';
		}
		
		return $recoding_engine;
	}

	
	/**
	 * If covert engine was found, convert all to desired codepage
	 *
	 * @param string $src_charset
	 * @param string $dest_charset
	 * @param string $what
	 * @return string
	 */
	public function convert_file($src_charset, $dest_charset, $fileName) { 
		if (function_exists('iconv')) {
			if (file_exists($fileName)) { 
				$data = file_get_contents($fileName); 
				$data = iconv($src_charset, $dest_charset, $data); 
				file_put_contents($fileName,$data); 
			}
		} else {
			return false;
		}
	}  
	
	
	/**
	 * If covert engine was found, convert all to desired codepage
	 *
	 * @param string $src_charset
	 * @param string $dest_charset
	 * @param string $what
	 * @return string
	 */
	public function convert_string($src_charset, $dest_charset, $what, $extra_params=null) {
		if ($src_charset == $dest_charset) {
			return $what;
		}
		
		$convert_engine = $this->GetConvertEngine();
		
		switch ($convert_engine) {
			case 'recode':
				return recode_string($src_charset.'..'.$dest_charset, $what);
			case 'iconv':
				return iconv($src_charset, $dest_charset.$extra_params, $what);
			default:
				return $what;
		}
	}
	
	
}

?>
