Просмотр файла index.php

Размер файла: 30.19Kb
<?php
# Morgan

	require 'sys/inc/core.php';


		switch(MODE)
	{
	default:
	// вывод форумов
	{

	show_title($cfg['index_title']);

	$template -> isset_forums = false;

	$count_forums = $db -> one('SELECT COUNT(*) FROM `forums`');

	if(USER_LEVEL >= USER_ADMIN)
		{
		// добавление форума
		if(isset($_GET['addforum']))
			{
			check_fields(PATH.'index.php', array(array('forum_name', 'not null', 'maxlen' => 50)));

			$forum_name = str($_POST['forum_name']);

			if($count_forums > 0 && $db -> one("SELECT COUNT(*) FROM `forums` WHERE `name` = '$forum_name'") > 0)
				{
				err('Форум &quot;'.$forum_name.'&quot; уже существует', PATH.'index.php');
				}

			$forum_position = ($count_forums > 0 ? ($db -> one("SELECT MAX(`position`) FROM `forums`") + 1) : 1);

			if($db -> sql("INSERT INTO `forums` SET `name` = '$forum_name', `position` = '$forum_position', `level` = '0', `level_topics` = '1', `counter_topics` = '1', `counter_posts` = '1'"))
				{
				msg('Форум &quot;'.$forum_name.'&quot; создан', PATH.'index.php');
				}
			else
				{
				err('Ошибка', PATH.'index.php');
				}

			}
		// перемещение
		elseif(isset($_GET['position_forum']))
			{
			$forum_id = int($_GET['position_forum']);
			if($db -> one("SELECT COUNT(*) FROM `forums` WHERE `id` = '$forum_id'") == 0 || !in_array(MODE, array('up', 'down')))locate(PATH.'index.php');
			$forum_position = $db -> one("SELECT `position` FROM `forums` WHERE `id` = '$forum_id'");

			if(MODE == 'up')
				{
				$db -> sql("UPDATE `forums` SET `position` = 0 WHERE `position` = '$forum_position' - 1");
				$db -> sql("UPDATE `forums` SET `position` = '$forum_position' - 1 WHERE `id` = '$forum_id'");
				$db -> sql("UPDATE `forums` SET `position` = '$forum_position' WHERE `position` = 0");
				locate(PATH.'index.php');
				}
			else
				{
				$db -> sql("UPDATE `forums` SET `position` = 0 WHERE `position` = '$forum_position' + 1");
				$db -> sql("UPDATE `forums` SET `position` = '$forum_position' + 1 WHERE `id` = '$forum_id'");
				$db -> sql("UPDATE `forums` SET `position` = '$forum_position' WHERE `position` = 0");
				locate(PATH.'index.php');
				}

			}
		// расстановка верного position
		elseif(isset($_GET['re_position']))
			{
			$i = 0;

			$db -> sql("UPDATE `forums` SET `position` = '0'");

					while($cat = $db -> fetch("SELECT `id` FROM `forums` ORDER BY `name` ASC"))
				{
				$i ++;
				$db -> sql("UPDATE `forums` SET `position` = '$i' WHERE `id` = '{$cat['id']}'");
				}

			msg('Индексы заново расставлены', PATH.'index.php');
			}
		}

	$all_posts = 0;

	$count_forums = $db -> one("SELECT COUNT(*) FROM `forums` WHERE `level` <= '".USER_LEVEL."'");
	if($count_forums > 0)
		{
		$template -> isset_forums = true;
		$template_forums = array();

		$need_re_position = false;

		$i = 0;
				while($forum = $db -> fetch("SELECT * FROM `forums` WHERE `level` <= '".USER_LEVEL."' ORDER BY `position` ASC"))
			{
			$i ++;

			$template_forum = array('id' => $forum['id'], 'i' => $i, 'name' => $forum['name'], 'description' => $forum['description'], 'count_topics' => $forum['count_topics'], 'count_posts' => $forum['count_posts']);

			$all_posts += $forum['count_posts'];

			if($forum['position'] != $i)$need_re_position = true;

			if(!empty($template_forum['description']))$template_forum['description'] = '<small>'.$template_forum['description'].'</small><br />';

			if(USER_LEVEL >= USER_ADMIN && $count_forums > 1)
				{
				$template_forum['managment'] = '[';
				#if($i > 1)$template_forum['managment'] .= '<a href="'.PATH.'index.php?position_forum='.$forum['id'].'&mode=up">вверх</a>';
				if($i > 1)$template_forum['managment_up'] = true;
				#if($i < $count_forums)$template_forum['managment'] .= ' <a href="'.PATH.'index.php?position_forum='.$forum['id'].'&mode=down">вниз</a>';
				if($i < $count_forums)$template_forum['managment_down'] = true;
				$template_forum['managment'] .= ']';
				}

			$template_forums[] = $template_forum;
			}


		$template -> assign('forums', $template_forums);

		$template -> need_re_position = $need_re_position;

		}

	$template -> count_online_users = $db -> one("SELECT COUNT(*) FROM `users` WHERE `date_last_visit` > ('".TIME."' - 300)");

	$template -> count_all_users = $db -> one("SELECT COUNT(*) FROM `users`");

	$template -> count_all_posts = $all_posts;

	$template -> index_page = true;

	$template -> block = 'index';

	}
	break;
	############################################################################
	case 'stat':
	{

	show_title($cfg['index_title'], 'Статистика');

	$all_posts = $db -> one("SELECT COUNT(*) FROM `posts`");

	$usefull_posts = $db -> one("SELECT COUNT(*) FROM `posts` WHERE (SELECT `counter_posts` FROM `forums` WHERE `id` = `posts`.`fid`) = 1");

	$today_posts = $db -> one("SELECT COUNT(*) FROM `posts` WHERE `date` >= '".TIME_TODAY."'");

	$all_topics = $db -> one("SELECT COUNT(*) FROM `topics`");

	$today_topics = $db -> one("SELECT COUNT(*) FROM `topics` WHERE `date` >= '".TIME_TODAY."'");

	$all_users = $db -> one("SELECT COUNT(*) FROM `users`");

	$today_users_reg = $db -> one("SELECT COUNT(*) FROM `users`  WHERE `date_reg` >= '".TIME_TODAY."'");

	$today_users_visit = $db -> one("SELECT COUNT(*) FROM `users`  WHERE `date_last_visit` >= '".TIME_TODAY."'");

	$users_topics = round(($all_topics / $all_users), 2);

	$users_posts = round(($all_posts / $all_users), 2);

	$all_userfull_posts = floor(($usefull_posts / $all_posts) * 100);

	$posts_on_day = round($all_posts / floor((TIME - $cfg['date_start_forum']) / 86400), 2);

	$template -> assign(array
		(
		'all_posts' => $all_posts,
		'usefull_posts' => $usefull_posts,
		'all_usefull_posts' => $all_userfull_posts,
		'today_posts' => $today_posts,
		'posts_on_day' => $posts_on_day,
		'all_topics' => $all_topics,
		'today_topics' => $today_topics,
		'all_users' => $all_users,
		'today_users_reg' => $today_users_reg,
		'today_users_visit' => $today_users_visit,
		'users_topics' => $users_topics,
		'users_posts' => $users_posts
#		'' => $,

		)
	);

	if(!LOCALHOST)sleep(3);


	$template -> block = 'stat';

	}
	break;
	############################################################################
	case 'deactive':
	// страница для деактивированных
	{

	show_title($cfg['index_title'], 'Деактивация');

	only_reg();
	if($userdata['active'])locate(PATH.'index.php');


	$template -> user_new = empty($userdata['date_last_visit']);

	$template -> block = 'deactive';

	}
	break;
	############################################################################
	case 'users':
	// список пользователей
	{
	
	show_title($cfg['index_title'], 'Пользователи');

	// сортировка
	if(isset($_GET['sort']) && in_array($_GET['sort'], array('nick', 'level', 'date_reg', 'date_last_visit', 'info_name', 'info_city', 'info_sex')))
		{
		$sort_field = $_GET['sort'];
		}
	else
		{
		$sort_field = 'date_last_visit';
		}
	$template -> sort_field = $sort_field;

	$sort_order = (isset($_GET['desc']) || $sort_field == 'date_last_visit') ? 'DESC': 'ASC';
	$template -> sort_order = $sort_order;

	$where = null;

	if($sort_field == 'date_last_visit')
		{
		$where = '`date_last_visit` > 0';
		}
	elseif($sort_field == 'level')
		{
		$where = '`level` != \'1\'';
		}
	elseif($sort_field == 'info_name' || $sort_field == 'info_city')
		{
		$where = '`'.$sort_field.'` != \'\'';
		}

	if(!empty($where))$where = 'WHERE '.$where;

	$count_users = $db -> one("SELECT COUNT(*) FROM `users` $where");

	if($count_users > 0)
		{
		$template -> count_users = $count_users;

		check_page($count_users, PATH.'index.php?mode=users&page={$page}', ONPAGE_TOPICS);



		$template_users = array();

		$i = START_TOPICS;


				while($user = $db -> fetch("SELECT `nick`, `id`, `date_last_visit`, `$sort_field` FROM `users` $where ORDER BY `$sort_field` $sort_order, `date_last_visit` DESC LIMIT ".START_TOPICS.", ".ONPAGE_TOPICS))
			{
			$i ++;

			$template_user = array('id' => $user['id'], 'nick' => $user['nick'], 'i' => $i);

			$template_user['online']  = ' <small>'.(((TIME - $user['date_last_visit']) < 300) ? '<font color="green">'.(($user['date_last_visit'] - TIME) == 0 ? 'on' : 'away '.(TIME - $user['date_last_visit'])).'</font>' : '<font color="red">off</font>').'</small>';

			if($sort_field == 'date_reg' || $sort_field == 'date_last_visit')
				{
				#$template_user['date'] = 'Дата '.($sort_field == 'date_reg' ? 'регистрации' : 'авторизации').' : '.xdate($user[$sort_field]).'<br />';
				$template_user[$sort_field] = xdate($user[$sort_field]);
				}
			elseif($sort_field == 'level')
				{
				#$template_user['level'] = 'Статус на форуме : '.$levels[$user['level']][1].'<br />';
				$template_user['level'] = $levels[$user['level']][1];
				}
			elseif($sort_field == 'info_sex')
				{
				$template_user['sex'] = ($user['info_sex'] ? 'Муж' : 'Жен');
				}
			elseif($sort_field == 'info_name' || $sort_field == 'info_city')
				{
				#$template_user['info'] = ($sort_field == 'info_name' ? 'Звать' : 'Проживает в ').' : '.$user[$sort_field].'<br />';
				$template_user[$sort_field] = $user[$sort_field];
				}

			$template_users[] = $template_user;
			}

		$template -> assign('users', $template_users);

		pagebar($str, PAGE, PATH.'index.php?mode=users&sort='.$sort_field.($sort_order ? '&desc=1' : null).'&page={$page}');

		}


	$template -> block = 'users';

	}
	break;
	############################################################################
	// BB коды
	case 'bbcode':
	case 'bbcodes':
	{

	show_title($cfg['index_title'], 'BB коды');

	$template -> block = 'bbcodes';

	}
	break;
	############################################################################
	// транслит
	case 'translit':
	{

	show_title($cfg['index_title'], 'Правила транслита');

	$template -> block = 'translit';

	}
	break;
	############################################################################
	// смайлы
	case 'smile':
	case 'smiles':
	{

	show_title($cfg['index_title'], 'Смайлы');

	$template_smiles = array();
	// немного изменяем структуру массива
			foreach($smiles as $smile => $image)
		{
		$template_smiles[] = array('smile' => $smile, 'image' => $image);
		}

	$template -> assign('smiles', $template_smiles);

	$template -> block = 'smiles';

	}
	break;
	############################################################################
	case 'rules':
	// правила
	{

	if(ID > 0 && $db -> one("SELECT COUNT(*) FROM `rules_cats` WHERE `id` = '".ID."'") > 0)
		{

		$rules_cat_info = $db -> fetch("SELECT * FROM `rules_cats` WHERE `id` = '".ID."'");

		show_title($cfg['index_title'], 'Правила форума : '.$rules_cat_info['name']);

		$template -> rules_cat_id = ID;
		$template -> rules_cat_name = $rules_cat_info['name'];

		// подсветка правила
		$rid = 0;
		if(!empty($_GET['rid']))$rid = int($_GET['rid']);

		$i = 0;

		// управление
		if(USER_LEVEL >= USER_ADMIN && in_array(SACT, array('edit', 'del')) && $db -> one("SELECT COUNT(*) FROM `rules` WHERE `cid` = '".ID."' AND `id` = '$rid'") > 0)
			{

			$rule_info = $db -> fetch("SELECT * FROM `rules` WHERE `cid` = '".ID."' AND `id` = '$rid'");

			$template -> rule_title = $rule_info['title'];
			$template -> rule_text = $rule_info['text'];

			$template -> rule_id = $rid;

			// изменение
			if(SACT == 'edit')
				{

				if(isset($_GET['edit']) && postval('edit', 1))
					{
					check_fields(PATH.'index.php?mode=rules&id='.ID.'&rid='.$rid.'&sact=edit&'.RAND, array(array('title', 'maxlen' => 70), array('text', 'maxlen' => 500)));

					$title = str($_POST['title']);
					$text = str($_POST['text']);

					if($db -> sql("UPDATE `rules` SET `title` = '$title', `text` = '$text' WHERE `id` = '$rid'"))
						{
						msg('Правило изменено', PATH.'index.php?mode=rules&id='.ID.'&rid='.$rid);
						}
					else
						{
						err('Ошибка', PATH.'index.php?mode=rules&id='.ID.'&rid='.$rid.'&sact=edit&'.RAND);
						}

					}

				$template -> block = 'rule_edit';

				}
			else
				{

				if(isset($_GET['del']) && postval('del', 1))
					{
					if($db -> sql("DELETE FROM `rules` WHERE `id` = '$rid'"))
						{
						msg('Правило удалено', PATH.'index.php?mode=rules&id='.ID);
						}
					else
						{
						err('Ошибка', PATH.'index.php?mode=rules&id='.ID.'&rid='.$rid.'&sact=del&'.RAND);
						}
					}

				$template -> block = 'rule_del';
				}

			}
		else
			{

					switch(ACT)
				{
				default:
				{
				// просмотр правил

					// добавление
				if(isset($_GET['add']) && postval('add', 1))
					{
					check_fields(PATH.'index.php?mode=rules&id='.ID.'&'.RAND, array(array('title', 'maxlen' => 70), array('text', 'maxlen' => 500)));

					$title = str($_POST['title']);
					$text = str($_POST['text']);

					if(!empty($title) && $db -> one("SELECT COUNT(*) FROM `rules` WHERE `cid` = '".ID."' AND `title` = '$title'") > 0)
						{
						err('Такое правило уже есть', PATH.'index.php?mode=rules&id='.ID.'&'.RAND);
						}

					if($db -> sql("INSERT INTO `rules` SET `cid` = '".ID."', `title` = '$title', `text` = '$text'"))
						{
						$rid = $db -> last_id();
						msg('Правило изменено', PATH.'index.php?mode=rules&id='.ID.'&rid='.$rid.'#rule-'.$rid);
						}
					else
						{
						err('Ошибка', PATH.'index.php?mode=rules&id='.ID.'&'.RAND);
						}

					}

				// правила
				$count_rules = $db -> one("SELECT COUNT(*) FROM `rules` WHERE `cid` = '".ID."'");
				if($count_rules > 0)
					{
					$template_rules = array();



							while($rule = $db -> fetch("SELECT * FROM `rules` WHERE `cid` = '".ID."' ORDER BY `title` ASC"))
						{
						$i ++;

						#$template_rule = array('i' => $i, 'id' => $rule['id'], 'divclass' => ($rid == $rule['id'] ? 'select_unit' : 'unit'), 'title' => (!empty($rule['title']) ? '<b>'.$rule['title'].'</b><br />' : null), 'text' => post($rule['text']));
						$template_rule = array('i' => $i, 'id' => $rule['id'], 'divclass' => ($rid == $rule['id'] ? 'select_unit' : 'unit'), 'title' => $rule['title'], 'text' => post($rule['text']));

						$template_rules[] = $template_rule;
						}


					$template -> rules = $template_rules;
					}

				$template -> block = 'rules';
				}
				break;
				################################################################
				case 'edit':
				// изменение категори
				{

				if(isset($_GET['edit']) && postval('edit', 1))
					{
					check_fields(PATH.'index.php?mode=rules&id='.ID.'&act=edit&'.RAND, array(array('name', 'not null', 'maxlen' => 50)));

					$name = str($_POST['name']);

					if($name == $rules_cat_info['name'])msg('Данные не изменены', PATH.'index.php?mode=rules&id='.ID);

					if($db -> one("SELECT COUNT(*) FROM `rules_cats` WHERE `name` = '$name'"))err('Категория &quot;'.$name.'&quot; уже существует', PATH.'index.php?mode=rules&id='.ID.'&act=edit&'.RAND);

					if($db -> sql("UPDATE `rules_cats` SET `name` = '$name' WHERE `id` = '".ID."'"))
						{
						msg('Категория изменена', PATH.'index.php?mode=rules&id='.ID);
						}
					else
						{
						err('Ошибка', PATH.'index.php?mode=rules&id='.ID.'&act=edit&'.RAND);
						}

					}

				$template -> block = 'rules_cat_edit';
				}
				break;
				################################################################
				case 'del':
				// удаление категории
				{

				if(isset($_GET['del']) && postval('del', 1))
					{
					// удаляем правила
					if($db -> sql("DELETE FROM `rules` WHERE `cid` = '".ID."'"))
						{
						if($db -> sql("DELETE FROM `rules_cats` WHERE `id` = '".ID."'"))
							{
							msg('Категория &quot;'.$rules_cat_info['name'].'&quot; удалена', PATH.'index.php?mode=rules');
							}
						else
							{
							err('Ошибка при удалении категории', PATH.'index.php?mode=rules&id='.ID.'&act=del');
							}
						}
					else
						{
						err('Ошибка при удалении правил', PATH.'index.php?mode=rules&id='.ID.'&act=del');
						}

					}

				$template -> block = 'rules_cat_del';

				}
				break;
				}
			}

		}
	else
		{

		show_title($cfg['index_title'], 'Правила форума');

		// категории правил
		$count_rules_cats = $db -> one("SELECT COUNT(*) FROM `rules_cats`");

		if(USER_LEVEL >= USER_ADMIN)
			{
			// добавление категории
			if(isset($_GET['addcat']))
				{
				check_fields(PATH.'index.php?mode=rules', array(array('name', 'not null', 'maxlen' => 50)));

				$cat_name = str($_POST['name']);

				if($count_rules_cats > 0 && $db -> one("SELECT COUNT(*) FROM `rules_cats` WHERE `name` = '$cat_name'") > 0)
					{
					err('Категория &quot;'.$name.'&quot; уже существует', PATH.'index.php?mode=rules');
					}

				$cat_position = ($count_rules_cats > 0 ? ($db -> one("SELECT MAX(`position`) FROM `rules_cats`") + 1) : 1);

				if($db -> sql("INSERT INTO `rules_cats` SET `name` = '$cat_name', `position` = '$cat_position'"))
					{
					msg('Категория &quot;'.$cat_name.'&quot; создана', PATH.'index.php?mode=rules');
					}
				else
					{
					err('Ошибка', PATH.'index.php?mode=rules');
					}

				}
			// перемещения
			elseif(isset($_GET['position_cat']))
				{
				$cat_id = int($_GET['position_cat']);
				if($db -> one("SELECT COUNT(*) FROM `rules_cats` WHERE `id` = '$cat_id'") == 0 || !in_array(ACT, array('up', 'down')))locate(PATH.'index.php?mode=rules');
				$cat_position = $db -> one("SELECT `position` FROM `rules_cats` WHERE `id` = '$cat_id'");

				if(ACT == 'up')
					{
					$db -> sql("UPDATE `rules_cats` SET `position` = 0 WHERE `position` = '$cat_position' - 1");
					$db -> sql("UPDATE `rules_cats` SET `position` = '$cat_position' - 1 WHERE `id` = '$cat_id'");
					$db -> sql("UPDATE `rules_cats` SET `position` = '$cat_position' WHERE `position` = 0");
					locate(PATH.'index.php?mode=rules');
					}
				else
					{
					$db -> sql("UPDATE `rules_cats` SET `position` = 0 WHERE `position` = '$cat_position' + 1");
					$db -> sql("UPDATE `rules_cats` SET `position` = '$cat_position' + 1 WHERE `id` = '$cat_id'");
					$db -> sql("UPDATE `rules_cats` SET `position` = '$cat_position' WHERE `position` = 0");
					locate(PATH.'index.php?mode=rules');
					}

				}
			// расстановка верного position
			elseif(isset($_GET['re_position']))
				{
				$i = 0;

				$db -> sql("UPDATE `rules_cats` SET `position` = '0'");

						while($cat = $db -> fetch("SELECT `id` FROM `rules_cats` ORDER BY `name` ASC"))
					{
					$i ++;
					$db -> sql("UPDATE `rules_cats` SET `position` = '$i' WHERE `id` = '{$cat['id']}'");
					}

				msg('Индексы заново расставлены', PATH.'index.php?mode=rules');

				}
			}

		if($count_rules_cats > 0)
			{
			$template_rules_cats = array();

			$need_re_position = false;

			$i = 0;

					while($rules_cat = $db -> fetch("SELECT *, (SELECT COUNT(*) FROM `rules` WHERE `cid` = `rules_cats`.`id`) AS `count_rules` FROM `rules_cats` ORDER BY `position` ASC"))
				{
				$i ++;

				$template_rules_cat = array('i' => $i, 'id' => $rules_cat['id'], 'name' => $rules_cat['name'], 'count_rules' => $rules_cat['count_rules']);

				if($rules_cat['position'] != $i)$need_re_position = true;

				// ссылки "вверх/вниз"
				if(USER_LEVEL >= USER_ADMIN && $count_rules_cats > 1)
				{
					$template_rules_cat['managment'] = '[';
					#if($i > 1)$template_rules_cat['managment'] .= '<a href="'.PATH.'index.php?mode=rules&position_cat='.$rules_cat['id'].'&act=up">вверх</a>';
					if($i > 1)$template_rules_cat['managment_up'] = true;
					#if($i < $count_rules_cats)$template_rules_cat['managment'] .= ' <a href="'.PATH.'index.php?mode=rules&position_cat='.$rules_cat['id'].'&act=down">вниз</a>';
					if($i < $count_rules_cats)$template_rules_cat['managment_down'] = true;
					$template_rules_cat['managment'] .= ']';
				}

				$template_rules_cats[] = $template_rules_cat;
				}


			$template -> rules_cats = $template_rules_cats;
			$template -> need_re_position = $need_re_position;
			}

		$template -> block = 'rules_cats';

		}

	}
	break;
	############################################################################
	case 'search':
	// поиск
	{

	only_reg();

	show_title($cfg['index_title'], 'Поиск');

	// данные по дефолту
	$q_view = null;
	$type = 'full';
	$forum = 0;
	$what = 'posts';

	if(!empty($_GET['q']))
		{

		check_fields(PATH.'index.php?mode=search&'.RAND, array(array('q', 'not null', 'minlen' => 2, 'maxlen' => 100), array('type', 'cant set', 'values' => array('full', 'one', 'all')), array('forum', 'cant set'), array('what', 'cant set', 'values' => array('topics', 'posts'))), 'GET');



		$q = $_GET['q'];
		$q_mysql = str_replace(array('%', '_'), array('\%', '\_'), str($q));
		$q_view = str($q);


		// дополнительно устанавливаемые параметры
		if(isset($_GET['type']))$type = $_GET['type'];
		if(isset($_GET['forum']))$forum = int($_GET['forum']);
		if(isset($_GET['what']))$what = $_GET['what'];

		if($forum > 0 && $db -> one("SELECT COUNT(*) FROM `forums` WHERE `id` = '$forum' AND `level` <= '".USER_LEVEL."'"))$forum = 0;

		// составлям скул запрос для поиска в базе
		if($type == 'full')
			{
			$words_view = array($q_view);
			$q_mysql = '`'.($what == 'topics' ? 'name' : 'text').'` LIKE \'%'.$q_mysql.'%\'';
			}
		else
			{
			$words = explode(' ', $q_mysql);
			$words_view = explode(' ', $q_view);
			$count_words = count($words);

			$q_mysql = null;

					for($i = 0;$i < $count_words;$i ++)
				{
				$word = trim($words[$i]);
				if(xstrlen($word) <= 1)break;

				$q_mysql .= ' '.($type == 'one' ? 'OR' : 'AND').' `'.($what == 'topics' ? 'name' : 'text').'` LIKE \'%'.$word.'%\'';

				}

			}


		if(!empty($q_mysql))
			{
			$q_mysql = ($type == 'full' ? $q_mysql : xsubstr($q_mysql, ($type == 'one' ? 4 : 5)));

			// поиск по темам
			if($what == 'topics')
				{

				#d($db -> set_prefix("SELECT COUNT(*) FROM `topics` WHERE ($q_mysql) AND `level` <= '".USER_LEVEL."' AND (SELECT `level` FROM `forums` WHERE `id` = `topics`.`fid`) <= '".USER_LEVEL."'"));

				$count_results =  $db -> one("SELECT COUNT(*) FROM `topics` WHERE ($q_mysql) AND `level` <= '".USER_LEVEL."' AND (SELECT `level` FROM `forums` WHERE `id` = `topics`.`fid`) <= '".USER_LEVEL."'");

				#d($count_results);

				if($count_results > 0)
					{
					check_page($count_results, PATH.'index.php?mode=search&q='.$q.'&type='.$type.'&forum='.$forum.'&what='.$what.'&page={$page}', ONPAGE_TOPICS);

					$template_topics = array();

					$i = START_TOPICS;

							while($topic = $db -> fetch("SELECT `id`, `name`, `last_user_id`, `last_date`, `date`, `count_posts`, (SELECT `nick` FROM `users` WHERE `id` = IF(`topics`.`last_user_id` > 0, `topics`.`last_user_id`, `topics`.`user_id`)) AS `last_user` FROM `topics` WHERE ($q_mysql) AND `level` <= '".USER_LEVEL."' AND (SELECT `level` FROM `forums` WHERE `id` = `topics`.`fid`) <= '".USER_LEVEL."' ORDER BY `last_date` DESC, `date` DESC LIMIT ".START_TOPICS.",".ONPAGE_TOPICS))
						{
						$i ++;

						$template_topic = array('id' => $topic['id'], 'name' => $topic['name'], 'user' => $topic['last_user'], 'date' => xdate(!empty($topic['last_date']) ? $topic['last_date'] : $topic['date']), 'count_posts' => $topic['count_posts'], 'i' => $i);

						$template_topics[] = $template_topic;
						}

					$template -> assign('topics', $template_topics);

					pagebar($str, PAGE, PATH.'index.php?mode=search&q='.$q.'&type='.$type.'&forum='.$forum.'&what='.$what.'&page={$page}');

					}
				}
			// поиск по постам
			else
				{
				$count_results =  $db -> one("SELECT COUNT(*) FROM `posts` WHERE (SELECT COUNT(*) FROM `posts_text` WHERE `pid` = `posts`.`id` AND ($q_mysql)) > 0 AND (SELECT `level` FROM `topics` WHERE `id` = `posts`.`tid`) <= '".USER_LEVEL."' AND (SELECT `level` FROM `forums` WHERE `id` = `posts`.`fid`) <= '".USER_LEVEL."'");

				if($count_results > 0)
					{

					check_page($count_results, PATH.'index.php?mode=search&q='.$q.'&type='.$type.'&forum='.$forum.'&what='.$what.'&page={$page}');

					$template_topics = array();

					$i = START_POSTS;

							while($post = $db -> fetch("SELECT `p`.`id`, `p`.`date`, `p`.`tid`, `p_t`.`text` AS `text`, `t`.`name` AS `topic_name`, `t`.`count_posts` AS `topic_count_posts`
FROM `posts` AS `p`, `topics` AS `t`, `posts_text` AS `p_t`, `forums` AS `f`
WHERE `p_t`.`pid` = `p`.`id` AND ($q_mysql) AND `t`.`id` = `p`.`tid` AND `t`.`level` <= '".USER_LEVEL."' AND `f`.`id` = `p`.`fid` AND `f`.`level` <= '".USER_LEVEL."'
"))
						{
						$i ++;

						$template_post = array('i' => $i, 'id' => $post['id'], 'date' => xdate($post['date']), 'tid' => $post['tid'], 'topic_name' => $post['topic_name'], 'topic_count_posts' => $post['topic_count_posts']);

						// подсветка найденного места в тексте
						$text = preg_replace('~('.preg_quote(implode('|', $words_view), '~').')~ui', '<font color="red">$1</font>', $post['text']);

						$template_post['text'] = $text;

						$template_posts[] = $template_post;
						}

					$template -> assign('posts', $template_posts);

					pagebar($str, PAGE, PATH.'index.php?mode=search&q='.$q.'&type='.$type.'&forum='.$forum.'&what='.$what.'&page={$page}');

					}
				}

			// простенький труЪ antoflood
			if(!LOCALHOST)sleep(3);

			}

		}


		$template -> search = array('q' => $q_view, 'type' => $type, 'forum' => $forum, 'what' => $what);




	// выбираем форумы для переноса данных
	if($db -> one("SELECT COUNT(*) FROM `forums` WHERE `id` != '".ID."' AND `level` <= '".USER_LEVEL."'") > 0)
		{
		$template_forums = array();

				while($forum = $db -> fetch("SELECT `id`, `name` FROM `forums` WHERE `id` != '".ID."' AND `level` <= '".USER_LEVEL."' ORDER BY `position` ASC"))
			{
			$template_forum = array('id' => $forum['id'], 'name' => $forum['name']);

			$template_forums[] = $template_forum;

			}

		$template -> assign('forums', $template_forums);

		}
	else
		{
		err('Искать негде :(', PATH.'index.php');
		}

	$template -> block = 'search';

	}
	break;
	############################################################################
	case 'last_topics':
	// последние темы
	{

	show_title($cfg['index_title'], 'Последние темы');
	only_reg();

	$template -> block = 'last_topics';

	$only_new = isset($_GET['only_new']) ? true : false;
	$template -> only_new = $only_new;
	$where = null;
	if($only_new)
		{
		$where = "AND (SELECT `date` FROM `topics_views` WHERE `user_id` = '".USER_ID."' AND `tid` = `topics`.`id`) < `last_date`";
		}

	$count_topics =  $db -> one("SELECT COUNT(*) FROM `topics` WHERE `level` <= '".USER_LEVEL."' AND (SELECT `level` FROM `forums` WHERE `id` = `topics`.`fid`) <= '".USER_LEVEL."' $where");


	if($count_topics > 0)
		{

		$template_topics = array();

		$i = 0;

				while($topic = $db -> fetch("SELECT `id`, `name`, `last_user_id`, `date`, `count_posts`, (SELECT `nick` FROM `users` WHERE `id` = `topics`.`user_id`) AS `user` FROM `topics` WHERE `level` <= '".USER_LEVEL."' AND (SELECT `level` FROM `forums` WHERE `id` = `topics`.`fid`) <= '".USER_LEVEL."' $where ORDER BY `date` DESC LIMIT 0, 15"))
			{
			$i ++;

			$template_topic = array('i' => $i, 'id' => $topic['id'], 'name' => $topic['name'], 'user' => $topic['user'], 'date' => xdate($topic['date']), 'count_posts' => $topic['count_posts'], 'i' => $i);

			$template_topics[] = $template_topic;
			}

		$template -> assign('topics', $template_topics);

		}

	}
	break;
	############################################################################
	case 'last_posts':
	// последние сообщения
	{

	show_title($cfg['index_title'], 'Последние сообщения');
	only_reg();

	$only_new = isset($_GET['only_new']) ? true : false;
	$template -> only_new = $only_new;
	$where = null;
	if($only_new)
		{
		$where = "AND (SELECT `date` FROM `topics_views` WHERE `user_id` = '".USER_ID."' AND `tid` = `posts`.`tid`) < `posts`.`date`";
		}

	$count_posts =  $db -> one("SELECT COUNT(*) FROM `posts` WHERE (SELECT `level` FROM `topics` WHERE `id` = `posts`.`tid`) <= '".USER_LEVEL."' AND (SELECT `level` FROM `forums` WHERE `id` = `posts`.`fid`) <= '".USER_LEVEL."' $where");


	if($count_posts > 0)
		{

		$template_posts = array();

		$i = 0;

		if($only_new)
			{
			$where = "AND (SELECT `date` FROM `topics_views` WHERE `user_id` = '".USER_ID."' AND `tid` = `p`.`tid`) < `p`.`date`";
			}

			while($post = $db -> fetch("SELECT `p`.`id`, `p`.`date`, `p`.`tid`, `p_t`.`text` AS `text`, `t`.`name` AS `topic_name`, `t`.`count_posts` AS `topic_count_posts`
FROM `posts` AS `p`, `topics` AS `t`, `posts_text` AS `p_t`, `forums` AS `f`
WHERE `p_t`.`pid` = `p`.`id` AND `t`.`id` = `p`.`tid` AND `t`.`level` <= '".USER_LEVEL."' AND `f`.`id` = `p`.`fid` AND `f`.`level` <= '".USER_LEVEL."' $where
ORDER BY `p`.`date` DESC
LIMIT 0, 20
"))
			{
			$i ++;

			$template_post = array('i' => $i, 'id' => $post['id'], 'date' => xdate($post['date']), 'text' => get_short_post($post['text']), 'tid' => $post['tid'], 'topic_name' => $post['topic_name'], 'topic_count_posts' => $post['topic_count_posts']);


			$template_posts[] = $template_post;
			}

		$template -> assign('posts', $template_posts);

		}

	$template -> block = 'last_posts';

	}
	break;
	}

$template -> display('index.page');

#exit;

show_foot();

# Morgan
?>