<?php
// +---------------------------------------------------------------------------------------+
// | TenderSystem                                                                          |
// +---------------------------------------------------------------------------------------+
// | The contents of this file are subject to the TenderSystem Public License Version 1.1  |
// | ("License"); you may not use this file except in compliance with the License. You may |
// | obtain a copy of the License at http://www.tendersystem.com/tpl/                      |
// |                                                                                       |
// | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT    |
// | WARRANTY OF ANY KIND, either express or implied. See the License for the specific     |
// | language governing rights and limitations under the License.                          |
// |                                                                                       |
// | All copies of the Covered Code must include the "Powered by TenderSystem" logo and    |
// | ValueCard copyright notice on every user interface screen and in every outgoing       |
// | email in the same form as they appear in the distribution.                            |
// |                                                                                       |
// | The Original Code is: TenderSystem                                                    |
// | The Initial Developer of the Original Code is ValueCard (Pty) Limited.                |
// | Portions created by ValueCard are Copyright (C) 2002 ValueCard (Pty) Limited.         |
// | All Rights Reserved.                                                                  |
// | Contributor(s): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Generic functions
* @package TenderSystem
* @subpackage language
* @copyright Copyright &copy; 2002, ValueCard (Pty) Ltd
* @license http://www.tendersystem.com/tpl/ TenderSystem Public License
* @version 
*/

// Security - ensure that file never called directly
// not required if global variables are off or API is hosted on a non-public server
if (eregi(basename(__FILE__),$_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

/**
* determine which language packs are loaded on the server
* @return array
*/
function read_language(&$params,$cfg) {
	$file_path = "modules/";
	// open the directory
	$dir = opendir($file_path);
	// if folder accessible
	if ($dir) {
		// loop through all the files (modules)
		while(($file=readdir($dir)) !== FALSE) {
			// determine if hidden file not included
			if($file{0} != "." && $file != "CVS" && is_dir($file_path."/".$file)) {
				$full_path = $file_path."/".$file;
				// find language folder
				if(is_dir($full_path."/language")) {
					$params['guimodule'][] = $file;
					if(!file_exists($full_path."/language/".$params['lang']."/default.xml")) {
						$params['inactiveguimodule'][] = $file;
					}
				}
			}
		}
		// close the directory
		closedir($dir);
	}
	$params['nocalendar'] = "0";
	if(!file_exists("modules/external/language/".$params['lang']."/calendar.js")) {
		$params['nocalendar'] = "1";
	}
	$params['nocountry'] = "0";
	if(!file_exists("modules/generic/language/".$params['lang']."/country.xml")) {
		$params['nocountry'] = "1";
	}
	$params['nolanguage'] = "0";
	if(!file_exists("modules/generic/language/".$params['lang']."/language.xml")) {
		$params['nolanguage'] = "1";
	}
	return TRUE;
}

/**
* determine which language packs are loaded on the server
* @return array
*/
function repair_language(&$params,$cfg) {
	// go through gui langauge files
	$files = examinedir("modules");
	foreach($files as $value) {
		// default.xml
		if(strpos($value,"language/".$params['reflang']."/default.xml")) {
			$file['name'] = str_replace("/".$params['reflang']."/","/".$params['lang']."/",$value);
			if(file_exists($file) && !is_writable($file)) {
				$file['status'] = "cantwrite";
			} else {
				$result = check_default($file['name'],$value,$params['lang'],$cfg);
				if($result === FALSE) {
					$file['status'] = "corrupted";
				} else {
					$file['status'] = $result;
				}
			}
			$params['file'][] = $file;
		} elseif(strpos($value,"language/".$params['reflang']."/error.xml")) {
			$file['name'] = str_replace("/".$params['reflang']."/","/".$params['lang']."/",$value);
			if(file_exists($file) && !is_writable($file)) {
				$file['status'] = "cantwrite";
			} else {
				$result = check_error($file['name'],$value,$params['lang'],$cfg);
				if($result === FALSE) {
					$file['status'] = "corrupted";
				} else {
					$file['status'] = $result;
				}
			}
			$params['file'][] = $file;
		}
		unset($file);
	}
	return TRUE;
}

function google_language() {
 	// English to German
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "de"
	);
	// English to Spanish
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "es"
	);
	// English to French
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "fr"
	);
	// English to Italian
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "it"
	);
	// English to Portuguese
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "pt"
	);
	// English to Japanese
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "ja"
	);
	// English to Korean
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "ko"
	);
	// English to Chinese
	$params['langpair'][] = array(
		'current'	=> "en",
		'new'		=> "zh"
	);
	
	// German to English
	$params['langpair'][] = array(
		'current'	=> "de",
		'new'		=> "en"
	);
	// German to French
	$params['langpair'][] = array(
		'current'	=> "de",
		'new'		=> "fr"
	);
	
	// Spanish to English
	$params['langpair'][] = array(
		'current'	=> "es",
		'new'		=> "en"
	);
	
	// French to English
	$params['langpair'][] = array(
		'current'	=> "fr",
		'new'		=> "en"
	);
	
	// Italian to English
	$params['langpair'][] = array(
		'current'	=> "it",
		'new'		=> "en"
	);
	
	// Portuguese to English
	$params['langpair'][] = array(
		'current'	=> "pt",
		'new'		=> "en"
	);
	
	// Japanese to English
	$params['langpair'][] = array(
		'current'	=> "ja",
		'new'		=> "en"
	);
	
	// Korean to English
	$params['langpair'][] = array(
		'current'	=> "ko",
		'new'		=> "en"
	);
	return $params['langpair'];
}

if (!function_exists('array_diff_key')) {
	function array_diff_key($array1,$array2) {
		$array1_keys = array_keys($array1);
		$array2_keys = array_keys($array2);
		$array_diff = array_diff($array1_keys,$array2_keys);
		$array_result = array();
		foreach($array_diff as $key) {
			$array_result[$key] = $array1[$key];
		}
		return $array_result;
	}
}

if (!function_exists('array_intersect_key')) {
	function array_intersect_key($array1,$array2) {
		$array1_keys = array_keys($array1);
		$array2_keys = array_keys($array2);
		$array_intersect = array_intersect($array1_keys,$array2_keys);
		$array_result = array();
		foreach($array_intersect as $key) {
			$array_result[$key] = $array1[$key];
		}
		return $array_result;
	}
}

function check_default($file,$reffile,$lang,$cfg) {
	if(!file_exists($file)) {
		$main_xml['xml_index'] = array();
		$main_xml['xml_array'] = array();
	} else {
		$main_xml = get_xml_info($file);
	}
	$ref_xml = get_xml_info($reffile);
	if($main_xml === FALSE || $ref_xml === FALSE) {
		return FALSE;
	}
	$missing_index = array_diff_key($ref_xml['xml_index'],$main_xml['xml_index']);
	$intersect_index = array_intersect_key($main_xml['xml_index'],$ref_xml['xml_index']);
	// check for missing
	if(empty($missing_index)) {
		return 0;
	} else {
		$file_contents = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
		$file_contents.= '<l lang="'.$lang.'" editor="'.$cfg['module']['version'].'">'."\n";
		// add existing
		foreach($intersect_index as $key => $value) {
			if($key != "L") {
				foreach($value as $index) {
					if($main_xml['xml_array'][$index]['level'] == 2) {
						$tag = strtolower($main_xml['xml_array'][$index]['tag']);
						$content = strtolower($main_xml['xml_array'][$index]['value']);
						$file_contents.= "\t<".$tag.">".$content."</".$tag.">\n";
					}
				}
			}
		}
		// add missing
		foreach($missing_index as $key => $value) {
			if($key != "L") {
				foreach($value as $index) {
					if($ref_xml['xml_array'][$index]['level'] == 2) {
						$tag = strtolower($ref_xml['xml_array'][$index]['tag']);
						$content = strtolower($ref_xml['xml_array'][$index]['value']);
						$file_contents.= "\t<".$tag." translated=\"no\">".$content."</".$tag.">\n";
						$count++;
					}
				}
			}
		}
		$file_contents.= '</l>'."\n";
		if(write_file($file_contents,$file)) {
			return $count;
		}
	}
	return FALSE;
}

function check_error($file,$reffile,$lang,$cfg) {
	if(!file_exists($file)) {
		$main_xml['xml_index'] = array();
		$main_xml['xml_array'] = array();
	} else {
		$main_xml = get_xml_info($file);
	}
	$ref_xml = get_xml_info($reffile);
	if($main_xml === FALSE || $ref_xml === FALSE) {
		return FALSE;
	}
	$missing_index = array_diff_key($ref_xml['xml_index'],$main_xml['xml_index']);
	$intersect_index = array_intersect_key($main_xml['xml_index'],$ref_xml['xml_index']);
	// check for missing
	if(empty($missing_index)) {
		return 0;
	} else {
		$file_contents = '<?xml version="1.0" encoding="utf-8"?>'."\n";
		$file_contents.= '<e lang="'.$lang.'" editor="'.$cfg['module']['version'].'">'."\n";
		// add existing
		foreach($intersect_index as $key => $value) {
			if($key != "E") {
				foreach($value as $index) {
					if($main_xml['xml_array'][$index]['level'] == 2) {
						$id = strtolower($main_xml['xml_array'][$index]['attributes']['ID']);
						$content = strtolower($main_xml['xml_array'][$index]['value']);
						$file_contents.= "\t<error id=\"".$id."\">".$content."</error>\n";
					}
				}
			}
		}
		// add missing
		foreach($missing_index as $key => $value) {
			if($key != "E") {
				foreach($value as $index) {
					if($ref_xml['xml_array'][$index]['level'] == 2) {
						$id = strtolower($ref_xml['xml_array'][$index]['attributes']['ID']);
						$content = strtolower($ref_xml['xml_array'][$index]['value']);
						$file_contents.= "\t<error id=\"".$id."\" translated=\"no\">".$content."</error>\n";
						$count++;
					}
				}
			}
		}
		$file_contents.= '</e>'."\n";
		if(write_file($file_contents,$file)) {
			return $count;
		}
	}
	return FALSE;
}

function translate_default($reffile,$reflang,$lang,$translator,$missing) {
	$file = str_replace("/".$reflang."/","/".$lang."/",$reffile);
	if($missing && file_exists($file)) {
		$main_xml = get_xml_info($file);
	} else {
		$main_xml['xml_index'] = array();
		$main_xml['xml_array'] = array();
	}
	$ref_xml = get_xml_info($reffile);
	if($main_xml === FALSE || $ref_xml === FALSE) {
		return FALSE;
	}
	$missing_index = array_diff_key($ref_xml['xml_index'],$main_xml['xml_index']);
	$intersect_index = array_intersect_key($main_xml['xml_index'],$ref_xml['xml_index']);
	$file_contents = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
	$file_contents.= '<l lang="'.$lang.'">'."\n";
	// add existing
	foreach($intersect_index as $key => $value) {
		if($key != "L") {
			foreach($value as $index) {
				if($main_xml['xml_array'][$index]['level'] == 2) {
					$translated = strtolower($main_xml['xml_array'][$index]['attributes']['TRANSLATED']);
					$tag = strtolower($main_xml['xml_array'][$index]['tag']);
					$content = strtolower($main_xml['xml_array'][$index]['value']);
					if($translated != "no") {
						$file_contents.= "\t<".$tag.">".$content."</".$tag.">\n";
					} elseif($tag == "language_date") {
						$file_contents.= "\t<".$tag.">".date("Y-m-d")."</".$tag.">\n";
					} else {
						if($tag == "language_translator") {
							$content = "Google Translator";
						}
						$new_content = $translator($content,$reflang,$lang);
						if($new_content) {
							// translate
							$file_contents.= "\t<".$tag.">".$new_content."</".$tag.">\n";
						} else {
							$file_contents.= "\t<".$tag." translated=\"no\">".$content."</".$tag.">\n";
						}
					}
				}
			}
		}
	}
	// add missing
	foreach($missing_index as $key => $value) {
		if($key != "L") {
			foreach($value as $index) {
				if($ref_xml['xml_array'][$index]['level'] == 2) {
					$tag = strtolower($ref_xml['xml_array'][$index]['tag']);
					$content = strtolower($ref_xml['xml_array'][$index]['value']);
					if($tag == "language_date") {
						$file_contents.= "\t<".$tag.">".date("Y-m-d")."</".$tag.">\n";
					} else {
						if($tag == "language_translator") {
							$content = "Google Translator";
						}
						$new_content = $translator($content,$reflang,$lang);
						if($new_content) {
							// translate
							$file_contents.= "\t<".$tag.">".$new_content."</".$tag.">\n";
						} else {
							$file_contents.= "\t<".$tag." translated=\"no\">".$content."</".$tag.">\n";
						}
					}
				}
			}
		}
	}
	$file_contents.= '</l>'."\n";
	return write_file($file_contents,$file);
}

function translate_country($file,$reflang,$lang,$translator,$missing) {
	$xml_file = str_replace("/".$reflang."/","/".$lang."/",$file);
	$xml_array = $index = array();
	$xml_content = str_replace("&","&amp;",file_get_contents($file));
	// create parser
	$xml_parser = xml_parser_create();
	// parse xml into $xml_array
	$good_parse = xml_parse_into_struct($xml_parser, $xml_content, $xml_array, $index);
	// free parser
	xml_parser_free($xml_parser);
	// load info
	if($good_parse) {
		foreach($xml_array as $value2) {
			// country name
			if($value2['tag'] == "NAME") {
				$country['value'] = $value2['value'];
			}
			if($value2['tag'] == "DIALCODE") {
				$country['tag'] = $value2['value'];
			}
			if($value2['tag'] == "COUNTRY" && $value2['type'] == "close") {
				$tag[] = $country;
				unset($country);
			}
		}
	} else {
		return FALSE;
	}
	
	// xml header
	$file_contents = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
	$file_contents.= '<c lang="'.$lang.'">'."\n";
	// main contents
	foreach($tag as $value1) {
		$file_contents.= "\t<country>\n";
		$new_content = $translator($value1['value'],$reflang,$lang);
		if($new_content) {
			// translate
			$file_contents.= "\t\t<name>".$new_content."</name>\n";
		} else {
			$file_contents.= "\t\t<name translated=\"no\">".$value1['value']."</name>\n";
		}
		
		$file_contents.= "\t\t<dialcode>".$value1['tag']."</dialcode>\n";
		$file_contents.= "\t</country>\n";
	}
	$file_contents.= '</c>'."\n";
	return write_file($file_contents,str_replace("/".$reflang."/","/".$lang."/",$file));
}

function translate_language($file,$reflang,$lang,$translator,$missing) {
	$xml_file = str_replace("/".$reflang."/","/".$lang."/",$file);
	$xml_array = $index = array();
	$xml_content = str_replace("&","&amp;",file_get_contents($file));
	// create parser
	$xml_parser = xml_parser_create();
	// parse xml into $xml_array
	$good_parse = xml_parse_into_struct($xml_parser, $xml_content, $xml_array, $index);
	// free parser
	xml_parser_free($xml_parser);
	// load info
	if($good_parse) {
		foreach($xml_array as $value2) {
			// country name
			if($value2['tag'] == "NAME") {
				$langcode['value'] = $value2['value'];
			}
			if($value2['tag'] == "ISOCODE") {
				$langcode['tag'] = $value2['value'];
			}
			if($value2['tag'] == "LANGCODE" && $value2['type'] == "close") {
				$tag[] = $langcode;
				unset($langcode);
			}
		}
	} else {
		return FALSE;
	}
	
	// xml header
	$file_contents = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
	$file_contents.= '<l lang="'.$lang.'">'."\n";
	// main contents
	foreach($tag as $value1) {
		$file_contents.= "\t<langcode>\n";
		$new_content = $translator($value1['value'],$reflang,$lang);
		if($new_content) {
			// translate
			$file_contents.= "\t\t<name>".$new_content."</name>\n";
		} else {
			$file_contents.= "\t\t<name translated=\"no\">".$value1['value']."</name>\n";
		}
		
		$file_contents.= "\t\t<isocode>".$value1['tag']."</isocode>\n";
		$file_contents.= "\t</langcode>\n";
	}
	$file_contents.= '</l>'."\n";
	return write_file($file_contents,str_replace("/".$reflang."/","/".$lang."/",$file));
}

function translate_error($reffile,$reflang,$lang,$translator,$missing) {
	$file = str_replace("/".$reflang."/","/".$lang."/",$reffile);
	if(!$missing || !file_exists($file)) {
		$main_xml['xml_index'] = array();
		$main_xml['xml_array'] = array();
	} else {
		$main_xml = get_xml_info($file);
	}
	$ref_xml = get_xml_info($reffile);
	if($main_xml === FALSE || $ref_xml === FALSE) {
		return FALSE;
	}
	$missing_index = array_diff_key($ref_xml['xml_index'],$main_xml['xml_index']);
	$intersect_index = array_intersect_key($main_xml['xml_index'],$ref_xml['xml_index']);
	$file_contents = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
	$file_contents.= '<e lang="'.$lang.'">'."\n";
	// add existing
	foreach($intersect_index as $key => $value) {
		if($key != "E") {
			foreach($value as $index) {
				if($main_xml['xml_array'][$index]['level'] == 2) {
					$translated = strtolower($main_xml['xml_array'][$index]['attributes']['TRANSLATED']);
					$id = strtolower($main_xml['xml_array'][$index]['attributes']['ID']);
					$content = strtolower($main_xml['xml_array'][$index]['value']);
					if($translated != "no") {
						$file_contents.= "\t<error id=\"".$id."\">".$content."</error>\n";
					} else {
						$new_content = $translator($content,$reflang,$lang);
						if($new_content) {
							// translate
							$file_contents.= "\t<error id=\"".$id."\">".$new_content."</error>\n";
						} else {
							$file_contents.= "\t<error id=\"".$id."\" translated=\"no\">".$content."</error>\n";
						}
					}
				}
			}
		}
	}
	// add missing
	foreach($missing_index as $key => $value) {
		if($key != "E") {
			foreach($value as $index) {
				if($ref_xml['xml_array'][$index]['level'] == 2) {
					$translated = strtolower($ref_xml['xml_array'][$index]['attributes']['TRANSLATED']);
					$id = strtolower($ref_xml['xml_array'][$index]['attributes']['ID']);
					$content = strtolower($ref_xml['xml_array'][$index]['value']);
					$new_content = $translator($content,$reflang,$lang);
					if($new_content) {
						// translate
						$file_contents.= "\t<error id=\"".$id."\">".$new_content."</error>\n";
					} else {
						$file_contents.= "\t<error id=\"".$id."\" translated=\"no\">".$content."</error>\n";
					}
				}
			}
		}
	}
	$file_contents.= '</e>'."\n";
	return write_file($file_contents,$file);
}

function translate_php($file,$reflang,$newlang,$translator,$missing) {
	$xml_file = str_replace("/".$reflang."/","/".$newlang."/",$file);
	if($missing && file_exists($file)) {
		return TRUE;
	}
	// main contents
	$lang = array();
	require($file);
	// loop through lang
	foreach($lang as $lang_key => $lang_value) {
		if(is_array($lang_value)) {
			foreach($lang_value as $lang1_key => $lang1_value) {
				$lang_info['tag'] = $lang_key;
				$lang_info['tag1'] = $lang1_key;
				$lang_info['value'] = $lang1_value;
				$tag[] = $lang_info;
			}
		} else {
			$lang_info['tag'] = $lang_key;
			$lang_info['value'] = $lang_value;
			$tag[] = $lang_info;
		}
	}
	// file header
	$file_contents = '<?php'."\n";
	// loop through lang
	foreach($tag as $key => $value) {
		// translate
		$new_content = $translator($value['value'],$reflang,$newlang);
		if($new_content) {
			$value['value'] = $new_content;
		}
		$value['value'] = str_replace("\"","\\\"",$value['value']);
		if(isset($value['tag1'])) {
			$file_contents.= '$lang['."'".$value['tag']."'".']['."'".$value['tag1']."'".'] = "'.$value['value'].'";'."\n";
		} else {
			$file_contents.= '$lang['."'".$value['tag']."'".'] = "'.$value['value'].'";'."\n";
		}
	}
	$file_contents.= '?>';
	return write_file($file_contents,str_replace("/".$reflang."/","/".$newlang."/",$file));
}

function write_file($file_contents,$file_name) {
	if(!file_exists(dirname($file_name))) {
		if(!mkdir(dirname($file_name),0775)) {
			return FALSE;
		}	
	}
	// open file for writing
	$fp = fopen($file_name,"w+");
	// check if file open okay
	if (!$fp) {
		return FALSE;
	} else {
		// write new data back into file
		fwrite($fp,$file_contents,strlen($file_contents));
		// close file
		fclose($fp); 
	}
	// response
	return TRUE;
}

function google_translate($value,$reflang,$lang) {
	if(strcasecmp($value,"TenderSystem") == 0) {
		return "TenderSystem";
	}
	if($reflang=="zh") {
		$reflang="zh-CN";
	}
	if($lang=="zh") {
		$lang="zh-CN";
	}
	if($value) {
		// set the paramater string
		$post_fields['text'] = $value;
		$post_fields['langpair'] =  $reflang."|".$lang;
		$post_fields['ie'] =  "UTF8";
		$post_fields['hl'] =  "en";
		// post
		$result = get_web_contents("http://www.google.com/translate_t",urlencode_array($post_fields));
		$html = $result['web_contents'];
		$curl_info = $result['curl_info'];
		$content_type = str_replace(array(" ","text/html;","charset","="),"",$curl_info['content_type']);
		// convert to utf-8
		$html = iconv($content_type, "UTF-8",$html);
		$start = strpos($html,"<textarea");
		$start = strpos($html,">",$start) + 1;
		$end = strpos($html,"</",$start);
		if($start === FALSE || $end === FALSE || strpos($html,"Sorry, this text cannot be translated")) {
			return FALSE;	
		} else {
			$value = substr($html,$start,$end-$start);
		}
	}
	return $value;
}
?>