<?php


if ( !defined('IN_PHPBB') )
{
	die('Hacking attempt');
	exit;
}

if ( !$board_config['shop'] ) 
{ 
	message_die(GENERAL_MESSAGE, 'Магазин отключён.'); 
}

if ( isset($HTTP_POST_VARS['start1']) )
{
	$start1 = abs(intval($HTTP_POST_VARS['start1']));
	$start1 = ($start1 < 1) ? 1 : $start1;
	$start = (($start1 - 1) * $board_config['topics_per_page']);
}
else
{
	$start = ( isset($HTTP_GET_VARS['start']) ) ? intval($HTTP_GET_VARS['start']) : 0;
	$start = ($start < 0) ? 0 : $start;
}

if (isset($HTTP_GET_VARS['nick']))
{
//to do
$name = $userdata['username'];
//to do
	if ( $userdata['user_points'] < $board_config['smena_nika'] )
	{
		message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для покупки данного товара.');
	}
	if ( isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS['username']) )
	{
		include($phpbb_root_path . 'includes/functions_validate.'.$phpEx);
		$username = phpbb_clean_username($HTTP_POST_VARS['username']);
		$result = validate_username($username);
		if ( $result['error'] )
		{
			message_die(GENERAL_MESSAGE, $result['error_msg']);
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET username = '" . str_replace("\'", "''", $username) . "'
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_points = user_points - " . $board_config['smena_nika'] . "
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}
		$ostatok = $userdata['user_points'] - $board_config['smena_nika'];
              //to do
todo($lang['todo_shop_name'], $userdata['user_id'], $userdata['user_id'], $name, $username, time());
//to do

		message_die(GENERAL_MESSAGE, 'Ваш ник успешно изменён.<br/>Со счёта списано '.$board_config['smena_nika'].' монет.<br/>Остаток на вашем счёте '.$ostatok.' монет.');
	}
	else
	{
		$page_title = 'Сменить ник';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action.tpl')
		);

		$template->assign_vars(array(
			'L_SHOP_ACTION' => 'Сменить ник',
			'SHOP_ACTION' => 'Введите желаемый ник',
			'SHOP_ACTION_DB' => 'username',
			'SHOP_ACTION_MAX' => '25',
			'SHOP_MONEY' => $board_config['smena_nika'],
			'S_SHOP_ACTION' => append_sid("profile.$phpEx?mode=money&amp;nick"))
		);

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
} elseif (isset($HTTP_GET_VARS['color'])) {
	if ( $userdata['user_points'] < $board_config['smena_cveta'] )
	{
		message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для покупки данного товара.');
	}
	if ( isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS['color']) )
	{
		$color = trim(htmlspecialchars($HTTP_POST_VARS['color']));
		if ( !ereg("^[A-Za-z0-9#]+$", $color) )
		{
			message_die(GENERAL_MESSAGE, 'Нельзя использовать недопустимые символы.');
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_nic_color = '" . str_replace("\'", "''", $color) . "'
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_points = user_points - " . $board_config['smena_cveta'] . "
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}
		$ostatok = $userdata['user_points'] - $board_config['smena_cveta'];
//to do
todo($lang['todo_shop_color'], $userdata['user_id'], $userdata['user_id'], $userdata['username'], '', time());
//to do


		message_die(GENERAL_MESSAGE, 'Цвет вашего ника успешно изменён.<br/>Со счёта списано '.$board_config['smena_cveta'].' монет.<br/>Остаток на вашем счёте '.$ostatok.' монет.');
	}
	else
	{
		$page_title = 'Цвет ника';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action.tpl')
		);

		$template->assign_vars(array(
			'L_SHOP_ACTION' => 'Сменить цвет ника',
			'SHOP_ACTION' => 'Введите желаемый цвет',
			'SHOP_ACTION_DB' => 'color',
			'SHOP_ACTION_MAX' => '25',
			'SHOP_MONEY' => $board_config['smena_cveta'],
			'S_SHOP_ACTION' => append_sid("profile.$phpEx?mode=money&amp;color"))
		);

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
} elseif (isset($HTTP_GET_VARS['rank'])) {
	if ( $userdata['user_points'] < $board_config['smena_zvaniya'] )
	{
		message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для покупки данного товара.');
	}
	if ( isset($HTTP_POST_VARS['submit']) )
	{
		$rank = trim(htmlspecialchars($HTTP_POST_VARS['rank']));

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_zvanie = '" . str_replace("\'", "''", $rank) . "'
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_points = user_points - " . $board_config['smena_zvaniya'] . "
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}
		$ostatok = $userdata['user_points'] - $board_config['smena_zvaniya'];
//to do
todo($lang['todo_shop_rank'], $userdata['user_id'], $userdata['user_id'], $userdata['username'], $rank, time());
//to do

		message_die(GENERAL_MESSAGE, 'Личное звание установлено.<br/>Со счёта списано '.$board_config['smena_zvaniya'].' монет.<br/>Остаток на вашем счёте '.$ostatok.' монет.');
	}
	else
	{
		$page_title = 'Личное звание';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action.tpl')
		);

		$template->assign_vars(array(
			'L_SHOP_ACTION' => 'Установить личное звание',
			'SHOP_ACTION' => 'Введите желаемое звание',
			'SHOP_ACTION_DB' => 'rank',
			'SHOP_ACTION_MAX' => '50',
			'SHOP_MONEY' => $board_config['smena_zvaniya'],
			'S_SHOP_ACTION' => append_sid("profile.$phpEx?mode=money&amp;rank"))
		);

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
} elseif (isset($HTTP_GET_VARS['acc'])) {
	if ( $userdata['user_points'] < $board_config['pokupka_uchetki'] )
	{
		message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для покупки данного товара.');
	}
	if ( isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS['useracc']) )
	{
		$useracc = phpbb_clean_username($HTTP_POST_VARS['useracc']);
		$nedeli = time() - ($board_config['pokupka_uchetki_nedeli'] * 604800);

		$sql = "SELECT * 
			FROM " . USERS_TABLE . " 
			WHERE username LIKE '" . str_replace("\'", "''", $useracc) . "' AND user_id <> " . ANONYMOUS . " AND user_level = " . USER . "
			AND user_posts <= " . $board_config['pokupka_uchetki_posts'] . " AND user_regdate <= $nedeli";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain search results', '', __LINE__, __FILE__, $sql);
		}
		if ( $row = $db->sql_fetchrow($result) )
		{
			$arr = array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
			$new_password = $arr[rand(0,61)].$arr[rand(0,61)].$arr[rand(0,61)].$arr[rand(0,61)].$arr[rand(0,61)].$arr[rand(0,61)].$arr[rand(0,61)];
			$new_password_md = md5($new_password);

			$sql = "UPDATE " . USERS_TABLE . "
				SET user_password = '$new_password_md', user_active = 1, user_email = 'sale" . time() . "@account.forum'
				WHERE user_id = " . $row['user_id'];
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
			}
		} else {
			message_die(GENERAL_MESSAGE, 'Приобрести аккаунт '.$useracc.' невозможно. Возможны следующие причины ошибки:<br/>- его регистрационные данные или количество постов не удовлетворяют требованиям покупки аккаунта в нашем магазине<br/>- вы пытаетесь купить учётную запись кого-нибудь из администрации форума<br/>- либо такого пользователя просто не существует (в этом случае, если вам понравился ник '.$useracc.', вы можете <a href="'.append_sid("shop.$phpEx?id=1").'">сменить свой ник</a> на подобный).');
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_points = user_points - " . $board_config['pokupka_uchetki'] . "
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}
		$ostatok = $userdata['user_points'] - $board_config['pokupka_uchetki'];
//to do
todo($lang['todo_shop_acc'], $userdata['user_id'], $row['user_id'], $userdata['username'], $row['username'], time());
//to do

		message_die(GENERAL_MESSAGE, 'Поздравляем, вы приобрели аккаунт <b>'.$useracc.'</b>.<br/>Его новый пароль '.$new_password.'<br/>С этого момента во избежании недоразумений на нём установлен несуществующий адрес e-mail, смените его на свой.<br/>С вашего счёта списано '.$board_config['pokupka_uchetki'].' монет.<br/>Остаток на счёте '.$ostatok.' монет.');
	}
	else
	{
		$page_title = 'Купить аккаунт';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action.tpl')
		);

		$template->assign_vars(array(
			'L_SHOP_ACTION' => 'Купить аккаунт',
			'SHOP_ACTION' => 'Введите ник приобретаемой учётки',
			'SHOP_ACTION_DB' => 'useracc',
			'SHOP_ACTION_MAX' => '25',
			'SHOP_MONEY' => $board_config['pokupka_uchetki'],
			'S_SHOP_ACTION' => append_sid("profile.$phpEx?mode=money&amp;acc"))
		);

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
} elseif (isset($HTTP_GET_VARS['ban'])) {
	if ( $userdata['user_points'] < $board_config['razblokirovka_druga'] )
	{
		message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для покупки данного товара.');
	}
	if ( isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS['userban']) )
	{
		$userban = phpbb_clean_username($HTTP_POST_VARS['userban']);

		$sql = "SELECT * 
			FROM " . USERS_TABLE . " 
			WHERE username LIKE '" . str_replace("\'", "''", $userban) . "' AND user_id <> " . ANONYMOUS . " 
			AND user_id <> " . $userdata['user_id'] . " AND user_level = " . USER . " AND user_warnings > 0";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain users results', '', __LINE__, __FILE__, $sql);
		}
		if ( $row = $db->sql_fetchrow($result) )
		{
			$sql = "SELECT id, user_id, expire, modification 
				FROM " . REPUTATION_TABLE . "
				WHERE user_id = " . $row['user_id'] . " AND modification = 4";
			if( !($resultat = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not query users', '', __LINE__, __FILE__, $sql);
			}
			if ( $roww = $db->sql_fetchrow($resultat) )
			{
				$expire_money = ceil((($roww['expire'] - time()) / 60) / 60) * $board_config['razblokirovka_druga'];
				if ( $expire_money > $userdata['user_points'] )
				{
					message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для разблокировки пользователя '.$userban.'.');
				}
				db_query('DELETE FROM {REPUTATION_TABLE} WHERE id = %d', $roww['id']);
				db_query('DELETE FROM {REPUTATION_TEXT_TABLE} WHERE id = %d', $roww['id']);
				db_query('DELETE FROM {BANLIST_TABLE} WHERE ban_userid = %d', $row['user_id']);
				db_query('UPDATE {USERS_TABLE} SET user_warnings = user_warnings - 1 WHERE user_id = %d', $row['user_id']);
				db_query('UPDATE {USERS_TABLE} SET user_allow_pm = 1 WHERE user_id = %d', $row['user_id']);
			} else {
				message_die(GENERAL_MESSAGE, 'Вашего друга не забанили, а всего лишь предупредили.');
			}
		}
		else
		{
			message_die(GENERAL_MESSAGE, 'Вы что-то путаете, этот пользователь незаблокирован, либо его вообще не существует, либо вы пытаетесь разблокировать самого себя.');
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_points = user_points - $expire_money
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}
		$ostatok = $userdata['user_points'] - $expire_money;
//to do
todo($lang['todo_shop_ban'], $userdata['user_id'], $row['user_id'], $userdata['username'], $row['username'], time());
//to do


		message_die(GENERAL_MESSAGE, 'Пользователь '.$userban.' успешно разблокирован.<br/>С вашего счёта списано '.$expire_money.' монет.<br/>Остаток на счёте '.$ostatok.' монет.');
	}
	else
	{
		$page_title = 'Разбанить друга';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action.tpl')
		);

		$template->assign_vars(array(
			'L_SHOP_ACTION' => 'Разбанить друга',
			'SHOP_ACTION' => 'Введите ник заблокированной учётки',
			'SHOP_ACTION_DB' => 'userban',
			'SHOP_ACTION_MAX' => '25',
			'SHOP_MONEY' => 'за каждый час бана ' . $board_config['razblokirovka_druga'],
			'S_SHOP_ACTION' => append_sid("profile.$phpEx?mode=money&amp;ban"))
		);

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
} elseif (isset($HTTP_GET_VARS['icq'])) {

	if ( $userdata['user_points'] > 0 )
	{
	if ( isset($HTTP_GET_VARS['icq']) && !empty($HTTP_GET_VARS['id']) )
	{
		$uin = abs(intval($HTTP_GET_VARS['id']));

		$sql = "SELECT * 
			FROM ".$table_prefix."shop_icq
			WHERE id = $uin";
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not query icq', '', __LINE__, __FILE__, $sql);
		}
		if ( $row = $db->sql_fetchrow($result) )
		{
			if ( $userdata['user_points'] < $row['icq_cost'] )
			{
				message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно монет для покупки данного номера');
			}

			$cost = $row['icq_cost'];
			$pass = $row['icq_password'];
			$number = $row['icq_number'];

			$sql = "DELETE FROM ".$table_prefix."shop_icq 
				WHERE id = $uin";
			if ( !$result = $db->sql_query($sql) )
			{
				message_die(GENERAL_MESSAGE, 'Не удалось удалить UIN');
			}

			$sql = "UPDATE " . USERS_TABLE . "
				SET user_points = user_points - " . $cost . "
				WHERE user_id = " . $userdata['user_id'];
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
			}
			$ostatok = $userdata['user_points'] - $cost;
//to do
todo($lang['todo_shop_icq'].$number, $userdata['user_id'], '', $userdata['username'], '', time());
//to do

			message_die(GENERAL_MESSAGE, 'Номер <b>'.$number.'</b> успешно куплен.<br/>Пароль от номера '.$pass.'<br/>Скопировать<br/><input type="text" value="'.$pass.'" /><br/>Со счёта списано '.$cost.' монет.<br/>Остаток '.$ostatok.' монет.');
		} else {
			message_die(GENERAL_MESSAGE, 'Такого номера не существует');
		}
	}
	else
	{
		$page_title = 'ICQ';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action_icq.tpl')
		);

		$sql = "SELECT * 
			FROM ".$table_prefix."shop_icq
			ORDER BY id ASC LIMIT $start, " . $board_config['topics_per_page'];
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not query users', '', __LINE__, __FILE__, $sql);
		}

		if ( $row = $db->sql_fetchrow($result) )
		{
			$i = 0;
			do
			{
				$uin = $row['icq_number'];
				$cost = $row['icq_cost'];
				$id = $row['id'];

				$template->assign_block_vars('memberrow', array(
					'UIN' => $uin,
					'COST' => $cost,
					'U_PAY' => append_sid("profile.$phpEx?mode=money&amp;icq&amp;id=$id"))
				);

				$i++;
			}
			while ( $row = $db->sql_fetchrow($result) );
			$db->sql_freeresult($result);
		} else {
			$template->assign_block_vars('no_pay', array() );
		}
		$sql = "SELECT count(*) AS total
			FROM ".$table_prefix."shop_icq";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Error getting total users', '', __LINE__, __FILE__, $sql);
		}

		if ( $total = $db->sql_fetchrow($result) )
		{
			$total_members = $total['total'];
			$pagination = generate_pagination("profile.$phpEx?mode=money&amp;icq", $total_members, $board_config['topics_per_page'], $start);
		}
		$db->sql_freeresult($result);

		if ( $total_members > $board_config['topics_per_page'] )
		{
			$template->assign_vars(array(
				'PAGINATION' => $pagination)
			);
		}
		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
	} else {
		message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для покупки номера.');
	}
} elseif (isset($HTTP_GET_VARS['sites'])) {
	if ( !$board_config['sites'] )
	{
		message_die(GENERAL_MESSAGE, 'Покупка рекламы на этом форуме отключена.');
	}
	if ( ($userdata['user_points'] > $board_config['verh_pay']) || ($userdata['user_points'] > $board_config['niz_pay']) )
	{
		$sql = "SELECT count(*) AS total FROM ".$table_prefix."shop_sites WHERE site_order = 0";
		$result = $db->sql_query($sql);
		$total = $db->sql_fetchrow($result);
		$total_verh = $total['total'];
		$sql = "SELECT count(*) AS total FROM ".$table_prefix."shop_sites WHERE site_order = 1";
		$result = $db->sql_query($sql);
		$total = $db->sql_fetchrow($result);
		$total_niz = $total['total'];
		if ( ($board_config['verh'] == $total_verh) && ($board_config['niz'] == $total_niz) )
		{
			message_die(GENERAL_MESSAGE, 'Все места заняты');
		}

		if ( isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS['url']) && !empty($HTTP_POST_VARS['desc']) && !empty($HTTP_POST_VARS['time']) )
		{
			$time = intval($HTTP_POST_VARS['time']);
			$url = trim(htmlspecialchars($HTTP_POST_VARS['url']));
			$desc = trim(htmlspecialchars($HTTP_POST_VARS['desc']));
			$order = ( isset($HTTP_POST_VARS['order']) ) ? ( ($HTTP_POST_VARS['order']) ? 1 : 0 ) : 1;

			if ( preg_match('#\?#', $url) && $board_config['ref_url'] )
			{
				message_die(GENERAL_MESSAGE, 'Ссылка должна быть прямой.');
			}
			if ( !$order )
			{
				if ( $board_config['verh'] == $total_verh )
				{
					message_die(GENERAL_MESSAGE, 'Вверху места заняты');
				}
				$stoimost = $board_config['verh_pay'] * $time;

				if ( $stoimost > $userdata['user_points'] )
				{
					message_die(GENERAL_MESSAGE, 'У вас недостаточно средств для покупки рекламы наверху на такой срок');
				}
				$vremya_sek = $time * 604800;
				$vremya_okonch = time() + $vremya_sek;

				$sql = "INSERT INTO ".$table_prefix."shop_sites (site_url, site_desc, site_time, site_order) VALUES ('" . str_replace("\'", "''", $url) . "', '" . str_replace("\'", "''", $desc) . "', $vremya_okonch, 0)";
				if ( !$result = $db->sql_query($sql) )
				{
					message_die(GENERAL_MESSAGE, 'Не удалось добавить ссылку');
				}

				$sql = "UPDATE " . USERS_TABLE . "
					SET user_points = user_points - " . $stoimost . "
					WHERE user_id = " . $userdata['user_id'];
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
				}
				$ostatok = $userdata['user_points'] - $stoimost;

				message_die(GENERAL_MESSAGE, 'Рекламная ссылка была успешно установлена.<br/>Со счёта списано '.$stoimost.' монет.<br/>Остаток '.$ostatok.' монет.');
			} else {
				if ( $board_config['niz'] == $total_niz )
				{
					message_die(GENERAL_MESSAGE, 'Внизу места заняты');
				}
				$stoimost = $board_config['niz_pay'] * $time;

				if ( $stoimost > $userdata['user_points'] )
				{
					message_die(GENERAL_MESSAGE, 'У вас недостаточно средств для покупки рекламы внизу на такой срок');
				}
				$vremya_sek = $time * 604800;
				$vremya_okonch = time() + $vremya_sek;

				$sql = "INSERT INTO ".$table_prefix."shop_sites (site_url, site_desc, site_time, site_order) VALUES ('" . str_replace("\'", "''", $url) . "', '" . str_replace("\'", "''", $desc) . "', $vremya_okonch, 1)";
				if ( !$result = $db->sql_query($sql) )
				{
					message_die(GENERAL_MESSAGE, 'Не удалось добавить ссылку');
				}

				$sql = "UPDATE " . USERS_TABLE . "
					SET user_points = user_points - " . $stoimost . "
					WHERE user_id = " . $userdata['user_id'];
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
				}
				$ostatok = $userdata['user_points'] - $stoimost;

				message_die(GENERAL_MESSAGE, 'Рекламная ссылка была успешно установлена.<br/>Со счёта списано '.$stoimost.' монет.<br/>Остаток '.$ostatok.' монет.');
			}
		}
		else
		{
			$page_title = 'Купить рекламу';
			include($phpbb_root_path . 'includes/page_header.'.$phpEx);

			$template->set_filenames(array(
				'body' => 'shop_action_sites.tpl')
			);
			$template->assign_vars(array(
				'S_SHOP_ACTION' => append_sid("profile.$phpEx?mode=money&amp;sites"))
			);
			$template->pparse('body');

			include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
		}
	} else {
		message_die(GENERAL_MESSAGE, 'На вашем счету недостаточно средств для покупки рекламы.');
	}
} elseif (isset($HTTP_GET_VARS['url'])) {

	if ( isset($HTTP_GET_VARS['url']) && !empty($HTTP_GET_VARS['id']) )
	{
		$uin = abs(intval($HTTP_GET_VARS['id']));

		$sql = "SELECT * 
			FROM ".$table_prefix."shop_url
			WHERE id = $uin";
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not query icq', '', __LINE__, __FILE__, $sql);
		}
		if ( $row = $db->sql_fetchrow($result) )
		{
			$cost = $row['url_cost'];
			$url = $row['url'];
			if ( ($userdata['time_last_click'] + $board_config['time_click']) < time() )
			{
				$sql = "UPDATE " . USERS_TABLE . "
					SET user_points = user_points + " . $cost . ", time_last_click = '" . time() . "' 
					WHERE user_id = " . $userdata['user_id'];
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
				}

				header('Location: ' . $url);
				exit;
			} else {
				$ost = time() - ($userdata['time_last_click'] + $board_config['time_click']);
				message_die(GENERAL_MESSAGE, 'Вы пытаетесь накручивать. Попробуйте нажать на ссылку через '.$ost.' сек.');
			}
		} else {
			message_die(GENERAL_MESSAGE, 'Такой ссылки не существует');
		}
	}
	else
	{
		$page_title = 'Заработок';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action_url.tpl')
		);

		$sql = "SELECT * 
			FROM ".$table_prefix."shop_url
			ORDER BY id ASC LIMIT $start, " . $board_config['topics_per_page'];
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not query users', '', __LINE__, __FILE__, $sql);
		}

		if ( $row = $db->sql_fetchrow($result) )
		{
			$i = 0;
			do
			{
				$cost = $row['url_cost'];
				$nazv = $row['nazvanie'];
				$id = $row['id'];

				$template->assign_block_vars('memberrow', array(
					'NAZVANIE' => $nazv,
					'COST' => $cost,
					'U_PAY' => append_sid("profile.$phpEx?mode=money&amp;url&amp;id=$id"))
				);

				$i++;
			}
			while ( $row = $db->sql_fetchrow($result) );
			$db->sql_freeresult($result);
		} else {
			$template->assign_block_vars('no_pay', array() );
		}
		$sql = "SELECT count(*) AS total
			FROM ".$table_prefix."shop_url";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Error getting total users', '', __LINE__, __FILE__, $sql);
		}

		if ( $total = $db->sql_fetchrow($result) )
		{
			$total_members = $total['total'];
			$pagination = generate_pagination("profile.$phpEx?mode=money&amp;url", $total_members, $board_config['topics_per_page'], $start);
		}
		$db->sql_freeresult($result);

		if ( $total_members > $board_config['topics_per_page'] )
		{
			$template->assign_vars(array(
				'PAGINATION' => $pagination)
			);
		}
		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
} elseif (isset($HTTP_GET_VARS['exch'])) {
	if ( !$board_config['pay_money'] )
	{
		message_die(GENERAL_MESSAGE, 'Система выплат на этом форуме отключена.');
	}
	$HTTP_POST_VARS['exch'] = str_replace('-','+',$HTTP_POST_VARS['exch']);
	if ($userdata['user_points'] < $HTTP_POST_VARS['exch'])
	{
		message_die(GENERAL_MESSAGE, 'Попытка обмана не удалась');
	}
	if ( isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS['exch']) )
	{
		$userexch = abs(intval($HTTP_POST_VARS['exch']));
		$payexch = $userexch * $board_config['kurs_payment'];

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_money_earned = user_money_earned + $payexch
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}

		$sql = "UPDATE " . CONFIG_TABLE . "
			SET config_value = config_value + $payexch
			WHERE config_name = 'money_earned'";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update config table', '', __LINE__, __FILE__, $sql);
		}

		$sql = "UPDATE " . USERS_TABLE . "
			SET user_points = user_points - $userexch
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}
		$ostatok = $userdata['user_points'] - $userexch;
		$ostatok_rub = $userdata['user_money_earned'] + $payexch;

		message_die(GENERAL_MESSAGE, 'Обмен успешно совершён.<br/>На ваш рублёвый счёт на форуме перечислено '.$payexch.' руб.<br/>Итого у вас '.$ostatok_rub.' руб.<br/>Со счёта списано '.$userexch.' монет.<br/>Остаток '.$ostatok.' монет.');
	}
	else
	{
		$page_title = 'Обмен';
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'shop_action.tpl')
		);

		$template->assign_vars(array(
			'L_SHOP_ACTION' => 'Конвертировать в рубли',
			'SHOP_ACTION' => 'Введите количество монет, которое вы хотите обменять на рубли (не более '.$userdata['user_points'].')',
			'SHOP_ACTION_DB' => 'exch',
			'SHOP_ACTION_MAX' => '100',
			'SHOP_MONEY' => 'указанное вами количество',
			'S_SHOP_ACTION' => append_sid("profile.$phpEx?mode=money&amp;exch"))
		);

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
} else {

if ( empty($HTTP_GET_VARS[POST_USERS_URL]) || $HTTP_GET_VARS[POST_USERS_URL] == ANONYMOUS )
{
	message_die(GENERAL_MESSAGE, $lang['No_user_id_specified']);
}

$user = intval($HTTP_GET_VARS[POST_USERS_URL]);

if ( $user == $userdata['user_id'] )
{
	message_die(GENERAL_MESSAGE, 'Нафига тебе самому себе пересылать деньги?');
}

$sql = "SELECT username 
	FROM " . USERS_TABLE . " 
	WHERE user_id = '$user'";
if ( !$result = $db->sql_query($sql) )
{
	message_die(GENERAL_ERROR, 'Could not obtain user information for sendpassword', '', __LINE__, __FILE__, $sql);
}
if ( !$row = $db->sql_fetchrow($result) )
{
	message_die(GENERAL_MESSAGE, $lang['No_user_id_specified']);
}
$username = $row['username'];

if ( isset($HTTP_POST_VARS['submit']) && !empty($HTTP_POST_VARS['money_send']) )
{
	$money = intval($HTTP_POST_VARS['money_send']);
	if ( $userdata['user_level'] != ADMIN )
	{
		$money = abs($money);
	}

	if ( $money > $userdata['user_points'] && $userdata['user_level'] != ADMIN )
	{
		message_die(GENERAL_MESSAGE, 'У вас недостаточно средств для перевода такой суммы');
	}

	$sql = "UPDATE " . USERS_TABLE . "
		SET user_points = user_points + $money
		WHERE user_id = $user";
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
	}

	if ( $userdata['user_level'] != ADMIN )
	{
		$sql = "UPDATE " . USERS_TABLE . "
			SET user_points = user_points - $money
			WHERE user_id = " . $userdata['user_id'];
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}
	}

	if ( $userdata['user_level'] == ADMIN )
	{
		message_die(GENERAL_MESSAGE, 'На счёт пользователя '.$username.' перечислено '.$money.' монет');
	} else {
		message_die(GENERAL_MESSAGE, 'С вашего счёта списано '.$money.' монет и перечислено на счёт пользователя '.$username);
	}
}
else
{
	$page_title = 'Передача монет';
	include($phpbb_root_path . 'includes/page_header.'.$phpEx);

	$template->set_filenames(array(
		'body' => 'profile_send_money.tpl')
	);

	if ( isset($HTTP_POST_VARS['submit']) && empty($HTTP_POST_VARS['money_send']) )
	{
		$template->set_filenames(array(
			'reg_header' => 'error_body.tpl')
		);
		$template->assign_vars(array(
			'ERROR_MESSAGE' => 'Вы не ввели количество монет')
		);
		$template->assign_var_from_handle('ERROR_BOX', 'reg_header');
	}

	$template->assign_vars(array(
		'USERNAME' => $username,
		'USER_MONEY' => $userdata['user_points'],
		'L_SUBMIT' => $lang['Submit'],
		'S_POST_ACTION' => append_sid("profile.$phpEx?mode=money&amp;u=$user"))
	);

	$template->pparse('body');

	include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
}

}

?>