<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
	$lang_info=Db::i()->selectRow("SELECT `key`, lang_name, lang_id FROM ?_langs WHERE lang_id=?", $_GET['var1']);
	if (!$lang_info) return LabCMS::i()->error("Язык не найден");

	$name=str_replace('/', '', $_GET['var2']);
	$module=Db::i()->selectRow("SELECT * FROM ?_modules WHERE module=?", $name);
	if (!$module) return LabCMS::i()->error("Модуль не найден");
	
	addBreadcrumb($lang_info['lang_name'], _url($lang_info['lang_id'], 'files'));
	
	Tpl::i()->assign('lang', $lang_info);
	
	$mod_template="edit_text.tpl";
	
	addBreadcrumb($module['name']);
	
	$langpath=LAB_PATH_KERNEL.'/languages/'.$lang_info['key'];
	if (!is_dir($langpath) && !@mkdir($langpath, 0777))
	{
		LabCMS::i()->error(sprintf(_m("Не могу создать каталог %s"),  $langpath), true);
		return;
	}
	
	$filename="lang.".$name.".php";
	
	$filepath=$langpath.'/'.$filename;
	
	$default=merge_langs($lang_info['key'], $filename);
	
	if ($_SERVER['REQUEST_METHOD']=='POST')
	{
		User::checkToken();
		if (count($_POST['del'])==count($_POST['var'])) unlink($filepath);
		else
		{
			$array=array();
			foreach($_POST['var'] as $key=>$var)
			{
				if (!$_POST['del'][$key]) $array[$var]=$_POST['val'][$key];
			}
			makeLangFile($array, $filepath);
		}
		refresh('', LabCMS::i()->url($_GET['var1'], 'files'));
	}
	
	$arr=getLang($filepath);
	$text=file_get_contents($filepath);
	
	if (count($arr))
	{
		foreach($arr as $key=>$var)
		{
			Tpl::i()->append('strings', array('key'=>$key, 'val'=>$var, 'active'=>array_key_exists($key, $default)));
		}
	}
	
	
	function merge_langs($target_lang, $file)
	{
		$langpath=LAB_PATH_KERNEL.'/languages';
		$default=getLang($langpath.'/'.LabConfig::$cfg['default_lang'].'/'.$file);
		$target=getLang($langpath.'/'.$target_lang.'/'.$file);
		if (count($default)) foreach ($default as $key=>$val)
		{
			if (!array_key_exists($key, $target)) $target[$key]=''; 
		}
		ksort($target);
		makeLangFile($target, $langpath.'/'.$target_lang.'/'.$file);
		return $default;
	}
	
	function getLang($file)
	{
		$lang=array();
		if (file_exists($file))
		{
			include $file;
			return $lang;
		}
		else return array();
	}
	
	function makeLangFile($array, $file)
	{
		if (file_exists($file) && !is_writable($file))
			return LabCMS::i()->error(sprintf(_m("Недоступен для записи файл %s"), $file), true);
		elseif(!is_writable(dirname($file)))
			return LabCMS::i()->error(sprintf(_m("Недоступен для записи каталог %s"), dirname($file)), true);
			
		$data='<?'."\r\n";
		foreach($array as $key=>$var)
		{
			$data.='$lang[\''.str_replace(array("\\", "'"), array("\\\\", "\'"), $key).'\']="'.str_replace(array("\\", '"'), array("\\\\", '\"'), $var).'";'."\r\n";
		}
		file_put_contents($file, $data);
		@chmod($file, 0666);
	}
	