<?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): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Replace key words in language files
* @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...");
}

// field request errors and type 
$fields_request = array (
	'tagreplace'	=> array(),
	'phrasereplace'	=> array()		
);
get_request($fields_request,$action,$error,$cfg);
if(!$cfg['languageeditor']['enable']) {
	// Not Enabled
	xml_generator("languageeditor","error","e44","",$cfg);
} elseif(!$_SESSION['ts_id']) {
	// No Session
	xml_generator("languageeditor","error","e17","",$cfg);
}
if($action['tagreplace']) {
	if($cfg['api']['connection'] == "module") {
		// field request errors and type 
		$fields_request = array (
			'reflang'			=> array("e25",	REQUEST_LANG,	FORMAT_NONE,	"e27"),
			'lang'				=> array("e26",	REQUEST_LANG,	FORMAT_NONE,	"e28"),
			'tag'				=> array("e33",	REQUEST_ANY,	FORMAT_LOWER),
			'content'			=> array(),
		);
		if(get_request($fields_request,$info,$error,$cfg)) {
			$params['reflang'] = $info['reflang'];
			$params['lang'] = $info['lang'];
			$tag['start'] = "<".$info['tag'].">";
			$tag['end'] = "</".$info['tag'].">";
			$tag['php'] = "'".$info['tag']."'";
			$content = $info['content'];
			// go through gui langauge files
			$files = examinedir("modules");
			foreach($files as $value) {
				if(strpos($value,$params['lang']) && strpos($value,"language") && strpos($value,"default.xml")) {
					$xml_content = file_get_contents($value);
					$start = strpos($xml_content,$tag['start']);
					if ($start) {
					 $start += strlen($tag['start']);
					 $end = strpos($xml_content,$tag['end'],$start);
					}
					while($start !== FALSE && $end !== FALSE) {
						$xml_content = substr_replace($xml_content,$content,$start,$end - $start);
						$params['updatedtags']++;
						$start = strpos($xml_content,$tag['start'],$end);
						if ($start) {
					 		$start += strlen($tag['start']);
					 		$end = strpos($xml_content,$tag['end'],$start);
						}
					}
					$fp = fopen($value,"w+");
					// check if file open okay
					if (!$fp) {
						$params['error'][] = "e21";
					} else {
						// write new data back into file
						if(!fwrite($fp,$xml_content,strlen($xml_content))) {
							$params['error'][] = "e21";
						}
						// close file
						fclose($fp); 
						$params['updated'] = "1";
					}
				}
			}
			// go through api langauge files
			$files = examinedir("application/include/modules");
			foreach($files as $value) {
				if(strpos($value,$params['lang']) && strpos($value,"language") && strpos($value,".php")) {
					$lang_content = file_get_contents($value);
					$start = strpos($lang_content,$tag['php']);
					if($start) { 
					$start+= strlen($tag['php']);
					$start_c = strpos($lang_content,'"',$start) + 1;
					$end_c = strpos($lang_content,'";',$start_c);
					}
					while($start !== FALSE && $start_c !== FALSE && $end_c !== FALSE) {
						$lang_content = substr_replace($lang_content,$content,$start_c,$end_c - $start_c);
						$params['updatedtags']++;
						$start = strpos($lang_content,$tag['php'],$end_c);
						if($start) {
							$start += strlen($tag['php']);
							$start_c = strpos($lang_content,'"',$start) + 1;
							$end_c = strpos($lang_content,'";',$start_c);
						}
					}
					$fp = fopen($value,"w+");
					// check if file open okay
					if (!$fp) {
						$params['error'][] = "e22";
					} else {
						// write new data back into file
						if(!fwrite($fp,$lang_content,strlen($lang_content))) {
							$params['error'][] = "e22";
						}
						// close file
						fclose($fp); 
						$params['updated'] = "1";
					}
				}
			}
		} else {
			// display error
			xml_generator("languageeditor","error",$error,"",$cfg);
		}
	}
} elseif($action['phrasereplace']) {
	if($cfg['api']['connection'] == "module") {
		// field request errors and type 
		$fields_request = array (
			'reflang'		=> array("e25",	REQUEST_LANG,	FORMAT_NONE,	"e27"),
			'lang'			=> array("e26",	REQUEST_LANG,	FORMAT_NONE,	"e28"),
			'phrase'		=> array("e34"),
			'newphrase'		=> array(),
		);
		if(get_request($fields_request,$info,$error,$cfg)) {
			$params['reflang'] = $info['reflang'];
			$params['lang'] = $info['lang'];
			$phrase = $info['phrase'];
			$newphrase = $info['newphrase'];
			// go through gui langauge files
			$files = examinedir("modules");
			foreach($files as $value) {
				if(strpos($value,$params['lang']) && strpos($value,"language") && strpos($value,"default.xml")) {
					$tag = array();
					$xml_content = str_replace("&","&amp;",file_get_contents($value));
					// 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) {
							if($value2['level'] == "2") {
								$info['tag'] = strtolower($value2['tag']);
								$info['value'] = str_replace($phrase,$newphrase,$value2['value']);
								$tag[] = $info;
							}	
						}
					} else {
						$params['error'][] = "e23";
					}
					// write info
					if($tag) {
						// xml header
						$file_contents = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
						$file_contents.= '<l lang="'.$params['lang'].'">'."\n";
						// main contents
						foreach($tag as $value1) {
							$file_contents.= "\t<".strtolower($value1['tag']).">".$value1['value']."</".strtolower($value1['tag']).">\n";
						}
						$file_contents.= '</l>';
						// open file for writing
						$fp = fopen($value,"w+");
						// check if file open okay
						if (!$fp) {
							$errors[] = "e21";
						} else {
							// write new data back into file
							if(!fwrite($fp,$file_contents,strlen($file_contents))) {
								$errors[] = "e21";
							}
							// close file
							fclose($fp); 
							$params['updated'] = "1";
						}
					}
				}
			}
			// go through api langauge files
			$files = examinedir("application/include/modules");
			foreach($files as $value) {
				if(strpos($value,$params['lang']) && strpos($value,"language") && strpos($value,".php")) {
					unset($lang);
					require($value);
					$file_contents = "";
					if(isset($lang)) {
						if($info) {
							// xml header
							$file_contents = '<?php'."\n";
							// main contents
							foreach($lang as $key1 => $value1) {
								if(is_array($value1)) {
									foreach($value1 as $key2 => $value2) {
										$file_contents.= '$lang['."'$key1'".']['."'$key2'".'] = "'.str_replace(array($phrase,'"'),array($newphrase,'\\"'),$value2).'";'."\n";
									}
								} else {
									$file_contents.= '$lang['."'$key1'".'] = "'.str_replace(array($phrase,'"'),array($newphrase,'\\"'),$value1).'";'."\n";
								}
							}
							 $file_contents.= '?>';
							// open file for writing
							$fp = fopen($value,"w+");
							// check if file open okay
							if (!$fp) {
								$errors[] = "e22";
							} else {
								// write new data back into file
								if(!fwrite($fp,$file_contents,strlen($file_contents))) {
									$errors[] = "e22";
								}
								// close file
								fclose($fp); 
								$params['updated'] = "1";
							}
						}
					}
				}
			}			
		} else {
			// display error
			xml_generator("languageeditor","error",$error,"",$cfg);
		}
	}
}

if($cfg['api']['connection'] == "module") {
	// field request errors and type 
	$fields_request = array (
		'reflang'		=> array("e25",	REQUEST_LANG,	FORMAT_NONE,	"e27"),
		'lang'			=> array("e26",	REQUEST_LANG,	FORMAT_NONE,	"e28")
	);
	if(get_request($fields_request,$info,$error,$cfg)) {
		$params['reflang'] = $info['reflang'];
		$params['lang'] = $info['lang'];
		// go through gui langauge files
		$files = examinedir("modules");
		foreach($files as $value) {
			if(strpos($value,$params['lang']) && strpos($value,"language") && strpos($value,"default.xml")) {
				$xml_content = file_get_contents($value);
				// 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);
				if($good_parse) {
					// tags to ignore
					$skip[] = "MODULE_NAME";
					$skip[] = "LANGUAGE_TRANSLATOR";
					$skip[] = "LANGUAGE_DATE";
					// partial tags to ignore
					$skip_partial = "INST";
					foreach($xml_array as $value) {
						// count
						if($value['level'] == "2" && !in_array($value['tag'],$skip) && strpos($value['tag'],$skip_partial) === FALSE) {
							$tag_count[strtoupper($value['tag'])]++;
							$tag_values[strtoupper($value['tag'])][trim(strtoupper($value['value']))]++;
							$phrase_count[trim(strtoupper($value['value']))]++;
							$phrase_values[trim(strtoupper($value['value']))][strtoupper($value['tag'])]++;
						}
					}
				}
			}
		}
		// go through api langauge files
		$files = examinedir("application/include/modules");
		foreach($files as $value) {
			if(strpos($value,$params['lang']) && strpos($value,"language") && strpos($value,".php")) {
				unset($lang);
				include($value);
				if(isset($lang)) {
					foreach($lang as $key => $value) {
						// ignore arrays
						if(!is_array($value) && !is_numeric($key)) {
							$tag_count[strtoupper($key)]++;
							$tag_values[strtoupper($key)][strtoupper($value)]++;
							$phrase_count[strtoupper($value)]++;
							$phrase_values[strtoupper($value)][strtoupper($key)]++;
						}
					}
				}
			}
		}
		arsort($tag_count);
		arsort($phrase_count);
		$count = 0;
		foreach($tag_count as $key => $value) {
			$info['name'] = $key;
			arsort($tag_values[$key]);
			if(count($tag_values[$key]) > 1) {
				$info['behave'] = ((int)(max($tag_values[$key])/array_sum($tag_values[$key])*10000))/100;
				$info['most'] = key($tag_values[$key]);
				$count++;
				$params['tag'][] = $info;
			}
			if($count >= 20) {
				break;	
			}
		}
		$count = 0;
		foreach($phrase_count as $key => $value) {
			$info['name'] = $key;
			arsort($phrase_values[$key]);
			if(count($phrase_values[$key]) > 1) {
				$info['behave'] = ((int)(max($phrase_values[$key])/array_sum($phrase_values[$key])*10000))/100;
				$info['most'] = key($phrase_values[$key]);
				$count++;
				$params['content'][] = $info;
			}
			if($count >= 20) {
				break;	
			}
		}
		// display message
		xml_generator("languageeditor","massreplace",$errors,$params,$cfg);
	} else {
		// display error
		xml_generator("languageeditor","error",$error,"",$cfg);
	}
} else {
	// only on module
	xml_generator("languageeditor","error","e20",$params,$cfg);
}
?>