<?php
if (! defined ( "ADMIN_FILE" ))
	die ( "Illegal File Access" );
$shab_types = array ('auto' => 'Авто', 'file' => 'Файловое поле', 'text' => 'Текстовое поле', 'select' => 'Поле для выбора', 'radio' => 'Радио кнопка', 'textarea' => 'Текстовое поле(большое)', 'checkbox' => "Галочки выбора" );
$shab_construct = array ('rname' => "Имя", 'tor' => "Поле торрента", 'nfo' => 'NFO', 'poster' => "Постер", 'screens' => "Скриншот", 'descr' => "Описание", 'reliz' => "Релиз группа", 'dops' => "Доп. описание", 'name' => "Название", 'genre' => "Жанр" );
function Shablons() {
	global $pic_base_url, $admin_file;
	begin_frame ( "Управление шаблонами" );
	print ( "<table width='100%' align='center'><tr><td><b>Категория</b></td><td><b>Шаблон</b></td></tr>" );
	$sql = sql_query ( "SELECT c.name, c.image, (SELECT COUNT(*) FROM shablons WHERE shablons.catid = c.id LIMIT 1) AS catid, c.id FROM categories AS c" ) or sqlerr ( __FILE__, __LINE__ );
	while ( $res = mysql_fetch_assoc ( $sql ) ) {
		?><tr valign='middle'>
	<td align='center' width='10%'><img
		src='<?=$pic_base_url?>cats/<?=$res ['image']?>'><br /><?=$res ['name']?></td>
	<td><?=(! $res ['catid'] ? "Стандартный. <a href='" . $admin_file . ".php?op=CreateShablon&cid=" . $res ['id'] . "'>Создать</a> уникальный?" : "Имееся уникальный шаблон. <a href='" . $admin_file . ".php?op=CreateShablon&cid=" . $res ['id'] . "'><img src='" . $pic_base_url . "pen.gif'></a> <a href='" . $admin_file . ".php?op=DeleteShablon&cid=" . $res ['id'] . "'><img src='" . $pic_base_url . "warned2.gif'></a>")?></td>
</tr><?
	}
	print ( "</table>" );
}
function validrname($rname, $name = 0) {
	if (! $rname)
		return 'no_contents';
		
	// The following characters are allowed in user names
	$allowedchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" . ($name ? "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ[]/:\" " : "");
	for($i = 0; $i < strlen ( $rname ); ++ $i)
		if (strpos ( $allowedchars, $rname [$i] ) === false)
			return false;
	return true;
}
function CreateShablon() {
	global $admin_file, $shab_construct, $shab_types, $pic_base_url;
	$cid = ( int ) $_GET ["cid"];
	if (! $cid)
		location ( $admin_file . ".php?op=Shablons" );
	if ((is_array ( $_POST ['addtype'] ) && is_array ( $_POST ['addconst'] )) || (is_array ( $_POST ['edittype'] ) && is_array ( $_POST ['editconst'] ))) {
		if ($_POST ['addname'])
			foreach ( $_POST ['addname'] as $num => $name ) {
				$rname = $_POST ['addrname'] [$num];
				$type = $_POST ['addtype'] [$num];
				$const = $_POST ['addconst'] [$num];
				$scrabe = $_POST ['addscrabes'] [$num];
				$descr = $_POST ['adddescr'] [$num];
				$sort = $_POST ['addsort'] [$num];
				$value = $_POST ['addvals'] [$num];
				$validrname = validrname ( $rname );
				$validname = validrname ( $name, 1 );
				if ($type && $const) {
					if (! $validrname)
						continue;
					if (! $validname)
						continue;
					if ($validname == 'no_contents' && $validrname == 'no_contents' && ! $scrabe)
						continue;
					if (! $shab_types [$type])
						continue;
					if (! $shab_construct [$const])
						continue;
					$values [] = '(' . $cid . ', ' . sqlesc ( $name ) . ', ' . sqlesc ( $rname ) . ', ' . sqlesc ( $type ) . ', ' . sqlesc ( $const ) . ', ' . sqlesc ( $scrabe ) . ', ' . sqlesc ( $descr ) . ', ' . intval ( $sort ) . ', ' . sqlesc ( $value ) . ')';
				}
			}
		if ($values)
			sql_query ( "INSERT INTO shablons (catid, name, rname, type, construct, scrabes, descr, `orderby`, `values`) VALUES" . implode ( ", ", $values ) ) or sqlerr ( __FILE__, __LINE__ );
		if ($_POST ['editids'])
			foreach ( $_POST ['editids'] as $num => $id ) {
				$id = intval ( $id );
				$name = $_POST ['editname'] [$num];
				$rname = $_POST ['editrname'] [$num];
				$type = $_POST ['edittype'] [$num];
				$const = $_POST ['editconst'] [$num];
				$scrabe = $_POST ['editscrabes'] [$num];
				$descr = $_POST ['editdescr'] [$num];
				$sort = $_POST ['editsort'] [$num];
				$value = $_POST ['editvals'] [$num];
				$validrname = validrname ( $rname );
				$validname = validrname ( $name, 1 );
				if ($type && $const) {
					if (! $validrname)
						continue;
					if (! $validname)
						continue;
					if ($validname == 'no_contents' && $validrname == 'no_contents' && ! $scrabe)
						continue;
					if (! $shab_types [$type])
						continue;
					if (! $shab_construct [$const])
						continue;
					$upvalues [$id] = '`name` = ' . sqlesc ( $name ) . ', `rname` = ' . sqlesc ( $rname ) . ', `type` = ' . sqlesc ( $type ) . ', `construct` =  ' . sqlesc ( $const ) . ', `scrabes` = ' . sqlesc ( $scrabe ) . ', `descr` = ' . sqlesc ( $descr ) . ', `orderby` = ' . intval ( $sort ) . ', `values` = ' . sqlesc ( $value );
				}
			}
		if ($upvalues) {
			foreach ( $upvalues as $id => $value ) {
				sql_query ( "UPDATE shablons SET " . $value . " WHERE shabid=" . $id ) or sqlerr ( __FILE__, __LINE__ );
			}
		}
		if (is_array ( $_POST ["copy"] )) {
			$toid = ( int ) $_POST ["toid"];
			$ids = $_POST ["copy"];
			if ($toid) {
				$sql = sql_query ( "SELECT * FROM shablons WHERE shabid IN (" . implode ( ",", array_map ( "intval", $ids ) ) . ")" ) or sqlerr ( __FILE__, __LINE__ );
				while ( $res = mysql_fetch_array ( $sql ) ) {
					$invalues [] = '(' . $toid . ', ' . sqlesc ( $res ["name"] ) . ', ' . sqlesc ( $res ["rname"] ) . ', ' . sqlesc ( $res ["type"] ) . ', ' . sqlesc ( $res ["construct"] ) . ', ' . sqlesc ( $res ["scrabes"] ) . ', ' . sqlesc ( $res ["descr"] ) . ', ' . intval ( $res ["orderby"] ) . ', ' . sqlesc ( $res ["values"] ) . ')';
				}
				if ($invalues)
					sql_query ( "INSERT INTO shablons (catid, name, rname, type, construct, scrabes, descr, `orderby`, `values`) VALUES" . implode ( ', ', $invalues ) ) or sqlerr ( __FILE__, __LINE__ );
			}
		}
		location ( $admin_file . ".php?op=Shablons", 3 );
		begin_frame ( (! $upvalues ? "Добавление" : "Редактирование") . " шаблона к категории ID " . $cid );
		print ( "<center><strong>Успешно! Было добавлено " . count ( $values ) . ($upvalues ? " и обновлено " . count ( $upvalues ) : "") . " значений в ID категории - " . $cid . "</strong></center>" );
		if ($invalues)
			print ( "<center><strong>Успешно! Было скопировано " . count ( $invalues ) . " значений в ID категории - " . $toid . "</strong></center>" );
	} else {
		$sql = sql_query ( "SELECT * FROM shablons WHERE catid=" . $cid . " ORDER BY construct, orderby" ) or sqlerr ( __FILE__, __LINE__ );
		if ($sql) {
			$strings = '';
			while ( $row = mysql_fetch_array ( $sql ) ) {
				$id = $row ["shabid"];
				$rname = $row ["rname"];
				$name = $row ["name"];
				$type = $row ["type"];
				$construct = $row ["construct"];
				$scrabes = $row ["scrabes"];
				$descr = $row ["descr"];
				$orderby = $row ["orderby"];
				$values = $row ["values"];
				$types = "<select name='edittype[]'>";
				foreach ( $shab_types as $ttype => $shab ) {
					$types .= "<option value='" . $ttype . "'" . ($type == $ttype ? " selected" : "") . ">" . $shab . "</option>";
				}
				$types .= "</select>";
				$constructs = "<select name='editconst[]'>";
				foreach ( $shab_construct as $tconstruct => $shab ) {
					$constructs .= "<option value='" . $tconstruct . "'" . ($construct == $tconstruct ? " selected" : "") . ">" . $shab . "</option>";
				}
				$constructs .= "</select>";
				$strings .= "<br /><input type='hidden' name='editids[]' value='$id'><table align='center'>
	<tr>
		<td align='right'>Название</td>
		<td align='left'><input type='text' name='editname[]' size=25 value='$name'></td>
	</tr>
	<tr>
		<td align='right'>Наст. название(лат.)</td>
		<td align='left'><input type='text' name='editrname[]' size=25 value='$rname'></td>
	</tr>
	<tr>
		<td align='right'>Заключить в...(содержание - {content})</td>
		<td align='left'><textarea name='editscrabes[]' rows=2 cols=60 style='overflow: auto;'>$scrabes</textarea></td>
	</tr>
	<tr>
		<td align='right'>Подописание</td>
		<td align='left'><textarea name='editdescr[]' rows=2 cols=60 style='overflow: auto;'>$descr</textarea></td>
	</tr>
	<tr>
		<td align='right'>Значения(разделять \"|\" название<br/> и значение, а группы - \"||\")</td>
		<td align='left'><textarea name='editvals[]' rows=5 cols=60>$values</textarea></td>
	</tr>
	<tr>
		<td align='right'>Сортировка</td>
		<td align='left'><input type='text' name='editsort[]' size=15 value='$orderby'></td>
	</tr>
	<tr>
		<td align='right'>Тип</td>
		<td align='left'>$types</td>
	</tr>
	<tr>
		<td align='right'>Конструкция</td>
		<td align='left'>$constructs</td>
	</tr>
	<tr>
		<td align='right'>Доп. операции</td>
		<td align='left'><span onclick='deleting($id);'><img src='" . $pic_base_url . "warned2.gif'></span>&nbsp;Скопировать <input type='checkbox' name='copy[]' value='$id'><div id='delete$id'></div></td>
	</tr>	
</table>";
			}
		}
		if ($strings) {
			$cats = "";
			$sql = sql_query ( "SELECT name, id FROM categories WHERE id <> " . $cid ) or sqlerr ( __FILE__, __LINE__ );
			while ( $res = mysql_fetch_array ( $sql ) ) {
				$cats .= "<option value='" . $res ['id'] . "'>" . $res ['name'] . "</option>";
			}
			if ($cats)
				$cats = "<center>Скопировать в... <select name='toid'><option value='0'>Не копировать</option>$cats</select></center>";
		}
		begin_frame ( (! $strings ? "Добавление" : "Редактирование") . " шаблона к категории ID " . $cid );
		?><form action="<?=$admin_file?>.php?op=CreateShablon&cid=<?=$cid?>"
	method='post' name='add'>
	<?=$strings?>
	<?=$cats?>
<center><input type='submit' value='Сохранить' name='save' disabled>&nbsp;&nbsp;&nbsp;<a
	onclick="adding();"><input type='button' value='Добавить поле'></a></center>
<center><font size=1>*Максимальное кол-во добавляемых полей - 100, вы
можете изменить эту цифру в этом файле</font></center>
<script language="javascript" type="text/javascript" src="js/ajax.js"></script><script
	type="text/javascript"> <!-- 
num = 0;
function adding() {
	this.num++;
    var ajax = new engine_ajax(); 
    ajax.onShow = function() { }; 
    var varsString = ""; 
    ajax.requestFile = "admin/ajax_modules/ajax_addshab.php";
    ajax.method = 'POST'; 
    ajax.setVar("num", this.num); 
    ajax.element = 'adding'+this.num; 
    ajax.sendAJAX(varsString); 
    document.add.save.disabled=0;
    return false;
}
function deleting(id) {
    var ajax = new engine_ajax(); 
    ajax.onShow = function() { }; 
    var varsString = ""; 
    ajax.requestFile = "admin/ajax_modules/ajax_delshab.php";
    ajax.method = 'POST'; 
    ajax.setVar("id", id); 
    ajax.element = 'delete'+id;
    ajax.sendAJAX(varsString); 
    return false;
}
max_nums = 100; // Максимальное кол-во добавляемых полей.
for(nums = max_nums; nums >= 1; nums --)
	document.write ( '<div id=\'adding' + nums + '\'></div>' );
adding();
--></script></form><?
	}
}
function DeleteShablon() {
	global $admin_file;
	$cid = ( int ) $_GET ["cid"];
	if ($_GET ['sure'] == 'yes') {
		sql_query ( "DELETE FROM shablons WHERE catid=" . $cid ) or sqlerr ( __FILE__, __LINE__ );
		location ( $admin_file . '.php?op=Shablons' );
	} else {
		begin_frame ( "Удаление шаблона" );
		print ( "<table width='100%' align='center'><tr><td><b>Вы уверены, что хотите удалить шаблон категории ID " . $cid . ". <a href='" . $admin_file . ".php?op=DeleteShablon&cid=" . $cid . "&sure=yes'>Да</a> или <a href='" . $admin_file . ".php?op=Shablons'>Нет</a>.</b></td></tr></table>" );
	}
}
switch ($op) {
	case "Shablons" :
		Shablons ();
		break;
	case "CreateShablon" :
		CreateShablon ();
		break;
	case "DeleteShablon" :
		DeleteShablon ();
		break;
}
?>