<?php
if ( !defined( 'SMARTY_DIR' ) ) {
	include_once( '../init.php' );
}

if (isset($_REQUEST['langname'])) {
	if ($_REQUEST['loadlang'] != '') {
		$file = LANG_DIR.$language_files[$_REQUEST['langname']];

		$lang = array();

		include $file;

		$file=str_replace('\\','/',$file);


		$osDB->query('delete from ! where lang = ?', array( LANGUAGE_TABLE, strtolower($_REQUEST['langname'])) );

		$sql = 'insert into ! (lang, mainkey, subkey, descr) values (?, ?, ?, ?)';
		foreach ($lang as $key => $val) {
			if (is_array($val)) {
				foreach ($val as $subkey => $descr) {
					$osDB->query($sql, array(LANGUAGE_TABLE, $_REQUEST['langname'], $key, $subkey, htmlspecialchars($descr)));
				}
			} else {
				$osDB->query($sql, array(LANGUAGE_TABLE, $_REQUEST['langname'], $key, "", htmlspecialchars($val)));
			}
		}

		/* Now delete all files for this language from templates_c directory */
		$dir = opendir(TEMPLATE_C_DIR);
		while ($fl = readdir($dir)) {
			if ($fl == '.' || $fl == '..' || $fl == 'index.html') {
				continue;
			} else {
				if (strpos($fl,$_REQUEST['langname']) == 0 ) {
					unlink(TEMPLATE_C_DIR.$fl);
				}
			}
		}
		closedir($dir);
		$m_msg = str_replace('#LANGUAGE#', strtoupper($_REQUEST['langname']), get_lang('langfile_loaded'));

		$t->assign('msg', $m_msg);
		$t->assign('msg_file',$file);

	} elseif ($_REQUEST['deletelang'] != '') {
		/* Delete language from DB */

		$osDB->query('delete from ! where lang = ?', array(LANGUAGE_TABLE, $_REQUEST['langname']) );

		/* Now delete all files for this language from templates_c directory */
		$dir = opendir(TEMPLATE_C_DIR);
		while ($fl = readdir($dir)) {
			if ($fl == '.' || $fl == '..' || $fl == 'index.html') {
				continue;
			} else {
				if (strpos($fl,$_REQUEST['langname']) == 0 ) {
					unlink(TEMPLATE_C_DIR.$fl);
				}
			}
		}
		closedir($dir);

		$t->assign('msg', str_replace('#LANGUAGE#', strtoupper($_REQUEST['langname']), get_lang('lang_deleted')));

	}

	/* optimize language table for performance */
	$osDB->query('optimize table '.LANGUAGE_TABLE);

}

$t->assign('langname', $_REQUEST['langname']);

$t->assign('language_options',$language_options);

$t->assign('language_files', $language_files);

$t->assign('lang_dir', LANG_DIR);

$t->assign('rendered_page', $t->fetch('admin/load_language.tpl'));

$t->display('admin/index.tpl');

?>