<?
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////   MISOFT 2018 V. 1.0.0.0    ////////////////////////////////////
///////////////////////////////////  OFSITE - www.misoft.store  ////////////////////////////////////
/////////////////////////////////// MAIL - support@misoft.store ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

session_start();
set_time_limit( 0 );
header( 'Content-type: text/html; charset=windows-1251' );

define( 'ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] );
include_once ROOT_DIR . '/engine/config.php'; # config base
include_once ROOT_DIR . '/engine/function.php'; # php_function
include_once ROOT_DIR . '/engine/classes/bbcode.class.php'; #bbcode
include_once ROOT_DIR . '/engine/classes/smsc_api.php'; # sms
define( 'ROOT', 'http://'.$config_site['site_url'] );

### Регистрация
if ( $_GET['func'] == 'reg' ) {
    
    sleep(1);
    if ( isset( $_SESSION['iduser'] ) ) { exit(); }
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $check_nik = mysql_num_rows( mysql_query( "SELECT id FROM user WHERE username = '" . check_text( $_POST['nik'] ) . "' LIMIT 1" ) );
    $check_email = mysql_num_rows( mysql_query( "SELECT id FROM user WHERE email = '" . check_text( $_POST['email'] ) . "' LIMIT 1" ) );
	
	$caphaType = $config_site["capthaType"];
	$recapha_n2 = $config_site["recapthaSecretKey"];
    
    if ( empty( $_POST['name'] ) ) {
        echo 'Вы не указали как вас зовут!';
        exit();
    } else
	if ( empty( $_POST['nik'] ) ) {
        echo 'Вы не указали свой ник!';
        exit();
    } else
	if ( $check_nik > 0 ) {
        echo 'Извините. Ник уже кем-то занят!';
        exit();
    } else
    if ( strlen( check_text( $_POST['name'] ) ) < 4 or strlen( check_text( $_POST['name'] ) ) > 15 ) {
        echo 'Имя может состоят от 4 до 15 символов!';
        exit();
    } else
    if ( strlen( check_text( $_POST['nik'] ) ) < 4 or strlen( check_text( $_POST['nik'] ) ) > 20 ) {
        echo 'Ник может состоят от 4 до 20 символов!';
        exit();
    } else
    if ( !preg_match( "/^[a-z,A-Z,0-9,а-я,А-Я,\-]+$/is", check_text( $_POST['name'] ) ) ) {
        echo 'Недопустимые символы в имени!';
        exit();
    } else
    if ( !preg_match( "/^[a-z,A-Z,0-9,а-я,А-Я,\-]+$/is", check_text( $_POST['nik'] ) ) ) {
        echo 'Недопустимые символы в нике!';
        exit();
    } else
    if ( empty( $_POST['pass'] ) ) {
        echo 'Вы не указали пароль!';
        exit();
    } else
    if ( strlen( check_text( $_POST['pass'] ) ) < 5 or strlen( check_text( $_POST['pass'] ) ) > 50 ) {
        echo 'Пароль может состоят от 5 до 50 символов!';
        exit();
    } else
    if ( !preg_match( "/^[a-z,A-Z,0-9,\-]+$/is", check_text( $_POST['pass'] ) ) ) {
        echo 'Недопустимые символы в пароле!';
        exit();
    } else
    if ( !preg_match( "/^(?:[a-z0-9]+(?:[-_]?[a-z0-9\.\-\_]+)?@[a-z0-9]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i", $_POST['email'] ) ) {
        echo 'Неверно указан email, проверьте введенные данные!';
        exit();
    } else
    if ( $check_email > 0 ) {
        echo 'Такой email уже зарегистрирован!';
        exit();
    } else
    if ( preg_match( '/^((.+?)@mailspeed\.ru)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@tempinbox\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@rtrtr\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@sharklasers\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@guerrillamailblock\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@guerrillamail\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@guerrillamail\.net)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@guerrillamail\.biz)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@guerrillamail\.org)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@guerrillamail\.de)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@yopmail\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@mailcatch\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@meltmail\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@TempEmail\.net)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@spamfree24\.org)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@jetable\.org)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@asdasd\.ru)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@anobox\.ru)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@llogin\.ru)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@mailinator\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@thismail\.ru)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@mail\.ua)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@trashmail\.net)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@kurzepost\.de)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@objectmail\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@proxymail\.eu)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@rcpt\.at)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@trash\-mail\.at)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@trashmail\.at)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@trashmail\.me)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@wegwerfmail\.de)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@wegwerfmail\.net)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@wegwerfmail\.org)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@mailinator\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@spam\.su)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@mailmetrash\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@dispostable\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@tittbit\.in)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@incognitomail\.org)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@mailforspam\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@mytempemail\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@no\-spam\.ws)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@spambog\.com)$/is', $_POST['email'] ) or preg_match( '/^((.+?)@spambog\.ru)$/is', $_POST['email'] ) ) {
        echo 'Запрещено использовать одноразовый email!';
        exit();
    } else
    if ( $_POST['rules'] != 'option1' ) {
        echo 'Вы не подтвердили ознакомление и согласие с правилами проекта!';
        exit();
    } else
    if ( $_POST['policy'] != 'option1' ) {
        echo 'Вы не подтвердили ознакомление и согласие с услугими и оплатой!';
        exit();
    } else 
    #Проверяем тип капчи (аналоговая капча или рекапча от гугла)
    if ( $caphaType == 0 ) {
        
		if ( $_SESSION['get_code'] != strtoupper( $_POST['capcha'] ) ) {
			echo 'Вы указали неверно проверочный код!';
			exit();
		} else {
		    if ( isset( $_COOKIE['referer'] ) ) {
				
				$check_ref = mysql_query( "SELECT id, referer, autoback, greetingRef FROM user WHERE id = '" . ( int ) $_COOKIE['referer'] . "' LIMIT 1" );
				
				if ( mysql_num_rows( $check_ref ) == 0 ) {
					$_COOKIE['referer'] = 0;
				} else {
					$ref_row = mysql_fetch_array( $check_ref );
					mysql_query( "UPDATE user SET referals = referals + 1 WHERE id = '" . $ref_row['id'] . "'" );
					#Пишем событие в ленту пользователю
					mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Поздравляем у вас новый реферал " . check_text( $_POST['nik'] ) . " пришел через реф-ссылку.', iduser = '" . $ref_row['id'] . "' " );
				}
				
			} else {
				$_COOKIE['referer'] = 0;
			}
			
			if ( GeoIP( real_IP() ) == 'XX' ) {
				include_once ROOT_DIR .  '/engine/geoip/GeoIP.php';
				$geoip = Net_GeoIP::getInstance( ROOT_DIR . '/engine/geoip/GeoIP.dat' );
				try {
					$regcountry = mb_convert_encoding( $geoip->lookupCountryName( real_IP() ), 'CP1251', 'UTF8' );
					$regcode = strtolower( $geoip->lookupCountryCode( real_IP() ) );
				}
				catch ( Exception $e ) {
					$regcountry = '';
					$regcode = '';
				}
			} else {
				$regcountry = $countrys[strtolower( GeoIP( real_IP() ) )];
				$regcode = strtolower( GeoIP( real_IP() ) );
			}

			include_once ROOT_DIR . '/engine/classes/idna_convert.class.php';
			
			$idn = new idna_convert(array('idn_version'=>2008));
			
			if ( strpos( check_text( $_COOKIE['rsite'] ), 'xn--' ) !== FALSE ) {
				preg_match( '/([a-z0-9а-я\.])+([a-z0-9а-я\-])+(\.)([a-z0-9а-я]{2,5}\.)?([a-z0-9а-я\-]{2,8})/i', check_text( $_COOKIE['rsite'] ), $rsite );
				$rsite[0] = substr( check_text( $idn->decode( $rsite[0] ) ), 0, 50 );
			} else {
				preg_match( '/([a-z0-9а-я\.])+([a-z0-9а-я\-])+(\.)([a-z0-9а-я]{2,5}\.)?([a-z0-9а-я]{2,5})/i', check_text( $_COOKIE['rsite'] ), $rsite );
				$rsite[0] = substr( $rsite[0], 0, 50 );
			}
			
			if($config_site['mobileKodType'] != 1 AND $config_site['mobileKodType'] != 2) {
				$act_key = generate( 6 );
			} else {
				$act_key = pincode( 4 );
			}
			
			$pinkode = pincode( 5 );
			
			$randavatar = rand(1, 11);
			
			mysql_query( 
				"INSERT INTO user (name, username, password, email, ip, referer, referer2, country, city_code, regdate, autoproc, reyting, act_code, rsite, pincode, reg_ip, avatar) 
					VALUES 
				('" . check_text( $_POST['name'] ) . "', '" . check_text( $_POST['nik'] ) . "', '" . iconv( 'UTF-8', 'windows-1251', md5_pass( $message_md5, $_POST['pass'] ) ) . "', '" . check_text( substr( $_POST['email'], 0, 50 ) ) . "', '" . real_IP() . "', '" . $ref_row['id'] . "', '" . ( int ) $ref_row['referer'] . "', '" . $regcountry . "', '" . $regcode . "', '" . time() . "', '" . $ref_row['autoback'] . "', '" . $config['reyting'] . "', '" . $act_key . "', '" . check_text( $rsite[0] ) . "', '" . $pinkode . "', '" . real_IP() . "', 'no" . $randavatar . ".png')" 
			) or die( mysql_error() );
			
			$pr_static = mysql_fetch_array( mysql_query( "SELECT id FROM user WHERE email = '" . $_POST['email'] . "' LIMIT 1" ) );
			
			#класс отправки привествия
			if ($ref_row['id'] > 0 and $ref_row['greetingRef'] != '') {
				mysql_query( "INSERT INTO messages SET from_id = '" . $ref_row['id'] . "', to_id = '" . $pr_static['id'] . "', text = '" . $ref_row['greetingRef'] . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $ref_row['id'] . "'" );
				mysql_query( "INSERT INTO messages SET from_id = '" . $ref_row['id'] . "', to_id = '" . $pr_static['id'] . "', text = '" . $ref_row['greetingRef'] . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . $pr_static['id'] . "'" );
			}
			
			include_once ROOT_DIR . '/engine/classes/libmail.php'; # подключаем SMTP class
			
			if($config_site['mobileKodType'] != 1 AND $config_site['mobileKodType'] != 2) {
				$message = '
				<html>
				<head>
				<title>Регистрация на проекте ' . $config_site['sitename'] . '</title>
				<style type="text/css">
				html, body {
					margin:0;
					margin-left:5px;
					padding:0;
					font-size:12px;
				}
				p {
					margin:0;
					padding:3px;
				}
				</style>
				</head>
				<body>
				<p>Здравствуйте, <b>' . check_text( $_POST['nik'] ) . '</b>.</p>
				<p>Вы успешно зарегистрировались на проекте <b>http://' . $_SERVER["HTTP_HOST"] . '</b></p>
				<p>--------------------------------------------------------------------------</p>
				<p>Для входа на сайт используйте следующие данные:</p>
				<p>--------------------------------------------------------------------------</p>
				логин: <b>' . check_text( $_POST['email'] ) . '</b><br />
				пароль: <b>' . check_text( $_POST['pass'] ) . '</b><br />
				код активации: <b>' . $act_key . '</b><br />
				пин-код: <b>' . $pinkode . '</b><br />
				IP: <b>' . real_IP() . '</b><br />
				Дата: <b>' . date( 'd.m.Y H:i', time() ) . '</b><br />
				<p>--------------------------------------------------------------------------</p>
				<p><font color="#800000">Внимание! </font>Не передавайте письмо 3-м лицам, запишите данные и удалите письмо, во избежания кражи Вашей личной информации...</p>
				<p>Письмо отправлено автоматически. На него отвечать не нужно.</p>
				</body>
				</html>';
			} else {
				$message = '
				<html>
				<head>
				<title>Регистрация на проекте ' . $config_site['sitename'] . '</title>
				<style type="text/css">
				html, body {
					margin:0;
					margin-left:5px;
					padding:0;
					font-size:12px;
				}
				p {
					margin:0;
					padding:3px;
				}
				</style>
				</head>
				<body>
				<p>Здравствуйте, <b>' . check_text( $_POST['nik'] ) . '</b>.</p>
				<p>Вы успешно зарегистрировались на проекте <b>http://' . $_SERVER["HTTP_HOST"] . '</b></p>
				<p>--------------------------------------------------------------------------</p>
				<p>Для входа на сайт используйте следующие данные:</p>
				<p>--------------------------------------------------------------------------</p>
				логин: <b>' . check_text( $_POST['email'] ) . '</b><br />
				пароль: <b>' . check_text( $_POST['pass'] ) . '</b><br />
				пин-код: <b>' . $pinkode . '</b><br />
				IP: <b>' . real_IP() . '</b><br />
				Дата: <b>' . date( 'd.m.Y H:i', time() ) . '</b><br />
				<p>--------------------------------------------------------------------------</p>
				<p><font color="#800000">Внимание! </font>Не передавайте письмо 3-м лицам, запишите данные и удалите письмо, во избежания кражи Вашей личной информации...</p>
				<p>Письмо отправлено автоматически. На него отвечать не нужно.</p>
				</body>
				</html>';
			}
			
			$m = new Mail;
			$m->From( 'Администрация;' . $config_site['email'] ); #от кого отправляется почта
			$m->To( $_POST['email'] ); #кому адресованно
			$m->Subject( 'Регистрация на проекте ' . $_SERVER["HTTP_HOST"] );
			$m->Body( $message );
			$m->Priority( 3 ); #приоритет письма
			$m->smtp_on( $config_site['smtpemail'], $config_site['email'], $config_site['emailpass'], $config_site['portemail'] ); #если указана эта команда, отправка пойдет через SMTP
			$m->Send(); #а теперь пошла отправка
			
			echo 1;
			exit();
		}
		
    } else {
        
        $recaptcha = check_text($_POST['g-recaptcha-response']);
		$secret = $recapha_n2;
		$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret ."&response=".$recaptcha."&remoteip=".$_SERVER['REMOTE_ADDR'];
		$status = 1;
		if(!empty($recaptcha)) {
			$curl = curl_init();
			if(!$curl) {
			$status = 2;    
			} else {
				curl_setopt($curl, CURLOPT_URL, $url);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($curl, CURLOPT_TIMEOUT, 10);
				curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
				$curlData = curl_exec($curl);
				curl_close($curl);    
				$curlData = json_decode($curlData, true);
				if($curlData['success']) {
					$status = 0;
				}
			}
		}
		
		if($status === 0) {
		
			if ( isset( $_COOKIE['referer'] ) ) {
				
				$check_ref = mysql_query( "SELECT id, referer, autoback, greetingRef FROM user WHERE id = '" . ( int ) $_COOKIE['referer'] . "' LIMIT 1" );
				
				if ( mysql_num_rows( $check_ref ) == 0 ) {
					$_COOKIE['referer'] = 0;
				} else {
					$ref_row = mysql_fetch_array( $check_ref );
					mysql_query( "UPDATE user SET referals = referals + 1 WHERE id = '" . $ref_row['id'] . "'" );
					#Пишем событие в ленту пользователю
					mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Поздравляем у вас новый реферал " . check_text( $_POST['nik'] ) . " пришел через реф-ссылку.', iduser = '" . $ref_row['id'] . "' " );
				}
				
			} else {
				$_COOKIE['referer'] = 0;
			}
			
			if ( GeoIP( real_IP() ) == 'XX' ) {
				include_once ROOT_DIR .  '/engine/geoip/GeoIP.php';
				$geoip = Net_GeoIP::getInstance( ROOT_DIR . '/engine/geoip/GeoIP.dat' );
				try {
					$regcountry = mb_convert_encoding( $geoip->lookupCountryName( real_IP() ), 'CP1251', 'UTF8' );
					$regcode = strtolower( $geoip->lookupCountryCode( real_IP() ) );
				}
				catch ( Exception $e ) {
					$regcountry = '';
					$regcode = '';
				}
			} else {
				$regcountry = $countrys[strtolower( GeoIP( real_IP() ) )];
				$regcode = strtolower( GeoIP( real_IP() ) );
			}

			include_once ROOT_DIR . '/engine/classes/idna_convert.class.php';
			
			$idn = new idna_convert(array('idn_version'=>2008));
			
			if ( strpos( check_text( $_COOKIE['rsite'] ), 'xn--' ) !== FALSE ) {
				preg_match( '/([a-z0-9а-я\.])+([a-z0-9а-я\-])+(\.)([a-z0-9а-я]{2,5}\.)?([a-z0-9а-я\-]{2,8})/i', check_text( $_COOKIE['rsite'] ), $rsite );
				$rsite[0] = substr( check_text( $idn->decode( $rsite[0] ) ), 0, 50 );
			} else {
				preg_match( '/([a-z0-9а-я\.])+([a-z0-9а-я\-])+(\.)([a-z0-9а-я]{2,5}\.)?([a-z0-9а-я]{2,5})/i', check_text( $_COOKIE['rsite'] ), $rsite );
				$rsite[0] = substr( $rsite[0], 0, 50 );
			}
			
			if($config_site['mobileKodType'] != 1 AND $config_site['mobileKodType'] != 2) {
				$act_key = generate( 6 );
			} else {
				$act_key = pincode( 4 );
			}
			
			$pinkode = pincode( 5 );
			
			$randavatar = rand(1, 11);
			
			mysql_query( 
				"INSERT INTO user (name, username, password, email, ip, referer, referer2, country, city_code, regdate, autoproc, reyting, act_code, rsite, pincode, reg_ip, avatar) 
					VALUES 
				('" . check_text( $_POST['name'] ) . "', '" . check_text( $_POST['nik'] ) . "', '" . iconv( 'UTF-8', 'windows-1251', md5_pass( $message_md5, $_POST['pass'] ) ) . "', '" . check_text( substr( $_POST['email'], 0, 50 ) ) . "', '" . real_IP() . "', '" . $ref_row['id'] . "', '" . ( int ) $ref_row['referer'] . "', '" . $regcountry . "', '" . $regcode . "', '" . time() . "', '" . $ref_row['autoback'] . "', '" . $config['reyting'] . "', '" . $act_key . "', '" . check_text( $rsite[0] ) . "', '" . $pinkode . "', '" . real_IP() . "', 'no" . $randavatar . ".png')" 
			) or die( mysql_error() );
			
			$pr_static = mysql_fetch_array( mysql_query( "SELECT id FROM user WHERE email = '" . $_POST['email'] . "' LIMIT 1" ) );
			
			#класс отправки привествия
			if ($ref_row['id'] > 0 and $ref_row['greetingRef'] != '') {
				mysql_query( "INSERT INTO messages SET from_id = '" . $ref_row['id'] . "', to_id = '" . $pr_static['id'] . "', text = '" . $ref_row['greetingRef'] . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $ref_row['id'] . "'" );
				mysql_query( "INSERT INTO messages SET from_id = '" . $ref_row['id'] . "', to_id = '" . $pr_static['id'] . "', text = '" . $ref_row['greetingRef'] . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . $pr_static['id'] . "'" );
			}
			
			include_once ROOT_DIR . '/engine/classes/libmail.php'; # подключаем SMTP class
			
			if($config_site['mobileKodType'] != 1 AND $config_site['mobileKodType'] != 2) {
				$message = '
				<html>
				<head>
				<title>Регистрация на проекте ' . $config_site['sitename'] . '</title>
				<style type="text/css">
				html, body {
					margin:0;
					margin-left:5px;
					padding:0;
					font-size:12px;
				}
				p {
					margin:0;
					padding:3px;
				}
				</style>
				</head>
				<body>
				<p>Здравствуйте, <b>' . check_text( $_POST['nik'] ) . '</b>.</p>
				<p>Вы успешно зарегистрировались на проекте <b>http://' . $_SERVER["HTTP_HOST"] . '</b></p>
				<p>--------------------------------------------------------------------------</p>
				<p>Для входа на сайт используйте следующие данные:</p>
				<p>--------------------------------------------------------------------------</p>
				логин: <b>' . check_text( $_POST['email'] ) . '</b><br />
				пароль: <b>' . check_text( $_POST['pass'] ) . '</b><br />
				код активации: <b>' . $act_key . '</b><br />
				пин-код: <b>' . $pinkode . '</b><br />
				IP: <b>' . real_IP() . '</b><br />
				Дата: <b>' . date( 'd.m.Y H:i', time() ) . '</b><br />
				<p>--------------------------------------------------------------------------</p>
				<p><font color="#800000">Внимание! </font>Не передавайте письмо 3-м лицам, запишите данные и удалите письмо, во избежания кражи Вашей личной информации...</p>
				<p>Письмо отправлено автоматически. На него отвечать не нужно.</p>
				</body>
				</html>';
			} else {
				$message = '
				<html>
				<head>
				<title>Регистрация на проекте ' . $config_site['sitename'] . '</title>
				<style type="text/css">
				html, body {
					margin:0;
					margin-left:5px;
					padding:0;
					font-size:12px;
				}
				p {
					margin:0;
					padding:3px;
				}
				</style>
				</head>
				<body>
				<p>Здравствуйте, <b>' . check_text( $_POST['nik'] ) . '</b>.</p>
				<p>Вы успешно зарегистрировались на проекте <b>http://' . $_SERVER["HTTP_HOST"] . '</b></p>
				<p>--------------------------------------------------------------------------</p>
				<p>Для входа на сайт используйте следующие данные:</p>
				<p>--------------------------------------------------------------------------</p>
				логин: <b>' . check_text( $_POST['email'] ) . '</b><br />
				пароль: <b>' . check_text( $_POST['pass'] ) . '</b><br />
				пин-код: <b>' . $pinkode . '</b><br />
				IP: <b>' . real_IP() . '</b><br />
				Дата: <b>' . date( 'd.m.Y H:i', time() ) . '</b><br />
				<p>--------------------------------------------------------------------------</p>
				<p><font color="#800000">Внимание! </font>Не передавайте письмо 3-м лицам, запишите данные и удалите письмо, во избежания кражи Вашей личной информации...</p>
				<p>Письмо отправлено автоматически. На него отвечать не нужно.</p>
				</body>
				</html>';
			}
			
			$m = new Mail;
			$m->From( 'Администрация;' . $config_site['email'] ); #от кого отправляется почта
			$m->To( $_POST['email'] ); #кому адресованно
			$m->Subject( 'Регистрация на проекте ' . $_SERVER["HTTP_HOST"] );
			$m->Body( $message );
			$m->Priority( 3 ); #приоритет письма
			$m->smtp_on( $config_site['smtpemail'], $config_site['email'], $config_site['emailpass'], $config_site['portemail'] ); #если указана эта команда, отправка пойдет через SMTP
			$m->Send(); #а теперь пошла отправка
			
			echo 1;
			exit();
		
		} else if($status === 1) {  
			echo 'Капча не пройдена. Пожалуйста попробуйте еще раз!';
			exit();
		} else if($status === 2) {  
			echo 'Нарушен механизм регистрации, пожалуйста повторите еще раз, или сообщите информацию об этом, администрации!';
			exit();
		}
		
    } 
}

### Авторизация
if ( $_GET['func'] == 'login' ) {
    
    sleep(1);
    
    if ( isset( $_SESSION['iduser'] ) ) { exit(); }
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $check_user = mysql_query( "SELECT id, blockip, blockuser, ip, userdel, wmlogin FROM user WHERE email = '" . check_text( $_POST['email'] ) . "' and password = '" . md5_pass( $message_md5, $_POST['pass'] ) . "' LIMIT 1" );
    $check_user_row = mysql_fetch_array( $check_user );
    
    $caphaType = $config_site["capthaType"];
	$recapha_n2 = $config_site["recapthaSecretKey"]; 
	
	if ( !mysql_num_rows($check_user) ) {
        echo 'Вы указали неверный email или пароль!';
        exit();
    } else
    if ( $check_user_row['userdel'] ) {
        echo 'Пользователь удален!';
        exit();
    } else
    if ( $check_user_row['blockuser'] ) {
        echo 'Ваш аккаунт заблокирован!';
        exit();
    } else
    if ( $check_user_row['blockip'] != 0 and $check_user_row['ip'] != real_IP() ) {
        echo 'Ваш IP адрес не соответствует разрешенному!';
        exit();
    } else
    if ( $check_user_row['wmlogin'] ) {
        echo 'Доступ запрещен!';
        exit();
    } else
	
#Проверяем тип капчи (аналоговая капча или рекапча от гугла)
    if ( $caphaType == 0 ) {
		
        if ( $_SESSION['get_code'] != strtoupper( $_POST['capcha'] ) ) {
			echo 'Вы указали неверно проверочный код!';
			exit();
		} else {  
			
			session_set_cookie_params(0, '/', '.centrseomani.ru'); 
			session_start(); 
			$_SESSION['iduser'] = ( int ) $check_user_row['id'];
			
			if ( $_POST['savelp'] == 'option1' ) {
				setcookie( 'email', $_POST['email'], time() + 365 * 86400 );
				setcookie( 'pass', $_POST['pass'], time() + 365 * 86400 );
			} else {
				setcookie( 'email', '', time() - 1 );
				setcookie( 'pass', '', time() - 1 );
			}
			
			mysql_query( "UPDATE user SET logindate = '" . time() . "', ip = '" . real_IP() . "', browser = '" . check_text( user_browser( $_SERVER['HTTP_USER_AGENT'] ) ) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
			
			echo 1;
			exit();
		}
		
    } else {
        $recaptcha = check_text($_POST['g-recaptcha-response']);
		$secret = $recapha_n2;
		$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret ."&response=".$recaptcha."&remoteip=".$_SERVER['REMOTE_ADDR'];
		$status = 1;
		if(!empty($recaptcha)) {
			$curl = curl_init();
			if(!$curl) {
			$status = 2;    
			} else {
				curl_setopt($curl, CURLOPT_URL, $url);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($curl, CURLOPT_TIMEOUT, 10);
				curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
				$curlData = curl_exec($curl);
				curl_close($curl);    
				$curlData = json_decode($curlData, true);
				if($curlData['success']) {
					$status = 0;
				}
			}
		}
		
		if($status === 0) {  
			
			session_set_cookie_params(0, '/', '.centrseomani.ru'); 
			session_start(); 
			$_SESSION['iduser'] = ( int ) $check_user_row['id'];
			
			if ( $_POST['savelp'] == 'option1' ) {
				setcookie( 'email', $_POST['email'], time() + 365 * 86400 );
				setcookie( 'pass', $_POST['pass'], time() + 365 * 86400 );
			} else {
				setcookie( 'email', '', time() - 1 );
				setcookie( 'pass', '', time() - 1 );
			}
			
			mysql_query( "UPDATE user SET logindate = '" . time() . "', ip = '" . real_IP() . "', browser = '" . check_text( user_browser( $_SERVER['HTTP_USER_AGENT'] ) ) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
			
			echo 1;
			exit();
		
		} else if($status === 1) {  
			echo 'В авторизации отказано! Капча не пройдена.';
			exit();
		} else if($status === 2) {  
			echo 'Нарушен механизм авторизации, пожалуйста повторите еще раз, или сообщите информацию об этом, администрации!';
			exit();
		}
    }
}

### Восстановления пароля
if ( $_GET['func'] == 'resore_pass' ) {
    
    sleep(1);
    
    if ( isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$caphaType = $config_site["capthaType"];
	$recapha_n2 = $config_site["recapthaSecretKey"];
    
    if ( !preg_match( "/^(?:[a-z0-9]+(?:[-_]?[a-z0-9\.\-\_]+)?@[a-z0-9]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i", $_POST['email'] ) ) {
        echo 'Неверно указан email, проверьте введенные данные!';
        exit();
    } else
    #Проверяем тип капчи (аналоговая капча или рекапча от гугла)
    if ( $caphaType == 0 ) {
        echo 'Не верный тип каптчи';
        exit();
    } else {
        $recaptcha = check_text($_POST['g-recaptcha-response']);
		$secret = $recapha_n2;
		$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret ."&response=".$recaptcha."&remoteip=".$_SERVER['REMOTE_ADDR'];
		$status = 1;
		if(!empty($recaptcha)) {
			$curl = curl_init();
			if(!$curl) {
			$status = 2;    
			} else {
				curl_setopt($curl, CURLOPT_URL, $url);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($curl, CURLOPT_TIMEOUT, 10);
				curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
				$curlData = curl_exec($curl);
				curl_close($curl);    
				$curlData = json_decode($curlData, true);
				if($curlData['success']) {
					$status = 0;
				}
			}
		}
		if($status === 0) { 
			$sql = mysql_query( "SELECT id, username FROM user WHERE email = '" . check_text( $_POST['email'] ) . "'" );
			if ( mysql_num_rows( $sql ) > 0 ) {
				$row = mysql_fetch_array( $sql );
				
				$recovery_pass = generate( 6 );
				
				include_once ROOT_DIR . '/engine/classes/libmail.php'; # подключаем SMTP class
			
				$message = '
				<html>
				<head>
				<title>Восстановление пароля на проекте ' . $config_site['sitename'] . '</title>
				<style type="text/css">
				html, body {
					margin:0;
					margin-left:5px;
					padding:0;
					font-size:12px;
				}
				p {
					margin:0;
					padding:3px;
				}
				</style>
				</head>
				<body>
				<p>Здравствуйте, <b>' . $row['username'] . '</b>.</p>
				<p>--------------------------------------------------------------------------</p>
				<p>Для входа на сайт используйте следующие данные:</p>
				<p>--------------------------------------------------------------------------</p>
				логин: <b>' . check_text( $_POST['email'] ) . '</b><br />
				новый пароль: <b>' . $recovery_pass . '</b><br />
				IP: <b>' . real_IP() . '</b><br />
				Дата: <b>' . date( 'd.m.Y H:i', time() ) . '</b><br />
				<p>--------------------------------------------------------------------------</p>
				<p><font color="#800000">Внимание! </font>Зайдите в аккаунт и измените пароль...</p>
				<p>Письмо отправлено автоматически. На него отвечать не нужно.</p>
				</body>
				</html>';
				
				$m = new Mail;
				$m->From( 'Администрация;' . $config_site['email'] ); # от кого отправляется почта 
				$m->To( $_POST['email'] ); # кому адресованно
				$m->Subject( 'Восстановление пароля на проекте ' . $_SERVER["HTTP_HOST"] );
				$m->Body( $message );    
				$m->Priority( 3 ); # приоритет письма
				$m->smtp_on( $config_site['smtpemail'], $config_site['email'], $config_site['emailpass'], $config_site['portemail'] ); # если указана эта команда, отправка пойдет через SMTP 
				$m->Send(); # а теперь пошла отправка
				
				mysql_query( "UPDATE user SET password = '" . md5_pass( $message_md5, $recovery_pass ) . "' WHERE id = '" . $row['id'] . "'" );
				
				echo 1;
				exit();
			} else {
				echo 'Указанный email не существует!';
				exit();
			}
		} else if($status === 1) {  
			echo 'Капча не пройдена, будьте внимательнее';
			exit();
		} else if($status === 2) {  
			echo 'Нарушен механизм авторизации капчи, пожалуйста повторите еще раз, или сообщите информацию об этом, администрации!';
			exit();
		}
		
    }
}

### Активация аккаунта gsm часть первая отсылка смс
if ( $_GET['func'] == 'actkey' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$mobile = ( int ) $_POST['mobile'];
	
	$num_mobile_end = mysql_fetch_array( mysql_query( "SELECT mobile FROM user WHERE mobile = '" . $mobile . "'" ) );
	
	$proverkaStran = '/^\+?([87](?!95[4-79]|99[08]|907|94[^0]|336)([348]\d|9[0-6789]|7[0247])\d{8}|[1246]\d{9,13}|68\d{7}|5[1-46-9]\d{8,12}|55[1-9]\d{9}|55[12]19\d{8}|500[56]\d{4}|5016\d{6}|5068\d{7}|502[45]\d{7}|5037\d{7}|50[4567]\d{8}|50855\d{4}|509[34]\d{7}|376\d{6}|855\d{8}|856\d{10}|85[0-4789]\d{8,10}|8[68]\d{10,11}|8[14]\d{10}|82\d{9,10}|852\d{8}|90\d{10}|96(0[79]|17[01]|13)\d{6}|96[23]\d{9}|964\d{10}|96(5[69]|89)\d{7}|96(65|77)\d{8}|92[023]\d{9}|91[1879]\d{9}|9[34]7\d{8}|959\d{7}|989\d{9}|97\d{8,12}|99[^4568]\d{7,11}|994\d{9}|9955\d{8}|996[57]\d{8}|9989\d{8}|380[3-79]\d{8}|381\d{9}|385\d{8,9}|375[234]\d{8}|372\d{7,8}|37[0-4]\d{8}|37[6-9]\d{7,11}|30[69]\d{9}|34[67]\d{8}|3[12359]\d{8,12}|36\d{9}|38[1679]\d{8}|382\d{8,9}|46719\d{10})$/';
	if (!preg_match ($proverkaStran, $mobile) ) {
		echo 'Не верно указан номер! Нужно указывать обязательно с кодом страны!';
        exit();
	} else
	if ( $num_mobile_end['mobile'] > 0 ){
        echo 'Этот номер уже используется!';
        exit();
    } else
	if ( $config_user['activate'] ){
        echo 'Аккаунт уже активирован!';
        exit();
    } else
	if ( $mobile == "" or $mobile < 1 ) {
        echo "Введите номер телефона!";
        exit();
    } else
	if ( $config_user['mobileSend'] >= 3 ) {
        echo "Лимит отправки смс на сегодня исчерпан, повтор возможен через 24 часа.";
        exit();
    } else
    
    if($config_site['mobileKodType'] == 1) {
		$m = send_sms("" .$mobile. "", "Ваш код активации: " .$config_user['act_code']. " в проекте " .$config_site['sitename']. "", 0);
	} else {
		$m = send_sms("" .$mobile. "", "Код активации " .$config_user['act_code']. "", 0, 0, 0, 9, false);
	}
	
	if ($m[1] > 0) {
		mysql_query( "UPDATE user SET mobileSend = mobileSend+1, mobileTimeActivate = '" .time(). "', mobileTemporary = '" .$mobile. "' WHERE id = '" . $_SESSION['iduser'] . "'" );
		echo 1;
		exit();
	} else {
		if(-$m[1] == 1) {
			echo 2;
			exit();
		} else 
		if(-$m[1] == 2) {
			echo 3;
			exit();
		} else  
		if(-$m[1] == 3) {
			echo 4;
			exit();
		} else  
		if(-$m[1] == 4) {
			echo 5;
			exit();
		} else  
		if(-$m[1] == 5) {
			echo 6;
			exit();
		} else  
		if(-$m[1] == 6) {
			echo 7;
			exit();
		} else  
		if(-$m[1] == 7) {
			echo 8;
			exit();
		} else    
		if(-$m[1] == 8) {
			echo 9;
			exit();
		} else    
		if(-$m[1] == 9) {
			echo 10;
			exit();
		} else {
			echo "Ошибка, нельзя так часто отправлять запросы!";
			exit();
		} 
	}
    
}

### Активация аккаунта gsm часть вторая проверка кода
if ( $_GET['func'] == 'actkeyend' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	$num_mobile_end = mysql_fetch_array( mysql_query( "SELECT mobile FROM user WHERE mobile = '" . $config_user['mobileTemporary'] . "'" ) );
	
	if ( $num_mobile_end['mobile'] > 0 ){
        echo 'Номер телефона уже используется!';
        exit();
    } else
	
    if ( $config_user['kodactivefail'] >= 100 ){
        echo 'Активация аккаунта заблокирована, за превышенный лимит ошибок с вводом кода! Обратитесь в администрацию!';
        exit();
    } else
    if ( $config_user['activate'] ){
        echo 'Аккаунт уже активирован!';
        exit();
    } else
    if ( empty( $_POST['key'] ) ) {
        echo 'Вы не указали код активации!';
        exit();
    } else
    if ( $config_user['act_code'] != ( int ) $_POST['key'] ) {
        mysql_query( "UPDATE user SET kodactivefail = kodactivefail + 1 WHERE id = '" . $_SESSION['iduser'] . "'" );
		echo 'Вы указали неверный код активации!';
        exit();
    } else {
        
        mysql_query( "UPDATE user SET activate = 1, mobile = mobileTemporary WHERE id = '" . $_SESSION['iduser'] . "'" );
		
		#Конкурс от админа
        if ( $config_user['referer'] != 0 ) {
            $chKonkurs = mysql_query( "SELECT id, date_start, date_end FROM konkurs WHERE type = 1 LIMIT 1" );
            if ( mysql_num_rows( $chKonkurs ) > 0 ) {
                $chKonkursRow = mysql_fetch_array( $chKonkurs );
                #Проверяем дату регистрации
                if ( $config_user['regdate'] >= $chKonkursRow['date_start'] and $config_user['regdate'] <= $chKonkursRow['date_end'] ) {
                    $chKonkursTemp = mysql_query( "SELECT id FROM konkurs_temp WHERE iduser = '" . $config_user['referer'] . "' and id_konkurs = '" . $chKonkursRow['id'] . "' and type = 1" );
                    if ( mysql_num_rows( $chKonkursTemp ) > 0 ) {
                        mysql_query( "UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '" . $config_user['referer'] . "'  and type = 1 LIMIT 1" );
                    } else {
                        mysql_query( "INSERT INTO konkurs_temp SET id_konkurs = '" . $chKonkursRow['id'] . "', iduser = '" . $config_user['referer'] . "', summ = 1, type = 1" );
                    }
                }
            }
        }
		
		#Конкурсы от реферера
		if ( $config_user['referer2'] != 0 ) {
			#Приглашение рефералов
			$chKonkursWan = mysql_query( "SELECT * FROM contests WHERE type = 2 and date_end > '". time() ."' and autor = '".$config_user['referer2']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursWan ) > 0 ) {
				$chKonkursRowWan = mysql_fetch_array( $chKonkursWan );
				if ( $config_user['regdate'] >= $chKonkursRowWan['date_start'] and $config_user['regdate'] <= $chKonkursRowWan['date_end'] ) {
					$chKonkursTempWan = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . $config_user['referer'] . "' and id_konkurs = '" . $chKonkursRowWan['id'] . "' and type = 2" );
					if ( mysql_num_rows( $chKonkursTempWan ) > 0 ) {
						mysql_query( "UPDATE contests_temp SET summ = summ + 7 WHERE iduser = '" . $config_user['referer'] . "' and type = 2 and id_konkurs = '" . $chKonkursRowWan['id'] . "' LIMIT 1" );
					} else {
						mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowWan['id'] . "', iduser = '" . $config_user['referer'] . "', summ = 7, type = 2" );
					}
				}
			}
			#Комплексный
			$chKonkursComplex = mysql_query( "SELECT * FROM contests WHERE type = 3 and date_end > '". time() ."' and autor = '".$config_user['referer2']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursComplex ) > 0 ) {
				$chKonkursRowComplex = mysql_fetch_array( $chKonkursComplex );
				if ( $config_user['regdate'] >= $chKonkursRowComplex['date_start'] and $config_user['regdate'] <= $chKonkursRowComplex['date_end'] ) {
					$chKonkursTempComplex = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . $config_user['referer'] . "' and id_konkurs = '" . $chKonkursRowComplex['id'] . "' and type = 3" );
					if ( mysql_num_rows( $chKonkursTempComplex ) > 0 ) {
						mysql_query( "UPDATE contests_temp SET summ = summ + 7 WHERE iduser = '" . $config_user['referer'] . "' and type = 3 and id_konkurs = '" . $chKonkursRowComplex['id'] . "' LIMIT 1" );
					} else {
						mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowComplex['id'] . "', iduser = '" . $config_user['referer'] . "', summ = 7, type = 3" );
					}
				}
			}
		}
		
        echo 1;
        exit();
    }
}

### Активация аккаунта OLD
if ( $_GET['func'] == 'actkeymaill' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if($config_site['mobileKodType'] != 3){
        echo 'Нарушен механизм!';
        exit();
    } else
    if ( $config_user['activate'] ){
        echo 'Аккаунт уже активирован!';
        exit();
    } else
    if ( empty( $_POST['key'] ) ) {
        echo 'Вы не указали код активации!';
        exit();
    } else
    if ( $config_user['act_code'] != $_POST['key'] ) {
        echo 'Вы указали неверный код активации!';
        exit();
    } else {
        
        mysql_query( "UPDATE user SET activate = 1 WHERE id = '" . $_SESSION['iduser'] . "'" );
        
        #Конкурс от админа
        if ( $config_user['referer'] != 0 ) {
            $chKonkurs = mysql_query( "SELECT id, date_start, date_end FROM konkurs WHERE type = 1 LIMIT 1" );
            if ( mysql_num_rows( $chKonkurs ) > 0 ) {
                $chKonkursRow = mysql_fetch_array( $chKonkurs );
                #Проверяем дату регистрации
                if ( $config_user['regdate'] >= $chKonkursRow['date_start'] and $config_user['regdate'] <= $chKonkursRow['date_end'] ) {
                    $chKonkursTemp = mysql_query( "SELECT id FROM konkurs_temp WHERE iduser = '" . $config_user['referer'] . "' and id_konkurs = '" . $chKonkursRow['id'] . "' and type = 1" );
                    if ( mysql_num_rows( $chKonkursTemp ) > 0 ) {
                        mysql_query( "UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '" . $config_user['referer'] . "'  and type = 1 LIMIT 1" );
                    } else {
                        mysql_query( "INSERT INTO konkurs_temp SET id_konkurs = '" . $chKonkursRow['id'] . "', iduser = '" . $config_user['referer'] . "', summ = 1, type = 1" );
                    }
                }
            }
        }
		
		#Конкурсы от реферера
		if ( $config_user['referer2'] != 0 ) {
			#Приглашение рефералов
			$chKonkursWan = mysql_query( "SELECT * FROM contests WHERE type = 2 and date_end > '". time() ."' and autor = '".$config_user['referer2']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursWan ) > 0 ) {
				$chKonkursRowWan = mysql_fetch_array( $chKonkursWan );
				if ( $config_user['regdate'] >= $chKonkursRowWan['date_start'] and $config_user['regdate'] <= $chKonkursRowWan['date_end'] ) {
					$chKonkursTempWan = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . $config_user['referer'] . "' and id_konkurs = '" . $chKonkursRowWan['id'] . "' and type = 2" );
					if ( mysql_num_rows( $chKonkursTempWan ) > 0 ) {
						mysql_query( "UPDATE contests_temp SET summ = summ + 7 WHERE iduser = '" . $config_user['referer'] . "' and type = 2 and id_konkurs = '" . $chKonkursRowWan['id'] . "' LIMIT 1" );
					} else {
						mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowWan['id'] . "', iduser = '" . $config_user['referer'] . "', summ = 7, type = 2" );
					}
				}
			}
			#Комплексный
			$chKonkursComplex = mysql_query( "SELECT * FROM contests WHERE type = 3 and date_end > '". time() ."' and autor = '".$config_user['referer2']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursComplex ) > 0 ) {
				$chKonkursRowComplex = mysql_fetch_array( $chKonkursComplex );
				if ( $config_user['regdate'] >= $chKonkursRowComplex['date_start'] and $config_user['regdate'] <= $chKonkursRowComplex['date_end'] ) {
					$chKonkursTempComplex = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . $config_user['referer'] . "' and id_konkurs = '" . $chKonkursRowComplex['id'] . "' and type = 3" );
					if ( mysql_num_rows( $chKonkursTempComplex ) > 0 ) {
						mysql_query( "UPDATE contests_temp SET summ = summ + 7 WHERE iduser = '" . $config_user['referer'] . "' and type = 3 and id_konkurs = '" . $chKonkursRowComplex['id'] . "' LIMIT 1" );
					} else {
						mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowComplex['id'] . "', iduser = '" . $config_user['referer'] . "', summ = 7, type = 3" );
					}
				}
			}
		}
        
        echo 1;
        exit();
    }
}

### Блокировка входа в аккаунт по IP
if ( $_GET['func'] == 'blockip' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['blockip'] == 0 ) {
        mysql_query( "UPDATE user SET blockip = 1 WHERE id = '" . $_SESSION['iduser'] . "'" );
        echo 1;
        exit();
    } else {
        mysql_query( "UPDATE user SET blockip = 0 WHERE id = '" . $_SESSION['iduser'] . "'" );
        echo 1;
        exit();
    }
}

### Авторизация Login.webmoney
if ( $_GET['func'] == 'wmlogin' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( empty( $config_user['wmid'] ) ) {
        echo 'Установите WM кошелек!';
        exit();
    } else
    if ( $config_user['wmlogin'] == 0 ) {
        mysql_query( "UPDATE user SET wmlogin = 1 WHERE id = '" . $_SESSION['iduser'] . "'" );
        echo 1;
        exit();
    } else {
        mysql_query( "UPDATE user SET wmlogin = 0 WHERE id = '" . $_SESSION['iduser'] . "'" );
        echo 1;
        exit();
    }
}

### Изменение аватара
if ( $_GET['func'] == 'addavatar' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( !$_FILES['addavatar']['name'] ) {
        echo 'Выберите в начале файл изображения аватара!';
        exit();
    } else
    if ( $_FILES["addavatar"]["size"] <= 0 and $_FILES["addavatar"]["size"] > 300 * 1024 ) {
        echo 'Максималный размер аватара 300 кб.!';
        exit();
    } else
    if ( $_FILES['addavatar']['type'] != 'image/jpg' and  $_FILES['addavatar']['type'] != 'image/jpeg' and $_FILES['addavatar']['type'] != 'image/png' and $_FILES['addavatar']['type'] != 'image/gif') {
        echo 'Неверный формат изображения!';
        exit();
    } else
    if ( is_uploaded_file( $_FILES["addavatar"]["tmp_name"] ) ) {
        $imgwh = GetImageSize( $_FILES["addavatar"]["tmp_name"] );
        
        if ( $imgwh[0] > 100 or $imgwh[1] > 100 or $imgwh[0] < 100 or $imgwh[1] < 100 ) {
            echo 'Допустимое расширение аватара: 100х100 пикселей!';
            exit();
        } else {
            $type_file = str_replace("theme/tmp/", "", basename($_FILES['addavatar']['type']));
            
            if ( $config_user['avatar'] != 'no.png' AND $config_user['avatar'] != 'no1.png' AND $config_user['avatar'] != 'no2.png' AND $config_user['avatar'] != 'no3.png' AND $config_user['avatar'] != 'no4.png' AND $config_user['avatar'] != 'no5.png' AND $config_user['avatar'] != 'no6.png' AND $config_user['avatar'] != 'no7.png' AND $config_user['avatar'] != 'no8.png' AND $config_user['avatar'] != 'no9.png' AND $config_user['avatar'] != 'no10.png' AND $config_user['avatar'] != 'no11.png' ) {
                unlink( ROOT_DIR . '/temp/avatar/' . $config_user['avatar'] );
            }
            
            if ( @move_uploaded_file( $_FILES['addavatar']['tmp_name'], "temp/avatar/" . $_SESSION["iduser"] . "avatar." . $type_file ) ) {
                mysql_query( "UPDATE user SET avatar = '" . $_SESSION['iduser'] . "avatar." . $type_file . "' WHERE id='" . $_SESSION['iduser'] . "'" );
                echo 1;
                exit();
            } else {
                echo 'Произошла внутренняя ошибка! Попробуйте позже!';
                exit();
            }
        }
    } else {
        echo 'Произошла внутренняя ошибка! Попробуйте позже!';
        exit();
    }
}

### Устанавливаем кошелек
if ( $_GET['func'] == 'addpurse' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $gwmid = getwmid( $_POST['purse'] );
    
    if ( substr( $_POST['purse'], 0, 1) != $config['valuta'] or strlen($_POST['purse']) != 13 or !is_numeric(substr($_POST['purse'], 1, 13)) or $gwmid == 1 ) {
        echo 'Неверно указан кошелек. Будьте внимательны!';
        exit();
    } else
    if ( $config_user['purse'] != '' ) {
        echo 'Вы уже указали кошелек!';
        exit();
    } else {
        $proverka_wmid = mysql_query( "SELECT id FROM user WHERE wmid = '" . $gwmid . "'" );
        if ( mysql_num_rows( $proverka_wmid ) > 0 ) {
            echo 'В системе уже используеться данный WMID';
            exit();
        } else {
            mysql_query( "UPDATE user SET purse = '" . check_text( $_POST['purse'] ) . "', wmid = '" . $gwmid . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
            echo 1;
            exit();
        }
    }
}

### Устанавливаем кошелек паеер
if ( $_GET['func'] == 'addpayeer' ) {
   
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	include_once ROOT_DIR . '/engine/classes/cpayeer.php';
	$accountNumber = $config_site['shetpayeer']; 
	$payer_user = $config_user['payeer'];
	$apiId = $config_site['apiIdpayeer'];         
	$apiKey = $config_site['maskeypayeer'];   
	$payeer = new CPayeer($accountNumber, $apiId, $apiKey);
	
	if($payeer->checkUser(array( 'user' => '' . check_text( $_POST['pursepayeer'] ) . '', ))) {
	  
	  if ( strlen(check_text( $_POST['pursepayeer'] )) < 6 OR strlen(check_text( $_POST['pursepayeer'] )) > 15 ) {
        echo 'Неверно указан кошелек. Будьте внимательны!';
        exit();
      } else
      if ( $config_user['payeer'] != '' ) {
        echo 'Вы уже указали кошелек Payeer!';
        exit();
      } else {
        $proverka_payeer_add = mysql_query( "SELECT id FROM user WHERE payeer = '" . check_text( $_POST['pursepayeer'] ) . "'" );
        
		if ( mysql_num_rows( $proverka_payeer_add ) > 0 ) {
          echo 'В системе уже используеться данный кошелек';
          exit();
        } else {
          mysql_query( "UPDATE user SET payeer = '" . check_text( $_POST['pursepayeer'] ) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
          echo 1;
          exit();
        }
      }
	
	} else {  
	  echo 'Неверно указан кошелек. Будьте внимательны!';
      exit();
	}
}

### Изменение пароля
if ( $_GET['func'] == 'reloadpass' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( empty( $_POST['pass'] ) ) {
        echo 'Вы не указали пароль!';
        exit();
    } else
    if ( strlen( check_text( $_POST['pass'] ) ) < 5 or strlen( check_text( $_POST['pass'] ) ) > 50 ) {
        echo 'Пароль может состоят от 5 до 50 символов!';
        exit();
    } else
    if ( !preg_match( "/^[a-z,A-Z,0-9,\-]+$/is", check_text( $_POST['pass'] ) ) ) {
        echo 'Недопустимые символы в пароле!';
        exit();
    } else
    if ( $_POST['pass2'] != $_POST['pass'] ) {
        echo 'Пароли не совпадают!';
        exit();
    } else
    if ( $config_user['pincode'] != $_POST['pin'] ) {
        echo 'Неверный pin код!';
        exit();
    } else {
        mysql_query( "UPDATE user SET password = '" . md5_pass( $message_md5, $_POST['pass'] ) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
        echo 1;
        exit();
    }
    
}

### Ежедневный рейтинг (яблоко рейтинга)
if ( $_GET['func'] == 'addreyting' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['addreyting'] == '' or $config_user['addreyting'] < time() ) {
        mysql_query( "UPDATE user SET reyting = reyting + '" . $config['everybonus'] . "', addreyting = '" . time() . "' + 86400 WHERE id = '" . $_SESSION['iduser'] . "'" );
        
        echo 1;
        exit();
    }
}

### Изменение пола
if ( $_GET['func'] == 'editsex' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $sex = ( int ) $_POST['sex'];
    
    if ( ( int ) $_POST['sex'] != 0 and ( int ) $_POST['sex'] != 1 ) {
        $sex = 0;
    }
    
    mysql_query( "UPDATE user SET sex = '" . $sex . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
    exit();
}

### Дата рождения
if ( $_GET['func'] == 'birthday' ) {
    
    sleep(1);
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $get_date = check_text( $_POST['date'] );
    
    if ( !empty( $config_user['birthday'] ) ) exit();
    
    $get_date = DateTime::createFromFormat('Y-m-d', $get_date);
	if ($get_date) {
		$get_date = $get_date -> format('d.m.Y');
		mysql_query( "UPDATE user SET birthday = '$get_date' WHERE id = '" . $_SESSION['iduser'] . "'" );
        
        echo 1;
        exit();
	} else {
		echo 'Вы ввели неверное значение даты!';
        exit();
	}    
}

### Установка рефбека рефералу
if ( $_GET['func'] == 'refback' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $sql = mysql_query( "SELECT autoproc FROM user WHERE id = '" . ( int ) $_POST['id'] . "' and referer = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $sql ) > 0 ) {
        $row = mysql_fetch_array( $sql );
        
        if ( ( int ) $_POST['refback'] == $row['autoproc'] ) {
            echo 'Вы не указали изменений, зачем пере сохранять значение? <i class="fa fa-meh-o" aria-hidden="true"></i>';
			exit();
        } else
        if ( ( int ) $_POST['refback'] < $row['autoproc'] ) {
            echo 'Нельзя установить рефбек в меньшую сторону!';
			exit();
        } else
        if ( ( int ) $_POST['refback'] < 0 or ( int ) $_POST['refback'] > 80 ) {
            echo 'Рефбек не может быть меньше 0 или больше 80 процентов!';
			exit();
        } else {
            mysql_query( "UPDATE user SET autoproc = '" . ( int ) $_POST['refback'] . "' WHERE id = '" . ( int ) $_POST['id'] . "' and referer = '" . $_SESSION['iduser'] . "'" );
            
            echo 1;
            exit();
        }
    } else {
		echo 'Реферал не существует или не принадлежит вам!';
        exit();
    }
}

### Авторефбек
if ( $_GET['func'] == 'autorefback' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( ( int ) $_POST['refback'] < 0 or ( int ) $_POST['refback'] > 80 ) {
        echo 'Авторефбек не может быть меньше 0 или больше 80 процентов!';
		exit();
    } else {
        mysql_query( "UPDATE user SET autoback = '" . ( int ) $_POST['refback'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
        
        echo 1;
        exit();
    }
}

### Удаление реферала
if ( $_GET['func'] == 'delreferal' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT id FROM user WHERE id = '" . ( int ) $_POST['id'] . "' and referer = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        mysql_query( "UPDATE user SET referer = 0, autoproc = 0, toref = 0 WHERE id = '" . ( int ) $_POST['id'] . "' and referer = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "UPDATE user SET referals = referals - 1 WHERE id = '" . $_SESSION['iduser'] . "'" );
		echo 1;
		exit();
	} else {
		echo 'Реферал не существует или не принадлежит вам!';
		exit();
	}
       
}

### Разбудить реферала
if ( $_GET['func'] == 'wakesend' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $prov_ref = mysql_query( "SELECT id, email, username, referer FROM user WHERE id = '" . ( int ) $_POST['id'] . "' and referer = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( mysql_num_rows( $prov_ref ) > 0 ) {
        if ( $config_user['adv_money'] < 0.05 ) {
            echo 2;
            exit();
        } else {
            
            $refwake = mysql_fetch_array( $prov_ref );
            $referer = mysql_fetch_array( mysql_query( "SELECT username FROM user WHERE id = '" . $refwake['referer'] . "' LIMIT 1" ) );
            
            include_once ROOT_DIR . '/engine/classes/libmail.php'; # подключаем SMTP class
        
            $message = '
            <html>
            <head>
            <title>Информация ' . $config_site['sitename'] . '</title>
            <style type="text/css">
            html, body {
                margin:0;
                margin-left:5px;
                padding:0;
                font-size:12px;
            }
            p {
                margin:0;
                padding:3px;
            }
            </style>
            </head>
            <body>
            <p>Здравствуйте, <b>' . $refwake['username'] . '</b>.</p>
            <p>--------------------------------------------------------------------------</p>
            <p>Вы давно не посещали сайт <a href="http://' . $_SERVER["HTTP_HOST"] . '">' . $config_site['sitename'] . '</a>. За время Вашего отсутсвия произошли значительные изменения и улучшения. Ваш реферер <b>' . $referer['username'] . '</b>, просит вернуться Вас на проект.</p>
            <p>--------------------------------------------------------------------------</p>
            <p>Письмо отправлено автоматически. На него отвечать не нужно.</p>
            </body>
            </html>';
            
            $m = new Mail;
            $m->From( 'Администрация;' . $config_site['email'] ); # от кого отправляется почта 
            $m->To( $refwake['email'] ); # кому адресованно
            $m->Subject( 'Информация от реферера ' . $referer['username'] . ' c сайта ' . $_SERVER["HTTP_HOST"] );
            $m->Body( $message );    
            //$m->Cc( "copy@asd.com"); # копия письма отправится по этому адресу
            //$m->Bcc( "bcopy@asd.com"); # скрытая копия отправится по этому адресу
            $m->Priority( 3 ); # приоритет письма
            //$m->Attach( "asd.gif","", "image/gif" ) ; # прикрепленный файл 
            $m->smtp_on( $config_site['smtpemail'], $config_site['email'], $config_site['emailpass'], $config_site['portemail'] ); # если указана эта команда, отправка пойдет через SMTP 
            $m->Send(); # а теперь пошла отправка
            
            mysql_query( "UPDATE user SET adv_money = adv_money - 0.05 WHERE id = '" . $_SESSION['iduser'] . "'" );
            mysql_query( "UPDATE viruchka SET money = money + 0.05 WHERE ident = 6" );
            mysql_query( "UPDATE user SET wake = '" . time() . "' WHERE id = '" . $refwake['id'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    } else {
        exit();
    }
}

### Удаления реферера
if ( $_GET['func'] == 'delreferer' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['referer'] != ( int ) $_POST['id'] ) exit();
    
    $sql = mysql_fetch_array( mysql_query( "SELECT id, userdel FROM user WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" ) );
    
    if ( $sql['id'] == 0 ) exit();
    
    if ( $sql['userdel'] == 0 ) exit();
    
    mysql_query( "UPDATE user SET referer = 0 WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    mysql_query( "UPDATE user SET referals = referals - 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );
    echo 1;
    exit();
}

### Настройка приватности личные сообщения
if ( $_GET['func'] == 'messageaccess' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( ( int ) $_POST['type'] < 0 or ( int ) $_POST['type'] > 2 ) {
        exit();
    } else {
        mysql_query( "UPDATE user SET messblock = '" . ( int ) $_POST['type'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
        
        echo 1;
        exit();
    }
}

### Стать рефералом на стене
if ( $_GET['func'] == 'addreferer' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	if ( !$config_user['activate'] ) {
		exit();
	} else
    if ( $_SESSION['iduser'] == ( int ) $_POST['id'] ) {
        exit();
    } else
    if ( $config_user['referer'] != 0 ) {
        echo 'У вас уже есть реферер!';
		exit();
    } else {
        $sql = mysql_query( "SELECT autoback, userdel FROM user WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
        if ( mysql_num_rows( $sql ) > 0 ) {
            $row = mysql_fetch_array( $sql );
            
            if ( $row['userdel'] == 1 ) {
                echo 'Пользоатель удален!';
				exit();
            }
            
            mysql_query( "UPDATE user SET referer = '" . ( int ) $_POST['id'] . "', autoproc = '" . $row['autoback'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
            mysql_query( "UPDATE user SET referer2 = '" . ( int ) $_POST['id'] . "' WHERE referer = '" . $_SESSION['iduser'] . "' and id != '" . ( int ) $_POST['id'] . "'" );
            mysql_query( "UPDATE user SET referals = referals + 1, reyting = reyting + '" . $config['refreyting'] . "' WHERE id = '" . ( int ) $_POST['id'] . "'" );
			
			#Пишем событие в ленту пользователю
			mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Поздравляем у вас новый реферал " . $config_user['username'] . " пришел со стенки.', iduser = '" . ( int ) $_POST['id'] . "' " );
            
            echo 1;
            exit();
        } else {
            echo 'Нарушение алгоритма системы!!!';
			exit();
        }
    }
}

### Подарок на стенке
if ( $_GET['func'] == 'sendgift' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $sql = mysql_query( "SELECT id FROM user WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    if ( mysql_num_rows( $sql ) > 0 ) {
        
        $_POST['comms'] = trim( $_POST['comms'] );
        
        if ( ( int ) $_POST['id'] == $_SESSION['iduser'] ) {
            echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Зачем дарить самому себе подарки? Не страно ли?';
			exit();
        } else
        if ( $config_user['adv_money'] < $config['giftpay'] ) {
            echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> На рекламном счету недостаточно средств!';
			exit();
        } else
        if ( ( int ) $_POST['img'] <= 0 or ( int ) $_POST['img'] > 164 ) {
            echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Выберите подарок, который собераетесь подарить!';
			exit();
        } else
        if ( empty( $_POST['comms'] ) ) {
            echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Обязательно укажите комментарий к подарку, не ленитесь.';
			exit();
        } else {
            if ( $config_user['sex'] == 0 ) {
                $sex = 'Отправил';
            } else {
                $sex = 'Отправила';
            }
            
            mysql_query( "INSERT INTO gift SET to_user = '" . ( int ) $_POST['id'] . "', from_user = '" . $_SESSION['iduser'] . "', gift = '" . ( int ) $_POST['img'] . "', comms = '" . substr( check_text( $_POST['comms'] ), 0, 50 ) . "'" );
            mysql_query( "UPDATE user SET adv_money = adv_money - '" . $config['giftpay'] . "', reyting = reyting + '" . $config['giftreyting'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
			
			#Пишем событие в ленту пользователю
			mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Пользователь ".$config_user['username']." подарил вам подарок на стенке', iduser = '" . ( int ) $_POST['id'] . "' " );
            
            echo 1;
            exit();
        }
    } else {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Пользователь не найден!';
        exit();
    }
}

### Комментарий пользователю на стенке
if ( $_GET['func'] == 'addwallsmsg' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka_user = mysql_query( "SELECT id, referer, walls_message_access FROM user WHERE id = '" . ( int ) $_POST['id'] . "'" );
    
    if ( !$config_user['activate'] ) {
		exit();
	} else

	if ( mysql_num_rows( $proverka_user ) > 0 ) {
        
        $_POST['mess'] = trim( $_POST['mess'] );
        
        $row_user = mysql_fetch_array( $proverka_user );
        
        if ( $config_user['reyting'] < 10 ) {
            echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Для написания комментариев, Ваш рейтинг должен быть минимум 10';
			exit();
        }
        if ( $config_user['flood_walls'] == 1 ) {
            exit();
        } else
        if ( empty( $_POST['mess'] ) ) {
            echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Комментарий не может быть пустым! Напишите что нибудь!';
			exit();
        } else
        if ( $_POST['type'] != substr( md5( $message_md5 . $row_user['id'] ), 0, 22 ) ) {
            exit();
        } else
        if ( $row_user['walls_message_access'] == 2 ) {
            exit();
        } else
        if ( $row_user['walls_message_access'] == 1 and $config_user['referer'] != $row_user['id'] ) {
            exit();
        } else {
            
			$walls_mess = check_text( $_POST['mess'] );
            $walls_mess = parce_bb_code( $walls_mess, 'all' );
            $walls_mess = substr( $walls_mess, 0, 5000 );
            
            mysql_query( "INSERT INTO walls SET to_user = '" . ( int ) $_POST['id'] . "', from_user = '" . $_SESSION['iduser'] . "', message = '" . $walls_mess . "'" );
            #Пишем событие в ленту пользователю
			mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Пользователь ".$config_user['username']." написал новый комментарий на вашей стенке', iduser = '" . ( int ) $_POST['id'] . "' " );
			
            echo 1;
            exit();
        }
    } else {
        exit();
    }
}

### Поиск реферала
if ( $_GET['func'] == 'serchreferals' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $username = check_text( $_POST['username'] );
    $username = substr( $username, 0, 20 );
    
    $_POST['username'] = trim( $_POST['username'] );
    
    if ( strlen( check_text( $_POST['username'] ) ) < 2 ) {
        $json['ok'] = 2;
        print json_encode( $json );
        exit();
    }
    
    $get_ref1 = mysql_query( "SELECT * FROM user WHERE referer = '" . $_SESSION['iduser'] . "' and username LIKE '%$username%' LIMIT 100" );
    
	if ( mysql_num_rows( $get_ref1 ) > 0 ) {
        while ( $get_ref1_row = mysql_fetch_array( $get_ref1 ) ) {
            $ref_online = mysql_query( "SELECT id FROM online WHERE iduser = '" . $get_ref1_row['id'] . "'" );
			
			$month = array( 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря' );
            
            #Пол пользователя
			if ( $get_ref1_row['sex'] == 0 ) {
				$ref_sex = 'заходил';
			} else {
				$ref_sex = 'заходила';
			}
            
            #Дата последнего входа
			if ( $get_ref1_row['logindate'] == 0 ) {
				$ref_logindate = '<div class="ref-user-offline">еще не ' . $ref_sex . '</div>';
			} else
			if ( mysql_num_rows( $ref_online ) ) {
				$ref_logindate = '<div class="ref-user-online">онлайн</div>';
			} else
			if ( date( 'd.m.Y', $get_ref1_row['logindate'] ) == date( 'd.m.Y', time() ) ) {
				$ref_logindate = '<div class="ref-user-offline">сегодня в ' . date( 'H:i', $get_ref1_row['logindate'] ) . '</div>';
			} else {
				$ref_logindate = '<div class="ref-user-offline" >' . $ref_sex . ' ' . ( int ) date( 'd', $get_ref1_row['logindate'] ) . ' ' . $month[( int ) date( 'm', $get_ref1_row['logindate'] ) - 1] . ' ' . date( 'Y', $get_ref1_row['logindate'] ) . '</div>';
			}
            
            #Проверяем удален ли пользователь, если да, применяем нужные действия
			if ( $get_ref1_row['userdel'] == 1 ) {
				$btn_userdel = '<div class="referrals-while-dell" title="Данный пользователь был удален администрацией системы, за нарушения правил."><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Удален</div>';
				$get_ref1_row['avatar'] = 'del.png';
				$css_userdel = 'style="opacity: 0.5;"';
				$tags_user_dell = iconv( 'windows-1251', 'UTF-8', $btn_userdel );
			} else {
				$btn_userdel = '';
				$css_userdel = '';
				$tags_user_dell = '<div class="btn-group" style="margin-bottom: -3px;">
				  <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
					' . iconv( 'windows-1251', 'UTF-8', 'Опции' ) . '
				  </button>
				  <div class="dropdown-menu">
					<a class="dropdown-item" href="" onclick="function_ref.Info('.$get_ref1_row['id'].');return false;">' . iconv( 'windows-1251', 'UTF-8', 'Смотреть статистику' ) . '</a> 
					<a class="dropdown-item" href="" onclick="msg.showDialog('.$get_ref1_row['id'].', '.substr( md5( $message_md5 . $get_ref1_row['id'] ), 0, 22 ) .');return false;">' . iconv( 'windows-1251', 'UTF-8', 'Написать сообщение' ) . '</a>
					<a class="dropdown-item" href="id'.$get_ref1_row['id'].'">' . iconv( 'windows-1251', 'UTF-8', 'Перейти на стенку' ) . '</a>
					' . $fairUP . '
					<a class="dropdown-item" href="" onclick="function_ref.Refback('.$get_ref1_row['id'].'); return false;">' . iconv( 'windows-1251', 'UTF-8', 'Изменить рефбек' ) . '</a>  
					<a class="dropdown-item" href="" onclick="function_ref.Reward('.$get_ref1_row['id'].'); return false;">' . iconv( 'windows-1251', 'UTF-8', 'Вознаграждение' ) . '</a>  
					
					<a class="dropdown-item" href="" onclick="function_ref.Alert('.$get_ref1_row['id'].'); return false;">' . iconv( 'windows-1251', 'UTF-8', 'Удалить' ) . '</a> 
				  </div>
				</div>';
			}
            
            #Проверяем активирован ли аккаунт, если да то выводим галочку возле ника
			if ( $get_ref1_row['activate'] ) {
				$btn_act_ref1 = '<span class="user_activate" title="Аккаунт активирован"><i class="fa fa-check-circle-o" aria-hidden="true"></i></span>';
			} else {
				$btn_act_ref1 = '<span class="user_no_activate" title="Аккаунт не активирован, пользователь частично ограничен!"><i class="fa fa-times-circle-o" aria-hidden="true"></i></span>';
			}
			  
			#Проверяем прибыль и меняем цвет
			if( $get_ref1_row['toref'] > 0 ) {
				$ref_money_add = '<div class="referrals-while-toref-active">' . $get_ref1_row["toref"] . ' ' . $config["valutaname"] . '</div>';  
			} else {
				$ref_money_add = '<div class="referrals-while-toref">' . $get_ref1_row["toref"] . ' ' . $config["valutaname"] . '</div>';  
			}
			
			#Формируем кнопку ярмарки
			if($get_ref1_row['price'] == 0) { 
				$fairUPText = 'Продать на ярмарке'; 
			} else { 
				$fairUPText = 'Снять с продажи'; 
			}
			$fairUP = '<a class="dropdown-item" href="" onclick="function_ref.Fair('.$get_ref1_row['id'].'); return false;">' . iconv( 'windows-1251', 'UTF-8', $fairUPText ) . '</a> ';
			
			#Проверяем продается ли на ярмарке
			if($get_ref1_row['price'] == 0) {
				$btn_text_fair = 'Продать на ярмарке';  
				$icon_on_fair = '';  
			} else {
				$btn_text_fair = 'Снять с продажи'; 
				$icon_on_fair = iconv( 'windows-1251', 'UTF-8', '<div class="div_centralizator" ><div class="ref_fair_while_icon" title="Данный реферал выставлен на продажу на ярмарке."><i class="fa fa-gavel" aria-hidden="true"></i> '.$get_ref1_row["price"].'</div></div>' );
			}
            
            #Формируем ответ с результатами поиска
			$array = array( 'content' => '<tr class="wrap_ref" id="id'.$get_ref1_row['id'].'">
			  <td width="40" '.$css_userdel.'>
				<div class="referrals-avater">
				  <a href="/id'.$get_ref1_row['id'].'" >
					<img src="/temp/avatar/'.$get_ref1_row['avatar'].'" width="40" height="40" class="img-circle top-avatar" alt="" />
				  </a>
				</div>
			  </td>
			  <td width="150" '.$css_userdel.'>
				<div class="div_centralizator ">
				  <div class="referrals-while-username">' . iconv( 'windows-1251', 'UTF-8', $btn_act_ref1 ) . ' ' . iconv( 'windows-1251', 'UTF-8', $get_ref1_row['username'] ) . '</div>
				  <div class="">' . iconv( 'windows-1251', 'UTF-8', $ref_logindate ) . '</div>
				</div>
			  </td>
			  <td '.$css_userdel.'>
				<div class="div_centralizator" >
				  <div class="ref_bonus" title="' . iconv( 'windows-1251', 'UTF-8', 'Этому пользователю присвоен рефбек от вас' ) .' '.$get_ref1_row['autoproc'].'% ">'.$get_ref1_row['autoproc'].'% ' . iconv( 'windows-1251', 'UTF-8', 'бонуса' ) .'</div>
				</div>
			  </td>
			  <td '.$css_userdel.'>
				'.$icon_on_fair.'
			  </td>
			  <td width="85" '.$css_userdel.'>
				<div class="div_centralizator ">
				  ' . iconv( 'windows-1251', 'UTF-8', $ref_money_add ) . '
				</div>
			  </td>
			  <td width="80" class="top-symm" >
				<div class="referrals-while-opcion">
				   ' . $tags_user_dell . ' 
				</div>
			  </td>
			</tr>
			<script type="text/javascript">
			  var kolsearch = 0;
			  $(document).ready(function() {
				$(".user_activate").tipTip({defaultPosition:"right"});
				$(".user_no_activate").tipTip({defaultPosition:"right"});
				$(".ref_bonus").tipTip({defaultPosition:"right"});
				$(".referrals-while-dell").tipTip({defaultPosition:"right"});
				$(".ref_fair_while_icon").tipTip({defaultPosition:"right"});
			   });
			</script>' );
            
            $json['search'][] = $array;
            $json['ok'] = 1;
        }
    } else {
        $json['ok'] = 2;
    }
    print json_encode( $json );
    exit();
}

### Поиск пользователя на стене
if ( $_GET['func'] == 'searchuser' ) {
    
    $username = check_text( $_POST['username'] );
    $username = substr( $username, 0, 20 );
    
    $_POST['username'] = trim( $_POST['username'] );
    
    if ( strlen( check_text( $_POST['username'] ) ) < 2 ) {
        $json['ok'] = 2;
        print json_encode( $json );
        exit();
    }
    
    $sql = mysql_query( "SELECT id, username, avatar, logindate, sex FROM user WHERE username LIKE '%$username%' ORDER BY username ASC LIMIT 100" );
    
    if ( mysql_num_rows( $sql ) > 0 ) {
        while ( $row = mysql_fetch_array( $sql ) ) {
            
            $usonline = mysql_query( "SELECT id FROM online WHERE iduser = '" . $row['id'] . "'" );
            
            if ( $row['sex'] == 0 ) {
                $ref_sex = 'заходил';
            } else {
                $ref_sex = 'заходила';
            }
            
            if ( $row['logindate'] == 0 ) {
                $ref_logindate = 'еще не ' . $ref_sex;
            } else
            if ( mysql_num_rows( $usonline ) ) {
                $ref_logindate = 'онлайн';
            } else
            if ( date( 'd.m.Y', $row['logindate'] ) == date( 'd.m.Y', time() ) ) {
                $ref_logindate = 'сегодня в ' . date( 'H:i', $row['logindate'] );
            } else {
                $ref_logindate = $ref_sex . ' ' . date( 'd.m.Y', $row['logindate'] );
            }
            
            $array = array(
                'content' => '<div class="wrap_in_search"><div style="width: 30px; text-align: center; float: left;"><img src="/temp/avatar/' . $row['avatar'] . '" width="30" height="30" class="avatarWallSearch" /></div><a href="/id' . $row['id'] . '" class="a_box a_search" >' . iconv( 'windows-1251', 'UTF-8', $row['username'] ) . '</a><span class="user_search_time">' . iconv( 'windows-1251', 'UTF-8', $ref_logindate ) . '</span></div>'
            );
            
            $json['search'][] = $array;
        }
        $json['ok'] = 1;
    } else {
        $json['ok'] = 2;
    }
    print json_encode( $json );
    exit();
}

### Удаление сообщений на стене
if ( $_GET['func'] == 'delwallsmsg' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $sql = mysql_query( "SELECT id FROM walls WHERE to_user = '" . $_SESSION['iduser'] . "' and id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    $sql_adm = mysql_query( "SELECT to_user FROM walls WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    if ( $config_user['account'] == 5 ) {
        $rows = mysql_fetch_array( $sql_adm );
		mysql_query( "DELETE FROM walls WHERE id = '" . ( int ) $_POST['id'] . "'" );
        mysql_query( "DELETE FROM likes WHERE id_comment = '" . ( int ) $_POST['id'] . "'" );
		#Пишем событие в ленту пользователю
		mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Администратор удалил комментарий на вашей стенке', iduser = '" . $rows['to_user'] . "' " );
		echo 1;
        exit();
    } else
    if ( mysql_num_rows( $sql ) > 0 ) {
        $row = mysql_fetch_array( $sql );
        mysql_query( "DELETE FROM walls WHERE id = '" . ( int ) $_POST['id'] . "'" );
        mysql_query( "DELETE FROM likes WHERE id_comment = '" . ( int ) $_POST['id'] . "'" );
		echo 1;
        exit();
    } else {
        exit();
    }
}

### Вознаграждение рефералу
if ( $_GET['func'] == 'rewardsend' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте ваш аккаунт!';
		exit();
	} else
	if ( floatval( $_POST['reward'] ) < 0.01 ) {
        echo 'Минимальная сумма вознаграждения - 0.01 ' . $config['valutaname'] . '!';
        exit();
    }
	if ( moneyraund( floatval( $_POST['reward'] ), 2 ) < 0.01 ) {
        echo 'Минимальная сумма вознаграждения - 0.01 ' . $config['valutaname'] . '!';
        exit();
    }
    if ( !is_numeric( $_POST['reward'] ) ) {
        echo 'Неверная сумма вознаграждения!';
        exit();
    }
    if ( $config_user['adv_money'] < floatval( $_POST['reward'] ) ) {
        echo 'На вашем рекламном балансе недостаточно средств!';
        exit();
    }
    $sql_user = mysql_query( "SELECT id FROM user WHERE id = '" . ( int ) $_POST['id'] . "' and referer = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( mysql_num_rows( $sql_user ) > 0 ) {
        mysql_query( "UPDATE user SET money = money + '" . moneyraund( floatval( $_POST['reward'] ), 2 ) . "' WHERE id = '" . ( int ) $_POST['id'] . "' and referer = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "UPDATE user SET adv_money = adv_money - '" . moneyraund( floatval( $_POST['reward'] ), 2 ) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . ( int ) $_POST['id'] . "', text = 'Вы получили вознаграждение в размере <b>" . moneyraund( floatval( $_POST['reward'] ), 2 ) . "' '" . $config['valutaname'] . "</b>', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . ( int ) $_POST['id'] . "', text = 'Вы получили вознаграждение в размере <b>" . moneyraund( floatval( $_POST['reward'] ), 2 ) . "' '" . $config['valutaname'] . "</b>', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . ( int ) $_POST['id'] . "'" );
        
        echo 1;
        exit();
    } else {
        echo 'Пользователь не найден или не являеться вашим рефералом';
        exit();
    }
}

### Добавления на стену рефереров
if ( $_GET['func'] == 'addwallsref' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $ch_wallsRef = mysql_query( "SELECT id FROM wallsref WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте аккаунт!';
		exit();
	} else
    if ( mysql_num_rows( $ch_wallsRef ) > 0 ) {
        echo 'Вы уже размещены на стене рефереров!';
        exit();
    } else
    if ( !preg_match( '/^[-+]?[\d]+[\.][\d]{1,2}+$|^[-+]?[\d]+$/', $_POST['stavka'] ) ) {
        echo 'Неверная сумма ставки!';
        exit();
    } else
    if ( floatval( $_POST['stavka'] ) < 0.02 ) {
        echo 'Минимальная ставка 0.02!';
        exit();
    } else
    if ( floatval( $_POST['stavka'] ) + 1 > $config_user['adv_money'] ) {
        echo 'На Вашем рекламном счету недостаточно средств!';
        exit();
    } else {
        mysql_query( "UPDATE user SET adv_money = adv_money - 1 WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "INSERT INTO wallsref SET iduser = '" . $_SESSION['iduser'] . "', stavka = '" . floatval( $_POST['stavka'] ) . "'" );
        mysql_query( "UPDATE viruchka SET money = money + 1 WHERE ident = 13 LIMIT 1" );
        echo 1;
        exit();
    }
    
}

### Стать рефералом на стене рефереров
if ( $_GET['func'] == 'wallsrefererbuy' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['referer'] != 0 ) {
        echo 'У Вас уже есть реферер!';
        exit();
    }
    
    $ch_wallsRef = mysql_query( "SELECT iduser, stavka FROM wallsref WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    if ( mysql_num_rows( $ch_wallsRef ) > 0 ) {
        $ch_wallRefRow = mysql_fetch_array( $ch_wallsRef );
        $st_user = mysql_fetch_array( mysql_query( "SELECT adv_money, autoback FROM user WHERE id = '" . $ch_wallRefRow['iduser'] . "' LIMIT 1" ) );
        if ( !$config_user['activate'] ) {
			echo 'Для продолжения активируйте аккаунт!';
			exit();
		} else
		if ( $ch_wallRefRow['stavka'] > $st_user['adv_money'] ) {
            echo 'Недостаточно средств!';
            exit();
        } else
        if ( $config_user['id'] == $ch_wallRefRow['iduser'] ) {
            echo 'Вы не можете быть себе реферером!';
            exit();
        } else {
            mysql_query( "UPDATE user SET referer = '" . $ch_wallRefRow['iduser'] . "', autoproc = '" . $st_user['autoback'] . "', money = money + '" . $ch_wallRefRow['stavka'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
            mysql_query( "UPDATE user SET referer2 = '" . $ch_wallRefRow['iduser'] . "' WHERE referer = '" . $_SESSION['iduser'] . "' and id != '" . $ch_wallRefRow['iduser'] . "'" );
            mysql_query( "UPDATE user SET referals = referals + 1, adv_money = adv_money - '" . $ch_wallRefRow['stavka'] . "' WHERE id = '" . $ch_wallRefRow['iduser'] . "'" );
            echo 1;
            exit();
        }
    } else {
        echo 'Реферер не найден!';
        exit();
    }
}

### Изменение ставки на стене рефереров
if ( $_GET['func'] == 'savestavka' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $pr_wr = mysql_query( "SELECT id FROM wallsref WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( !preg_match( '/^[-+]?[\d]+[\.][\d]{1,2}+$|^[-+]?[\d]+$/', $_POST['stavka'] ) ) {
        echo 'Неверная сумма ставки!';
        exit();
    } else
    if ( floatval( $_POST['stavka'] ) < 0.02 ) {
        echo 'Минимальная ставка 0.02!';
        exit();
    } else
    if ( floatval( $_POST['stavka'] ) > $config_user['adv_money'] ) {
        echo 'На Вашем рекламном счету недостаточно средств!';
        exit();
    } else
    if ( mysql_num_rows( $pr_wr ) == 0 ) {
        echo 'Вы не размещены на стене рефереров!';
        exit();
    } else {
        mysql_query( "UPDATE wallsref SET stavka = '" . floatval( $_POST['stavka'] ) . "' WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        echo 1;
        exit();
    }
}

### Удаление со стены рефереров
if ( $_GET['func'] == 'sendwallsrefererdel' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $ch_del = mysql_query( "SELECT id FROM wallsref WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( mysql_fetch_array( $ch_del ) > 0 ) {
        mysql_query( "DELETE from wallsref WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        echo 1;
        exit();
    } else {
        echo 'Произошла ошибка!';
        exit();
    }
    
}

### Заказ динамических ссылок с сессией авторизации
if ( $_GET['func'] == 'adddyn' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else
    if ( !is_numeric( $_POST['timer'] ) ) {
        echo 'Вы не выбрали время просмотра!';
        exit();
    } else
    if ( !is_numeric( $_POST['obper'] ) ) {
        echo 'Вы не выбрали последующий переход!';
        exit();
    } else
    if ( !is_numeric( $_POST['active_window'] ) ) {
        echo 'Вы не выбрали параметр активного окна!';
        exit();
    } else
    if ( !is_numeric( $_POST['vip'] ) ) {
        echo 'Вы не выбрали статус ссылки!';
        exit();
    } else
    if ( ( int ) $_POST['timer'] != 0 and ( int ) $_POST['timer'] != 1 and ( int ) $_POST['timer'] != 2 and ( int ) $_POST['timer'] != 3 and ( int ) $_POST['timer'] != 4 and ( int ) $_POST['timer'] != 5 and ( int ) $_POST['timer'] != 6 and ( int ) $_POST['timer'] != 7 and ( int ) $_POST['timer'] != 8 and ( int ) $_POST['timer'] != 9 and ( int ) $_POST['timer'] != 10 and ( int ) $_POST['timer'] != 11 and ( int ) $_POST['timer'] != 12 and ( int ) $_POST['timer'] != 13 and ( int ) $_POST['timer'] != 14 ) {
        echo 'Неверный параметр таймера!';
        exit();
    } else
    if ( ( int ) $_POST['obper'] != 0 and ( int ) $_POST['obper'] != 1 ) {
        echo 'Неверный параметр последующего перехода!';
        exit();
    } else
    if ( ( int ) $_POST['vip'] != 0 and ( int ) $_POST['vip'] != 1 ) {
        echo 'Неверный параметр статуса ссылки!';
        exit();
    } else 
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
            
        $getframe = check_frame( $_POST['url'] );
        
        if ( $getframe == 'no' ) {
            echo 'Сайт разрушает фрейм!';
            exit();
        } else {
            if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
                $_POST['url'] = 'http://' . check_text( $_POST['url'] );
            }
            
            if ( $_POST['erotic'] == 'on' ) {
                $erotic = 1;
            } else {
                $erotic = 0;
            }
            
            if ( $_POST['freeid'] == 'on' ) {
                $freeid = 1;
            } else {
                $freeid = 0;
            }
            
            if ( $_POST['serf_plus'] == 'on' ) {
                $serf_plus = 1;
            } else {
                $serf_plus = 0;
            }
            
            mysql_query( "INSERT INTO dynlink (iduser, title, description, url, timer, obper, active_window, vip, freeid, erotic, plus, date, geo_ru, geo_ua, geo_by, geo_kz, geo_ge, geo_md, geo_am, geo_tj, geo_az, geo_uz, geo_pt, geo_es, geo_ee, geo_lv, geo_lt, geo_us, geo_gb, geo_fr, geo_de, geo_cn, geo_it, geo_all) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . ( int ) $_POST['timer'] . "', '" . ( int ) $_POST['obper'] . "', '" . ( int ) $_POST['active_window'] . "', '" . ( int ) $_POST['vip'] . "', '" . $freeid . "', '" . $erotic . "', '" . $serf_plus . "', '" . time() . "', '" . $geo_ru . "', '" . $geo_ua . "', '" . $geo_by . "', '" . $geo_kz . "', '" . $geo_ge . "', '" . $geo_md . "', '" . $geo_am . "', '" . $geo_tj . "', '" . $geo_az . "', '" . $geo_uz . "', '" . $geo_pt . "', '" . $geo_es . "', '" . $geo_ee . "', '" . $geo_lv . "', '" . $geo_lt . "', '" . $geo_us . "', '" . $geo_gb . "', '" . $geo_fr . "', '" . $geo_de . "', '" . $geo_cn . "', '" . $geo_it . "', '" . $geo_all . "')" );

            echo 1;
            exit();
        }
    }
}

### Заказ динамических ссылок без сессии авторизации
if ( $_GET['func'] == 'adddyn_nouser' ) {
    
    sleep(1);
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
	$check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	$check_bt_order = mysql_query( "SELECT nouser_order FROM dynlink WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	if ( mysql_num_rows( $check_bt_order ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( mysql_num_rows( $check_order_basket ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else
    if ( !is_numeric( $_POST['timer'] ) ) {
        echo 'Вы не выбрали время просмотра!';
        exit();
    } else
    if ( !is_numeric( $_POST['obper'] ) ) {
        echo 'Вы не выбрали последующий переход!';
        exit();
    } else
    if ( !is_numeric( $_POST['active_window'] ) ) {
        echo 'Вы не выбрали параметр активного окна!';
        exit();
    } else
    if ( !is_numeric( $_POST['vip'] ) ) {
        echo 'Вы не выбрали статус ссылки!';
        exit();
    } else
    if ( ( int ) $_POST['timer'] != 0 and ( int ) $_POST['timer'] != 1 and ( int ) $_POST['timer'] != 2 and ( int ) $_POST['timer'] != 3 and ( int ) $_POST['timer'] != 4 and ( int ) $_POST['timer'] != 5 and ( int ) $_POST['timer'] != 6 and ( int ) $_POST['timer'] != 7 and ( int ) $_POST['timer'] != 8 and ( int ) $_POST['timer'] != 9 and ( int ) $_POST['timer'] != 10 and ( int ) $_POST['timer'] != 11 and ( int ) $_POST['timer'] != 12 and ( int ) $_POST['timer'] != 13 and ( int ) $_POST['timer'] != 14 ) {
        echo 'Неверный параметр таймера!';
        exit();
    } else
    if ( ( int ) $_POST['obper'] != 0 and ( int ) $_POST['obper'] != 1 ) {
        echo 'Неверный параметр последующего перехода!';
        exit();
    } else
    if ( ( int ) $_POST['vip'] != 0 and ( int ) $_POST['vip'] != 1 ) {
        echo 'Неверный параметр статуса ссылки!';
        exit();
    } else 
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
            
        $getframe = check_frame( $_POST['url'] );
        
        if ( $getframe == 'no' ) {
            echo 'Сайт разрушает фрейм!';
            exit();
        } else {
            if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
              $_POST['url'] = 'http://' . check_text( $_POST['url'] );
            }
            
            if ( $_POST['erotic'] == 'on' ) {
              $erotic = 1;
            } else {
              $erotic = 0;
            }
            
            if ( $_POST['freeid'] == 'on' ) {
              $freeid = 1;
            } else {
              $freeid = 0;
            }
            
            if ( $_POST['serf_plus'] == 'on' ) {
              $serf_plus = 1;
            } else {
              $serf_plus = 0;
            }
			
			#Формируем цену заказа
			switch ( ( int ) $_POST['timer'] ) {
			  case 0:
                $time_price = $config['dyn10'];  
                break;
			  case 1:
                $time_price = $config['dyn20'];  
                break;
			  case 2:
                $time_price = $config['dyn30'];  
                break;
			  case 3:
                $time_price = $config['dyn40'];  
                break;
			  case 4:
                $time_price = $config['dyn50'];  
                break;
			  case 5:
                $time_price = $config['dyn60'];  
                break;
			  case 6:
                $time_price = $config['dyn70'];  
                break;
			  case 7:
                $time_price = $config['dyn80'];  
                break;
			  case 8:
                $time_price = $config['dyn90'];  
                break;
			  case 9:
                $time_price = $config['dyn100'];  
                break;
			  case 10:
                $time_price = $config['dyn125'];  
                break;
			  case 11:
                $time_price = $config['dyn150'];  
                break;
			  case 12:
                $time_price = $config['dyn200'];  
                break;
			  case 13:
                $time_price = $config['dyn250'];  
                break;
			  case 14:
                $time_price = $config['dyn300'];  
                break;	
			}
			
			if ( $_POST['obper'] == 1 ) {
			  $check_price_1 = $config['obper'];	
			} 
			if ( $_POST['active_window'] == 1 ) {
			  $check_price_2 = $config['active_window'];
			} 
			if ( $_POST['vip'] == 1 ) {
			  $check_price_3 = $config['vipdyn'];
			}
			
			$quantity = ( int ) $_POST['quantity'];
			$quantity_summ = (($time_price + $check_price_1 + $check_price_2 + $check_price_3) * $quantity);
			
			#Создаем счет в корзину на оплату заказа
			if ( $quantity < 100 OR $quantity >= 100000 ) {
			  echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 100, максимальное 100000.';
			  exit();
			} else {
			
			  #Делаем запрос на создание площадки
			  mysql_query( "INSERT INTO dynlink 
			   (iduser, title, description, url, timer, obper, active_window, vip, freeid, erotic, plus, date, geo_ru, geo_ua, geo_by, geo_kz, geo_ge, geo_md, geo_am, geo_tj, geo_az, geo_uz, geo_pt, geo_es, geo_ee, geo_lv, geo_lt, geo_us, geo_gb, geo_fr, geo_de, geo_cn, geo_it, geo_all, nouser, nouser_order ) VALUES ( '0', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . ( int ) $_POST['timer'] . "', '" . ( int ) $_POST['obper'] . "', '" . ( int ) $_POST['active_window'] . "', '" . ( int ) $_POST['vip'] . "', '" . $freeid . "', '" . $erotic . "', '" . $serf_plus . "', '" . time() . "', '" . $geo_ru . "', '" . $geo_ua . "', '" . $geo_by . "', '" . $geo_kz . "', '" . $geo_ge . "', '" . $geo_md . "', '" . $geo_am . "', '" . $geo_tj . "', '" . $geo_az . "', '" . $geo_uz . "', '" . $geo_pt . "', '" . $geo_es . "', '" . $geo_ee . "', '" . $geo_lv . "', '" . $geo_lt . "', '" . $geo_us . "', '" . $geo_gb . "', '" . $geo_fr . "', '" . $geo_de . "', '" . $geo_cn . "', '" . $geo_it . "', '" . $geo_all . "', '1', '" . ( int ) $_POST['bt_order'] . "' )" );
			  
			  #Делаем запрос на создание счета для оплаты площадки
			  mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '0', '" . ( int ) $_POST['bt_order'] . "')" );
				
			  echo 1;
			  exit();
			  
			}
		}
    }
}

### Редактирование динамических ссылок
if ( $_GET['func'] == 'updyn' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_num_rows(mysql_query( "SELECT id FROM dynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    
	$proverka_aray = mysql_query( "SELECT * FROM dynlink WHERE iduser = '" . $_SESSION['iduser'] . "' and id = '" . ( int ) $_POST['id'] . "'" );
    $proverka_aray_row = mysql_fetch_array( $proverka_aray );
	
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
	#Проверяем какого типа площадка, платная или тест драйв, true равен тест драйв
    if ( $proverka_aray_row['testdrive'] == 1 ) {
		if ( $proverka == 0 ) {
			echo 'Рекламная площадка не существует или не принадлежит Вам!';
			exit();
		} else    
		
		if ( empty( $_POST['title'] ) ) {
			echo 2;
			exit(); 
		} else
		if ( empty( $_POST['description'] ) ) {
			echo 3;
			exit();
		} else
		if ( empty( $_POST['url'] ) ) {
			echo 4;
			exit();
		} else
		
		if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
			echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
			exit();	
		} else {
			if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
				$_POST['url'] = 'http://' . check_text( $_POST['url'] );
			}
        
			#Проверка на блокировку
			$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
			if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
			$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
			if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
				$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
				echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
				exit();
			}
            
			$getframe = check_frame( $_POST['url'] );
        
			if ( $getframe == 'no' ) {
				echo 'Сайт разрушает фрейм!';
				exit();
			} else {
				if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
					$_POST['url'] = 'http://' . check_text( $_POST['url'] );
				}
            
				if ( $_POST['erotic'] == 'on' ) {
					$erotic = 1;
				} else {
					$erotic = 0;
				}
            
				if ( $_POST['freeid'] == 'on' ) {
					$freeid = 1;
				} else {
					$freeid = 0;
				}
            
				mysql_query( "UPDATE dynlink SET title = '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', description = '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', freeid = '" . $freeid . "', erotic = '" . $erotic . "', geo_ru = '" . $geo_ru . "', geo_ua = '" . $geo_ua . "', geo_by = '" . $geo_by . "', geo_kz = '" . $geo_kz . "', geo_ge = '" . $geo_ge . "', geo_md = '" . $geo_md . "', geo_am = '" . $geo_am . "', geo_tj = '" . $geo_tj . "', geo_az = '" . $geo_az . "', geo_uz = '" . $geo_uz . "', geo_pt = '" . $geo_pt . "', geo_es = '" . $geo_es . "', geo_ee = '" . $geo_ee . "', geo_lv = '" . $geo_lv . "', geo_lt = '" . $geo_lt . "', geo_us = '" . $geo_us . "', geo_gb = '" . $geo_gb . "', geo_fr = '" . $geo_fr . "', geo_de = '" . $geo_de . "', geo_cn = '" . $geo_cn . "', geo_it = '" . $geo_it . "', geo_all = '" . $geo_all . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );

				echo 1;
				exit();
			}
		}
	} else {
		if ( $proverka == 0 ) {
			echo 'Рекламная площадка не существует или не принадлежит Вам!';
			exit();
		} else    
		if ( empty( $_POST['title'] ) ) {
			echo 2;
			exit(); 
		} else
		if ( empty( $_POST['description'] ) ) {
			echo 3;
			exit();
		} else
		if ( empty( $_POST['url'] ) ) {
			echo 4;
			exit();
		} else
		if ( !is_numeric( $_POST['timer'] ) ) {
			echo 'Вы не выбрали время просмотра!';
			exit();
		} else
		if ( !is_numeric( $_POST['obper'] ) ) {
			echo 'Вы не выбрали последующий переход!';
			exit();
		} else
		if ( !is_numeric( $_POST['active_window'] ) ) {
			echo 'Вы не выбрали параметр активного окна!';
			exit();
		} else
		if ( !is_numeric( $_POST['vip'] ) ) {
			echo 'Вы не выбрали статус ссылки!';
			exit();
		} else
		if ( ( int ) $_POST['timer'] != 0 and ( int ) $_POST['timer'] != 1 and ( int ) $_POST['timer'] != 2 and ( int ) $_POST['timer'] != 3 and ( int ) $_POST['timer'] != 4 and ( int ) $_POST['timer'] != 5 and ( int ) $_POST['timer'] != 6 and ( int ) $_POST['timer'] != 7 and ( int ) $_POST['timer'] != 8 and ( int ) $_POST['timer'] != 9 and ( int ) $_POST['timer'] != 10 and ( int ) $_POST['timer'] != 11 and ( int ) $_POST['timer'] != 12 and ( int ) $_POST['timer'] != 13 and ( int ) $_POST['timer'] != 14 ) {
			echo 'Неверный параметр таймера!';
			exit();
		} else
		if ( ( int ) $_POST['obper'] != 0 and ( int ) $_POST['obper'] != 1 ) {
			echo 'Неверный параметр последующего перехода!';
			exit();
		} else
		if ( ( int ) $_POST['active_window'] != 0 and ( int ) $_POST['active_window'] != 1 ) {
			echo 'Неверный параметр активного окна!';
			exit();
		} else
		if ( ( int ) $_POST['vip'] != 0 and ( int ) $_POST['vip'] != 1 ) {
			echo 'Неверный параметр статуса ссылки!';
			exit();
		} else 
		if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
			echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
			exit();	
		} else {
			if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
				$_POST['url'] = 'http://' . check_text( $_POST['url'] );
			}
        
			#Проверка на блокировку
			$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
			if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
			$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
			if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
				$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
				echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
				exit();
			}
            
			$getframe = check_frame( $_POST['url'] );
        
			if ( $getframe == 'no' ) {
				echo 'Сайт разрушает фрейм!';
				exit();
			} else        
			if ( $_POST['erotic'] == 'on' ) {
				$erotic = 1;
			} else {
				$erotic = 0;
			}
		
			if ( $_POST['freeid'] == 'on' ) {
				$freeid = 1;
			} else {
				$freeid = 0;
			}
		
			mysql_query( "UPDATE dynlink SET title = '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', description = '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', timer = '" . ( int ) $_POST['timer'] . "', obper = '" . ( int ) $_POST['obper'] . "', active_window = '" . ( int ) $_POST['active_window'] . "', vip = '" . ( int ) $_POST['vip'] . "', freeid = '" . $freeid . "', erotic = '" . $erotic . "', geo_ru = '" . $geo_ru . "', geo_ua = '" . $geo_ua . "', geo_by = '" . $geo_by . "', geo_kz = '" . $geo_kz . "', geo_ge = '" . $geo_ge . "', geo_md = '" . $geo_md . "', geo_am = '" . $geo_am . "', geo_tj = '" . $geo_tj . "', geo_az = '" . $geo_az . "', geo_uz = '" . $geo_uz . "', geo_pt = '" . $geo_pt . "', geo_es = '" . $geo_es . "', geo_ee = '" . $geo_ee . "', geo_lv = '" . $geo_lv . "', geo_lt = '" . $geo_lt . "', geo_us = '" . $geo_us . "', geo_gb = '" . $geo_gb . "', geo_fr = '" . $geo_fr . "', geo_de = '" . $geo_de . "', geo_cn = '" . $geo_cn . "', geo_it = '" . $geo_it . "', geo_all = '" . $geo_all . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );

			echo 1;
			exit();
		}
	}
}

### Удаление динамических ссылок
if ( $_GET['func'] == 'deldyn' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, date, timer, obper, vip FROM dynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        switch ( $pr_row['timer'] ) {
            case 0: $timer = 'dyn10'; break;
            case 1: $timer = 'dyn20'; break;
            case 2: $timer = 'dyn30'; break;
            case 3: $timer = 'dyn40'; break;
            case 4: $timer = 'dyn50'; break;
            case 5: $timer = 'dyn60'; break;
        }
        
        if ( $pr_row['balance'] > $pr_row['obper'] * $config['obper'] + $pr_row['vip'] * $config['vipdyn'] + $config[$timer] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM dynlink_temp WHERE ident = '" . ( int ) $_POST['id'] . "'" );
        mysql_query( "DELETE FROM dynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 0" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение динамических ссылок
if ( $_GET['func'] == 'rundyn' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, timer, obper, vip, paused, testdrive FROM dynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
		
		$pr_row = mysql_fetch_array( $proverka );
		
		if($pr_row['testdrive'] == 1) {
			if ( $pr_row['paused'] == 1 ) {
				$paused = 0;
			} else {
				$paused = 1;
			}
            
			mysql_query( "UPDATE dynlink SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
            
			echo 1;
			exit();
			
		} else {
		
			switch ( $pr_row['timer'] ) {
				case 0: $timer = 'dyn10'; break;
				case 1: $timer = 'dyn20'; break;
				case 2: $timer = 'dyn30'; break;
				case 3: $timer = 'dyn40'; break;
				case 4: $timer = 'dyn50'; break;
				case 5: $timer = 'dyn60'; break;
			}
                
			if ( ( $pr_row['obper'] * $config['obper'] + $pr_row['vip'] * $config['vipdyn'] + $config[$timer] ) > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
				echo 'Недостаточно средств на балансе рекламной площадки!';
				exit();
			} else {
				if ( $pr_row['paused'] == 1 ) {
					$paused = 0;
				} else {
					$paused = 1;
				}
            
				mysql_query( "UPDATE dynlink SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
            
				echo 1;
				exit();
			}
    
		}
	
	}
}

### Заказ авто-серфинг ссылок
if ( $_GET['func'] == 'addautodyn' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else
    if ( !is_numeric( $_POST['timer'] ) ) {
        echo 'Вы не выбрали время просмотра!';
        exit();
    } else
    if ( ( int ) $_POST['timer'] != 0 and ( int ) $_POST['timer'] != 1 and ( int ) $_POST['timer'] != 2 and ( int ) $_POST['timer'] != 3 and ( int ) $_POST['timer'] != 4 and ( int ) $_POST['timer'] != 5 ) {
        echo 'Неверный параметр таймера!';
        exit();
    } else
    if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
            
        $getframe = check_frame( $_POST['url'] );
        
        if ( $getframe == 'no' ) {
            echo 'Сайт разрушает фрейм!';
            exit();
        } else {
            if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
                $_POST['url'] = 'http://' . check_text( $_POST['url'] );
            }
            
            if ( $_POST['freeid'] == 'on' ) {
                $freeid = 1;
            } else {
                $freeid = 0;
            }
            
            mysql_query( "INSERT INTO autodynlink ( iduser, title, url, timer, freeid, date, geo_ru, geo_ua, geo_by, geo_kz, geo_ge, geo_md, geo_am, geo_tj, geo_az, geo_uz, geo_pt, geo_es, geo_ee, geo_lv, geo_lt, geo_us, geo_gb, geo_fr, geo_de, geo_cn, geo_it, geo_all ) VALUES ( '" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . ( int ) $_POST['timer'] . "', '" . $freeid . "', '" . time() . "', '" . $geo_ru . "', '" . $geo_ua . "', '" . $geo_by . "', '" . $geo_kz . "', '" . $geo_ge . "', '" . $geo_md . "', '" . $geo_am . "', '" . $geo_tj . "', '" . $geo_az . "', '" . $geo_uz . "', '" . $geo_pt . "', '" . $geo_es . "', '" . $geo_ee . "', '" . $geo_lv . "', '" . $geo_lt . "', '" . $geo_us . "', '" . $geo_gb . "', '" . $geo_fr . "', '" . $geo_de . "', '" . $geo_cn . "', '" . $geo_it . "', '" . $geo_all . "') " );

            echo 1;
            exit();
        }
    }
}

### Заказ авто-серфинг ссылок без сессии авторизации
if ( $_GET['func'] == 'addautodyn_nouser' ) {
    
    sleep(1);
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
	$check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	$check_bt_order = mysql_query( "SELECT nouser_order FROM autodynlink WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	if ( mysql_num_rows( $check_bt_order ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( mysql_num_rows( $check_order_basket ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else
    if ( !is_numeric( $_POST['timer'] ) ) {
        echo 'Вы не выбрали время просмотра!';
        exit();
    } else
    if ( ( int ) $_POST['timer'] != 0 and ( int ) $_POST['timer'] != 1 and ( int ) $_POST['timer'] != 2 and ( int ) $_POST['timer'] != 3 and ( int ) $_POST['timer'] != 4 and ( int ) $_POST['timer'] != 5 ) {
        echo 'Неверный параметр таймера!';
        exit();
    } else
    if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
            
        $getframe = check_frame( $_POST['url'] );
        
        if ( $getframe == 'no' ) {
            echo 'Сайт разрушает фрейм!';
            exit();
        } else {
            if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
              $_POST['url'] = 'http://' . check_text( $_POST['url'] );
            }
            
            if ( $_POST['freeid'] == 'on' ) {
              $freeid = 1;
            } else {
              $freeid = 0;
            }
			
			#Формируем цену заказа
			switch ( ( int ) $_POST['timer'] ) {
			  case 0:
                $time_price = $config['autodyn10'];  
                break;
			  case 1:
                $time_price = $config['autodyn20'];  
                break;
			  case 2:
                $time_price = $config['autodyn30'];  
                break;
			  case 3:
                $time_price = $config['autodyn40'];  
                break;
			  case 4:
                $time_price = $config['autodyn50'];  
                break;
			  case 5:
                $time_price = $config['autodyn60'];  
                break;	
			}
			
			$quantity = ( int ) $_POST['quantity'];
			$quantity_summ = ($time_price * $quantity);
			
			#Создаем счет в корзину на оплату заказа
			if ( $quantity < 100 OR $quantity >= 100000 ) {
			  echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 100, максимальное 100000.';
			  exit();
			} else {
            
              mysql_query( "INSERT INTO autodynlink ( iduser, title, url, timer, freeid, date, geo_ru, geo_ua, geo_by, geo_kz, geo_ge, geo_md, geo_am, geo_tj, geo_az, geo_uz, geo_pt, geo_es, geo_ee, geo_lv, geo_lt, geo_us, geo_gb, geo_fr, geo_de, geo_cn, geo_it, geo_all, nouser, nouser_order ) VALUES ( '" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . ( int ) $_POST['timer'] . "', '" . $freeid . "', '" . time() . "', '" . $geo_ru . "', '" . $geo_ua . "', '" . $geo_by . "', '" . $geo_kz . "', '" . $geo_ge . "', '" . $geo_md . "', '" . $geo_am . "', '" . $geo_tj . "', '" . $geo_az . "', '" . $geo_uz . "', '" . $geo_pt . "', '" . $geo_es . "', '" . $geo_ee . "', '" . $geo_lv . "', '" . $geo_lt . "', '" . $geo_us . "', '" . $geo_gb . "', '" . $geo_fr . "', '" . $geo_de . "', '" . $geo_cn . "', '" . $geo_it . "', '" . $geo_all . "', '1', '" . ( int ) $_POST['bt_order'] . "') " );
			  
			  #Делаем запрос на создание счета для оплаты площадки
			  mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '16', '" . ( int ) $_POST['bt_order'] . "')" );

              echo 1;
              exit();
			
			}
			
        }
    }
}

### Редактирование авто-серфинг ссылок
if ( $_GET['func'] == 'upautodyn' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_num_rows(mysql_query( "SELECT id FROM autodynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    
	$proverka_aray = mysql_query( "SELECT * FROM autodynlink WHERE iduser = '" . $_SESSION['iduser'] . "' and id = '" . ( int ) $_POST['id'] . "'" );
    $proverka_aray_row = mysql_fetch_array( $proverka_aray );
	
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
	if ( $proverka == 0 ) {
		echo 'Рекламная площадка не существует или не принадлежит Вам!';
		exit();
	} else    
	if ( empty( $_POST['title'] ) ) {
		echo 2;
		exit();
	} else
	
	if ( empty( $_POST['url'] ) ) {
		echo 3;
		exit();
	} else
	if ( !is_numeric( $_POST['timer'] ) ) {
		echo 'Вы не выбрали время просмотра!';
		exit();
	} else
	if ( ( int ) $_POST['timer'] != 0 and ( int ) $_POST['timer'] != 1 and ( int ) $_POST['timer'] != 2 and ( int ) $_POST['timer'] != 3 and ( int ) $_POST['timer'] != 4 and ( int ) $_POST['timer'] != 5 ) {
		echo 'Неверный параметр таймера!';
		exit();
	} else
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
		exit();	
	} else {
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
			$_POST['url'] = 'http://' . check_text( $_POST['url'] );
		}
	
		#Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
			$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
			echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
			exit();
		}
		
		$getframe = check_frame( $_POST['url'] );
	
		if ( $getframe == 'no' ) {
			echo 'Сайт разрушает фрейм!';
			exit();
		} else {
			if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
				$_POST['url'] = 'http://' . check_text( $_POST['url'] );
			}
		
			if ( $_POST['freeid'] == 'on' ) {
				$freeid = 1;
			} else {
				$freeid = 0;
			}
		
			mysql_query( "UPDATE autodynlink SET title = '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', timer = '" . ( int ) $_POST['timer'] . "', freeid = '" . $freeid . "', geo_ru = '" . $geo_ru . "', geo_ua = '" . $geo_ua . "', geo_by = '" . $geo_by . "', geo_kz = '" . $geo_kz . "', geo_ge = '" . $geo_ge . "', geo_md = '" . $geo_md . "', geo_am = '" . $geo_am . "', geo_tj = '" . $geo_tj . "', geo_az = '" . $geo_az . "', geo_uz = '" . $geo_uz . "', geo_pt = '" . $geo_pt . "', geo_es = '" . $geo_es . "', geo_ee = '" . $geo_ee . "', geo_lv = '" . $geo_lv . "', geo_lt = '" . $geo_lt . "', geo_us = '" . $geo_us . "', geo_gb = '" . $geo_gb . "', geo_fr = '" . $geo_fr . "', geo_de = '" . $geo_de . "', geo_cn = '" . $geo_cn . "', geo_it = '" . $geo_it . "', geo_all = '" . $geo_all . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );

			echo 1;
			exit();
		}
	}
	
}

### Удаление авто-серфинг ссылок
if ( $_GET['func'] == 'delautodyn' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, date, timer FROM autodynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        switch ( $pr_row['timer'] ) {
            case 0: $timer = 'autodyn10'; break;
            case 1: $timer = 'autodyn20'; break;
            case 2: $timer = 'autodyn30'; break;
            case 3: $timer = 'autodyn40'; break;
            case 4: $timer = 'autodyn50'; break;
            case 5: $timer = 'autodyn60'; break;
        }
        
        if ( $pr_row['balance'] > $config[$timer] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM autodynlink_temp WHERE ident = '" . ( int ) $_POST['id'] . "'" );
        mysql_query( "DELETE FROM autodynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 16" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение авто-серфинг ссылок
if ( $_GET['func'] == 'runautodyn' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, timer, paused FROM autodynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
		
		$pr_row = mysql_fetch_array( $proverka );
		
		switch ( $pr_row['timer'] ) {
			case 0: $timer = 'autodyn10'; break;
			case 1: $timer = 'autodyn20'; break;
			case 2: $timer = 'autodyn30'; break;
			case 3: $timer = 'autodyn40'; break;
			case 4: $timer = 'autodyn50'; break;
			case 5: $timer = 'autodyn60'; break;
		}
			
		if ( $config[$timer] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
			echo 'Недостаточно средств на балансе рекламной площадки!';
			exit();
		} else {
			if ( $pr_row['paused'] == 1 ) {
				$paused = 0;
			} else {
				$paused = 1;
			}
		
			mysql_query( "UPDATE autodynlink SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
		
			echo 1;
			exit();
		}
    
	}
}

### Заказ контекстной рекламы
if ( $_GET['func'] == 'addklink' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
    
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
		
		#Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
			$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
			echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
			exit();
		}
		
		mysql_query( "INSERT INTO klink (iduser, title, description, url, date) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . time() . "')" );

		echo 1;
		exit();
        
    }
}

### Заказ контекстной рекламы  без сессии авторизации
if ( $_GET['func'] == 'addklink_nouser' ) {
    
  sleep(1);

  if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

  $_POST['title'] = trim( $_POST['title'] );
  $_POST['description'] = trim( $_POST['description'] );
  $_POST['url'] = trim( $_POST['url'] );

  $check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
  $check_bt_order = mysql_query( "SELECT nouser_order FROM klink WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
  if ( mysql_num_rows( $check_bt_order ) > 0 ) {
	echo 'Внутренняя ошибка, обновите страницу.';
	exit();
  } else
  if ( mysql_num_rows( $check_order_basket ) > 0 ) {
	echo 'Внутренняя ошибка, обновите страницу.';
	exit();
  } else
  if ( empty( $_POST['title'] ) ) {
	echo 2;
	exit();
  } else
  if ( empty( $_POST['description'] ) ) {
	echo 3;
	exit();
  } else
  if ( empty( $_POST['url'] ) ) {
	echo 4;
	exit();
  } else {
	if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
		$_POST['url'] = 'http://' . check_text( $_POST['url'] );
	}
	
	#Проверка на блокировку
	$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
	if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
	$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
	if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
	  $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
	  echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
	  exit();
	} else {
	  
	  $quantity = ( int ) $_POST['quantity'];
	  $quantity_summ = ($config['klink'] * $quantity);
	
	  #Создаем счет в корзину на оплату заказа
	  if ( $quantity < 10 OR $quantity >= 10000 ) {
	    echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 10, максимальное 10000.';
	    exit();
	  } else {
	    mysql_query( "INSERT INTO klink (iduser, title, description, url, date, nouser, nouser_order) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . time() . "', '1', '" . ( int ) $_POST['bt_order'] . "')" );
		#Делаем запрос на создание счета для оплаты площадки
		mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '1', '" . ( int ) $_POST['bt_order'] . "')" );

	    echo 1;
	    exit();
	  }
	}
  }
}

### Редактирование контекстной рекламы
if ( $_GET['func'] == 'upklink' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_num_rows(mysql_query( "SELECT id FROM klink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
    
    if ( $proverka == 0 ) {
        echo 'Рекламная площадка не существует или не принадлежит Вам!';
        exit();
    } else    
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        } else {
            if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
                $_POST['url'] = 'http://' . check_text( $_POST['url'] );
            }
            
            
            mysql_query( "UPDATE klink SET title = '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', description = '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', date = '" . time() . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );

            echo 1;
            exit();
        }
    }
}

### Удаление контекстной рекламы
if ( $_GET['func'] == 'delklink' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, date FROM klink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        if ( $pr_row['balance'] > $config['klink'] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM klink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 1" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение контекстной рекламы
if ( $_GET['func'] == 'runklink' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, paused FROM klink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
        $pr_row = mysql_fetch_array( $proverka );
                
        if ( $config['klink'] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
            echo 'Недостаточно средств на балансе рекламной площадки!';
            exit();
        } else {
            if ( $pr_row['paused'] == 1 ) {
                $paused = 0;
            } else {
                $paused = 1;
            }
            
            mysql_query( "UPDATE klink SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
}

### Заказ тестов
if ( $_GET['func'] == 'addtests' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
    $_POST['v1'] = trim( $_POST['v1'] );
    $_POST['answer1'] = trim( $_POST['answer1'] );
    $_POST['answer2'] = trim( $_POST['answer2'] );
    $_POST['answer3'] = trim( $_POST['answer3'] );
    $_POST['v2'] = trim( $_POST['v2'] );
    $_POST['answer4'] = trim( $_POST['answer4'] );
    $_POST['answer5'] = trim( $_POST['answer5'] );
    $_POST['answer6'] = trim( $_POST['answer6'] );
    $_POST['v3'] = trim( $_POST['v3'] );
    $_POST['answer7'] = trim( $_POST['answer7'] );
    $_POST['answer8'] = trim( $_POST['answer8'] );
    $_POST['answer9'] = trim( $_POST['answer9'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else
    if ( empty( $_POST['v1'] ) ) {
		echo 5;
		exit();
	} else
	if ( empty( $_POST['answer1'] ) ) {
		echo 6;
		exit();
	} else
	if ( empty( $_POST['answer2'] ) ) {
		echo 7;
		exit;
	} else
	if ( empty( $_POST['answer3'] ) ) {
		echo 8;
		exit;
	} else
	if ( empty( $_POST['v2'] ) ) {
		echo 9;
		exit;
	} else
	if ( empty( $_POST['answer4'] ) ) {
		echo 10;
		exit;
	} else
	if ( empty( $_POST['answer5'] ) ) {
		echo 11;
		exit;
	} else
	if ( empty( $_POST['answer6'] ) ) {
		echo 12;
		exit;
	} else
	if ( empty( $_POST['v3'] ) ) {
		echo 13;
		exit;
	} else
	if ( empty( $_POST['answer7'] ) ) {
		echo 14;
		exit;
	} else
	if ( empty( $_POST['answer8'] ) ) {
		echo 15;
		exit;
	} else
	if ( empty( $_POST['answer9'] ) ) {
        echo 16;
        exit();
    } else 
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
			$_POST['url'] = 'http://' . check_text( $_POST['url'] );
		}
		
		#Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
			$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
			echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
			exit();
		}
		
		mysql_query( "INSERT INTO tests (iduser, title, description, url, v1, answer1, answer2, answer3, v2, answer4, answer5, answer6, v3, answer7, answer8, answer9, date, geo_ru, geo_ua, geo_by, geo_kz, geo_ge, geo_md, geo_am, geo_tj, geo_az, geo_uz, geo_pt, geo_es, geo_ee, geo_lv, geo_lt, geo_us, geo_gb, geo_fr, geo_de, geo_cn, geo_it, geo_all) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . parce_bb_code( substr( check_text( $_POST['description'] ), 0, 5000 ), 'forum' ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['v1'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer1'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer2'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer3'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['v2'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer4'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer5'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer6'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['v3'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer7'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer8'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer9'] ), 0, 255 ) . "', '" . time() . "', '" . $geo_ru . "', '" . $geo_ua . "', '" . $geo_by . "', '" . $geo_kz . "', '" . $geo_ge . "', '" . $geo_md . "', '" . $geo_am . "', '" . $geo_tj . "', '" . $geo_az . "', '" . $geo_uz . "', '" . $geo_pt . "', '" . $geo_es . "', '" . $geo_ee . "', '" . $geo_lv . "', '" . $geo_lt . "', '" . $geo_us . "', '" . $geo_gb . "', '" . $geo_fr . "', '" . $geo_de . "', '" . $geo_cn . "', '" . $geo_it . "', '" . $geo_all . "')" );
		
		echo 1;
		exit();
        
    }
}

### Заказ тестов
if ( $_GET['func'] == 'addtests_nouser' ) {
    
    sleep(1);
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
    $_POST['v1'] = trim( $_POST['v1'] );
    $_POST['answer1'] = trim( $_POST['answer1'] );
    $_POST['answer2'] = trim( $_POST['answer2'] );
    $_POST['answer3'] = trim( $_POST['answer3'] );
    $_POST['v2'] = trim( $_POST['v2'] );
    $_POST['answer4'] = trim( $_POST['answer4'] );
    $_POST['answer5'] = trim( $_POST['answer5'] );
    $_POST['answer6'] = trim( $_POST['answer6'] );
    $_POST['v3'] = trim( $_POST['v3'] );
    $_POST['answer7'] = trim( $_POST['answer7'] );
    $_POST['answer8'] = trim( $_POST['answer8'] );
    $_POST['answer9'] = trim( $_POST['answer9'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
	$check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	$check_bt_order = mysql_query( "SELECT nouser_order FROM tests WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	if ( mysql_num_rows( $check_bt_order ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( mysql_num_rows( $check_order_basket ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else
    if ( empty( $_POST['v1'] ) ) {
		echo 5;
		exit();
	} else
	if ( empty( $_POST['answer1'] ) ) {
		echo 6;
		exit();
	} else
	if ( empty( $_POST['answer2'] ) ) {
		echo 7;
		exit;
	} else
	if ( empty( $_POST['answer3'] ) ) {
		echo 8;
		exit;
	} else
	if ( empty( $_POST['v2'] ) ) {
		echo 9;
		exit;
	} else
	if ( empty( $_POST['answer4'] ) ) {
		echo 10;
		exit;
	} else
	if ( empty( $_POST['answer5'] ) ) {
		echo 11;
		exit;
	} else
	if ( empty( $_POST['answer6'] ) ) {
		echo 12;
		exit;
	} else
	if ( empty( $_POST['v3'] ) ) {
		echo 13;
		exit;
	} else
	if ( empty( $_POST['answer7'] ) ) {
		echo 14;
		exit;
	} else
	if ( empty( $_POST['answer8'] ) ) {
		echo 15;
		exit;
	} else
	if ( empty( $_POST['answer9'] ) ) {
        echo 16;
        exit();
    } else 
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
			$_POST['url'] = 'http://' . check_text( $_POST['url'] );
		}
		
		#Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
			$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
			echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
			exit();
		} else {
		
		  $quantity = ( int ) $_POST['quantity'];
		  $quantity_summ = ( $config['tests'] * $quantity );
			
		  #Создаем счет в корзину на оплату заказа
		  if ( $quantity < 10 OR $quantity >= 10000 ) {
			echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 10, максимальное 10000.';
			exit();
		  } else {
		    
			mysql_query( "INSERT INTO tests (iduser, title, description, url, v1, answer1, answer2, answer3, v2, answer4, answer5, answer6, v3, answer7, answer8, answer9, date, geo_ru, geo_ua, geo_by, geo_kz, geo_ge, geo_md, geo_am, geo_tj, geo_az, geo_uz, geo_pt, geo_es, geo_ee, geo_lv, geo_lt, geo_us, geo_gb, geo_fr, geo_de, geo_cn, geo_it, geo_all, nouser, nouser_order) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . parce_bb_code( substr( check_text( $_POST['description'] ), 0, 5000 ), 'forum' ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['v1'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer1'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer2'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer3'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['v2'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer4'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer5'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer6'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['v3'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer7'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer8'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['answer9'] ), 0, 255 ) . "', '" . time() . "', '" . $geo_ru . "', '" . $geo_ua . "', '" . $geo_by . "', '" . $geo_kz . "', '" . $geo_ge . "', '" . $geo_md . "', '" . $geo_am . "', '" . $geo_tj . "', '" . $geo_az . "', '" . $geo_uz . "', '" . $geo_pt . "', '" . $geo_es . "', '" . $geo_ee . "', '" . $geo_lv . "', '" . $geo_lt . "', '" . $geo_us . "', '" . $geo_gb . "', '" . $geo_fr . "', '" . $geo_de . "', '" . $geo_cn . "', '" . $geo_it . "', '" . $geo_all . "', '1', '" . ( int ) $_POST['bt_order'] . "')" );
			
			#Делаем запрос на создание счета для оплаты площадки
			mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '2', '" . ( int ) $_POST['bt_order'] . "')" );
		
		    echo 1;
		    exit();
			
          }
		}
    }
}

### Редактирование тестов
if ( $_GET['func'] == 'uptests' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_num_rows(mysql_query( "SELECT id FROM tests WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
    $_POST['v1'] = trim( $_POST['v1'] );
    $_POST['answer1'] = trim( $_POST['answer1'] );
    $_POST['answer2'] = trim( $_POST['answer2'] );
    $_POST['answer3'] = trim( $_POST['answer3'] );
    $_POST['v2'] = trim( $_POST['v2'] );
    $_POST['answer4'] = trim( $_POST['answer4'] );
    $_POST['answer5'] = trim( $_POST['answer5'] );
    $_POST['answer6'] = trim( $_POST['answer6'] );
    $_POST['v3'] = trim( $_POST['v3'] );
    $_POST['answer7'] = trim( $_POST['answer7'] );
    $_POST['answer8'] = trim( $_POST['answer8'] );
    $_POST['answer9'] = trim( $_POST['answer9'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
    if ( $proverka == 0 ) {
        echo 'Рекламная площадка не существует или не принадлежит Вам!';
        exit();
    } else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else
    if ( empty( $_POST['v1'] ) ) {
		echo 5;
		exit();
	} else
	if ( empty( $_POST['answer1'] ) ) {
		echo 6;
		exit();
	} else
	if ( empty( $_POST['answer2'] ) ) {
		echo 7;
		exit;
	} else
	if ( empty( $_POST['answer3'] ) ) {
		echo 8;
		exit;
	} else
	if ( empty( $_POST['v2'] ) ) {
		echo 9;
		exit;
	} else
	if ( empty( $_POST['answer4'] ) ) {
		echo 10;
		exit;
	} else
	if ( empty( $_POST['answer5'] ) ) {
		echo 11;
		exit;
	} else
	if ( empty( $_POST['answer6'] ) ) {
		echo 12;
		exit;
	} else
	if ( empty( $_POST['v3'] ) ) {
		echo 13;
		exit;
	} else
	if ( empty( $_POST['answer7'] ) ) {
		echo 14;
		exit;
	} else
	if ( empty( $_POST['answer8'] ) ) {
		echo 15;
		exit;
	} else
	if ( empty( $_POST['answer9'] ) ) {
        echo 16;
        exit();
    } else 
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
        
        mysql_query( "UPDATE tests SET title = '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', description = '" . parce_bb_code( substr( check_text( $_POST['description'] ), 0, 500 ), 'forum' ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', v1 = '" . substr( check_text( $_POST['v1'] ), 0, 255 ) . "', answer1 = '" . substr( check_text( $_POST['answer1'] ), 0, 255 ) . "', answer2 = '" . substr( check_text( $_POST['answer2'] ), 0, 255 ) . "', answer3 = '" . substr( check_text( $_POST['answer3'] ), 0, 255 ) . "', v2 = '" . substr( check_text( $_POST['v2'] ), 0, 255 ) . "', answer4 = '" . substr( check_text( $_POST['answer4'] ), 0, 255 ) . "', answer5 = '" . substr( check_text( $_POST['answer5'] ), 0, 255 ) . "', answer6 = '" . substr( check_text( $_POST['answer6'] ), 0, 255 ) . "', v3 = '" . substr( check_text( $_POST['v3'] ), 0, 255 ) . "', answer7 = '" . substr( check_text( $_POST['answer7'] ), 0, 255 ) . "', answer8 = '" . substr( check_text( $_POST['answer8'] ), 0, 255 ) . "', answer9 = '" . substr( check_text( $_POST['answer9'] ), 0, 255 ) . "', date = '" . time() . "', geo_ru = '" . $geo_ru . "', geo_ua = '" . $geo_ua . "', geo_by = '" . $geo_by . "', geo_kz = '" . $geo_kz . "', geo_ge = '" . $geo_ge . "', geo_md = '" . $geo_md . "', geo_am = '" . $geo_am . "', geo_tj = '" . $geo_tj . "', geo_az = '" . $geo_az . "', geo_uz = '" . $geo_uz . "', geo_pt = '" . $geo_pt . "', geo_es = '" . $geo_es . "', geo_ee = '" . $geo_ee . "', geo_lv = '" . $geo_lv . "', geo_lt = '" . $geo_lt . "', geo_us = '" . $geo_us . "', geo_gb = '" . $geo_gb . "', geo_fr = '" . $geo_fr . "', geo_de = '" . $geo_de . "', geo_cn = '" . $geo_cn . "', geo_it = '" . $geo_it . "', geo_all = '" . $geo_all . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
        echo 1;
        exit();
        
    }
}

### Удаление тестов
if ( $_GET['func'] == 'deltests' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, date FROM tests WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            ///$t1 = new DateTime( date( 'Y-m-d', time() ) );
            ///$t2 = new DateTime( date( 'Y-m-d', $pr_row['date'] + 7 * 86400 ) );
            ///$interval = $t1->diff( $t2 );
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        if ( $pr_row['balance'] > $config['tests'] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM tests WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM tests_temp WHERE ident = '" . ( int ) $_POST['id'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 2" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение тесты
if ( $_GET['func'] == 'runtests' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, paused FROM tests WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
        $pr_row = mysql_fetch_array( $proverka );
                
        if ( $config['tests'] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
            echo 'Недостаточно средств на балансе рекламной площадки!';
            exit();
        } else {
            if ( $pr_row['paused'] == 1 ) {
                $paused = 0;
            } else {
                $paused = 1;
            }
            
            mysql_query( "UPDATE tests SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
}

### Выпопление тестов
if ( $_GET['type'] == 'answertests' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $view_test = mysql_query( "SELECT * FROM tests t1 WHERE t1.paused = 1 and t1.balance > '" . $config['tests'] . "' and id = '" . ( int ) $_POST['id'] . "' and NOT EXISTS ( SELECT ident, iduser FROM tests_temp t2 WHERE t1.id = t2.ident and t2.iduser = '" . $_SESSION['iduser'] . "') ORDER BY id DESC LIMIT 1" );
    
    $pr = mysql_num_rows( mysql_query( "SELECT id FROM tests WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    
    if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
	if ( mysql_num_rows( $view_test ) == 0 ) {
        echo 'Тест не существует или не активен';
        exit();
    } else
    if ( $pr ) {
        echo 'Вы не можете выполнить свой тест';
        exit();
    } else
    if ( $_POST['t1'] == '' or $_POST['t2'] == '' or $_POST['t3'] == '' ) {
        echo '<i id="error_div_icon" class="fa fa-exclamation-circle" aria-hidden="true"></i> <span style="margin-left: 22px;">Ответьте на все вопросы теста!</span>';
        exit();
    } else
    if ( md5( ( int ) $_POST['id'] . $message_md5 . '1' ) != $_POST['t1'] or md5( ( int ) $_POST['id'] . $message_md5 . '4' ) != $_POST['t2'] or md5( ( int ) $_POST['id'] . $message_md5 . '7' ) != $_POST['t3'] ) {
        mysql_query( "INSERT INTO tests_temp (ident, iduser, date) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "')" );
        echo 2;
        exit();
    } else {
		
		$factor = $config['tests'] * $config['factor_test'];
		
        #зачисляем рефбек рефералу I уровня
        if ( $config_user['referer'] != 0 ) {
            $ref_1 = mysql_fetch_array( mysql_query( "SELECT reyting FROM user WHERE id = '" . $config_user['referer'] . "' LIMIT 1" ) );
            
			if ( $ref_1['reyting'] >= $config_site['status_meaning_1a'] and $ref_1['reyting'] <= $config_site['status_meaning_1b'] ) {
                $ref1_back = $factor * $config['st1'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_2a'] and $ref_1['reyting'] <= $config_site['status_meaning_2b'] ) {
                $ref1_back = $factor * $config['st2'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_3a'] and $ref_1['reyting'] <= $config_site['status_meaning_3b'] ) {
                $ref1_back = $factor * $config['st3'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_4a'] and $ref_1['reyting'] <= $config_site['status_meaning_4b'] ) {
                $ref1_back = $factor * $config['st4'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_5a'] and $ref_1['reyting'] <= $config_site['status_meaning_5b'] ) {
                $ref1_back = $factor * $config['st5'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_6a'] ) {
                $ref1_back = $factor * $config['st6'];
            } else {
                $ref1_back = 0;
            }
            
            if ( !is_numeric( $ref1_back ) ) $my_refback = 0;
            $my_refback = $ref1_back * ( $config_user['autoproc'] / 100 );
            if ( !is_numeric( $my_refback ) ) $my_refback = 0;
            $ref1_refback = $ref1_back - $my_refback;
            if ( !is_numeric( $ref1_refback ) ) $ref1_refback = 0;
            mysql_query( "UPDATE user SET money = money + '" . $ref1_refback . "' WHERE id = '" . $config_user['referer'] . "' LIMIT 1" );
        }
        #зачисляем рефбек рефералу II уровня
        if ( $config_user['referer2'] != 0 ) {
            $ref_2 = mysql_fetch_array( mysql_query( "SELECT reyting FROM user WHERE id = '" . $config_user['referer2'] . "' LIMIT 1" ) );
            
            if ( $ref_2['reyting'] >= $config_site['status_meaning_1a'] and $ref_2['reyting'] < $config_site['status_meaning_1b'] ) {
                $ref2_back = $config['st7'];
            } else
            if ( $ref_2['reyting'] >= $config_site['status_meaning_2a'] and $ref_2['reyting'] < $config_site['status_meaning_2b'] ) {
                $ref2_back = $config['st8'];
            } else
            if ( $ref_2['reyting'] >= $config_site['status_meaning_3a'] and $ref_2['reyting'] < $config_site['status_meaning_3b'] ) {
                $ref2_back = $config['st9'];
            } else
            if ( $ref_2['reyting'] >= $config_site['status_meaning_4a'] and $ref_2['reyting'] < $config_site['status_meaning_4b'] ) {
                $ref2_back = $config['st10'];
            } else
            if ( $ref_2['reyting'] >= $config_site['status_meaning_5a'] and $ref_2['reyting'] < $config_site['status_meaning_5b'] ) {
                $ref2_back = $config['st11'];
            } else
            if ( $ref_2['reyting'] >= $config_site['status_meaning_6a'] ) {
                $ref2_back = $config['st12'];
            } else {
                $ref2_back = 0;
            }
            
            if ( !is_numeric($ref2_back) ) $ref2_back = 0;
            mysql_query( "UPDATE user SET money = money + '" . $ref2_back . "' WHERE id = '" . $config_user['referer2'] . "' LIMIT 1" );
        }
        
        $money_minus = $config['tests'];
        $my_money = $factor + $my_refback;
        
		#Снимаем с баланса деньги с площадки
        mysql_query( "UPDATE tests SET balance = balance - '" . $money_minus . "', visits = visits + 1 WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
        
		#Зачисляем деньги работнику
		mysql_query( "UPDATE user SET earnings_test = earnings_test + '" . $my_money . "', money = money + '" . $my_money . "', toref = toref + '" . $ref1_refback . "', toref2 = toref2 + '" . $ref2_back . "', test_view = test_view + 1 WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        
		#Пишем отчет о выполение
		mysql_query( "INSERT INTO tests_temp SET ident = '" . ( int ) $_POST['id'] . "', iduser = '" . $_SESSION['iduser'] . "', date = '" . time() . "', tok = 1" );
		
		#конкурсы от реферера
		if ( $config_user['referer'] != 0  and $config_user['activate'] == 1) {
			#кликер
			$chKonkursWan = mysql_query( "SELECT * FROM contests WHERE type = 0 and date_end > '". time() ."' and autor = '".$config_user['referer']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursWan ) > 0 ) {
				$chKonkursRowWan = mysql_fetch_array( $chKonkursWan );
				$chKonkursTempWan = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . $_SESSION['iduser'] . "' and id_konkurs = '" . $chKonkursRowWan['id'] . "' and type = 0" );
				if ( mysql_num_rows( $chKonkursTempWan ) > 0 ) {
					mysql_query( "UPDATE contests_temp SET summ = summ + 3 WHERE iduser = '" . $_SESSION['iduser'] . "' and type = 0 and id_konkurs = '" . $chKonkursRowWan['id'] . "' LIMIT 1" );
				} else {
					mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowWan['id'] . "', iduser = '" . $_SESSION['iduser'] . "', summ = 3, type = 0" );
				}
			}
			#комплексный
			$chKonkursComplex = mysql_query( "SELECT * FROM contests WHERE type = 3 and date_end > '". time() ."' and autor = '".$config_user['referer']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursComplex ) > 0 ) {
				$chKonkursRowComplex = mysql_fetch_array( $chKonkursComplex );
				$chKonkursTempComplex = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . $_SESSION['iduser'] . "' and id_konkurs = '" . $chKonkursRowComplex['id'] . "' and type = 3" );
				if ( mysql_num_rows( $chKonkursTempComplex ) > 0 ) {
					mysql_query( "UPDATE contests_temp SET summ = summ + 3 WHERE iduser = '" . $_SESSION['iduser'] . "' and type = 3 and id_konkurs = '" . $chKonkursRowComplex['id'] . "' LIMIT 1" );
				} else {
					mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowComplex['id'] . "', iduser = '" . $_SESSION['iduser'] . "', summ = 3, type = 3" );
				}
			}
		}
        
		#Пишем выручку от клика для проекта
        $viruchka = $money_minus - $ref1_refback - $my_money - $ref2_back;
        mysql_query( "UPDATE viruchka SET money = money + '" . $viruchka . "' WHERE ident = 4 LIMIT 1" );
        
        #Создаем по днях статистику зароботка
		mysql_query( "INSERT INTO earnings_statistics SET iduser = '" . $_SESSION['iduser'] . "', summ = '1', date = '" . time() . "', ident = '" . ( int ) $_POST['id'] . "', type = '3'" );
        
        echo 1;
        exit();
    }
}

### Заказ задания
if ( $_GET['func'] == 'addtasks' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
    $_POST['text'] = trim( $_POST['text'] );
	$openReyting = ( int ) $_POST['openReyting'];
	$ShownKategories = ( int ) $_POST['tkategorian'];
	$addTimeout = ( int ) $_POST['addTimeout'];
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
	
    
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['text'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 4;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 5;
        exit();
    } else
    if ( floatval( $_POST['price'] ) < $config['tasks'] ) {
        echo 6;
        exit();
    } else    
		
	if ( !is_numeric( check_text( $_POST['tkategorian'] ) ) ) {
        echo 'Вы не выбрали категорию задания';
        exit();
    } else
	if ( $ShownKategories < '1' OR $ShownKategories > '16' ) {
        echo 'Неверная категория задания!';
        exit();
    } else	
	
	if ( !is_numeric( check_text( $_POST['tmode'] ) ) ) {
        echo 'Вы не выбрали тип выполнения';
        exit();
    } else
	if ( check_text( $_POST['tmode'] ) != '0' and check_text( $_POST['tmode'] ) != '1' ) {
        echo 'Неверный тип выполнения!';
        exit();
    } else
	if(check_text( $_POST['tmode'] ) == '1'){
		if ( !is_numeric( check_text( $_POST['re_execution'] ) ) ) {
			echo 'Вы не выбрали параметер повторного выполнения до проверки!';
			exit();
		} else
		if ( check_text( $_POST['re_execution'] ) != '0' and check_text( $_POST['re_execution'] ) != '1' ) {
			echo 'Вы не выбрали параметер повторного выполнения до проверки!';
			exit();
		} else
		
		if ( check_text( $_POST['tmode'] ) == '0' and check_text( $_POST['re_execution'] ) == '1' ) {
			echo 'В задание одноразового типа не может быть выбран параметер повторного выполнения. Повторное выполнение доступно только в заданиях многоразового типа!';
			exit();
		} else
		
	
		if ( !is_numeric( check_text( $_POST['pdays'] ) ) ) {
			echo 'Вы не выбрали параметер повтора выполнения задания!';
			exit();
		} else
		if ( ( int ) $_POST['pdays'] != 0 and ( int ) $_POST['pdays'] != 3600 and ( int ) $_POST['pdays'] != 3600 * 3 and ( int ) $_POST['pdays'] != 3600 * 6 and ( int ) $_POST['pdays'] != 3600 * 12 and ( int ) $_POST['pdays'] != 86400 and ( int ) $_POST['pdays'] != 86400 * 2 and ( int ) $_POST['pdays'] != 86400 * 3 and ( int ) $_POST['pdays'] != 86400 * 5 ) {
			echo 'Неверный параметер повтора выполнения задания!';
			exit();
		} 
		$re_execution = ( int ) $_POST['re_execution'];
		$_POST['pdays'] = ( int ) $_POST['pdays'];
	}  
	if ( !is_numeric( check_text( $_POST['tdays'] ) ) ) {
        echo 'Вы не выбрали максимальный срок выполнения!';
        exit();
    } else
	if ( ( int ) $_POST['tdays'] != 3600 and ( int ) $_POST['tdays'] != 7200 and ( int ) $_POST['tdays'] != 3600 * 6 and ( int ) $_POST['tdays'] != 3600 * 12 and ( int ) $_POST['tdays'] != 86400 and ( int ) $_POST['tdays'] != 86400 * 2 and ( int ) $_POST['tdays'] != 86400 * 3 and ( int ) $_POST['tdays'] != 86400 * 4 and ( int ) $_POST['tdays'] != 86400 * 5 and ( int ) $_POST['tdays'] != 86400 * 6 and ( int ) $_POST['tdays'] != 86400 * 7 and ( int ) $_POST['tdays'] != 86400 * 10 and ( int ) $_POST['tdays'] != 86400 * 15 and ( int ) $_POST['tdays'] != 86400 * 20 and ( int ) $_POST['tdays'] != 86400 * 30 ) {
        echo 'Неверный максимальный срок выполнения!';
        exit();
    } else 
	if ( !is_numeric( check_text( $_POST['fdays'] ) ) ) {
        echo 'Вы не выбрали время ожидания между выполнениями!';
        exit();
    } else
	if ( ( int ) $_POST['fdays'] != 0 and ( int ) $_POST['fdays'] != 600 and ( int ) $_POST['fdays'] != 600 * 2 and ( int ) $_POST['fdays'] != 600 * 3 and ( int ) $_POST['fdays'] != 600 * 5 and ( int ) $_POST['fdays'] != 3600 and ( int ) $_POST['fdays'] != 3600 * 2 and ( int ) $_POST['fdays'] != 3600 * 3 and ( int ) $_POST['fdays'] != 3600 * 4 and ( int ) $_POST['fdays'] != 3600 * 5 and ( int ) $_POST['fdays'] != 3600 * 6 and ( int ) $_POST['fdays'] != 3600 * 12 and ( int ) $_POST['fdays'] != 86400 and ( int ) $_POST['fdays'] != 86400 * 2 and ( int ) $_POST['fdays'] != 86400 * 3  and ( int ) $_POST['fdays'] != 86400 * 5 ) {
        echo 'Неверный параметер время ожидания между выполнениями!';
        exit();
    } else 
	if ( !is_numeric( check_text( $_POST['ip'] ) ) ) {
        echo 'Вы не выбрали параметер IP фильтра!';
        exit();
    } else
	if ( ( int ) $_POST['ip'] != 0 AND ( int ) $_POST['ip'] != 1 AND ( int ) $_POST['ip'] != 2 ) {
        echo 'Неверный параметер IP фильтра!';
        exit();
    } else
	if (( int ) $_POST['ip'] == 1 OR ( int ) $_POST['ip'] == 2 ) {
		if ( ( int ) $_POST['ipfilter'] < 1 OR ( int ) $_POST['ipfilter'] > 240 ) {
			echo 7;
			exit();
		} 
	}
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else
    if($openReyting > 5001){
		echo 8;
		exit();
	} else
	if ($openReyting < 0) {
			echo 8;
			exit();
	} else 
    if($addTimeout > 90000){
		echo 9;
		exit();
	} else
	if ($addTimeout < 0) {
			echo 9;
			exit();
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        if(check_text( $_POST['tmode'] ) == '0'){
			$re_execution = '0';
			$_POST['pdays'] = '0';
		} 
        
        $getframe = check_frame( $_POST['url'] );
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        } else {
            if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
                $_POST['url'] = 'http://' . check_text( $_POST['url'] );
            }
            
            if ( $_POST['clearcookie'] == 'on' ) {
                $clearcookie = 1;
            } else {
                $clearcookie = 0;
            }
			
			if ( $_POST['openWmid'] == 'on' ) {
                $openWmid = 1;
            } else {
                $openWmid = 0;
            }
			
			switch ( $ShownKategories ) {
				case 1:
					$KategoriesTitle = '(Только регистрация)';
					break;
				case 2:
					$KategoriesTitle = '(Только клики)';
					break;
				case 3:
					$KategoriesTitle = '(Регистрация с активностью)';
					break;
				case 4:
					$KategoriesTitle = '(Приглашение в рефералы)';
					break;
				case 5:
					$KategoriesTitle = '(Социальные сети)';
					break;
				case 6:
					$KategoriesTitle = '(YouTube)';
					break;
				case 7:
					$KategoriesTitle = '(Постинг в форумы и/или блоги)';
					break;
				case 8:
					$KategoriesTitle = '(Написать статью или пресс-релиз)';
					break;
				case 9:
					$KategoriesTitle = '(Отзыв/проголосовать)';
					break;
				case 10:
					$KategoriesTitle = '(Forex)';
					break;
				case 11:
					$KategoriesTitle = '(Bitcoin/Litecoin/Dogecoin)';
					break;
				case 12:
					$KategoriesTitle = '(Играть в игры)';
					break;
				case 13:
					$KategoriesTitle = '(Инвестировать)';
					break;
				case 14:
					$KategoriesTitle = '(Мобильные приложения)';
					break;
				case 15:
					$KategoriesTitle = '(Бонусы)';
					break;
				case 16:
					$KategoriesTitle = '(Прочее)';
					break;
				default:
					$KategoriesTitle = '()';
					break;
			}
			
			if($addTimeout < 1 ){
				$addTimeout = '';
			} 
			
			if (( int ) $_POST['ip'] == 1 OR ( int ) $_POST['ip'] == 2 ) {
				$iptimefilter = (( int ) $_POST['ipfilter'] * 3600);
			} else {
				$iptimefilter = 0;
			}
            
            mysql_query( "INSERT INTO tasks SET iduser = '" . $_SESSION['iduser'] . "', price = '" . moneyraund( floatval( $_POST['price'] ), 2 ) . "', title = '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', text = '" . parce_bb_code ( substr( check_text( $_POST['text'] ), 0, 3000 ), 'forum' ) . "', description = '" . parce_bb_code( substr( check_text( $_POST['description'] ), 0, 3000 ), 'forum' ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', KategoriesTitle = '" . $KategoriesTitle . "', ShownKategories = '" . $ShownKategories . "', many = '" . ( int ) $_POST['tmode'] . "', ipFilter = '" . ( int ) $_POST['ip'] . "', timeIpFilter = '" . $iptimefilter . "', nextExecutionOn = '" . ( int ) $_POST['fdays'] . "', re_execution = '" . $re_execution . "', maxtime = '" . ( int ) $_POST['tdays'] . "', executionTime = '" . ( int ) $_POST['pdays'] . "', TimeoutResidue = '" . $addTimeout . "', TimeoutInExecution = '" . $addTimeout . "', date = '" . time() . "', clearcookie = '" . $clearcookie . "', openWmid = '" . $openWmid . "', openReyting = '" . $openReyting . "', geo_ru = '" . $geo_ru . "', geo_ua = '" . $geo_ua . "', geo_by = '" . $geo_by . "', geo_kz = '" . $geo_kz . "', geo_ge = '" . $geo_ge . "', geo_md = '" . $geo_md . "', geo_am = '" . $geo_am . "', geo_tj = '" . $geo_tj . "', geo_az = '" . $geo_az . "', geo_uz = '" . $geo_uz . "', geo_pt = '" . $geo_pt . "', geo_es = '" . $geo_es . "', geo_ee = '" . $geo_ee . "', geo_lv = '" . $geo_lv . "', geo_lt = '" . $geo_lt . "', geo_us = '" . $geo_us . "', geo_gb = '" . $geo_gb . "', geo_fr = '" . $geo_fr . "', geo_de = '" . $geo_de . "', geo_cn = '" . $geo_cn . "', geo_it = '" . $geo_it . "', geo_all = '" . $geo_all . "'" );
            
            echo 1;
            exit();
        }
    }
}

### Редактирование задания
if ( $_GET['func'] == 'uptasks' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_num_rows(mysql_query( "SELECT id FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    $tasks_cena_minimum = mysql_fetch_array( mysql_query( "SELECT price FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
	
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
    $_POST['text'] = trim( $_POST['text'] );
	$openReyting = ( int ) $_POST['openReyting'];
	$ShownKategories = ( int ) $_POST['tkategorian'];
	$addTimeout = ( int ) $_POST['addTimeout'];
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
    if ( $proverka == 0 ) {
        echo 'Рекламная площадка не существует или не принадлежит Вам!';
        exit();
    } else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['text'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 4;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 5;
        exit();
    } else
    if ( floatval( $_POST['price'] ) < $config['tasks'] ) {
        echo 6;
        exit();
    } else   
	if ( floatval( $_POST['price'] ) < $tasks_cena_minimum['price'] ) {
        echo 'После создания задания цена не может изменятся в меньшую сторону!';
        exit();
    } else
	if ( !is_numeric( check_text( $_POST['tkategorian'] ) ) ) {
        echo 'Вы не выбрали категорию задания';
        exit();
    } else
	if ( $ShownKategories < '1' OR $ShownKategories > '16' ) {
        echo 'Неверная категория задания!';
        exit();
    } else	
    if ( !is_numeric( check_text( $_POST['tmode'] ) ) ) {
        echo 'Вы не выбрали тип выполнения';
        exit();
    } else
	if ( check_text( $_POST['tmode'] ) != '0' and check_text( $_POST['tmode'] ) != '1' ) {
        echo 'Неверный тип выполнения!';
        exit();
    } else
	
	if(check_text( $_POST['tmode'] ) == '1'){
		if ( !is_numeric( check_text( $_POST['re_execution'] ) ) ) {
			echo 'Вы не выбрали параметер повторного выполнения до проверки!';
			exit();
		} else
		if ( check_text( $_POST['re_execution'] ) != '0' and check_text( $_POST['re_execution'] ) != '1' ) {
			echo 'Вы не выбрали параметер повторного выполнения до проверки!';
			exit();
		} else
		
		if ( check_text( $_POST['tmode'] ) == '0' and check_text( $_POST['re_execution'] ) == '1' ) {
			echo 'В задание одноразового типа не может быть выбран параметер повторного выполнения. Повторное выполнение доступно только в заданиях многоразового типа!';
			exit();
		} else
		
	
		if ( !is_numeric( check_text( $_POST['pdays'] ) ) ) {
			echo 'Вы не выбрали параметер повтора выполнения задания!';
			exit();
		} else
		if ( ( int ) $_POST['pdays'] != 0 and ( int ) $_POST['pdays'] != 3600 and ( int ) $_POST['pdays'] != 3600 * 3 and ( int ) $_POST['pdays'] != 3600 * 6 and ( int ) $_POST['pdays'] != 3600 * 12 and ( int ) $_POST['pdays'] != 86400 and ( int ) $_POST['pdays'] != 86400 * 2 and ( int ) $_POST['pdays'] != 86400 * 3 and ( int ) $_POST['pdays'] != 86400 * 5 ) {
			echo 'Неверный параметер повтора выполнения задания!';
			exit();
		} 
		$re_execution = ( int ) $_POST['re_execution'];
		$_POST['pdays'] = ( int ) $_POST['pdays'];
	}  	
	
	if ( !is_numeric( check_text( $_POST['tdays'] ) ) ) {
        echo 'Вы не выбрали максимальный срок выполнения!';
        exit();
    } else
    if ( ( int ) $_POST['tdays'] != 3600 and ( int ) $_POST['tdays'] != 7200 and ( int ) $_POST['tdays'] != 3600 * 6 and ( int ) $_POST['tdays'] != 3600 * 12 and ( int ) $_POST['tdays'] != 86400 and ( int ) $_POST['tdays'] != 86400 * 2 and ( int ) $_POST['tdays'] != 86400 * 3 and ( int ) $_POST['tdays'] != 86400 * 4 and ( int ) $_POST['tdays'] != 86400 * 5 and ( int ) $_POST['tdays'] != 86400 * 6 and ( int ) $_POST['tdays'] != 86400 * 7 and ( int ) $_POST['tdays'] != 86400 * 10 and ( int ) $_POST['tdays'] != 86400 * 15 and ( int ) $_POST['tdays'] != 86400 * 20 and ( int ) $_POST['tdays'] != 86400 * 30 ) {
        echo 'Неверно выбран максимальный срок выполнения!';
        exit();
    } else
	if ( !is_numeric( check_text( $_POST['fdays'] ) ) ) {
        echo 'Вы не выбрали время ожидания между выполнениями!';
        exit();
    } else
	if ( ( int ) $_POST['fdays'] != 0 and ( int ) $_POST['fdays'] != 600 and ( int ) $_POST['fdays'] != 600 * 2 and ( int ) $_POST['fdays'] != 600 * 3 and ( int ) $_POST['fdays'] != 600 * 5 and ( int ) $_POST['fdays'] != 3600 and ( int ) $_POST['fdays'] != 3600 * 2 and ( int ) $_POST['fdays'] != 3600 * 3 and ( int ) $_POST['fdays'] != 3600 * 4 and ( int ) $_POST['fdays'] != 3600 * 5 and ( int ) $_POST['fdays'] != 3600 * 6 and ( int ) $_POST['fdays'] != 3600 * 12 and ( int ) $_POST['fdays'] != 86400 and ( int ) $_POST['fdays'] != 86400 * 2 and ( int ) $_POST['fdays'] != 86400 * 3  and ( int ) $_POST['fdays'] != 86400 * 5 ) {
        echo 'Неверный параметер время ожидания между выполнениями!';
        exit();
    } else 
	if ( !is_numeric( check_text( $_POST['ip'] ) ) ) {
        echo 'Вы не выбрали параметер IP фильтра!';
        exit();
    } else
	if ( ( int ) $_POST['ip'] != 0 AND ( int ) $_POST['ip'] != 1 AND ( int ) $_POST['ip'] != 2 ) {
        echo 'Неверный параметер IP фильтра!';
        exit();
    } else
	if (( int ) $_POST['ip'] == 1 OR ( int ) $_POST['ip'] == 2 ) {
		if ( ( int ) $_POST['ipfilter'] < 1 OR ( int ) $_POST['ipfilter'] > 240 ) {
			echo 7;
			exit();
		} 
	}
	if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else
	if($openReyting > 5001){
		echo 8;
		exit();
	} else
	if ($openReyting < 0) {
			echo 8;
			exit();
	} else 
	if($addTimeout > 90000){
		echo 9;
		exit();
	} else
	if ($addTimeout < 0) {
			echo 9;
			exit();
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        if(check_text( $_POST['tmode'] ) == '0'){
			$re_execution = '0';
			$_POST['pdays'] = '0';
		}
        
		$getframe = check_frame( $_POST['url'] );
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        } else {
            if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
                $_POST['url'] = 'http://' . check_text( $_POST['url'] );
            }
            
			if ( $_POST['clearcookie'] == 'on' ) {
                $clearcookie = 1;
            } else {
                $clearcookie = 0;
            }            
			
			if ( $_POST['openWmid'] == 'on' ) {
                $openWmid = 1;
            } else {
                $openWmid = 0;
            }
			
			switch ( $ShownKategories ) {
				case 1:
					$KategoriesTitle = '(Только регистрация)';
					break;
				case 2:
					$KategoriesTitle = '(Только клики)';
					break;
				case 3:
					$KategoriesTitle = '(Регистрация с активностью)';
					break;
				case 4:
					$KategoriesTitle = '(Приглашение в рефералы)';
					break;
				case 5:
					$KategoriesTitle = '(Социальные сети)';
					break;
				case 6:
					$KategoriesTitle = '(YouTube)';
					break;
				case 7:
					$KategoriesTitle = '(Постинг в форумы и/или блоги)';
					break;
				case 8:
					$KategoriesTitle = '(Написать статью или пресс-релиз)';
					break;
				case 9:
					$KategoriesTitle = '(Отзыв/проголосовать)';
					break;
				case 10:
					$KategoriesTitle = '(Forex)';
					break;
				case 11:
					$KategoriesTitle = '(Bitcoin/Litecoin/Dogecoin)';
					break;
				case 12:
					$KategoriesTitle = '(Играть в игры)';
					break;
				case 13:
					$KategoriesTitle = '(Инвестировать)';
					break;
				case 14:
					$KategoriesTitle = '(Мобильные приложения)';
					break;
				case 15:
					$KategoriesTitle = '(Бонусы)';
					break;
				case 16:
					$KategoriesTitle = '(Прочее)';
					break;
				default:
					$KategoriesTitle = '()';
					break;
			}
			
			if($addTimeout < 1 ){
				$addTimeout = '0';
			}
			
			if (( int ) $_POST['ip'] == 1 OR ( int ) $_POST['ip'] == 2 ) {
				$iptimefilter = (( int ) $_POST['ipfilter'] * 3600);
			} else {
				$iptimefilter = 0;
			}
			
            mysql_query( "UPDATE tasks SET iduser = '" . $_SESSION['iduser'] . "', price = '" . moneyraund( floatval( $_POST['price'] ), 2 ) . "', title = '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', text = '" . parce_bb_code ( substr( check_text( $_POST['text'] ), 0, 3000 ), 'forum' ) . "', description = '" . parce_bb_code( substr( check_text( $_POST['description'] ), 0, 3000 ), 'forum' ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', ShownKategories = '" . $ShownKategories . "', KategoriesTitle = '" . $KategoriesTitle . "', many = '" . ( int ) $_POST['tmode'] . "', ipFilter = '" . ( int ) $_POST['ip'] . "', timeIpFilter = '" . $iptimefilter . "', nextExecutionOn = '" . ( int ) $_POST['fdays'] . "', re_execution = '" . $re_execution . "', maxtime = '" . ( int ) $_POST['tdays'] . "', executionTime = '" . ( int ) $_POST['pdays'] . "', TimeoutResidue = '" . $addTimeout . "', TimeoutInExecution = '" . $addTimeout . "', clearcookie = '" . $clearcookie . "', openWmid = '" . $openWmid . "', openReyting = '" . $openReyting . "', geo_ru = '" . $geo_ru . "', geo_ua = '" . $geo_ua . "', geo_by = '" . $geo_by . "', geo_kz = '" . $geo_kz . "', geo_ge = '" . $geo_ge . "', geo_md = '" . $geo_md . "', geo_am = '" . $geo_am . "', geo_tj = '" . $geo_tj . "', geo_az = '" . $geo_az . "', geo_uz = '" . $geo_uz . "', geo_pt = '" . $geo_pt . "', geo_es = '" . $geo_es . "', geo_ee = '" . $geo_ee . "', geo_lv = '" . $geo_lv . "', geo_lt = '" . $geo_lt . "', geo_us = '" . $geo_us . "', geo_gb = '" . $geo_gb . "', geo_fr = '" . $geo_fr . "', geo_de = '" . $geo_de . "', geo_cn = '" . $geo_cn . "', geo_it = '" . $geo_it . "', geo_all = '" . $geo_all . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
}

### Начало выполнения задания
if ( $_GET['func'] == 'starttask' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$pr_tasks = mysql_query( "SELECT * FROM tasks t1 WHERE t1.paused = 1 and t1.balance >= (t1.t_wait + t1.t_work ) * t1.price  / '" . $config['factor_tasks'] . "' + t1.price  / '" . $config['factor_tasks'] . "' - 0.02 and id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
	
	if ( !$config_user['activate'] ) {
		exit();
	} else
	
    if ( mysql_num_rows( $pr_tasks ) > 0 ) {
        
		$pr_tasks_row = mysql_fetch_array( $pr_tasks );
		
		if($pr_tasks_row['TimeoutInExecution'] > 0 ) {
			$TimeoutPlus = '1';
		} else {
			$TimeoutPlus = '0';
		}
		
		#Првоеряем тип задания, многоразовое или одноразовое, ибо схема начала для каждого разная
		if($pr_tasks_row['re_execution'] == '1'){
			
			$pr_tasks_temp = mysql_query( "SELECT * FROM tasks_temp WHERE execution = '2' and ident = '" . $pr_tasks_row['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        
			#черный список
			$get_black_list = mysql_query( "SELECT id FROM tasks_black_list_user WHERE ident = '" . $pr_tasks_row['id'] . "' and to_user = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        
			$pr_tasks_temp_row = mysql_fetch_array( $pr_tasks_temp );
				
			#если задание одноразовое и его уже выполняли
			if ( $pr_tasks_row['many'] == 0 and $pr_tasks_temp_row['status'] == 1 ) {
				exit();
			} else
				
			#если включен параметер ограничения по количеству выполнений в сутки и он исчерпан
			if ( $pr_tasks_row['TimeoutInExecution'] > 0 and $pr_tasks_row['TimeoutResidue'] < 1 ) {
				exit();
			} else
				
			if ( mysql_num_rows( $pr_tasks_temp ) > 0 ) {
				#если уже начали выполнять
				if ( $pr_tasks_temp_row['status'] == 0 ) {
					exit();
				} 
			}
			#если задание отправлено на доработку
			if ( $pr_tasks_temp_row['status'] == 3 ) {
				exit();
			} else
				
			#если задание многоразовое и задание уже выпоняли и еще не прошло 24 часа (Переделать под повторное выполнение через определеное время)
			if ( $pr_tasks_temp_row['status'] == 1 and $pr_tasks_row['many'] == 1 and $pr_tasks_temp_row['startdate'] + $pr_tasks_row['executionTime'] > time() ) {
				exit();
			} else
				
			#если исполнитель занесен в чернй список
			if ( mysql_num_rows( $get_black_list ) > 0 ) {
				exit();
			} 
				
			#если отказано и еще не прошло 24 часа (Переделать под повторное выполнение через определеное время)
			if ( $pr_tasks_temp_row['status'] == 2 and $pr_tasks_temp_row['startdate'] + $pr_tasks_row['executionTime'] > time() ) {
				exit();
			}
			
			#если задание являеться автора
			if ( $pr_tasks_row['iduser'] == $_SESSION['iduser'] ) {
				exit();
			} else {
				
				if ( $pr_tasks_row['nextExecutionOn'] > 0 ) {
					$timeNextExecutionOn = time();
				} else {
					$timeNextExecutionOn = '0';
				}
				
				$tasksIP=explode('.', real_IP());
				
				switch ( $pr_tasks_row['ipFilter'] ) {
					case 0:
						$ipsel = '';
						break;
					case 1:
						$ipsel = $tasksIP[0].$tasksIP[1].$tasksIP[2].$tasksIP[3];
						break;
					case 2:
						$ipsel = $tasksIP[0].$tasksIP[1].$tasksIP[2];
						break;
					default:
						$ipsel = '';
						break;
				}
				
				mysql_query( "INSERT INTO tasks_temp SET status = 0, startdate = '" . time() . "', enddate = '" . time() . "' + '" . $pr_tasks_row['maxtime'] . "', ident = '" . $pr_tasks_row['id'] . "', iduser = '" . $_SESSION['iduser'] . "', price = '" . $pr_tasks_row['price'] . "', execution = '2', ip = '". $ipsel ."' " );
				
				mysql_query( "UPDATE tasks SET t_work = t_work + 1, TimeoutResidue = TimeoutResidue - '".$TimeoutPlus."', nextExecution = '".$timeNextExecutionOn."' WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
				echo 1;
				exit();
			
			}
			
		} else {
		
			$pr_tasks_temp = mysql_query( "SELECT * FROM tasks_temp WHERE ident = '" . $pr_tasks_row['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        
			#черный список
			$get_black_list = mysql_query( "SELECT id FROM tasks_black_list_user WHERE ident = '" . $pr_tasks_row['id'] . "' and to_user = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        
			if ( mysql_num_rows( $pr_tasks_temp ) > 0 ) {
				$pr_tasks_temp_row = mysql_fetch_array( $pr_tasks_temp );
				#если задание одноразовое и его уже выполняли
				if ( $pr_tasks_row['many'] == 0 and $pr_tasks_temp_row['status'] == 1 ) {
					exit();
				} else
				#если уже начали выполнять
				if ( $pr_tasks_temp_row['status'] == 0 ) {
					exit();
				} else
				#если уже ответили и ждут ответа от рекламодателя
				if ( $pr_tasks_temp_row['status'] == 4 AND $pr_tasks_row['re_execution'] != 1 ) {
					exit();
				} else
				#если задание отправлено на доработку
				if ( $pr_tasks_temp_row['status'] == 3 ) {
					exit();
				} else
				#если включен параметер ограничения по количеству выполнений в сутки и он исчерпан
				if ( $pr_tasks_row['TimeoutInExecution'] > 0 and $pr_tasks_row['TimeoutResidue'] < 1 ) {
					exit();
				} else	
				#если задание многоразовое и задание уже выпоняли и еще не прошло 24 часа
				if ( $pr_tasks_temp_row['status'] == 1 and $pr_tasks_row['many'] == 1 and $pr_tasks_temp_row['startdate'] + $pr_tasks_row['executionTime'] > time() ) {
					exit();
				} else
				#если исполнитель занесен в чернй список
				if ( mysql_num_rows( $get_black_list ) > 0 ) {
					exit();
				} else
				#если отказано и еще не прошло 24 часа
				if ( $pr_tasks_temp_row['status'] == 2 and $pr_tasks_temp_row['startdate'] + $pr_tasks_row['executionTime'] > time() ) {
					exit();
				} else {
					
					if ( $pr_tasks_row['nextExecutionOn'] > 0 ) {
						$timeNextExecutionOn = time();
					} else {
						$timeNextExecutionOn = '0';
					}
					
					$tasksIP=explode('.', real_IP());
				
					switch ( $pr_tasks_row['ipFilter'] ) {
						case 0:
							$ipsel = '';
							break;
						case 1:
							$ipsel = $tasksIP[0].$tasksIP[1].$tasksIP[2].$tasksIP[3];
							break;
						case 2:
							$ipsel = $tasksIP[0].$tasksIP[1].$tasksIP[2];
							break;
						default:
							$ipsel = '';
							break;
					}
					
					mysql_query( "UPDATE tasks_temp SET status = 0, answer = '', startdate = '" . time() . "', enddate = '" . time() . "' + '" . $pr_tasks_row['maxtime'] . "', price = '" . $pr_tasks_row['price'] . "', execution = '1', ip = '".$ipsel."' WHERE ident = '" . $pr_tasks_row['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
					mysql_query( "UPDATE tasks SET t_work = t_work + 1, TimeoutResidue = TimeoutResidue - '".$TimeoutPlus."', nextExecution = '".$timeNextExecutionOn."' WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
					echo 1;
					exit();
				}
			} else
			#если задание являеться автора
			if ( $pr_tasks_row['iduser'] == $_SESSION['iduser'] ) {
				exit();
			} else {
				
				if ( $pr_tasks_row['nextExecutionOn'] > 0 ) {
					$timeNextExecutionOn = time();
				} else {
					$timeNextExecutionOn = '0';
				}
				
				$tasksIP=explode('.', real_IP());
				
					switch ( $pr_tasks_row['ipFilter'] ) {
						case 0:
							$ipsel = '';
							break;
						case 1:
							$ipsel = $tasksIP[0].$tasksIP[1].$tasksIP[2].$tasksIP[3];
							break;
						case 2:
							$ipsel = $tasksIP[0].$tasksIP[1].$tasksIP[2];
							break;
						default:
							$ipsel = '';
							break;
					}
				
				mysql_query( "INSERT INTO tasks_temp SET status = 0, startdate = '" . time() . "', enddate = '" . time() . "' + '" . $pr_tasks_row['maxtime'] . "', ident = '" . $pr_tasks_row['id'] . "', iduser = '" . $_SESSION['iduser'] . "', price = '" . $pr_tasks_row['price'] . "', execution = '1', ip = '".$ipsel."'" );
				mysql_query( "UPDATE tasks SET t_work = t_work + 1, TimeoutResidue = TimeoutResidue - '".$TimeoutPlus."', nextExecution = '".$timeNextExecutionOn."' WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
				echo 1;
				exit();
			}
    
		}
	
	} else {
        exit();
    }
}

### Включение - Отключение задание
if ( $_GET['func'] == 'runtasks' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, paused FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
        $pr_row = mysql_fetch_array( $proverka );
        
        $pr_tasks_temp = mysql_query( "SELECT id FROM tasks_temp WHERE ident = '" . ( int ) $_POST['id'] . "' and status in (0,3,4) LIMIT 1" );
                
        if ( $config['tasks'] / $config['factor_tasks'] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
            echo 'Недостаточно средств на балансе рекламной площадки!';
            exit();
        } else {
            if ( $pr_row['paused'] == 1 ) {
                if ( mysql_num_rows( $pr_tasks_temp ) > 0 ) {
                    echo 'Задание нельзя остановить пока его выполняют!';
                    exit();
                } else {
                    $paused = 0;
                }
                
            } else {
                $paused = 1;
            }
            
            mysql_query( "UPDATE tasks SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
}

### Отказ от выполнения задания
if ( $_GET['func'] == 'refuse_answer' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $sql_task = mysql_query( "SELECT ident FROM tasks_temp WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and status in (0,3) LIMIT 1" );
    if ( mysql_num_rows( $sql_task ) > 0 ) {
        $sql_task_row = mysql_fetch_array( $sql_task );
		
		# Вынимаем информацию о задание, а имено статус тайм аута
		$pr_tasks_row = mysql_fetch_array( mysql_query( "SELECT TimeoutInExecution FROM tasks WHERE id = '" . $sql_task_row['ident'] . "'" ) );
		# Проверяем если параметер ограничения выполнений посуточно включен, даем перемене значение 1
		if($pr_tasks_row['TimeoutInExecution'] > 0 ) {
			$TimeoutPlus = '1';
		} else {
			$TimeoutPlus = '0';
		}
		
        mysql_query( "UPDATE tasks SET t_work = t_work - 1, TimeoutResidue = TimeoutResidue + '".$TimeoutPlus."', nextExecution = '0' WHERE id = '" . $sql_task_row['ident'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM tasks_temp WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and status in (0,3)" );
        echo 1;
        exit();
    }
}

### Отчет о выполнения задания
if ( $_GET['func'] == 'send_answer' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['answer'] = trim( $_POST['answer'] );
    
    if ( empty( $_POST['answer'] ) ) {
        echo 2;
        exit();
    }
    
    $sql_task = mysql_query( "SELECT ident FROM tasks_temp WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and status in (0,3) LIMIT 1" );
    if ( mysql_num_rows( $sql_task ) > 0 ) {
        $sql_task_row = mysql_fetch_array( $sql_task );
        
        #черный список
        $get_black_list = mysql_query( "SELECT id FROM tasks_black_list_user WHERE ident = '" . $sql_task_row['ident'] . "' and to_user = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $get_black_list ) > 0 ) {
            exit();
        } else {
            mysql_query( "UPDATE tasks SET t_work = t_work - 1, t_wait = t_wait + 1 WHERE id = '" . $sql_task_row['ident'] . "' LIMIT 1" );
            mysql_query( "UPDATE tasks_temp SET status = 4, answer = '" . substr( check_text( $_POST['answer'] ), 0, 255 ) . "', startdate = '" . time() . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and status in (0,3) LIMIT 1" );
            echo 1;
            exit();
        }
    }
}

### Задание на доработку
if ( $_GET['func'] == 'task_revision' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['revision'] = trim( $_POST['revision'] );
    
    if ( empty( $_POST['revision'] ) ) {
        echo 2;
        exit();
    }
    
    $get_task = mysql_query( "SELECT id, ident FROM tasks_temp WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . ( int ) $_POST['user'] . "' and status in (4) and ident IN(SELECT id FROM tasks WHERE iduser = '" . $_SESSION['iduser'] . "') LIMIT 1" );
    if ( mysql_num_rows( $get_task ) > 0 ) {
        $get_task_row = mysql_fetch_array( $get_task );
        
        $maxtime = mysql_fetch_array( mysql_query( "SELECT maxtime FROM tasks WHERE id = '" . $get_task_row['ident'] . "'" ) );
		
		$revision_task = check_text( $_POST['revision'] );
        $revision_task = parce_bb_code( $revision_task, 'all' );
        $revision_task = substr( $revision_task, 0, 3000 );
        
        mysql_query( "UPDATE tasks SET t_wait = t_wait - 1, t_work = t_work + 1 WHERE id = '" . $get_task_row['ident'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "UPDATE tasks_temp SET status = 3, enddate = enddate + '" . $maxtime['maxtime'] . "', refuse = '" . $revision_task . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . ( int ) $_POST['user'] . "' LIMIT 1" );
        echo 1;
        exit();
    }
}

### Отклонение задания
if ( $_GET['func'] == 'send_refuse' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['refuse'] = trim( $_POST['refuse'] );
    
    if ( empty( $_POST['refuse'] ) ) {
        echo 2;
        exit();
    }
    
    $get_task = mysql_query( "SELECT id, ident FROM tasks_temp WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . ( int ) $_POST['user'] . "' and status in (4) and ident IN(SELECT id FROM tasks WHERE iduser = '" . $_SESSION['iduser'] . "') LIMIT 1" );
    if ( mysql_num_rows( $get_task ) > 0 ) {
        $get_task_row = mysql_fetch_array( $get_task );
		
		$refuse_task = check_text( $_POST['refuse'] );
        $refuse_task = parce_bb_code( $refuse_task, 'all' );
        $refuse_task = substr( $refuse_task, 0, 3000 );
		
        mysql_query( "UPDATE tasks SET t_wait = t_wait - 1, t_bad = t_bad + 1 WHERE id = '" . $get_task_row['ident'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "UPDATE tasks_temp SET status = 2, refuse = '" . $refuse_task . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . ( int ) $_POST['user'] . "' LIMIT 1" );
        mysql_query( "UPDATE user SET tasks_view = tasks_view - 1 WHERE id = '" . ( int ) $_POST['user'] . "' LIMIT 1" );
        echo 1;
        exit();
    }
}

### Принятие отчета для задания
if ( $_GET['func'] == 'ok_tasks' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $get_task = mysql_query( "SELECT id, ident, price FROM tasks_temp WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . ( int ) $_POST['user'] . "' and status in (4) and ident IN(SELECT id FROM tasks WHERE iduser = '" . $_SESSION['iduser'] . "' and balance >= price / '" . $config['factor_tasks'] . "') ORDER BY id DESC LIMIT 1" );
    if ( mysql_num_rows( $get_task ) > 0 ) {
        $get_task_row = mysql_fetch_array( $get_task );
        
        $get_user = mysql_fetch_array( mysql_query( "SELECT referer, autoproc FROM user WHERE id = '" . ( int ) $_POST['user'] . "' LIMIT 1" ) );
        
        #зачисляем рефбек рефералу I уровня
        if ( $get_user['referer'] != 0 ) {
            $ref_1 = mysql_fetch_array( mysql_query( "SELECT reyting FROM user WHERE id = '" . $get_user['referer'] . "' LIMIT 1" ) );
            
            if ( $ref_1['reyting'] >= $config_site['status_meaning_1a'] and $ref_1['reyting'] <= $config_site['status_meaning_1b'] ) {
                $ref1_back = $get_task_row['price'] * $config['st13'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_2a'] and $ref_1['reyting'] <= $config_site['status_meaning_2b'] ) {
                $ref1_back = $get_task_row['price'] * $config['st14'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_3a'] and $ref_1['reyting'] <= $config_site['status_meaning_3b'] ) {
                $ref1_back = $get_task_row['price'] * $config['st15'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_4a'] and $ref_1['reyting'] <= $config_site['status_meaning_4b'] ) {
                $ref1_back = $get_task_row['price'] * $config['st16'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_5a'] and $ref_1['reyting'] <= $config_site['status_meaning_5b'] ) {
                $ref1_back = $get_task_row['price'] * $config['st17'];
            } else
            if ( $ref_1['reyting'] >= $config_site['status_meaning_6a'] ) {
                $ref1_back = $get_task_row['price'] * $config['st18'];
            } else {
                $ref1_back = 0;
            }
            
            if ( !is_numeric( $ref1_back ) ) $my_refback = 0;
            $my_refback = $ref1_back * ( $get_user['autoproc'] / 100 );
            if ( !is_numeric( $my_refback ) ) $my_refback = 0;
            $ref1_refback = $ref1_back - $my_refback;
            if ( !is_numeric( $ref1_refback ) ) $ref1_refback = 0;
            mysql_query( "UPDATE user SET money = money + '" . $ref1_refback . "' WHERE id = '" . $get_user['referer'] . "' LIMIT 1" );
        }
        
        $my_money = $get_task_row['price'] + $my_refback;
        $adv_money = ( $get_task_row['price'] / $config['factor'] );
        
        if ($config_user['activate'] == 1) {
			#Конкурс выполнения заданий от админа
			$chKonkurs = mysql_query( "SELECT id FROM konkurs WHERE type = 2 and date_end > '". time() ."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkurs ) > 0 ) {
				$get_user_status = mysql_fetch_array( mysql_query( "SELECT account FROM user WHERE id = '" . ( int ) $_POST['user'] . "'" ) );
				if($get_user_status['account'] != 5) {
					$chKonkursRow = mysql_fetch_array( $chKonkurs );
					$chKonkursTemp = mysql_query( "SELECT id FROM konkurs_temp WHERE iduser = '" . ( int ) $_POST['user'] . "' and id_konkurs = '" . $chKonkursRow['id'] . "' and type = 2" );
					if ( mysql_num_rows( $chKonkursTemp ) > 0 ) {
						mysql_query( "UPDATE konkurs_temp SET summ = summ + '1' WHERE iduser = '" . ( int ) $_POST['user'] . "' and type = 2 LIMIT 1" );
					} else {
						mysql_query( "INSERT INTO konkurs_temp SET id_konkurs = '" . $chKonkursRow['id'] . "', iduser = '" . ( int ) $_POST['user'] . "', summ = '1', type = 2" );
					}
				}
			}
			#Конкурс задание дателя от админа
			$get_act_user_a = mysql_fetch_array( mysql_query( "SELECT activate FROM user WHERE id = '" . $_SESSION['iduser'] . "'" ) );
			if($get_act_user_a['activate'] == 1) {
				$chKonkurs_adv = mysql_query( "SELECT id FROM konkurs WHERE type = 3 and date_end > '". time() ."' LIMIT 1" );
				if ( mysql_num_rows( $chKonkurs_adv ) > 0 ) {
					$get_user_status_adv = mysql_fetch_array( mysql_query( "SELECT account FROM user WHERE id = '" . $_SESSION['iduser'] . "'" ) );
					if($get_user_status_adv['account'] != 5) {
						$chKonkursRow_adv = mysql_fetch_array( $chKonkurs_adv );
						$chKonkursTemp_adv = mysql_query( "SELECT id FROM konkurs_temp WHERE iduser = '" . $_SESSION['iduser'] . "' and id_konkurs = '" . $chKonkursRow_adv['id'] . "' and type = 3" );
						if ( mysql_num_rows( $chKonkursTemp_adv ) > 0 ) {
							mysql_query( "UPDATE konkurs_temp SET summ = summ + '". $adv_money ."' WHERE iduser = '" . $_SESSION['iduser'] . "' and type = 3 LIMIT 1" );
						} else {
							mysql_query( "INSERT INTO konkurs_temp SET id_konkurs = '" . $chKonkursRow_adv['id'] . "', iduser = '" . $_SESSION['iduser'] . "', summ = '". $adv_money ."', type = 3" );
						}
					}
				}
			}
		}
		
		mysql_query( "UPDATE user SET earnings_task = earnings_task + '" . $my_money . "', money = money + '" . $my_money . "', toref = toref + '" . $ref1_refback . "', tasks_view = tasks_view + 1 WHERE id = '" . ( int ) $_POST['user'] . "' LIMIT 1" );
        
        $viruchka = ( $get_task_row['price'] / $config['factor_tasks'] ) - $ref1_refback - $my_money;
        mysql_query( "UPDATE viruchka SET money = money + '" . $viruchka . "' WHERE ident = 5 LIMIT 1" );
		
		#конкурсы от реферера
		if ( $get_user['referer'] != 0  and $config_user['activate'] == 1) {
			#выполнения заданий
			$chKonkursWan = mysql_query( "SELECT * FROM contests WHERE type = 1 and date_end > '". time() ."' and autor = '".$get_user['referer']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursWan ) > 0 ) {
				$chKonkursRowWan = mysql_fetch_array( $chKonkursWan );
				$chKonkursTempWan = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . ( int ) $_POST['user'] . "' and id_konkurs = '" . $chKonkursRowWan['id'] . "' and type = 1" );
				if ( mysql_num_rows( $chKonkursTempWan ) > 0 ) {
					mysql_query( "UPDATE contests_temp SET summ = summ + 5 WHERE iduser = '" . ( int ) $_POST['user'] . "' and type = 1 and id_konkurs = '" . $chKonkursRowWan['id'] . "' LIMIT 1" );
				} else {
					mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowWan['id'] . "', iduser = '" . ( int ) $_POST['user'] . "', summ = 5, type = 1" );
				}
			}
			#комплексный
			$chKonkursComplex = mysql_query( "SELECT * FROM contests WHERE type = 3 and date_end > '". time() ."' and autor = '".$get_user['referer']."' LIMIT 1" );
			if ( mysql_num_rows( $chKonkursComplex ) > 0 ) {
				$chKonkursRowComplex = mysql_fetch_array( $chKonkursComplex );
				$chKonkursTempComplex = mysql_query( "SELECT id FROM contests_temp WHERE iduser = '" . ( int ) $_POST['user'] . "' and id_konkurs = '" . $chKonkursRowComplex['id'] . "' and type = 3" );
				if ( mysql_num_rows( $chKonkursTempComplex ) > 0 ) {
					mysql_query( "UPDATE contests_temp SET summ = summ + 5 WHERE iduser = '" . ( int ) $_POST['user'] . "' and type = 3 and id_konkurs = '" . $chKonkursRowComplex['id'] . "' LIMIT 1" );
				} else {
					mysql_query( "INSERT INTO contests_temp SET id_konkurs = '" . $chKonkursRowComplex['id'] . "', iduser = '" . ( int ) $_POST['user'] . "', summ = 5, type = 3" );
				}
			}
		}
        
        mysql_query( "UPDATE tasks_temp SET status = 1, refuse = '' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . ( int ) $_POST['user'] . "' and status = 4 LIMIT 1" );
        mysql_query( "UPDATE tasks SET t_wait = t_wait - 1, t_goods = t_goods + 1, balance = balance - price / '" . $config['factor_tasks'] . "' WHERE id = '" . $get_task_row['ident'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        
        #Создаем по днях статистику зароботка
		mysql_query( "INSERT INTO earnings_statistics SET iduser = '" . ( int ) $_POST['user'] . "', summ = '1', date = '" . time() . "', ident = '" . $get_task_row['ident'] . "', type = '4'" );
    
        echo 1;
        exit();
    }
}

### Удаление задания
if ( $_GET['func'] == 'deltasks' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT price, balance, date FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        $pr_tasks_temp = mysql_query( "SELECT id FROM tasks_temp WHERE ident = '" . ( int ) $_POST['id'] . "' and status in (0,3,4) LIMIT 1" );
        if ( mysql_num_rows( $pr_tasks_temp ) > 0 ) {
            echo 'Задание нельзя удалить пока его выполняют!';
            exit();
        }
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        if ( $pr_row['balance'] > 0.2 / $config['factor_tasks'] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM tasks_temp WHERE ident = '" . ( int ) $_POST['id'] . "'" );
        mysql_query( "DELETE FROM tasks_comment WHERE ident = '" . ( int ) $_POST['id'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 5" );
        
        echo 1;
        exit();
    }
}

### Авто подьем задания
if ( $_GET['func'] == 'tasksup' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT * FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( ( int ) $_POST['upreser'] != 0 and ( int ) $_POST['upreser'] != 600 and ( int ) $_POST['upreser'] != 600*3 and ( int ) $_POST['upreser'] != 3600 and ( int ) $_POST['upreser'] != 3600*2 and ( int ) $_POST['upreser'] != 3600*3 and ( int ) $_POST['upreser'] != 3600*5 and ( int ) $_POST['upreser'] != 3600*10 and ( int ) $_POST['upreser'] != 86400 ) {
        echo 'Вы не выбрали частоту поднятия задания!';
        exit();
		} else 
			
		if(( int ) $_POST['upreser'] == 0){
			mysql_query( "UPDATE tasks SET dateup = '0' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
			echo 1;
			exit();
		} else {
			mysql_query( "UPDATE tasks SET dateup = '".( int ) $_POST['upreser']."' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
			echo 1;
			exit();	
		}
    }
}

### Подьем задания
if ( $_GET['func'] == 'tasksupw' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT * FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
		$up_user_balance = mysql_fetch_array( mysql_query( "SELECT adv_money FROM user WHERE id = '".$pr_row['iduser']."'" ) );
		
		if($pr_row['paused'] <= 0){
			echo 'В начале запустите задание!';
			exit();
		} else
		
		if($up_user_balance["adv_money"] >= $config['tasksup']) {
			
			mysql_query( "UPDATE tasks SET date = '".time()."' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
			mysql_query( "UPDATE user SET adv_money = adv_money - '".$config['tasksup']."' WHERE id = '" . $pr_row['iduser'] . "' LIMIT 1" );
			mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $pr_row['iduser'] . "', price = '" . $config['tasksup'] . "', type = 4, date = '" . time() . "', h_text = 'Подъем задания <b>№" . ( int ) $_POST['id'] . "</b> в списке выдачи', payopt = 0 " );
			echo 1;
			exit();
		
		} else {
			echo 'Недостаточно средств на рекламном счете!';
			exit();	
		}
	}
}

### Комментарий к заданию
if ( $_GET['func'] == 'addtaskcomm' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['comm'] = trim( $_POST['comm'] );
    
    if ( empty( $_POST['comm'] ) ) {
        echo 'Комментарий не может быть пустым!';
        exit();
    }
    
    $sql_tasks = mysql_query( "SELECT id FROM tasks_temp WHERE ident = '" . ( int ) $_POST['id'] . "' and status in (1,2) and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( mysql_num_rows( $sql_tasks ) > 0 ) {
        $task_comm = mysql_query( "SELECT id FROM tasks_comment WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $task_comm ) == 0 ) {
            if ( $_POST['typecomm'] == 'on' ) {
                $typecomm = 1;
            } else {
                $typecomm = 0;
            }
			
			$comment_task = check_text( $_POST['comm'] );
            $comment_task = parce_bb_code( $comment_task, 'all' );
            $comment_task = substr( $comment_task, 0, 3000 );
            
            mysql_query( "INSERT INTO tasks_comment SET ident = '" . ( int ) $_POST['id'] . "', iduser = '" . $_SESSION['iduser'] . "', comm = '" . $comment_task . "', type = '" . $typecomm . "', date = '" . time() . "'" );
            
            echo 1;
            exit();
        } else {
			echo 'Вы уже оставляли отзыв об этом задание!';
			exit();
		}
    } else {
		echo 'Отзыв могут писать только те, кто выполнил задание!';
        exit();
	}
}

### Черный список пользователей, задания
if ( $_GET['func'] == 'tasks_black_user' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $get_task = mysql_query( "SELECT id, ident FROM tasks_temp WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . ( int ) $_POST['user'] . "' and status in (4) and ident IN(SELECT id FROM tasks WHERE iduser = '" . $_SESSION['iduser'] . "') LIMIT 1" );
    if ( mysql_num_rows( $get_task ) > 0 ) {
        $get_task_row = mysql_fetch_array( $get_task );
        $tasks_black_list = mysql_query( "SELECT id FROM tasks_black_list_user WHERE ident = '" . $get_task_row['ident'] . "' and to_user = '" .( int ) $_POST['user'] . "' and from_user = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $tasks_black_list ) > 0 ) {
            echo 'Исполнитель уже находиться в черном списке!';
            exit();
        } else {
            mysql_query( "INSERT INTO tasks_black_list_user SET ident = '" . $get_task_row['ident'] . "', to_user = '" .( int ) $_POST['user'] . "', from_user = '" . $_SESSION['iduser'] . "', date = '" . time() . "'" );
            echo 1;
            exit();
        }
    }
}

### Удаление из черноего списка задания
if ( $_GET['func'] == 'remove_user_black_list' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $bl = mysql_query( "SELECT id FROM tasks_black_list_user WHERE id = '" . ( int ) $_POST['id'] . "' and from_user = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( mysql_num_rows( $bl ) > 0 ) {
        mysql_query( "DELETE FROM tasks_black_list_user WHERE id = '" . ( int ) $_POST['id'] . "' and from_user = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        echo 1;
        exit();
    }
}

### Добавления в избранное задание
if ( $_GET['func'] == 'addtasksfav' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $pr_task = mysql_query( "SELECT id FROM tasks t1 WHERE many = 1 and id = '" . ( int ) $_POST['id'] . "' and NOT EXISTS(SELECT ident, iduser FROM tasks_favorites t2 WHERE t2.ident = t1.id and t2.iduser = '" . $_SESSION['iduser'] . "')" );
    if ( mysql_num_rows( $pr_task ) > 0 ) {
        mysql_query( "INSERT INTO tasks_favorites SET ident = '" . ( int ) $_POST['id'] . "', iduser = '" . $_SESSION['iduser'] . "'" );
        echo 1;
        exit();
    } else {
        echo 'Задание не существует или уже в избранном!';
        exit();
    }
}

### Удалить из избранного задание
if ( $_GET['func'] == 'deltasksfav' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $pr_fav = mysql_query( "SELECT id FROM tasks_favorites WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( mysql_num_rows( $pr_fav ) > 0 ) {
        mysql_query( "DELETE FROM tasks_favorites WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        echo 1;
        exit();
    } else {
        echo 'Ничего не найдено!';
        exit();
    }
}

### Заказ баннера 200 х 300
if ( $_GET['func'] == 'addbanner200x300' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	#Проверка на блокировку
    $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
    if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
    $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
    if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
        $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
        echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
        exit();
    }
    
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) )  {
        echo 'erurl';
        exit();
    } else
	
    if ( !$_FILES['banner']['name'] ) {
        echo 'Файл не выбран!';
        exit();
    } else
		
	if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
    	$_POST['url'] = 'http://' . check_text( $_POST['url'] );
    }
	
    if ( $_FILES["banner"]["size"] <= 0 and $_FILES["banner"]["size"] > 500 * 1024 ) {
        echo 'Максималный размер баннера 500 кб.!';
        exit();
    } else
    if ( $_FILES['banner']['type'] != 'image/jpg' and  $_FILES['banner']['type'] != 'image/jpeg' and $_FILES['banner']['type'] != 'image/png' and $_FILES['banner']['type'] != 'image/gif') {
        echo 'Неверный формат изображения!';
        exit();
    } else
    if ( is_uploaded_file( $_FILES["banner"]["tmp_name"] ) ) {
        $imgwh = GetImageSize( $_FILES["banner"]["tmp_name"] );
        
        if ( $imgwh[0] > 200 or $imgwh[1] > 300 or $imgwh[0] < 200 or $imgwh[1] < 300 ) {
            echo 'Допустимый размер баннера 200 х 300!';
            exit();
        } else {
            $type_file = str_replace("theme/tmp/", "", basename($_FILES['banner']['type']));
            
            if ( @move_uploaded_file( $_FILES['banner']['tmp_name'], "temp/banner/200x300/" . time() . $_SESSION["iduser"] . '.' . $type_file ) ) {
                mysql_query( "INSERT INTO banners (iduser, img, url, title, date, type) VALUES ('" . $_SESSION['iduser'] . "', '" . time() . $_SESSION["iduser"] . "." . $type_file . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . time() . "', 0)" );
                echo 1;
                exit();
            } else {
                echo 'Произошла внутренняя ошибка! Попробуйте позже!';
                exit();
            }
        }
    } else {
        echo 'Произошла внутренняя ошибка! Попробуйте позже!';
        exit();
    }
}

### Заказ баннера 200 х 300 без сессии авторизации
if ( $_GET['func'] == 'addbanner200x300_nouser' ) {
    
    sleep(1);
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	#Проверка на блокировку
    $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
    if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
    $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
    if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
        $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
        echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
        exit();
    }
    
	$check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	$check_bt_order = mysql_query( "SELECT nouser_order FROM banners WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	if ( mysql_num_rows( $check_bt_order ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( mysql_num_rows( $check_order_basket ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) )  {
        echo 'erurl';
        exit();
    } else
	
    if ( !$_FILES['banner']['name'] ) {
        echo 'Файл не выбран!';
        exit();
    } else
		
	if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
    	$_POST['url'] = 'http://' . check_text( $_POST['url'] );
    }
	
    if ( $_FILES["banner"]["size"] <= 0 and $_FILES["banner"]["size"] > 500 * 1024 ) {
        echo 'Максималный размер баннера 500 кб.!';
        exit();
    } else
    if ( $_FILES['banner']['type'] != 'image/jpg' and  $_FILES['banner']['type'] != 'image/jpeg' and $_FILES['banner']['type'] != 'image/png' and $_FILES['banner']['type'] != 'image/gif') {
        echo 'Неверный формат изображения!';
        exit();
    } else
    if ( is_uploaded_file( $_FILES["banner"]["tmp_name"] ) ) {
        $imgwh = GetImageSize( $_FILES["banner"]["tmp_name"] );
        
        if ( $imgwh[0] > 200 or $imgwh[1] > 300 or $imgwh[0] < 200 or $imgwh[1] < 300 ) {
            echo 'Допустимый размер баннера 200 х 300!';
            exit();
        } else {
            
			$quantity = ( int ) $_POST['quantity'];
			$quantity_summ = ($config['banner200x300'] * $quantity);
			
			#Создаем счет в корзину на оплату заказа
			if ( $quantity < 10 OR $quantity >= 10000 ) {
			  echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 10, максимальное 10000.';
			  exit();
			} else {
			  $type_file = str_replace("theme/tmp/", "", basename($_FILES['banner']['type']));
              if ( @move_uploaded_file( $_FILES['banner']['tmp_name'], "temp/banner/200x300/" . time() . $_SESSION["iduser"] . '.' . $type_file ) ) {
                
				mysql_query( "INSERT INTO banners (iduser, img, url, title, date, type, nouser, nouser_order) VALUES ('" . $_SESSION['iduser'] . "', '" . time() . $_SESSION["iduser"] . "." . $type_file . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . time() . "', '0', '1', '" . ( int ) $_POST['bt_order'] . "')" );
                #Делаем запрос на создание счета для оплаты площадки
			    mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '3', '" . ( int ) $_POST['bt_order'] . "')" );
				
				echo 1;
                exit();
              
			  } else {
                echo 'Произошла внутренняя ошибка! Попробуйте позже!';
                exit();
              }
            }
		}
    } else {
        echo 'Произошла внутренняя ошибка! Попробуйте позже!';
        exit();
    }
}

### Удаление баннера 200х300
if ( $_GET['func'] == 'delban2x3' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, img, date FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        if ( $pr_row['balance'] > $config['banner200x300'] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        unlink( ROOT_DIR . '/temp/banner/200x300/' . $pr_row['img'] );
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 3" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение баннера 200х300
if ( $_GET['func'] == 'runban200x300' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, paused FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
        $pr_row = mysql_fetch_array( $proverka );
                
        if ( $config['tests'] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
            echo 'Недостаточно средств на балансе рекламной площадки!';
            exit();
        } else {
            if ( $pr_row['paused'] == 1 ) {
                $paused = 0;
            } else {
                $paused = 1;
            }
            
            mysql_query( "UPDATE banners SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
} 

### Заказ баннера 468 х 60
if ( $_GET['func'] == 'addbanner468x60' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	#Проверка на блокировку
    $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
    if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
    $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
    if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
        $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
        echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
        exit();
    }
    
	if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) )  {
        echo 'erurl';
        exit();
    } else
		
	if ( !$_FILES['banner']['name'] ) {
        echo 'Файл не выбран!';
        exit();
    } else
		
	if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
    	$_POST['url'] = 'http://' . check_text( $_POST['url'] );
    } 
    
    if ( $_FILES["banner"]["size"] <= 0 and $_FILES["banner"]["size"] > 500 * 1024 ) {
        echo 'Максималный размер баннера 500 кб.!';
        exit();
    } else
    if ( $_FILES['banner']['type'] != 'image/jpg' and  $_FILES['banner']['type'] != 'image/jpeg' and $_FILES['banner']['type'] != 'image/png' and $_FILES['banner']['type'] != 'image/gif') {
        echo 'Неверный формат изображения!';
        exit();
    } else
    if ( is_uploaded_file( $_FILES["banner"]["tmp_name"] ) ) {
        $imgwh = GetImageSize( $_FILES["banner"]["tmp_name"] );
        
        if ( $imgwh[0] > 468 or $imgwh[1] > 60 or $imgwh[0] < 468 or $imgwh[1] < 60 ) {
            echo 'Допустимый размер баннера 468 х 60!';
            exit();
        } else {
            $type_file = str_replace("theme/tmp/", "", basename($_FILES['banner']['type']));
            
            if ( @move_uploaded_file( $_FILES['banner']['tmp_name'], "temp/banner/468x60/" . time() . $_SESSION["iduser"] . '.' . $type_file ) ) {
                mysql_query( "INSERT INTO banners (iduser, img, url, title, date, type) VALUES ('" . $_SESSION['iduser'] . "', '" . time() . $_SESSION["iduser"] . "." . $type_file . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . time() . "', 1)" );
                echo 1;
                exit();
            } else {
                echo 'Произошла внутренняя ошибка! Попробуйте позже!';
                exit();
            }
        }
    } else {
        echo 'Произошла внутренняя ошибка! Попробуйте позже!';
        exit();
    }
}

### Заказ баннера 468 х 60 без сессии авторизации
if ( $_GET['func'] == 'addbanner468x60_nouser' ) {
    
    sleep(1);
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	#Проверка на блокировку
    $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
    if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
    $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
    if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
        $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
        echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
        exit();
    }
    
	$check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	$check_bt_order = mysql_query( "SELECT nouser_order FROM banners WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	if ( mysql_num_rows( $check_bt_order ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( mysql_num_rows( $check_order_basket ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) )  {
        echo 'erurl';
        exit();
    } else
		
	if ( !$_FILES['banner']['name'] ) {
        echo 'Файл не выбран!';
        exit();
    } else
		
	if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
    	$_POST['url'] = 'http://' . check_text( $_POST['url'] );
    } 
    
    if ( $_FILES["banner"]["size"] <= 0 and $_FILES["banner"]["size"] > 500 * 1024 ) {
        echo 'Максималный размер баннера 500 кб.!';
        exit();
    } else
    if ( $_FILES['banner']['type'] != 'image/jpg' and  $_FILES['banner']['type'] != 'image/jpeg' and $_FILES['banner']['type'] != 'image/png' and $_FILES['banner']['type'] != 'image/gif') {
        echo 'Неверный формат изображения!';
        exit();
    } else
    if ( is_uploaded_file( $_FILES["banner"]["tmp_name"] ) ) {
        $imgwh = GetImageSize( $_FILES["banner"]["tmp_name"] );
        
        if ( $imgwh[0] > 468 or $imgwh[1] > 60 or $imgwh[0] < 468 or $imgwh[1] < 60 ) {
            echo 'Допустимый размер баннера 468 х 60!';
            exit();
        } else {
			$quantity = ( int ) $_POST['quantity'];
			$quantity_summ = ($config['banner468x60'] * $quantity);
			
			#Создаем счет в корзину на оплату заказа
			if ( $quantity < 10 OR $quantity >= 10000 ) {
			  echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 10, максимальное 10000.';
			  exit();
			} else {
			
              $type_file = str_replace("theme/tmp/", "", basename($_FILES['banner']['type']));
              if ( @move_uploaded_file( $_FILES['banner']['tmp_name'], "temp/banner/468x60/" . time() . $_SESSION["iduser"] . '.' . $type_file ) ) {
                
				mysql_query( "INSERT INTO banners (iduser, img, url, title, date, type, nouser, nouser_order) VALUES ('" . $_SESSION['iduser'] . "', '" . time() . $_SESSION["iduser"] . "." . $type_file . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . time() . "', '1', '1', '" . ( int ) $_POST['bt_order'] . "')" );
                #Делаем запрос на создание счета для оплаты площадки
			    mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '4', '" . ( int ) $_POST['bt_order'] . "')" );
				
 			    echo 1;
                exit();
             
			 } else {
                echo 'Произошла внутренняя ошибка! Попробуйте позже!';
                exit();
              }
			}
        }
    } else {
        echo 'Произошла внутренняя ошибка! Попробуйте позже!';
        exit();
    }
}

### Удаление баннера 468х60
if ( $_GET['func'] == 'delban468x60' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, img, date FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        if ( $pr_row['balance'] > $config['banner468x60'] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        unlink( ROOT_DIR . '/temp/banner/468x60/' . $pr_row['img'] );
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 3" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение баннера 468х60
if ( $_GET['func'] == 'runban468x60' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, paused FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
        $pr_row = mysql_fetch_array( $proverka );
                
        if ( $config['tests'] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
            echo 'Недостаточно средств на балансе рекламной площадки!';
            exit();
        } else {
            if ( $pr_row['paused'] == 1 ) {
                $paused = 0;
            } else {
                $paused = 1;
            }
            
            mysql_query( "UPDATE banners SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
}

### Новое сообщение
if ( $_GET['func'] == 'newmsg' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['text'] = trim( $_POST['text'] );
    
    if ( $config_user['admmessblock'] ) {
        echo 'Вам запрещено отправлять сообщения';
        exit();
    }

    $text = check_text( $_POST['text'] );
    $text = parce_bb_code( $text, 'msg' );
    
    $sql = mysql_query( "SELECT id, messblock, userdel FROM user WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    $row = mysql_fetch_array( $sql );
    
    if ( mysql_num_rows( $sql ) == 0 ) {
        echo 'Пользователь не найден!';
        exit();
    } else
    if ( $row['userdel'] == 1 ) {
        echo 'Пользователь удален!';
        exit();
    } else
    if ( $_POST['type'] != substr( md5( $message_md5 . $row['id'] ), 0, 22 )  ) {
        echo 'Пользователь не является вашим собеседником!';
        exit();
    } else
    if ( $row['messblock'] == 2 ) {
        echo 'Пользователь запретил отправлять ему сообщения!';
        exit();
    } else
    if ( $row['messblock'] == 1 and $config_user['referer'] != $row['id'] and $config_user['account'] != 5 ) {
        echo 'Сообщения могут отправлять только рефералы!';
        exit();
    } else
    if ( ( int ) $_POST['id'] == $_SESSION['iduser'] ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['text'] ) ) {
        echo 2;
        exit();
    } else {
        mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . ( int ) $_POST['id'] . "', text = '" . substr( $text, 0, 3000 ) . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . ( int ) $_POST['id'] . "', text = '" . substr( $text, 0, 3000 ) . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . ( int ) $_POST['id'] . "'" );
        
        echo 1;
        exit();
    }
}

### Удаление личных входящих сообщений
if ( $_GET['func'] == 'delmsgin' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $msg = mysql_query( "SELECT from_id, to_id, m_state, from_del, to_del FROM messages WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $msg ) > 0 ) {
        $row = mysql_fetch_array( $msg );
        
        if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['iduser'] ) {
            mysql_query( "UPDATE messages SET to_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );
            
            echo 1;
            exit();
        } else
        if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['iduser'] ) {
            mysql_query( "UPDATE messages SET from_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );
            
            echo 1;
            exit();
        }
    }
}

### Удаление всех личных входящих сообщений
if ( $_GET['func'] == 'delmsginall' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $msg = mysql_query( "SELECT id, from_id, to_id, m_state, from_del, to_del, history FROM messages WHERE (from_id = '" . ( int ) $_POST['id'] . "' and to_id = '" . $_SESSION['iduser'] . "') or (from_id = '" . $_SESSION['iduser'] . "' and to_id = '" . ( int ) $_POST['id'] . "')" );
    
    if ( mysql_num_rows( $msg ) > 0 ) {
        while ( $row = mysql_fetch_array( $msg ) ) {
        
            if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['iduser'] ) {
                mysql_query( "UPDATE messages SET to_del = 1, m_type = 1 WHERE id = '" . $row['id'] . "'" );
            }
            if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['iduser']) {
                mysql_query( "UPDATE messages SET from_del = 1 WHERE id = '" . $row['id'] . "'" );
            }
        }
        echo 1;
        exit();
    }
}

### Удаление личных исходящих сообщений
if ( $_GET['func'] == 'delmsgout' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $msg = mysql_query( "SELECT from_id, to_id, m_state, from_del, to_del FROM messages WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $msg ) > 0 ) {
        $row = mysql_fetch_array( $msg );
        
        if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['iduser'] ) {
            mysql_query( "UPDATE messages SET from_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );
            
            echo 1;
            exit();
        } else
        if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['iduser'] ) {
            mysql_query( "UPDATE messages SET to_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );
            
            echo 1;
            exit();
        }
    }
}

### Удаление всех личных исходящих сообщений
if ( $_GET['func'] == 'delmsgoutall' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $msg = mysql_query( "SELECT id, from_id, to_id, m_state, from_del, to_del, history FROM messages WHERE (from_id = '" . ( int ) $_POST['id'] . "' and to_id = '" . $_SESSION['iduser'] . "') or (from_id = '" . $_SESSION['iduser'] . "' and to_id = '" . ( int ) $_POST['id'] . "')" );
    
    if ( mysql_num_rows( $msg ) > 0 ) {
        while ( $row = mysql_fetch_array( $msg ) ) {
        
            if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['iduser'] ) {
                mysql_query( "UPDATE messages SET from_del = 1 WHERE id = '" . $row['id'] . "'" );
            }
            if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['iduser'] ) {
                mysql_query( "UPDATE messages SET to_del = 1 WHERE id = '" . $row['id'] . "'" );
            }
        }
        echo 1;
        exit();
    }
}

### Добавление в корзину
if ( $_GET['func'] == 'addbasket' ) {

    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    #Серфинг
    if ( $_POST['type'] == 'dyn' ) {
        $proverka = mysql_query( "SELECT id FROM dynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 0)" );
            
            echo 1;
            exit();
        }
    }
	#Авто-серфинг
    if ( $_POST['type'] == 'autodyn' ) {
        $proverka = mysql_query( "SELECT id FROM autodynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 16)" );
            
            echo 1;
            exit();
        }
    }
    #Пиксворд
    if ( $_POST['type'] == 'pixword' ) {
        $proverka = mysql_query( "SELECT id FROM pixword WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 8)" );
            
            echo 1;
            exit();
        }
    }
    #Контекстная реклама
    if ( $_POST['type'] == 'klink' ) {
        $proverka = mysql_query( "SELECT id FROM klink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 1)" );
            
            echo 1;
            exit();
        }
    }
	#Статическая реклама
    if ( $_POST['type'] == 'statlink' ) {
        $proverka = mysql_query( "SELECT id FROM statlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 20)" );
            
            echo 1;
            exit();
        }
    }
	#Рекламная цепочка
    if ( $_POST['type'] == 'chain' ) {
        $proverka = mysql_query( "SELECT id FROM chain WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 18)" );
            
            echo 1;
            exit();
        }
    }
    #Тесты
    if ( $_POST['type'] == 'tests' ) {
        $proverka = mysql_query( "SELECT id FROM tests WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 2)" );
            
            echo 1;
            exit();
        }
    }
    #Баннер 200х300
    if ( $_POST['type'] == 'ban2x3' ) {
        $proverka = mysql_query( "SELECT id FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 3)" );
            
            echo 1;
            exit();
        }
    }
    #Баннер 468х60
    if ( $_POST['type'] == 'ban468x60' ) {
        $proverka = mysql_query( "SELECT id FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 4)" );
            
            echo 1;
            exit();
        }
    }
    #Задания
    if ( $_POST['type'] == 'tasks' ) {
        $proverka = mysql_query( "SELECT id FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['money'] < $config['minpay'] or !is_numeric( $_POST['money'] ) ) {
            echo 'Неверная сумма!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['money'] . "', 5)" );
            
            echo 1;
            exit();
        }
    }
    #V.I.P Задания
    if ( $_POST['type'] == 'viptasks' ) {
        $proverka = mysql_query( "SELECT id FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        if ( mysql_num_rows( $proverka ) == 0 ) {
            echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
            exit();
        } else
        if ( ( int ) $_POST['days'] <= 0 or ( int ) $_POST['days'] > 365 or !is_numeric( $_POST['days'] ) ) {
            echo 'Неверно указано количество дней!';
            exit();
        } else {
            mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . ( int ) $_POST['id'] . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . ( int ) $_POST['days'] . "', 6)" );
            
            echo 1;
            exit();
        }
    }
}

### Удаление с корзины
if ( $_GET['func'] == 'delbasket' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    mysql_query( "DELETE FROM basket WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
    
    echo 1;
    exit();
}

### Удаление истории операций
if ( $_GET['func'] == 'delhistory' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $del_history = mysql_query( "SELECT id FROM history_reklama_pay WHERE id = '" . ( int ) $_POST['id'] . "' and type = '" . ( int ) $_POST['type'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    if ( mysql_num_rows( $del_history ) > 0 ) {
        mysql_query( "DELETE FROM history_reklama_pay WHERE id = '" . ( int ) $_POST['id'] . "' and type = '" . ( int ) $_POST['type'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        echo 1;
        exit();
    } else {
        exit();
    }
}

### Предзагрузка перевод средств между площадками
if ( $_GET['func'] == 'preload_area' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    switch ( $_POST['id_area'] ) {
        case 1:
            $pr_transfer = mysql_query( "SELECT id, title FROM dynlink WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
        case 2:
            $pr_transfer = mysql_query( "SELECT id, title FROM klink WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
        case 3:
            $pr_transfer = mysql_query( "SELECT id, title FROM banners WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
        case 4:
            $pr_transfer = mysql_query( "SELECT id, title FROM tests WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
        case 5:
            $pr_transfer = mysql_query( "SELECT id, title FROM tasks WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
        case 6:
            $pr_transfer = mysql_query( "SELECT id, title FROM pixword WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
		case 8:
            $pr_transfer = mysql_query( "SELECT id, title FROM statlink WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
		case 7:
            $pr_transfer = mysql_query( "SELECT id, title FROM chain WHERE iduser = '" . $_SESSION['iduser'] . "'" );
            break;
        default:
            $json['ok'] = 2;
            print json_encode( $json );
            exit();
    }
    
    if ( mysql_num_rows( $pr_transfer ) > 0 ) {
        while ( $pr_transfer_row = mysql_fetch_array( $pr_transfer ) ) {
            $array = array( 'id' => $pr_transfer_row['id'], 'text' => iconv( 'windows-1251', 'UTF-8', substr( $pr_transfer_row['title'], 0, 25 ) . '' ) );
            
            $json['transfer'][] = $array;
            $json['ok'] = 1;
        }
        print json_encode( $json );
        exit();
    } else {
        $json['ok'] = 2;
        print json_encode( $json );
        exit();
    }
}

### Перевод средств между площадками
if ( $_GET['func'] == 'transfer_send' ) {
    
    sleep( 1 );
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( !is_numeric( $_POST['sum'] ) or floatval( $_POST['sum'] ) <= 0 ) {
        exit();
    }
    
    switch ( ( int ) $_POST['rek_area'] ) {
        case 1:
            $get_area = mysql_query( "SELECT id, testdrive FROM dynlink WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'dynlink';
            break;
        case 2:
            $get_area = mysql_query( "SELECT id FROM klink WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'klink';
            break;
        case 3:
            $get_area = mysql_query( "SELECT id FROM banners WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'banners';
            break;
        case 4:
            $get_area = mysql_query( "SELECT id FROM tests WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'tests';
            break;
        case 5:
            $get_area = mysql_query( "SELECT id FROM tasks WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'tasks';
            break;
        case 6:
            $get_area = mysql_query( "SELECT id FROM pixword WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'pixword';
            break;
		case 8:
            $get_area = mysql_query( "SELECT id FROM statlink WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'statlink';
            break;
		case 7:
            $get_area = mysql_query( "SELECT id FROM chain WHERE id = '" . ( int ) $_POST['id_area'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            $prefix_plus = 'chain';
            break;
        default:
            exit();
            break;
    }
    
    switch ( $_POST['type'] ) {
        case md5( $message_md5 . 'serfing' ):
            $pr_transfer = mysql_query( "SELECT id, plus FROM dynlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'dynlink';
            break;
        case md5( $message_md5 . 'pixword' ):
            $pr_transfer = mysql_query( "SELECT id FROM pixword WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'pixword';
            break;
        case md5( $message_md5 . 'klink' ):
            $pr_transfer = mysql_query( "SELECT id FROM klink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'klink';
            break;
		case md5( $message_md5 . 'statlink' ):
            $pr_transfer = mysql_query( "SELECT id FROM statlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'statlink';
            break;
		case md5( $message_md5 . 'chain' ):
            $pr_transfer = mysql_query( "SELECT id FROM chain WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'chain';
            break;
        case md5( $message_md5 . 'banners' ):
            $pr_transfer = mysql_query( "SELECT id FROM banners WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'banners';
            break;
        case md5( $message_md5 . 'tests' ):
            $pr_transfer = mysql_query( "SELECT id FROM tests WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'tests';
            break;
        case md5( $message_md5 . 'tasks' ):
            $pr_transfer = mysql_query( "SELECT id, t_wait, t_work FROM tasks WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and balance >= '" . moneyraund( $_POST['sum'], 3 ) . "' LIMIT 1" );
            $prefix_minus = 'tasks';
            break;
        default:
            exit();
            break;
    }
    
    if ( mysql_num_rows( $pr_transfer ) > 0 ) {
        if ( mysql_num_rows( $get_area ) > 0 ) {
            
            $get_area_row = mysql_fetch_array( $get_area );
            $pr_transfer_row = mysql_fetch_array( $pr_transfer );
            
            if ( $prefix_minus == 'tasks' ) {
                if ( $pr_transfer_row['t_wait'] != 0 or $pr_transfer_row['t_work'] != 0 ) {
                    exit();
                }
            }
            
            #Если площадка в серфинге Plus
            if ( $prefix_minus == 'dynlink' ) {
                if ( $pr_transfer_row['plus'] ) exit();
            }
			
			#Если площадка тест драйв
            if ( $prefix_plus == 'dynlink' ) {
                if ( $get_area_row['testdrive'] ) exit();
            }
            
            /*добавляем сумму к рекламной площадке*/
            mysql_query( "UPDATE $prefix_plus SET balance = balance + '" . moneyraund( $_POST['sum'], 3 ) . "' WHERE id = '" . $get_area_row['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
            /* отнимаем сумму от рекламной площадки*/
            mysql_query( "UPDATE $prefix_minus SET balance = balance - '" . moneyraund( $_POST['sum'], 3 ) . "' WHERE id = '" . $pr_transfer_row['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
            echo 1;
            exit();
        } else {
            exit();
        }
    } else {
        exit();
    }
}

### Новая тема на форуме
if ( $_GET['func'] == 'newtopic' ) {
    
    sleep( 1 );
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['forumblock'] == 1 ) exit();
    
    $forum_cat = mysql_query( "SELECT id FROM forum_cat WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    if ( mysql_num_rows( $forum_cat ) == 0 ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['msg'] = trim( $_POST['msg'] );
    
    #Задержка при создании
    $pr_forum_top = mysql_query( "SELECT date FROM forum_top WHERE iduser = '" . $_SESSION['iduser'] . "' ORDER BY id DESC LIMIT 1" );
    if ( mysql_num_rows( $pr_forum_top ) > 0 ) {
        $pr_forum_top_row = mysql_fetch_array( $pr_forum_top );
        if ( $pr_forum_top_row['date'] + $config['timeout_topic_forum'] > time() ) {
		    echo 4;
            exit();
        }
    }
    
    $forum_cat_row = mysql_fetch_array( $forum_cat );
    if ( $forum_cat_row['id'] == 1 and $config_user['account'] != 5 ) exit();
    
    if ( empty( $_POST['title'] ) ) {
        echo 3;
        exit();
    }
    
    if ( empty( $_POST['msg'] ) ) {
        echo 2;
        exit();
    }
    
    mysql_query( "INSERT INTO forum_top SET cat_id = '" . ( int ) $_POST['id'] . "', top_title = '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', iduser = '" . $_SESSION['iduser'] . "', date = '" . time() . "'" );
    $id_forum_top = mysql_fetch_array( mysql_query( "SELECT id FROM forum_top WHERE iduser = '" . $_SESSION['iduser'] . "' ORDER BY id DESC LIMIT 1" ) );
    mysql_query( "INSERT INTO forum_mes SET top_id = '" . $id_forum_top['id'] . "', iduser = '" . $_SESSION['iduser'] . "', mess = '" . parce_bb_code( substr( check_text( $_POST['msg'] ), 0, 3000 ), 'forum' ) . "', date = '" . time() . "'" );
    mysql_query( "UPDATE user SET reyting = reyting + '" . $config['new_topic_reyting'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    echo 1;
    exit();
}

###Новое сообщение на форуме
if ( $_GET['func'] == 'forumnewmsg' ) {
    
    sleep( 1 );
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['msg'] = trim( $_POST['msg'] );
    
    #Проверяем бан форума
	if ( $config_user['forumblock'] == 1 ) {
        $json['ok'] = 2;
		$error = iconv('windows-1251','UTF-8','Вы не можете писать сообщения на форуме, так как эта функция для вас заблокирована, за нарушение правил.');
		$json['error'][] = $error;
        print json_encode( $json );
        exit();
    }
    
	#Проверяем пустоту сообщения
    if ( empty( $_POST['msg'] ) ) {
        $json['ok'] = 4;
		$error = iconv('windows-1251','UTF-8','Сообщение не может быть пустым!');
		$json['error'][] = $error;
        print json_encode( $json );
        exit();
    }
    
    #Задержка при создании
    $pr_forum_mes = mysql_query( "SELECT date FROM forum_mes WHERE iduser = '" . $_SESSION['iduser'] . "' ORDER BY id DESC LIMIT 1" );
    if ( mysql_num_rows( $pr_forum_mes ) > 0 ) {
        $pr_forum_mes_row = mysql_fetch_array( $pr_forum_mes );
        if ( $pr_forum_mes_row['date'] + $config['timeout_mail_forum'] > time() ) {
			$json['ok'] = 3;
			$error = iconv('windows-1251','UTF-8','Сообщения можно отправлять раз в 5 сек!');
			$json['error'][] = $error;
			print json_encode( $json );
            exit();
        }
    }
    
    $forum_top = mysql_query( "SELECT id FROM forum_top WHERE id = '" . ( int ) $_POST['id'] . "' and t_close = 0 LIMIT 1" );
    if ( mysql_num_rows( $forum_top ) > 0 ) {
        
        #Обрабатываем цитирование
        $msg = parce_bb_code( substr( check_text( $_POST['msg'] ), 0, 3000 ), 'forum' );
        preg_match( '/\[quote\](\d+)\[\/quote\]/i', $msg, $match );
        $get_quote = mysql_query( "SELECT iduser, mess FROM forum_mes WHERE id = '" . $match['1'] . "' LIMIT 1" );
        if ( mysql_num_rows( $get_quote ) > 0 ) {
            $get_quote_row = mysql_fetch_array( $get_quote );
            $get_user = mysql_fetch_array( mysql_query( "SELECT username FROM user WHERE id = '" . $get_quote_row['iduser'] . "' LIMIT 1" ) );
            $get_quote_row['mess'] = preg_replace( "/\<div class\=\"forum\_quote\"\>.*\<\/div\>/", "", $get_quote_row['mess'] );
            $msg = preg_replace( "#\[quote\](\d+)\[\/quote\]#is", "<div class=\"forum_quote\"><div class=\"quote_title\">" . $get_user['username'] . ":</div><div class=\"f_top_arrow\"></div>" . $get_quote_row['mess'] . "</div>", $msg );
        } else {
            $msg = preg_replace( "#\[quote\](.+?)\[\/quote\]#is", '', $msg );
        }
        
        $msg = trim( $msg );
		
		#Проверяем пустоту сообщения
        if ( empty( $msg ) ) {
            $json['ok'] = 4;
			$error = iconv('windows-1251','UTF-8','Сообщение не может быть пустым!');
			$json['error'][] = $error;
            print json_encode( $json );
            exit();
        }
        
        mysql_query( "INSERT INTO forum_mes SET top_id = '" . ( int ) $_POST['id'] . "', iduser = '" . $_SESSION['iduser'] . "', mess = '" . $msg . "', date = '" . time() . "'" );
        $json['ok'] = 1;
        print json_encode( $json );
        exit();
    } else {
        exit();
    }
}

### Удаление сообщения на форуме
if ( $_GET['func'] == 'forumdelmsg' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	$forum_ava_user = mysql_fetch_array( mysql_query( "SELECT iduser FROM forum_mes WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" ) );
	
    if ( $config_user['account'] != 5 AND $_SESSION['iduser'] != $forum_ava_user['iduser'] ) exit();
    
    mysql_query( "DELETE FROM forum_mes WHERE id = '" . ( int ) $_POST['id'] . "'" );
    
    echo 1;
    exit();
}

### Удаление темы
if ( $_GET['func'] == 'deltopic' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['account'] != 5 ) exit();
    
    mysql_query( "DELETE FROM forum_top WHERE id = '" . ( int ) $_POST['id'] . "'" );
    mysql_query( "DELETE FROM forum_mes WHERE top_id = '" . ( int ) $_POST['id'] . "'" );
    
    echo 1;
    exit();
}

### Блокировка пользователя сообщений на форуме
if ( $_GET['func'] == 'forumblockmes' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['account'] != 5 ) exit();
    
    $get_us = mysql_fetch_array( mysql_query( "SELECT forumblock FROM user WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" ) );
    if ( $get_us['forumblock'] == 0 ) {
        mysql_query( "UPDATE user SET forumblock = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );
        echo 'Пользователь заблокирован!';
        exit();
    } else {
        mysql_query( "UPDATE user SET forumblock = 0 WHERE id = '" . ( int ) $_POST['id'] . "'" );
        echo 'Пользователь разблокирован!';
        exit();
    }
}

### Закрытие темы
if ( $_GET['func'] == 'closetopic' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['account'] != 5 ) exit();
    
    $close_topic = mysql_fetch_array( mysql_query( "SELECT t_close FROM forum_top WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" ) );
    if ( $close_topic['t_close'] ) {
        mysql_query( "UPDATE forum_top SET t_close = 0 WHERE id = '" . ( int ) $_POST['id'] . "'" );
        echo 1;
        exit();
    } else {
        mysql_query( "UPDATE forum_top SET t_close = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );
        echo 2;
        exit();
    }
}

### Проверка ссылок на вирусы с форума
if ( $_GET['func'] == 'forum_check_virus' ) {
    
    sleep(1);
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
        $_POST['url'] = 'http://' . check_text( $_POST['url'] );
    }
    
    $getvirus = checkvirus( $_POST['url'] );
    
    if ( $getvirus == 'virus' ) {
        echo 2;
        exit();
    } else
    if ( $getvirus == 'base' ) {
        echo 3;
        exit();
    } else {
        echo 1;
        exit();
    }
}

### Добавление рекламы в каталог
if ( $_GET['func'] == 'addcatalog' ) {
    
    sleep(1);
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
    $_POST['text'] = trim( $_POST['text'] );
    
    if ( $config['catalogPrice'] > $config_user['adv_money'] ) {
		echo 'На вашем рекламном счету недостаточно средств';
		exit();
	}
    if ( empty( $_POST['title'] ) )  { 
		echo 2; 
		exit(); 
	}
    if ( ( int ) $_POST['id'] < 1 or ( int ) $_POST['id'] > 80 ) { 
		echo 3; 
		exit(); 
	}
    if ( empty( $_POST['url'] ) ) { 
		echo 4; 
		exit(); 
	}
    if ( !preg_match( '/^(http:\/\/[a-z]+\.|https:\/\/[a-z]+\.|https:\/\/|http:\/\/)?([a-z0-9а-я\-]+\.?[a-z0-9а-я\-]+)(\.)([a-z0-9а-я]{2,5}\.)?([a-z0-9а-я]{2,5})/i', check_text( $_POST['url'] ) ) ) {
        echo 4;
        exit();
    }
    if ( empty( $_POST['text'] ) ) { 
		echo 5; 
		exit(); 
	}
    
    preg_match('/^(http:\/\/[a-z]+\.|https:\/\/[a-z]+\.|https:\/\/|http:\/\/)?([a-z0-9а-я\-]+\.?[a-z0-9а-я\-]+)(\.)([a-z0-9а-я]{2,5}\.)?([a-z0-9а-я]{2,5})/i', check_text( $_POST['url'] ), $out);
    
    if ( parse_url( $out[0], PHP_URL_SCHEME ) == '' ) {
        $out[0] = 'http://' . $out[0];
    }
    
	$sql_cat_id = mysql_fetch_array( mysql_query( "SELECT cat_id FROM catalog_id WHERE id = '" . ( int ) $_POST['id'] . "'" ) );
   
    mysql_query( "INSERT INTO catalog_mes SET cat_id = '" . ( int ) $_POST['id'] . "', cat_id_main = '" . $sql_cat_id['cat_id'] . "', title = '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', url = '" . substr( $out[0], 0, 255 ) . "', c_text = '" . parce_bb_code( substr( check_text( $_POST['text'] ), 0, 5000 ), 'forum' ) . "', iduser = '" . $_SESSION['iduser']. "', date = '" . time() . "'" );
    mysql_query( "UPDATE user SET adv_money = adv_money - '" . $config['catalogPrice'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
	mysql_query( "UPDATE viruchka SET money = money + '" . $config['catalogPrice'] . "' WHERE ident = '32'" );
    
    echo 1;
    exit();
}

### Заказ выплаты webmoney
if ( $_GET['func'] == 'payuserwebmoney' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    #поиск в заказах
    $proverka_zakaz = mysql_query( "SELECT id FROM payuser WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    #проверка аттестата
    $proverka_attestat = @file_get_contents( "http://passport.webmoney.ru/asp/CertView.asp?wmid=" . $config_user['wmid'] );
    #проверка одинаковых wmid
    $proverka_wmid = mysql_query( "SELECT id FROM user WHERE wmid != '' and wmid = '" . $config_user['wmid'] . "'" );
    
	if ( !$config_user['activate'] ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
    if ( $config_user['blockpay'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы не можете получить выплату. Ваш аккаунт заблокирован на выплату заработанных средств. Пожалуйста, свяжитесь с администрацией сайта.';
        exit();
    } else
    if ( $config_user['lastpay'] > time() ) {
        $month = array( 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек' );
        $pay_time = ( int ) date( 'd', $config_user['lastpay'] - 86400 ) . ' ' . $month[( int ) date( 'm', $config_user['lastpay'] - 86400 ) - 1] . ' ' . date( 'Y', $config_user['lastpay'] - 86400 ) . ' в ' . date( 'H:i', $config_user['lastpay'] - 86400 );
        
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Выплата производится раз в сутки. Последний раз вы получали выплату <b>' . $pay_time . '</b>.';
        exit();
    } else
    if ( strpos( $proverka_attestat, 'Аттестат псевдонима' ) ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> риносим свои извинения, мы не выплачиваем "Аттестату псевдонима". Как получить формальный аттестат? Для получения формального аттестата зайдите на сайт <a href="https://passport.webmoney.ru/asp/aProcess.asp" class="a_box">центра аттестации</a> и укажите свои персональные данные.';
        exit();
    } else
    if ( mysql_num_rows( $proverka_wmid ) > 1 ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Замечено более одного WMID. Выплата недоступна. Пожалуйста, свяжитесь с администрацией сайта.';
        exit();
    } else
    if ( mysql_num_rows( $proverka_zakaz ) > 0 ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ваша выплата находится на проверке.';
        exit();
    } else
    if ( empty( $config_user['wmid'] ) ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> У Вас не указан WM кошелек. Пожалуйста, перейдите в личные данные и укажите WM кошелек. <a href="/info" class="a_box" onclick="Page.Go(this.href);return false;">перейти в аккаунт</a>';
        exit();
    } else
    if ( !is_numeric( $_POST['money'] ) ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Возможно Вы ошиблись при вводе суммы.';
        exit();
    } else
	if ( floatval( $_POST['money']) <= 0) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Возможно Вы ошиблись при вводе суммы.';
        exit();
    } else
    if ( floatval( $_POST['money'] ) < $config['minpayuser'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Минимальная сумма вывода <b>' . $config['minpayuser'] . ' ' . $config['valutaname'] . '</b>';
        exit();
    } else
    if ( floatval( $_POST['money'] ) > $config_user['money'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. На Вашем счету недостаточно средств.';
        exit();
    } else {
        if ($config_user['reyting'] >= $config_site['status_meaning_1a'] and $config_user['reyting'] <= $config_site['status_meaning_1b']) {
            $maxpay = 15;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_2a'] and $config_user['reyting'] <= $config_site['status_meaning_2b']) {
            $maxpay = 50;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_3a'] and $config_user['reyting'] <= $config_site['status_meaning_3b']) {
            $maxpay = 100;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_4a'] and $config_user['reyting'] <= $config_site['status_meaning_4b']) {
            $maxpay = 200;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_5a'] and $config_user['reyting'] <= $config_site['status_meaning_5b']) {
            $maxpay = 300;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_6a']) {
            $maxpay = 500;
        }
        
        if ( floatval( $_POST['money'] ) >= $maxpay ) {
            $moneyzakaz = moneyraund( $maxpay * 0.992, 2 );
            $minusmoney = $maxpay;
        } else {
            $moneyzakaz = moneyraund( floatval( $_POST['money'] ) * 0.992, 2 );
            $minusmoney = floatval( $_POST['money'] );
        }
        
        if ( $config_site['autopay'] ) {
            include_once ROOT_DIR . '/modules/autopaywebmoney/xml.php';
            
            $response = $wmxi->X2(
  		        time(),
            	$config_site['purse'],
            	$config_user['purse'],
            	$moneyzakaz,
            	0,
            	"",
            	trim( 'Выплата с сайта ' . ROOT . ' пользователю ' . $config_user['username'] ),
            	0
      		);
            
            $structure = $parser->Parse( $response, DOC_ENCODING );
            $transformed = $parser->Reindex( $structure, true );
            $status = @$transformed["w3s.response"]["retval"];
            
            if ( $status == '0' ) {
                mysql_query( "UPDATE user SET money = money - '" . $minusmoney . "', paid = paid + '" . $moneyzakaz . "', lastpay = '" . time() . "' + 86400 WHERE id = '" . $_SESSION['iduser'] . "'" );
                #mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $_SESSION['iduser'] . "', price = '" . $moneyzakaz . "', type = 5, date = '" . time() . "', h_text = 'Вывод средств из системы (Webmoney)', payopt = 1" );
                mysql_query( "INSERT INTO pay_history SET purse = '" . $config_user['purse'] . "', iduser = '" . $_SESSION['iduser'] . "', money = '" . $moneyzakaz . "', date = '" . time() . "', type = 1" );
                
                echo 1;
                exit();
            } else {
                mysql_query( "INSERT INTO payuser SET iduser = '" . $_SESSION['iduser'] . "', purse = '" . $config_user['purse'] . "', type = 1, money = '" . $moneyzakaz . "', date = '" . time() . "'" );
                mysql_query( "UPDATE user SET money = money - '" . $minusmoney . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
            
                echo 2;
                exit();
            }
        } else {
            mysql_query( "INSERT INTO payuser SET iduser = '" . $_SESSION['iduser'] . "', purse = '" . $config_user['purse'] . "', type = 1, money = '" . $moneyzakaz . "', date = '" . time() . "'" );
            mysql_query( "UPDATE user SET money = money - '" . $minusmoney . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
            
            echo 2;
            exit();
        }
    }
}

### Заказ выплаты payeer
if ( $_GET['func'] == 'payuserpayeer' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    #поиск в заказах
    $proverka_zakaz = mysql_query( "SELECT id FROM payuser WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    #проверка одинаковых payeer кошельков
    $proverka_payeer = mysql_query( "SELECT id FROM user WHERE payeer != '' and payeer = '" . $config_user['payeer'] . "'" );
    
	if ( !$config_user['activate'] ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
    if ( $config_user['blockpay'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы не можете получить выплату. Ваш аккаунт заблокирован на выплату заработанных средств. Пожалуйста, свяжитесь с администрацией сайта.';
        exit();
    } else
    if ( $config_user['lastpay'] > time() ) {
        $month = array( 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек' );
        $pay_time = ( int ) date( 'd', $config_user['lastpay'] - 86400 ) . ' ' . $month[( int ) date( 'm', $config_user['lastpay'] - 86400 ) - 1] . ' ' . date( 'Y', $config_user['lastpay'] - 86400 ) . ' в ' . date( 'H:i', $config_user['lastpay'] - 86400 );
        
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Выплата производится раз в сутки. Последний раз вы получали выплату <b>' . $pay_time . '</b>.';
        exit();
    } else

    if ( mysql_num_rows( $proverka_payeer ) > 1 ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Замечено более одного кошелька. Выплата недоступна. Пожалуйста, свяжитесь с администрацией сайта.';
        exit();
    } else
    if ( mysql_num_rows( $proverka_zakaz ) > 0 ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ваша выплата находится на проверке.';
        exit();
    } else
    if ( empty( $config_user['payeer'] ) ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> У Вас не указан Payeer кошелек. Пожалуйста, перейдите в личные данные и укажите Payeer кошелек <a href="/info" class="a_box" onclick="Page.Go(this.href);return false;">перейти в аккаунт</a>';
        exit();
    } else
    if ( !is_numeric( $_POST['money'] ) ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Возможно Вы ошиблись при вводе суммы.';
        exit();
    } else
	if ( floatval( $_POST['money']) <= 0) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Возможно Вы ошиблись при вводе суммы.';
        exit();
    } else
    if ( floatval( $_POST['money'] ) < $config['minpayuser'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Минимальная сумма вывода <b>' . $config['minpayuser'] . ' ' . $config['valutaname'] . '</b>';
        exit();
    } else
    if ( floatval( $_POST['money'] ) > $config_user['money'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. На Вашем счету недостаточно средств.';
        exit();
    } else {
        if ($config_user['reyting'] >= $config_site['status_meaning_1a'] and $config_user['reyting'] <= $config_site['status_meaning_1b']) {
            $maxpay = 15;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_2a'] and $config_user['reyting'] <= $config_site['status_meaning_2b']) {
            $maxpay = 50;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_3a'] and $config_user['reyting'] <= $config_site['status_meaning_3b']) {
            $maxpay = 100;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_4a'] and $config_user['reyting'] <= $config_site['status_meaning_4b']) {
            $maxpay = 200;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_5a'] and $config_user['reyting'] <= $config_site['status_meaning_5b']) {
            $maxpay = 300;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_6a']) {
            $maxpay = 500;
        }
         
        if ( floatval( $_POST['money'] ) >= $maxpay ) {
            $moneyzakaz = moneyraund( $maxpay, 2 );
            $minusmoney = $maxpay;
        } else {
            $moneyzakaz = moneyraund( floatval( $_POST['money'] ), 2 );
            $minusmoney = floatval( $_POST['money'] );
        }
        
        include_once ROOT_DIR . '/engine/classes/cpayeer.php';
		$accountNumber = $config_site['shetpayeer']; 
		$payer_user = $config_user['payeer'];
		$apiId = $config_site['apiIdpayeer'];         
		$apiKey = $config_site['maskeypayeer'];   
		$payeer = new CPayeer($accountNumber, $apiId, $apiKey);
							
		function ViewPurse($purse){
			if( substr($purse,0,1) != "P" ) return false;
			#if( !ereg("^[0-9]$", substr($purse,1)) ) return false;	
			return $purse;
		}
								
		$purse = ViewPurse($payer_user);
		if($purse != false)	{								
									
			if ($payeer->isAuth())
			{
				$arBalance = $payeer->getBalance();
				$balance = $arBalance["balance"]["RUB"]["DOSTUPNO"];
				if( ($balance) >= ($moneyzakaz)) {
					$arTransfer = $payeer->transfer(array(
					'curIn' => 'RUB', 
					'sum' => $moneyzakaz, 
					'curOut' => 'RUB',   
					'to' => $payer_user,  
					'comment' => 'Payment to '.$config_site['sitename'].', user id: '.$_SESSION['iduser'].'',
					));
					if (!empty($arTransfer["historyId"])) {
						
						mysql_query( "UPDATE user SET money = money - '" . $minusmoney . "', paid = paid + '" . $moneyzakaz . "', lastpay = '" . time() . "' + 86400 WHERE id = '" . $_SESSION['iduser'] . "'" );
						#mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $_SESSION['iduser'] . "', price = '" . $moneyzakaz . "', type = 5, date = '" . time() . "', h_text = 'Вывод средств из системы (Payeer)', payopt = 1" );
						mysql_query( "INSERT INTO pay_history SET purse = '" . $config_user['payeer'] . "', iduser = '" . $_SESSION['iduser'] . "', money = '" . $moneyzakaz . "', date = '" . time() . "', type = 2" );
               
						echo 1;
						exit();
												
					} else {
						echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ошибка платежа, обратитесь к администрации!'; 
						exit();		
					}
				} else { 
					echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ошибка системы, обратитесь к администрации!'; 
					exit(); 
				}
			} else {
				echo '<pre>'.print_r($payeer->getErrors(), true).'</pre>';
			}
									
		} else { 
			echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Внимание! Не вернный кошелек. Обратитесь в администрацию'; exit(); 
		}		
						
	}
}

### Пополнение рекламного счета
	if ( $_GET['func'] == 'advertisingwebmoney' ) {
	    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
		$adv_completion = moneyraund( floatval( $_POST['money'] ), 2 );
		if( $adv_completion >= $config['minpay'] ) {
			if($adv_completion < 10000 ) {	
				mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . $adv_completion . "', 15)" );
				echo 1;
				exit();
			} else {
				echo "Максимальная сумма пополнения одним платежом составляет 10000.00 руб.";
				exit();
			}
		} else {
			echo "Минимальная сумма пополнения через корзину составляет " . $config['minpay'] . " руб.";
			exit();
		}
	}
	
### Обмен с основного на рекламный 
	if ( $_GET['func'] == 'advertisingmain' ) {
	    
		if ( !isset( $_SESSION['iduser'] ) ) exit();
    
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$adv_exchange = moneyraund( floatval( $_POST['money'] ), 2 );
		if($adv_exchange <= $config_user['money'] ) {
			if($adv_exchange >= 1 ) {
				if($adv_exchange < 10000 ) {	
					mysql_query( "UPDATE user SET money = money - '".$adv_exchange."', adv_money = adv_money + '".$adv_exchange."' WHERE id = '".$_SESSION['iduser']."'" );
					echo 1;
					exit();
				} else {
					echo "Максимальная сумма обмена одним платежом составляет 10000.00 руб.";
					exit();
				}
			} else {
				echo "Минимальная сумма обмена составляет 1.00 руб.";
				exit();
			}
		} else {
			echo "На вашем основном счете не достаточно средств для обмена!";
			exit();
		}
	}
	
### Доска почета, ставка 
    if ( $_GET['func'] == 'addboard' ) {
	    
	  if ( !isset( $_SESSION['iduser'] ) ) exit();
      if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
	  $board_bets = moneyraund( floatval( $_POST['stavka'] ), 2 );
	  
	  $recapha_n2 = $config_site["recapthaSecretKey"];
		
	  if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте аккаунт!';
		exit();
	  } else {
		$recaptcha = check_text($_POST['g-recaptcha-response']);
		$secret = $recapha_n2;
		$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret ."&response=".$recaptcha."&remoteip=".$_SERVER['REMOTE_ADDR'];
		$status = 1;
		if(!empty($recaptcha)) {
		  $curl = curl_init();
		  if(!$curl) {
		    $status = 2;    
		  } else {
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($curl, CURLOPT_TIMEOUT, 10);
			curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
			$curlData = curl_exec($curl);
			curl_close($curl);    
			$curlData = json_decode($curlData, true);
			if($curlData['success']) {
			  $status = 0;
			}
		  }
		}
		if($status === 0) {  
		  if($board_bets >= $config['board_bet'] AND $board_bets <= 100000) {
		    $board_array = mysql_fetch_array( mysql_query( "SELECT * FROM board_kon WHERE id = '1'" ) );
		    if($board_array['status'] == 0) {
			  if($board_bets <= $config_user['adv_money'] ) {
				mysql_query( "UPDATE user SET adv_money = adv_money - '" . $board_bets . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
			    mysql_query( "UPDATE board_kon SET actual_user = '" . $_SESSION['iduser'] . "', date_start = '" . time() . "', date_end = '" . (time()+86400) . "', status = '1', allsum = '" . $board_bets . "', bet = '" . $board_bets . "', end_user = '" . $_SESSION['iduser'] . "'" );
			    mysql_query( "INSERT INTO board_kon_temp SET iduser = '" . $_SESSION['iduser'] . "', summ = '" . $board_bets . "', bet = '1'" );
			    echo 1;
			    exit();
			  } else {
			    echo 'На вашем счету недостаточно средств для ставки!';
			    exit();
			  }
		    } else {
			  if($board_bets <= $config_user['adv_money'] ) {
			    if($board_array['actual_user'] != $_SESSION['iduser']) {
				  if($board_array['bet'] < $board_bets) {
					mysql_query( "UPDATE user SET adv_money = adv_money - '" . $board_bets . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
				    mysql_query( "UPDATE board_kon SET actual_user = '" . $_SESSION['iduser'] . "', allsum=allsum+'" . $board_bets . "', bet = '" . $board_bets . "', end_user = '" . $_SESSION['iduser'] . "'" );
				    $board_temp = mysql_query( "SELECT id FROM board_kon_temp WHERE iduser = '" . $_SESSION['iduser'] . "'" );
					if ( mysql_num_rows( $board_temp ) > 0 ) {
					  mysql_query( "UPDATE board_kon_temp SET summ = summ + '" . $board_bets . "', bet = bet + '1' WHERE iduser = '" . $_SESSION['iduser'] . "'" );
				    } else {
					  mysql_query( "INSERT INTO board_kon_temp SET iduser = '" . $_SESSION['iduser'] . "', summ = '" . $board_bets . "', bet = '1'" );
				    }
				    echo 1;
				    exit();
				  } else {
				    echo 'Ваша ставка не перебивает ставку лидера!';
				    exit();
				  }
			    } else {
				  echo 'Вашу ставку еще не перебили, повторно делать Запрещено!';
				  exit();
			    }
			  } else {
			    echo 'На вашем счету недостаточно средств для ставки!';
			    exit();
			  }
		    }
		  } else {
		    echo 'Ваша ставка ниже минимальной '.$config['board_bet'].'р';
			exit();
		  }
		} else if($status === 1) {  
		  echo 'Капча не пройдена.';
		  exit();
		} else if($status === 2) {  
		  echo 'Нарушен механизм, пожалуйста повторите еще раз, или сообщите информацию об этом, администрации!';
		  exit();
		}
	  }
	}	
	
### Доска почета, стать рефералом	
if ( $_GET['func'] == 'addrefboad' ) {
	    
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
	if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
	$board_right_ajax = mysql_fetch_array( mysql_query( "SELECT end_user FROM board_kon WHERE id = '1'" ) );
	
	if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
	if ( $_SESSION['iduser'] == ( int ) $board_right_ajax['end_user'] ) {
        echo 'Вы не можете стать самому себе реферером!';
		exit();
    } else
    if ( $config_user['referer'] != 0 ) {
        echo 'У вас уже есть реферер!';
		exit();
    } else {
        $sql = mysql_query( "SELECT autoback, userdel, referer FROM user WHERE id = '" . ( int ) $board_right_ajax['end_user'] . "' LIMIT 1" );
        if ( mysql_num_rows( $sql ) > 0 ) {
            $row = mysql_fetch_array( $sql );
            
            if ( $row['userdel'] == 1 ) {
                echo 'Вы не можете стать его рефералом, данный пользователь удален с проекта за нарушение!';
				exit();
            } else {
			
				if(	$_SESSION['iduser'] == $row['referer'] ) {
					echo 'Данный пользователь ваш реферал, вы не можете стать рефералом своего реферала!';
					exit();
				} else {
            
					mysql_query( "UPDATE user SET referer = '" . ( int ) $board_right_ajax['end_user'] . "', autoproc = '" . $row['autoback'] . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
					mysql_query( "UPDATE user SET referer2 = '" . ( int ) $board_right_ajax['end_user'] . "' WHERE referer = '" . $_SESSION['iduser'] . "' and id != '" . ( int ) $board_right_ajax['end_user'] . "'" );
					mysql_query( "UPDATE user SET referals = referals + 1, reyting = reyting + '" . $config['refreyting'] . "' WHERE id = '" . ( int ) $board_right_ajax['end_user'] . "'" );
					
					#Пишем событие в ленту пользователю
					mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Поздравляем у вас новый реферал " . $config_user['username'] . " пришел через доску почета.', iduser = '" . ( int ) $board_right_ajax['end_user'] . "' " );
            
					echo 1;
					exit();
				}
			}
		} else {
            exit();
        }
    }
}

### Добавляем реферала с биржи в корзину (бронируем)
if ( $_GET['func'] == 'sddfair' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$referID = ( int ) $_POST['id'];
    
	$ref_add_bascet_a = mysql_query( "SELECT id FROM basket WHERE ident = '" . $referID . "' AND type = '14'" );
	$infoReferadd = mysql_fetch_array( mysql_query( "SELECT price, referer FROM user WHERE id = '" . $referID . "'" ) );
	
	if ( mysql_num_rows( $ref_add_bascet_a ) ) {
	  echo 'Этот реферал уже забронирован покупкой другим пользователем!';
	  exit();
	} else {
		
	  if($referID == $_SESSION['iduser']){
		echo 'Вы не можете купить себя на ярмарке.';
		exit();
	  } else {
		if ($infoReferadd['referer'] == $_SESSION['iduser']) {
		  echo 'Зачем покупать реферала, у самого себя?';
		  exit();
		} else {
		  mysql_query( "INSERT INTO basket (ident, iduser, time, price, type) VALUES ('" . $referID . "', '" . $_SESSION['iduser'] . "', '" . time() . "', '" . $infoReferadd['price'] . "', 14)" );
		  echo 1;
		}
	  }
	}
}

### Добавляем реферала на биржу
if ( $_GET['func'] == 'addFair' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$addReferID = ( int ) $_POST['id'];
	$addReferPRICE = ( int ) $_POST['priceFair'];
    
	$ref_add_bascet_a = mysql_query( "SELECT id FROM basket WHERE ident = '" . $addReferID . "' AND type = '14'" );
	$infoReferadd = mysql_fetch_array( mysql_query( "SELECT id, price, referer, serf_view, reyting FROM user WHERE id = '" . $addReferID . "'" ) );
	
	if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
	if($infoReferadd['id'] < 1) {
		echo 'Реферал не найден, или не пренадлежит вам!';
		exit();
	} else {
		if($infoReferadd['price'] > 0) {
			echo 'Ваш реферал уже продается на ярмарке!';
			exit();
		} else
		if($config_user['reyting'] < $config['referer_min_rating']) {
			echo 'Вы не можете продавать на ярмарке!';
			exit();
		} else
		if($infoReferadd['serf_view'] < $config['referal_min_clix']) {
			echo 'Реферал к продажи еще не готов!';
			exit();
		} else 
		if($infoReferadd['reyting'] < $config['referal_min_rating']) {
			echo 'Реферал к продажи еще не готов!';
			exit();
		} else  
		if($infoReferadd['userdel'] == '1') {
			echo 'Реферал удален с проекта!';
			exit();
		} else  
		if($infoReferadd['blockuser'] == '1') {
			echo 'Реферал заблокирован на проекте!';
			exit();
		} else   
		if($config['price_min_fair'] > $addReferPRICE OR $config['price_max_fair'] < $addReferPRICE) {
			echo 'Цена указана не верно!';
			exit();
		} else {
			mysql_query( "UPDATE user SET price = '" . $addReferPRICE . "' WHERE id = '" . $infoReferadd['id'] . "'" );
			echo 1;
		}
	}
}

### Снимаем реферала с биржи
if ( $_GET['func'] == 'dellFair' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$addReferID = ( int ) $_POST['id'];
	$addReferPRICE = ( int ) $_POST['priceFair'];
    
	$ref_add_bascet_a = mysql_query( "SELECT id FROM basket WHERE ident = '" . $addReferID . "' AND type = '14'" );
	$infoReferadd = mysql_fetch_array( mysql_query( "SELECT id FROM user WHERE id = '" . $addReferID . "'" ) );
	
	if($infoReferadd['id'] < 1) {
		echo 'Реферал не найден, или не пренадлежит вам!';
		exit();
	} else {
		if ( mysql_num_rows( $ref_add_bascet_a ) ) {
			echo 'Реферал забронирован покупкой пользователем! Удаление с биржи невозможно.';
			exit();
		} else {
			mysql_query( "UPDATE user SET price = '0' WHERE id = '" . $infoReferadd['id'] . "'" );
			echo 1;
			exit();
		}
	}
}

### Заказ выплаты advcash
if ( $_GET['func'] == 'payuseradvcash' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    #поиск в заказах
    $proverka_zakaz = mysql_query( "SELECT id FROM payuser WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    #проверка одинаковых payeer кошельков
    $proverka_advcash = mysql_query( "SELECT id FROM user WHERE advcash != '' and advcash = '" . $config_user['advcash'] . "'" );
    
	if ( !$config_user['activate'] ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
    if ( $config_user['blockpay'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы не можете получить выплату. Ваш аккаунт заблокирован на выплату заработанных средств. Пожалуйста, свяжитесь с администрацией сайта.';
        exit();
    } else
    if ( $config_user['lastpay'] > time() ) {
        $month = array( 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек' );
        $pay_time = ( int ) date( 'd', $config_user['lastpay'] - 86400 ) . ' ' . $month[( int ) date( 'm', $config_user['lastpay'] - 86400 ) - 1] . ' ' . date( 'Y', $config_user['lastpay'] - 86400 ) . ' в ' . date( 'H:i', $config_user['lastpay'] - 86400 );
        
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Выплата производится раз в сутки. Последний раз вы получали выплату <b>' . $pay_time . '</b>.';
        exit();
    } else

    if ( mysql_num_rows( $proverka_advcash ) > 1 ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Замечено более одного кошелька. Выплата недоступна. Пожалуйста, свяжитесь с администрацией сайта.';
        exit();
    } else
    if ( mysql_num_rows( $proverka_zakaz ) > 0 ) {
        echo 'Ваша выплата находится на проверке.';
        exit();
    } else
    if ( empty( $config_user['advcash'] ) ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> У Вас не указан advcash кошелек. Пожалуйста, перейдите в личные данные и укажите advcash кошелек <a href="/info" class="a_box" onclick="Page.Go(this.href);return false;">перейти в аккаунт</a>';
        exit();
    } else
    if ( !is_numeric( $_POST['money'] ) ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Возможно Вы ошиблись при вводе суммы.';
        exit();
    } else
	if ( floatval( $_POST['money']) <= 0) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Возможно Вы ошиблись при вводе суммы.';
        exit();
    } else
    if ( floatval( $_POST['money'] ) < $config['minpayuser'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. Минимальная сумма вывода <b>' . $config['minpayuser'] . ' ' . $config['valutaname'] . '</b>';
        exit();
    } else
    if ( floatval( $_POST['money'] ) > $config_user['money'] ) {
        echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Неверная сумма. На Вашем счету недостаточно средств.';
        exit();
    } else {
        if ($config_user['reyting'] >= $config_site['status_meaning_1a'] and $config_user['reyting'] <= $config_site['status_meaning_1b']) {
            $maxpay = 15;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_2a'] and $config_user['reyting'] <= $config_site['status_meaning_2b']) {
            $maxpay = 50;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_3a'] and $config_user['reyting'] <= $config_site['status_meaning_3b']) {
            $maxpay = 100;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_4a'] and $config_user['reyting'] <= $config_site['status_meaning_4b']) {
            $maxpay = 200;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_5a'] and $config_user['reyting'] <= $config_site['status_meaning_5b']) {
            $maxpay = 300;
        } else
        if ($config_user['reyting'] >= $config_site['status_meaning_6a']) {
            $maxpay = 500;
        }
        
        if ( floatval( $_POST['money'] ) >= $maxpay ) {
            $moneyzakaz = moneyraund( $maxpay, 2 );
            $minusmoney = $maxpay;
        } else {
            $moneyzakaz = moneyraund( floatval( $_POST['money'] ), 2 );
            $minusmoney = floatval( $_POST['money'] );
        }
        
        error_reporting(E_ALL);
		ini_set('display_errors', '1');
		ini_set('max_execution_time', 0);
		require_once (ROOT_DIR .  "/engine/classes/MerchantWebService.php");
		$merchantWebService = new MerchantWebService();

		$arg0 = new authDTO();
		$arg0->apiName = $config_site['APIName'];
		$arg0->accountEmail = $config_site['advcashEMAILL'];
		$arg0->authenticationToken = $merchantWebService->getAuthenticationToken($config_site['secretADVcashAPI']);

		$arg1 = new sendMoneyRequest();
		$arg1->amount = $moneyzakaz;
		$arg1->currency = $config_site['currencyAdvcash'];;
		$arg1->walletId = $config_user['advcash'];
		$arg1->note = 'Payment to '.$config_site['sitename'].', user id: '.$_SESSION['iduser'].'';
		$arg1->savePaymentTemplate = false;

		$validationSendMoney = new validationSendMoney();
		$validationSendMoney->arg0 = $arg0;
		$validationSendMoney->arg1 = $arg1;

		$sendMoney = new sendMoney();
		$sendMoney->arg0 = $arg0;
		$sendMoney->arg1 = $arg1;

		try {
			$merchantWebService->validationSendMoney($validationSendMoney);
			$sendMoneyResponse = $merchantWebService->sendMoney($sendMoney);

			mysql_query( "UPDATE user SET money = money - '" . $minusmoney . "', paid = paid + '" . $moneyzakaz . "', lastpay = '" . time() . "' + 86400 WHERE id = '" . $_SESSION['iduser'] . "'" );
			#mysql_query( "INSERT INTO history_reklama_pay SET iduser = '" . $_SESSION['iduser'] . "', price = '" . $moneyzakaz . "', type = 5, date = '" . time() . "', h_text = 'Вывод средств из системы (advcash)', payopt = 6" );
			mysql_query( "INSERT INTO pay_history SET purse = '" . $config_user['advcash'] . "', iduser = '" . $_SESSION['iduser'] . "', money = '" . $moneyzakaz . "', date = '" . time() . "', type = 3" );
			echo 1;
			exit();
    
		} catch (Exception $e) {
			echo $e->getMessage(); # выводим ответ платежки в случае ошибки
			#echo $e->getTraceAsString(); закоментировано, используется для отладки, так как выводит системные ошибки файлов платежки и скрипта 
		}
						
	}
}

### Устанавливаем кошелек advcash
if ( $_GET['func'] == 'addadvcash' ) {
   
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
     
	$_POST['purseadvcash'] = str_replace(' ', '', $_POST['purseadvcash']);
	
	if ( strlen(check_text( $_POST['purseadvcash'] )) < 13 OR strlen(check_text( $_POST['purseadvcash'] )) > 13 ) {
        echo 'Неверно указан кошелек. Будьте внимательны!';
        exit();
    } else
    if ( $config_user['advcash'] != '' ) {
        echo 'Вы уже указали кошелек advcash!';
        exit();
    } else {
        $proverka_advcash_add = mysql_query( "SELECT id FROM user WHERE advcash = '" . check_text( $_POST['purseadvcash'] . "'" ));
        if ( mysql_num_rows( $proverka_advcash_add ) == 1 ) {
            echo 'В системе уже используеться данный кошелек';
            exit();
        } else {
            mysql_query( "UPDATE user SET advcash = '" . check_text( $_POST['purseadvcash'] ) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
            echo 1;
            exit();
        }
    }
}

### Выдаем бонус
if ( $_GET['func'] == 'addbonus' ) {
   
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo 'Получать бонус могут только авторизированные пользователи!';
		exit();
	} 
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
		
	if($config_user['bonusTIME'] > time()-86400 ) {
		echo 'Вы уже получали бонус сегодня. Получать бонус можно раз в 24 часа.';
		exit();
	}
	
	#Берем информацию о остатках резерва бонусов
	$InfoBNS = mysql_fetch_array( mysql_query( "SELECT * FROM bonus_status WHERE id = '1'" ) );
    
	#Рандом типа бонуса (1-рубли, 2-рейтинг)
	$RandPRIZtype = rand( 1, 2 ); 
	
	#Если выпал бонус деньгами
	if ($RandPRIZtype == 1) { 
		
		#Берем минимальное значение и максимальное и умножаем на 100 (для подготовки дробного числа к рандому, тоесть делаем его целым)
		$RandA = ($config['minBonus24hRUB'] * 100);
		$Randb = ($config['maxBonus24hRUB'] * 100);
		
		#Рандомим число, и делим на 100, что бы обратно вернуть в дробное.
		$RandRUBsume = rand( $RandA, $Randb ) / 100; 
		
		#Проверяем суму рандома с запасом резерва бонуса, и делаем зачисление
		if($InfoBNS['rubBall'] >= $RandRUBsume ) {
			mysql_query( "UPDATE user SET money = money + '" . $RandRUBsume . "', earnings_bonus = earnings_bonus + '". $RandRUBsume ."', bonusSUME = '". $RandRUBsume ."', bonusTIME = '". time() ."', bonusTUPE = '1' WHERE id = '" . $_SESSION['iduser'] . "'" );
			mysql_query( "UPDATE bonus_status SET rubBall = rubBall - '" . $RandRUBsume . "' WHERE id = '1'" );
            #Пишем событие в ленту пользователю
			mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Поздравляем вы получили ежедневный бонус в размере " . $RandRUBsume . " " . $config['valutaname'] . "', iduser = '" . $_SESSION['iduser'] . "' " );
			echo 1;
            exit();
		} else {
			echo 'Извините но резерв бонуса на сегодня исчерпан, попробуйте позже. <br>(бонус обновляется после 00:00)';
			exit();
		}
	}
	
	#Если выпал бонус рейтингом
	if ($RandPRIZtype == 2) { 
		
		#Берем минимальное значение и максимальное и умножаем на 100 (для подготовки дробного числа к рандому, тоесть делаем его целым)
		$Rand2A = ($config['minBonus24hRATING'] * 100);
		$Rand2b = ($config['maxBonus24hRATING'] * 100);
		
		#Рандомим число, и делим на 100, что бы обратно вернуть в дробное.
		$RandRATINGsume = rand( $Rand2A, $Rand2b ) / 100;
		
		#Проверяем суму рандома с запасом резерва бонуса, и делаем зачисление
		if($InfoBNS['ratingBall'] >= $RandRATINGsume) {
			mysql_query( "UPDATE user SET reyting = reyting + '" . $RandRATINGsume . "', bonusSUME = '". $RandRATINGsume ."', bonusTIME = '". time() ."', bonusTUPE = '2' WHERE id = '" . $_SESSION['iduser'] . "'" );
			mysql_query( "UPDATE bonus_status SET ratingBall = ratingBall - '" . $RandRATINGsume . "' WHERE id = '1'" );
            #Пишем событие в ленту пользователю
			mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Поздравляем вы получили ежедневный бонус в размере " . $RandRATINGsume . " рейтинга.', iduser = '" . $_SESSION['iduser'] . "' " );
			echo 1;
            exit();
		} else {
			echo 'Извините но резерв бонуса на сегодня исчерпан, попробуйте позже. <br>(бонус обновляется после 00:00)';
			exit();
		}
	}
}

### Создание конкурса от реферера
	if ( $_GET['func'] == 'addcontests' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$type = ( int ) $_POST['type'];
	$text = check_text( $_POST['text'] );
	$date_end = ( int ) $_POST['date_end'];
	$minimum = ( int ) $_POST['minimum'];
	$p1 = moneyraund( floatval( $_POST['p1'] ), 2 );
	$p2 = moneyraund( floatval( $_POST['p2'] ), 2 );
	$p3 = moneyraund( floatval( $_POST['p3'] ), 2 );
	$p4 = moneyraund( floatval( $_POST['p4'] ), 2 );
	$p5 = moneyraund( floatval( $_POST['p5'] ), 2 );
	$p6 = moneyraund( floatval( $_POST['p6'] ), 2 );
	$p7 = moneyraund( floatval( $_POST['p7'] ), 2 );
	$p8 = moneyraund( floatval( $_POST['p8'] ), 2 );
	$p9 = moneyraund( floatval( $_POST['p9'] ), 2 );
	$p10 = moneyraund( floatval( $_POST['p10'] ), 2 );
	
	$allsumm_table = ($p1 + $p2 + $p3 + $p4 + $p5 + $p6 + $p7 + $p8 + $p9 + $p10);
	$allsumm = ($p1 + $p2 + $p3 + $p4 + $p5 + $p6 + $p7 + $p8 + $p9 + $p10);
	$allsumm_coeficient = ($allsumm - ($allsumm * $config['coeficient_kon_ref']));
	$allsumm = ($allsumm + $allsumm_coeficient);
	$allsumm = moneyraund($allsumm, 2);
	
	$contests_round = mysql_fetch_array( mysql_query( "SELECT COUNT(id) as count FROM contests WHERE autor = '". $_SESSION['iduser']."' and type = '".$type."'" ) );
	$referals_round = mysql_fetch_array( mysql_query( "SELECT COUNT(id) as count FROM user WHERE referer = '". $_SESSION['iduser']."' and activate = '1' " ) );
	if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
	if(moneyraund( $config_user['adv_money'], 2 ) < $allsumm){
		echo 'На рекламном счету недостаточно средств для оплаты';
		exit();
	} else
	if( $type != 0 AND $type != 1 AND $type != 2 AND $type != 3 ) {
		echo 'Вы не выбрали тип конкурса!';
		exit();
	} else 
	if($contests_round['count'] >= 1) {
		echo 'Вы уже создавали конкурс такого типа, нельзя создавать конкурсы одинаковых типов одновременно! Дождитесь завершения ранее созданного!';
		exit();
	}
	if ( $date_end != 1 AND $date_end != 2 AND $date_end != 3 AND $date_end != 4 AND $date_end != 5 AND $date_end != 6 AND $date_end != 7 AND $date_end != 8 AND $date_end != 9 AND $date_end != 10 AND $date_end != 11 AND $date_end != 12 AND $date_end != 13 AND $date_end != 14 AND $date_end != 15 AND $date_end != 16 AND $date_end != 17 AND $date_end != 18 AND $date_end != 19 AND $date_end != 20 AND $date_end != 21 AND $date_end != 22 AND $date_end != 23 AND $date_end != 24 AND $date_end != 25 AND $date_end != 26 AND $date_end != 27 AND $date_end != 28 AND $date_end != 29 AND $date_end != 30 ) {
		echo 'Не корректный ввод даты завершения конкурса!';
		exit();
	} else
	if($minimum < 0 OR $minimum > 10000) {
		echo 'Минимальный порог указан не корректно!';
		exit();
	} else 
	if ( $p1 == 0 or $p2 == 0 or $p3 == 0 ) {
		echo 'Указывать первые три призовых места в конкурсе обязательно!';
		exit();
	} else
	if ( ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 == 0 and $p5 == 0 and $p6 == 0 and $p7 == 0 and $p8 == 0 and $p9 == 0 and $p10 == 0) OR ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 > 0 and $p5 == 0 and $p6 == 0 and $p7 == 0 and $p8 == 0 and $p9 == 0 and $p10 == 0) OR ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 > 0 and $p5 > 0 and $p6 == 0 and $p7 == 0 and $p8 == 0 and $p9 == 0 and $p10 == 0) OR ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 > 0 and $p5 > 0 and $p6 > 0 and $p7 == 0 and $p8 == 0 and $p9 == 0 and $p10 == 0) OR ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 > 0 and $p5 > 0 and $p6 > 0 and $p7 > 0 and $p8 == 0 and $p9 == 0 and $p10 == 0) OR ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 > 0 and $p5 > 0 and $p6 > 0 and $p7 > 0 and $p8 > 0 and $p9 == 0 and $p10 == 0) OR ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 > 0 and $p5 > 0 and $p6 > 0 and $p7 > 0 and $p8 > 0 and $p9 > 0 and $p10 == 0) OR ($p1 > 0 and $p2 > 0 and $p3 > 0 and $p4 > 0 and $p5 > 0 and $p6 > 0 and $p7 > 0 and $p8 > 0 and $p9 > 0 and $p10 > 0) ) {
			
		if(($p1 > 0 and $p1 < 1) or ($p2 > 0 and $p2 < 1) or ($p3 > 0 and $p3 < 1) or ($p4 > 0 and $p4 < 1) or ($p5 > 0 and $p5 < 1) or ($p6 > 0 and $p6 < 1) or ($p7 > 0 and $p7 < 1) or ($p8 > 0 and $p8 < 1) or ($p9 > 0 and $p9 < 1) or ($p10 > 0 and $p10 < 1)){
			echo 'Сума призового места не может быть меньше 1.00';
			exit();
		} else 
		if(($p1 > 0 and $p1 > 10000) or ($p2 > 0 and $p2 > 10000) or ($p3 > 0 and $p3 > 10000) or ($p4 > 0 and $p4 > 10000) or ($p5 > 0 and $p5 > 10000) or ($p6 > 0 and $p6 > 10000) or ($p7 > 0 and $p7 > 10000) or ($p8 > 0 and $p8 > 10000) or ($p9 > 0 and $p9 > 10000) or ($p10 > 0 and $p10 > 1000)){
			echo 'Сума призового места не может быть больше 10000';
			exit();
		} else 
		if($referals_round['count'] < 3) {
			echo 'Что бы создать конкурс вы должны иметь минимум 3 активных реферала! В противном случае для кого его создавать то? <i class="fa fa-meh-o" aria-hidden="true"></i>';
			exit();
		} else
		if ( empty( $text ) ) {
			echo 'Описание конкурса не может быть пустым!';
			exit();
		} else
		if ( mb_strlen( $text ) < 100 ) {
			echo 'Описание конкурса не может быть таким коротким!';
			exit();
		}

		$date_table = time()+($date_end*86400);
		
		mysql_query( "INSERT INTO contests SET type = '".$type."', description = '". parce_bb_code ( substr( $text, 0, 1000 ), 'forum' ) ."', date_end = '". $date_table ."', date_start = '". time() ."', min_type = '".$minimum."', priz1 = '".$p1."', priz2 = '".$p2."', priz3 = '".$p3."', priz4 = '".$p4."', priz5 = '".$p5."', priz6 = '".$p6."', priz7 = '".$p7."', priz8 = '".$p8."', priz9 = '".$p9."', priz10 = '".$p10."', allsumm = '".$allsumm_table."', autor = '".$_SESSION['iduser']."' " );
		mysql_query( "UPDATE user SET adv_money = adv_money - '" . $allsumm . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
		mysql_query( "UPDATE viruchka SET money = money + '" . $allsumm_coeficient . "' WHERE ident = '16'" );
		
		echo 1;
		exit();
	
	} else {
		echo 'Призовые места должны быть заполнены по порядку, (минимум 3 призовых места)!';
		exit();
	}
	
}

### Заказ рекламной площадки
if ( $_GET['func'] == 'addchain' ) {
    sleep(1);
    
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	$_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
    
	if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else {
        
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
			$_POST['url'] = 'http://' . check_text( $_POST['url'] );
		}
        #Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
			$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
			echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
			exit();
		}
		if ( ( int ) $_POST['chainColor'] == 1 ) {
			$color = 1;
		} else {
			$color = 0;
		}
		if ( ( int ) $_POST['chainColor'] != 0 and ( int ) $_POST['chainColor'] != 1 ) {
			echo 'Вы не выбрали параметр цвета!';
			exit();
		}
		mysql_query( "INSERT INTO chain (iduser, title, url, date, color) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . time() . "', '".$color."')" );
		echo 1;
		exit();
	
	}    
}

### Заказ рекламной площадки без сессии авторизации
if ( $_GET['func'] == 'addchain_nouser' ) {
    sleep(1);
    
	if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	$_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
    
	$check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	$check_bt_order = mysql_query( "SELECT nouser_order FROM chain WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	if ( mysql_num_rows( $check_bt_order ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( mysql_num_rows( $check_order_basket ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else {
        
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
			$_POST['url'] = 'http://' . check_text( $_POST['url'] );
		}
        #Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
			$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
			echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
			exit();
		}
		if ( ( int ) $_POST['chainColor'] == 1 ) {
			$color = 1;
			$check_price_1 = $config['chainColorPrice'];
		} else {
			$color = 0;
			$check_price_1 = 0;
		}
		if ( ( int ) $_POST['chainColor'] != 0 and ( int ) $_POST['chainColor'] != 1 ) {
			echo 'Вы не выбрали параметр цвета!';
			exit();
		} else {
		  $quantity = ( int ) $_POST['quantity'];
		  $quantity_summ = ( ( $check_price_1 + $config['chain'] ) * $quantity );
			
		  #Создаем счет в корзину на оплату заказа
		  if ( $quantity < 10 OR $quantity >= 10000 ) {
			echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 10, максимальное 10000.';
			exit();
		  } else {
		    
			mysql_query( "INSERT INTO chain (iduser, title, url, date, color, nouser, nouser_order) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . time() . "', '".$color."', '1', '" . ( int ) $_POST['bt_order'] . "')" );
			#Делаем запрос на создание счета для оплаты площадки
			mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '18', '" . ( int ) $_POST['bt_order'] . "')" );
		    
			echo 1;
		    exit();
		  }
	    }
	}    
}

### Редактирование рекламной площадки
if ( $_GET['func'] == 'upchain' ) {
    sleep(1);
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    $proverka = mysql_num_rows(mysql_query( "SELECT id FROM chain WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
    if ( $proverka == 0 ) {
        echo 'Рекламная площадка не существует или не принадлежит Вам!';
        exit();
    } else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
        if ( ( int ) $_POST['chainColor'] == 1 ) {
			$color = 1;
		} else {
			$color = 0;
		}
		if ( ( int ) $_POST['chainColor'] != 0 and ( int ) $_POST['chainColor'] != 1 ) {
			echo 'Вы не выбрали параметр цвета!';
			exit();
		}
		mysql_query( "UPDATE chain SET title = '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', date = '" . time() . "', color = '".$color."' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
		echo 1;
		exit();
	}
}

### Удаление рекламной площадки
if ( $_GET['func'] == 'delchain' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, date FROM chain WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            ///$t1 = new DateTime( date( 'Y-m-d', time() ) );
            ///$t2 = new DateTime( date( 'Y-m-d', $pr_row['date'] + 7 * 86400 ) );
            ///$interval = $t1->diff( $t2 );
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        if ( $pr_row['balance'] > $config['chain'] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM chain WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 1" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение рекламной площадки
if ( $_GET['func'] == 'runchain' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, paused FROM chain WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
        $pr_row = mysql_fetch_array( $proverka );
                
        if ( $config['chain'] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
            echo 'Недостаточно средств на балансе рекламной площадки!';
            exit();
        } else {
            if ( $pr_row['paused'] == 1 ) {
                $paused = 0;
            } else {
                $paused = 1;
            }
            
            mysql_query( "UPDATE chain SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
}

### Заказ статичиской рекламы
if ( $_GET['func'] == 'addstatlink' ) {
    sleep(1);
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else {
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
			$_POST['url'] = 'http://' . check_text( $_POST['url'] );
		}
		#Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
			$checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
			echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
			exit();
		}
		if ( ( int ) $_POST['statlinkColor'] == 1 ) {
			$color = 1;
		} else {
			$color = 0;
		}
		if ( ( int ) $_POST['statlinkColor'] != 0 and ( int ) $_POST['statlinkColor'] != 1 ) {
			echo 'Вы не выбрали параметр цвета!';
			exit();
		}
		mysql_query( "INSERT INTO statlink (iduser, title, url, date, color) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . time() . "', '".$color."')" );
		echo 1;
		exit();
	}
}

### Заказ статичиской рекламы без сессии авторизации
if ( $_GET['func'] == 'addstatlink_nouser' ) {
    sleep(1);
    
	if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	$_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
    
	$check_order_basket = mysql_query( "SELECT nouser_order FROM basket WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	$check_bt_order = mysql_query( "SELECT nouser_order FROM statlink WHERE nouser_order = '" . ( int ) $_POST['bt_order'] . "'" );
	if ( mysql_num_rows( $check_bt_order ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( mysql_num_rows( $check_order_basket ) > 0 ) {
		echo 'Внутренняя ошибка, обновите страницу.';
		exit();
	} else
	if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else {
		
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
		  $_POST['url'] = 'http://' . check_text( $_POST['url'] );
		}
		#Проверка на блокировку
		$blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
		if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
		$checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
		if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
		  $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
		  echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
		  exit();
		}
		if ( ( int ) $_POST['statlinkColor'] == 1 ) {
		  $color = 1;
		  $check_price_1 = $config['statlinkColorPrice'];
		} else {
		  $color = 0;
		  $check_price_1 = 0;
		}
		if ( ( int ) $_POST['statlinkColor'] != 0 and ( int ) $_POST['statlinkColor'] != 1 ) {
		  echo 'Вы не выбрали параметр цвета!';
		  exit();
		} else {
		  
		  $quantity = ( int ) $_POST['quantity'];
		  $quantity_summ = ( ( $check_price_1 + $config['statlink'] ) * $quantity );
			
		  #Создаем счет в корзину на оплату заказа
		  if ( $quantity < 10 OR $quantity >= 10000 ) {
			echo 'Неверная сумма количества просмотров!<br/> Минимальное количество 10, максимальное 10000.';
			exit();
		  } else {
		    mysql_query( "INSERT INTO statlink (iduser, title, url, date, color, nouser, nouser_order) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . time() . "', '".$color."', '1', '" . ( int ) $_POST['bt_order'] . "')" );
		    #Делаем запрос на создание счета для оплаты площадки
			mysql_query( "INSERT INTO basket (ident, iduser, time, price, type, nouser_order) VALUES ('0', '0', '" . time() . "', '" . $quantity_summ . "', '20', '" . ( int ) $_POST['bt_order'] . "')" );
			
 		    echo 1;
		    exit();
		  
		  }
	    }
	}
}

### Редактирование статичиской рекламы
if ( $_GET['func'] == 'upstatlink' ) {
    sleep(1);
    
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	$proverka = mysql_num_rows(mysql_query( "SELECT id FROM statlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['url'] = trim( $_POST['url'] );
    
	if ( $proverka == 0 ) {
        echo 'Рекламная площадка не существует или не принадлежит Вам!';
        exit();
    } else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 3;
        exit();
    } else {
        
		if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
        if ( ( int ) $_POST['statlinkColor'] == 1 ) {
			$color = 1;
		} else {
			$color = 0;
		}
		if ( ( int ) $_POST['statlinkColor'] != 0 and ( int ) $_POST['statlinkColor'] != 1 ) {
			echo 'Вы не выбрали параметр цвета!';
			exit();
		}
		mysql_query( "UPDATE statlink SET title = '" . substr( check_text( $_POST['title'] ), 0, 70 ) . "', url = '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', date = '" . time() . "', color = '".$color."' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
		echo 1;
		exit();
    
	}
}

### Удаление статичиской рекламы
if ( $_GET['func'] == 'delstatlink' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, date FROM statlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $pr_row = mysql_fetch_array( $proverka );
        
        if ( $pr_row['date'] + 7 * 86400 > time() ) {
            echo 'Рекламную площадку можно удалить через 7 дн. после ее создания';
            exit();
        }
        
        if ( $pr_row['balance'] > $config['statlink'] ) {
            echo 'Площадку нельзя удалить, пока на балансе сумма больше вознаграждения!';
            exit();
        }
        
        mysql_query( "UPDATE user SET adv_money = adv_money + '" . $pr_row['balance'] . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
        mysql_query( "DELETE FROM statlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        mysql_query( "DELETE FROM basket WHERE ident = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' and type = 20" );
        
        echo 1;
        exit();
    }
}

### Включение - Отключение статичиской рекламы
if ( $_GET['func'] == 'runstatlink' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT balance, paused FROM statlink WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
    
    if ( mysql_num_rows( $proverka ) == 0 ) {
        echo 'Рекламная площадка №' . ( int ) $_POST['id'] . ' не принадлежит Вам!';
        exit();
    } else {
        $pr_row = mysql_fetch_array( $proverka );
                
        if ( $config['statlink'] > $pr_row['balance'] or $pr_row['balance'] <= 0 ) {
            echo 'Недостаточно средств на балансе рекламной площадки!';
            exit();
        } else {
            if ( $pr_row['paused'] == 1 ) {
                $paused = 0;
            } else {
                $paused = 1;
            }
            
            mysql_query( "UPDATE statlink SET paused = '" . $paused . "' WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
            
            echo 1;
            exit();
        }
    }
}

### Привествие
if ( $_GET['func'] == 'greeting' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $greting = trim( $_POST['greeting'] );
    
	if ( empty( $greting ) ) {
		echo 'Приветствие не может быть пустым!';
		exit();
	} else
	if ( mb_strlen( $greting ) < 50 ) {
		echo 'Слишком короткое приветствие, напишите более вместительное!';
		exit();
	} else {       
		mysql_query( "UPDATE user SET greetingRef = '" . parce_bb_code ( substr( check_text( $greting ), 0, 2000 ), 'all' ) . "' WHERE id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
		echo 1;
		exit();
    }
	
}

### Тест драйв
if ( $_GET['func'] == 'adddyn_test' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['title'] = trim( $_POST['title'] );
    $_POST['description'] = trim( $_POST['description'] );
    $_POST['url'] = trim( $_POST['url'] );
	
	$geo_ru = trim( substr( check_text( $_POST['geo_ru'] ), 0, 3 ) );
	$geo_ua = trim( substr( check_text( $_POST['geo_ua'] ), 0, 3 ) );
	$geo_by = trim( substr( check_text( $_POST['geo_by'] ), 0, 3 ) );
	$geo_kz = trim( substr( check_text( $_POST['geo_kz'] ), 0, 3 ) );
	$geo_ge = trim( substr( check_text( $_POST['geo_ge'] ), 0, 3 ) );
	$geo_md = trim( substr( check_text( $_POST['geo_md'] ), 0, 3 ) );
	$geo_am = trim( substr( check_text( $_POST['geo_am'] ), 0, 3 ) );
	$geo_tj = trim( substr( check_text( $_POST['geo_tj'] ), 0, 3 ) );
	$geo_az = trim( substr( check_text( $_POST['geo_az'] ), 0, 3 ) );
	$geo_uz = trim( substr( check_text( $_POST['geo_uz'] ), 0, 3 ) );
	$geo_pt = trim( substr( check_text( $_POST['geo_pt'] ), 0, 3 ) );
	$geo_es = trim( substr( check_text( $_POST['geo_es'] ), 0, 3 ) );
	$geo_ee = trim( substr( check_text( $_POST['geo_ee'] ), 0, 3 ) );
	$geo_lv = trim( substr( check_text( $_POST['geo_lv'] ), 0, 3 ) );
	$geo_lt = trim( substr( check_text( $_POST['geo_lt'] ), 0, 3 ) );
	$geo_us = trim( substr( check_text( $_POST['geo_us'] ), 0, 3 ) );
	$geo_gb = trim( substr( check_text( $_POST['geo_gb'] ), 0, 3 ) );
	$geo_fr = trim( substr( check_text( $_POST['geo_fr'] ), 0, 3 ) );
	$geo_de = trim( substr( check_text( $_POST['geo_de'] ), 0, 3 ) );
	$geo_cn = trim( substr( check_text( $_POST['geo_cn'] ), 0, 3 ) );
	$geo_all = trim( substr( check_text( $_POST['geo_all'] ), 0, 3 ) );
	$geo_it = trim( substr( check_text( $_POST['geo_it'] ), 0, 3 ) );
    
	if ( !$config_user['activate'] ) {
		echo 'Для продолжения активируйте Ваш аккаунт!';
		exit();
	} else
	if($config['testdriveOn'] != 1) { 
		echo 'Эта функция отключена!';
		exit(); 
	} else
	if($config_user['Use_a_test_drive'] == 1) { 
		echo 'Вы уже использовали функцию TEST DRIVE!';
		exit(); 
	} else
	if( $config_user['wmid'] < 100 ) { 
		echo 'Для заказа TEST DRIVE вы должны подтвердить свой wmid!';
		exit(); 
	} else
	if( $config_user['reyting'] < $config['testdriveRating'] ) { 
		echo 'Для заказа TEST DRIVE у Вас должно быть минимум '.$config['testdriveRating'].' рейтинга!';
		exit(); 
	} else
    if ( empty( $_POST['title'] ) ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['description'] ) ) {
        echo 3;
        exit();
    } else
    if ( empty( $_POST['url'] ) ) {
        echo 4;
        exit();
    } else
    if ($geo_ru == '' AND $geo_ua == '' AND $geo_by == '' AND $geo_kz == '' AND $geo_ge == '' AND $geo_md == '' AND $geo_am == '' AND $geo_tj == '' AND $geo_az == '' AND $geo_uz == '' AND $geo_pt == '' AND $geo_es == '' AND    $geo_ee == '' AND $geo_lv == '' AND $geo_lt == '' AND $geo_us == '' AND $geo_gb == '' AND $geo_fr == '' AND $geo_de == '' AND $geo_cn == '' AND $geo_all == '' AND $geo_it == '') {
		echo 'Геотаргетинг - должна быть выбрана хотябы одна страна!';
        exit();	
	} else {
        if ( parse_url( check_text( $_POST['url'] ), PHP_URL_SCHEME ) == '' ) {
            $_POST['url'] = 'http://' . check_text( $_POST['url'] );
        }
        
        #Проверка на блокировку
        $blockSite = strtolower( parse_url( check_text( $_POST['url'] ), PHP_URL_HOST ) );
        if ( strpos( $blockSite, 'www.' ) !== false ) $blockSite = substr( $blockSite, 4 );
        $checkBlockSite = mysql_query( "SELECT opisanie FROM blockSite WHERE site = '" . $blockSite . "'" );
        if ( mysql_num_rows( $checkBlockSite ) > 0 ) {
            $checkBlockSiteRow = mysql_fetch_array( $checkBlockSite );
            echo 'Сайт находиться в чёрном списке!<br /><b>Причина:</b> ' . $checkBlockSiteRow['opisanie'];
            exit();
        }
            
        $getframe = check_frame( $_POST['url'] );
        
        if ( $getframe == 'no' ) {
            echo 'Сайт разрушает фрейм!';
            exit();
        } else
        
        if ( $_POST['erotic'] == 'on' ) {
			$erotic = 1;
		} else {
			$erotic = 0;
		}
		
		if ( $_POST['freeid'] == 'on' ) {
			$freeid = 1;
		} else {
			$freeid = 0;
		}
		
		mysql_query( "INSERT INTO dynlink (iduser, title, description, url, timer, obper, vip, freeid, erotic, plus, date, geo_ru, geo_ua, geo_by, geo_kz, geo_ge, geo_md, geo_am, geo_tj, geo_az, geo_uz, geo_pt, geo_es, geo_ee, geo_lv, geo_lt, geo_us, geo_gb, geo_fr, geo_de, geo_cn, geo_it, geo_all, testdrive) VALUES ('" . $_SESSION['iduser'] . "', '" . substr( check_text( $_POST['title'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['description'] ), 0, 55 ) . "', '" . substr( check_text( $_POST['url'] ), 0, 255 ) . "', '" . $config['testdriveTime'] . "', '" . $config['testdrivePerehod'] . "', '" . $config['testdriveVip'] . "', '" . $config['testdriveRef'] . "','" . $config['testdrive18'] . "', '0', '" . time() . "', '" . $geo_ru . "', '" . $geo_ua . "', '" . $geo_by . "', '" . $geo_kz . "', '" . $geo_ge . "', '" . $geo_md . "', '" . $geo_am . "', '" . $geo_tj . "', '" . $geo_az . "', '" . $geo_uz . "', '" . $geo_pt . "', '" . $geo_es . "', '" . $geo_ee . "', '" . $geo_lv . "', '" . $geo_lt . "', '" . $geo_us . "', '" . $geo_gb . "', '" . $geo_fr . "', '" . $geo_de . "', '" . $geo_cn . "', '" . $geo_it . "', '" . $geo_all . "', '1') " );
		mysql_query( "UPDATE user SET Use_a_test_drive = '1' WHERE id = '" . $_SESSION['iduser'] . "'" );

		echo 1;
		exit();
	}
  
}

### Рассылка рефералам
if ( $_GET['func'] == 'adddelivery' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    #текст рассылки
	$textmail = trim( $_POST['title'] );
    #тип рассылки, всем рефералам или только активным за последние 7 суток.
	$typemail = ( int ) $_POST['type'];
	
	if ( $textmail == "" ) {
		echo 'Сообщение не может быть пустым!';
		exit();
	} else
    
	#првоеряем режим рассылки платный или бесплатный, и соотвествено обрабатываем
	if ( $config['typedelivery'] == '0' ) {
		$ref1_rows = mysql_num_rows(mysql_query( "SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "'" ));
		$ref2_rows = mysql_num_rows(mysql_query( "SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "' and logindate + 86400 * 7 > '" . time() ."' " ));
		
		if ( $typemail != '0' AND $typemail != '1' ) {
			echo 'Что то пошло не так, обратитесь в тех-поддержку!';
			exit();
		} else
		
		if ( $typemail == 0 ) { 
			
			if ( $ref1_rows < 1 ) {
				echo 'Рассылать то некому!';
				exit();
			} else {
			
				$priceDelivery = $ref1_rows * $config['priceDelivery']; 
				
				if ($config_user['adv_money'] < $priceDelivery) {
					echo 'Недостаточно денег на рекламном счете!';
					exit();
				} else {
				
					$sql_ref_maill = mysql_query("SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "'");
					while ($row_ref_maill = mysql_fetch_array($sql_ref_maill)) {
						mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $_SESSION['iduser'] . "'" );
						mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . $row_ref_maill['id'] . "'" );
					}
					mysql_query( "UPDATE user SET adv_money = adv_money - '" . $priceDelivery . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
					mysql_query( "UPDATE viruchka SET money = money + '" . $priceDelivery . "' WHERE ident = '25'" );
					echo 1;
					exit();	
				}
			}
		} else { 
			
			if ( $ref2_rows < 1 ) {
				echo 'Рассылать то некому!';
				exit();
			} else {
			
				$priceDelivery = $ref2_rows * $config['priceDelivery']; 
				
				if ($config_user['adv_money'] < $priceDelivery) {
					echo 'Недостаточно денег на рекламном счете!';
					exit();
				} else {
				
					$sql_ref_maill = mysql_query("SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "' and logindate + 86400 * 7 > '" . time() ."'");
					while ($row_ref_maill = mysql_fetch_array($sql_ref_maill)) {
						mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $_SESSION['iduser'] . "'" );
						mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . $row_ref_maill['id'] . "'" );
					}
					mysql_query( "UPDATE user SET adv_money = adv_money - '" . $priceDelivery . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
					mysql_query( "UPDATE viruchka SET money = money + '" . $priceDelivery . "' WHERE ident = '25'" );
					echo 1;
					exit();
				}
			}
		}
		
	} else { 

		$ref1_rows = mysql_num_rows(mysql_query( "SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "'" ));
		$ref2_rows = mysql_num_rows(mysql_query( "SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "' and logindate + 86400 * 7 > '" . time() ."' " ));
		
		if ( $typemail != '0' AND $typemail != '1' ) {
			echo 'Что то пошло не так, обратитесь в тех-поддержку!';
			exit();
		} else
		if ( ($config_user['deliveryFreeTime'] + 86400 * 7) > time() ) {
			echo 'В бесплатном режиме можно рассылать не чаще одного раза в неделю.';
			exit();
		} else
		
		if ( $typemail == 0 ) { 
			
			if ( $ref1_rows < 1 ) {
				echo 'Рассылать то некому!';
				exit();
			} else {
			
				$sql_ref_maill = mysql_query("SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "'");
				while ($row_ref_maill = mysql_fetch_array($sql_ref_maill)) {
					mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $_SESSION['iduser'] . "'" );
					mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . $row_ref_maill['id'] . "'" );
				}
				mysql_query( "UPDATE user SET deliveryFreeTime = '" . time() . "' WHERE id = '" . $_SESSION['iduser'] . "'" );	
				echo 1;
				exit();	
				
			}
		} else { 
			
			if ( $ref2_rows < 1 ) {
				echo 'Рассылать то некому!';
				exit();
			} else {
			
				$sql_ref_maill = mysql_query("SELECT id FROM user WHERE referer = '" . $_SESSION['iduser'] . "' and logindate + 86400 * 7 > '" . time() ."'");
				while ($row_ref_maill = mysql_fetch_array($sql_ref_maill)) {
					mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $_SESSION['iduser'] . "'" );
					mysql_query( "INSERT INTO messages SET from_id = '" . $_SESSION['iduser'] . "', to_id = '" . $row_ref_maill['id'] . "', text = '" . parce_bb_code ( substr( check_text( $textmail ), 0, 1000 ), 'all' ) . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . $row_ref_maill['id'] . "'" );
				}
				mysql_query( "UPDATE user SET deliveryFreeTime = '" . time() . "' WHERE id = '" . $_SESSION['iduser'] . "'" );		
				echo 1;
				exit();
				
			}
		}
	}	
}

### Лайк пользователя (стенка)
if ( $_GET['func'] == 'LikeWalll' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ставить лайки могут только авторизованные пользователи!';
		exit();
    } else {
    
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$iduser = ( int ) $_POST['id'];
		
		if ($iduser == $_SESSION['iduser']) {
			echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы не можете ставить самому себе лайки или дизлайки!';
			exit();
		} else {       
			$InfoLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='1'  AND status ='0'" ) );
			$InfoDizLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='0'  AND status ='0'" ) );
			
			if($InfoLike['id'] < 1) {
				
				if($InfoDizLike['id'] > 0) {
					mysql_query( "UPDATE user SET dizlikes = dizlikes - 1 WHERE id = '" . $iduser . "' LIMIT 1" );
					mysql_query( "DELETE FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='0' AND status ='0'" );
				}
				mysql_query( "UPDATE user SET likes = likes + 1 WHERE id = '" . $iduser . "' LIMIT 1" );
				mysql_query( "INSERT INTO likes SET to_user = '".$iduser."', from_user = '".$_SESSION['iduser']."', what = '1' AND status ='0'" );
				#Пишем событие в ленту пользователю
				mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Пользователь ".$config_user['username']." поставил вам лайк на стенку <img src=\"/theme/images/smile/1.gif\" />', iduser = '" . $iduser . "' " );
				echo 1;
				exit();
			
			} else {
				echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы уже ставили лайк этому пользователю.';
				exit();
			}
		}	
	}
}

### Дизлайк пользователя (стенка)
if ( $_GET['func'] == 'DizlikeWall' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ставить лайки могут только авторизованные пользователи!';
		exit();
    } else {
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$iduser = ( int ) $_POST['id'];
		
		if ($iduser == $_SESSION['iduser']) {
			echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы не можете ставить самому себе лайки или дизлайки!';
			exit();
		} else {       
			$InfoLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='0' AND status ='0'" ) );
			$InfoDizLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='1' AND status ='0'" ) );
			
			if($InfoLike['id'] < 1) {
				
				if($InfoDizLike['id'] > 0) {
					mysql_query( "UPDATE user SET likes = likes - 1 WHERE id = '" . $iduser . "' LIMIT 1" );
					mysql_query( "DELETE FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='1' AND status ='0'" );
				}
				mysql_query( "UPDATE user SET dizlikes = dizlikes + 1 WHERE id = '" . $iduser . "' LIMIT 1" );
				mysql_query( "INSERT INTO likes SET to_user = '".$iduser."', from_user = '".$_SESSION['iduser']."', what = '0' AND status ='0' " );
				
				#Пишем событие в ленту пользователю
				mysql_query( "INSERT INTO developments_user SET date = '" . time() . "', status = '1', events = 'Пользователь ".$config_user['username']." поставил вам диз-лайк на стенку <img src=\"/theme/images/smile/4.gif\" />', iduser = '" . $iduser . "' " );
				
				echo 1;
				exit();
			
			} else {
				echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы уже ставили дизлайк этому пользователю.';
				exit();
			}
		}
	}
}

### Лайк комментария на стенке
if ( $_GET['func'] == 'LikeWalllComm' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ставить лайки могут только авторизованные пользователи!';
		exit();
    } else {
    
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$iduser = ( int ) $_POST['id'];
		$id_comment = ( int ) $_POST['comm'];
		
		if ($iduser == $_SESSION['iduser']) {
			echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы не можете ставить самому себе лайки или дизлайки!';
			exit();
		} else {       
			$InfoLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='1' AND status ='1' and id_comment = '".$id_comment."'" ) );
			$InfoDizLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='0' AND status ='1' and id_comment = '".$id_comment."'" ) );
			
			if($InfoLike['id'] < 1) {
				
				if($InfoDizLike['id'] > 0) {
					mysql_query( "UPDATE walls SET dizlikes = dizlikes - 1 WHERE id = '" . $id_comment . "' LIMIT 1" );
					mysql_query( "DELETE FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='0' AND status ='1' and id_comment = '".$id_comment."' " );
				}
				mysql_query( "UPDATE walls SET likes = likes + 1 WHERE id = '" . $id_comment . "' LIMIT 1" );
				mysql_query( "INSERT INTO likes SET to_user = '".$iduser."', from_user = '".$_SESSION['iduser']."', what = '1', status ='1', id_comment = '".$id_comment."' " );
				echo 1;
				exit();
			
			} else {
				echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы уже ставили лайк этому комментарию.';
				exit();
			}
		}	
	}
}

### Дизлайк коментария на стенке
if ( $_GET['func'] == 'DizlikeWallComm' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Ставить лайки могут только авторизованные пользователи!';
		exit();
    } else {
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$iduser = ( int ) $_POST['id'];
		$id_comment = ( int ) $_POST['comm'];
		
		if ($iduser == $_SESSION['iduser']) {
			echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы не можете ставить самому себе лайки или дизлайки!';
			exit();
		} else {       
			$InfoLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='0' AND status ='1' and id_comment = '".$id_comment."' " ) );
			$InfoDizLike = mysql_fetch_array( mysql_query( "SELECT * FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='1' AND status ='1' and id_comment = '".$id_comment."' " ) );
			
			if($InfoLike['id'] < 1) {
				
				if($InfoDizLike['id'] > 0) {
					mysql_query( "UPDATE walls SET likes = likes - 1 WHERE id = '" . $id_comment . "' LIMIT 1" );
					mysql_query( "DELETE FROM likes WHERE from_user = '".$_SESSION['iduser']."' AND to_user = '".$iduser."' AND what ='1' AND status ='1' and id_comment = '".$id_comment."' " );
				}
				mysql_query( "UPDATE walls SET dizlikes = dizlikes + 1 WHERE id = '" . $id_comment . "' LIMIT 1" );
				mysql_query( "INSERT INTO likes SET to_user = '".$iduser."', from_user = '".$_SESSION['iduser']."', what = '0', status ='1', id_comment = '".$id_comment."' " );
				echo 1;
				exit();
			
			} else {
				echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Вы уже ставили дизлайк этому комментарию.';
				exit();
			}
		}
	}
}

### Жалоба на рекламу
if ( $_GET['func'] == 'complaints_adv' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Отправлять жалобы на рекламу могут только авторизированные <div style="padding-left: 21px;">пользователи!</div>';
		exit();
    } else {
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$id = ( int ) $_POST['id'];
		$message = check_text( $_POST['text'] );
		$type = check_text( $_POST['type'] );
		
		$message = parce_bb_code( $message, 'all' );
        $message = substr( $message, 0, 3000 );
			
		if($type == 'serf') {
			$round_dynlink = mysql_fetch_array( mysql_query( "SELECT id FROM dynlink WHERE id = '".$id."' " ) );
			if ($round_dynlink['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_advertising SET ident = '".$id."', type = 'serf', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, рекламной площадки не существует!';
				exit();
			}
		} else
		if($type == 'test') {
			$round_test = mysql_fetch_array( mysql_query( "SELECT id FROM tests WHERE id = '".$id."' " ) );
			if ($round_test['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_advertising SET ident = '".$id."', type = 'test', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, рекламной площадки не существует!';
				exit();
			}
		} else
		if($type == 'task') {
			$round_task = mysql_fetch_array( mysql_query( "SELECT id FROM tasks WHERE id = '".$id."' " ) );
			if ($round_task['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_advertising SET ident = '".$id."', type = 'task', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, рекламной площадки не существует!';
				exit();
			}
		} else
		if($type == 'stat') {
			$round_stat = mysql_fetch_array( mysql_query( "SELECT id FROM statlink WHERE id = '".$id."' " ) );
			if ($round_stat['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_advertising SET ident = '".$id."', type = 'stat', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, рекламной площадки не существует!';
				exit();
			}
		} else {
			echo 'Ошибка, такого вида рекламы не существует!';
			exit();
		}
	}
}

### Жалоба на участника конкурса
if ( $_GET['func'] == 'complaints_comp' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Оставлять жалобы могут только авторизованные пользователи!';
		exit();
    } else {
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$id = ( int ) $_POST['id'];
		$message = check_text( $_POST['text'] );
		$type = check_text( $_POST['type'] );
		
		$message = parce_bb_code( $message, 'all' );
        $message = substr( $message, 0, 3000 );
			
		if($type == 'adv') {
			$round_dynlink = mysql_fetch_array( mysql_query( "SELECT id FROM konkurs WHERE id = '".$id."' " ) );
			if ($round_dynlink['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_competition SET ident = '".$id."', type = 'Конкурс рекламодателя', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, конкурса не существует!';
				exit();
			}
		} else
		if($type == 'ref') {
			$round_test = mysql_fetch_array( mysql_query( "SELECT id FROM konkurs WHERE id = '".$id."' " ) );
			if ($round_test['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_competition SET ident = '".$id."', type = 'Конкурс рефералов', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, конкурса не существует!';
				exit();
			}
		} else
		if($type == 'task') {
			$round_task = mysql_fetch_array( mysql_query( "SELECT id FROM konkurs WHERE id = '".$id."' " ) );
			if ($round_task['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_competition SET ident = '".$id."', type = 'Конкурс выполнения заданий', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, конкурса не существует!';
				exit();
			}
		} else
		if($type == 'task_adv') {
			$round_stat = mysql_fetch_array( mysql_query( "SELECT id FROM konkurs WHERE id = '".$id."' " ) );
			if ($round_stat['id'] > 0 ) {
				if($message != '') {
					mysql_query( "INSERT INTO complaints_competition SET ident = '".$id."', type = 'Конкурс размещения заданий', complaints = '".$message."', iduser ='".$_SESSION['iduser']."', date = '".time()."' , status = '1' " );
					echo 1;
					exit();
				} else {
					echo 'Сообщение не может быть пустым!';
					exit();
				}
			} else {
				echo 'Ошибка, конкурса не существует!';
				exit();
			}
		} else {
			echo 'Ошибка, такого вида конкурса не существует!';
			exit();
		}
	}
}

### Лайк новостей проекта
if ( $_GET['func'] == 'likes_news' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo 'Ставить лайки могут только авторизованные пользователи!';
		exit();
    } else {
    
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$iduser = $_SESSION['iduser'];
		$id_news = ( int ) $_POST['id'];
		
		$InfoLike = mysql_fetch_array( mysql_query( "SELECT id FROM like_news_temp WHERE iduser = '".$iduser."' AND id_news = '".$id_news."' " ) );
		
		if($InfoLike['id'] > 0) {
			mysql_query( "UPDATE news_of_the_project SET likes = likes - 1 WHERE id = '" . $id_news . "' LIMIT 1" );
			mysql_query( "DELETE FROM like_news_temp WHERE iduser = '".$iduser."' AND id_news = '".$id_news."'" );
			echo 1;
			exit();
		} else {
			mysql_query( "UPDATE news_of_the_project SET likes = likes + 1 WHERE id = '" . $id_news . "' LIMIT 1" );
			mysql_query( "INSERT INTO like_news_temp SET id_news = '".$id_news."', iduser = '".$iduser."'" );
			echo 1;
			exit();
		}
			
	}
}

### Лайк сайта в каталоге
if ( $_GET['func'] == 'likes_catalog' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) {
		echo 'Ставить лайки могут только авторизованные пользователи!';
		exit();
    } else {
    
		if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
		
		$iduser = $_SESSION['iduser'];
		$id_catalog = ( int ) $_POST['id'];
		
		$InfoLike = mysql_fetch_array( mysql_query( "SELECT id FROM like_catalog_temp WHERE iduser = '".$iduser."' AND id_catalog = '".$id_catalog."' " ) );
		
		if($InfoLike['id'] > 0) {
			mysql_query( "UPDATE catalog_mes SET likes = likes - 1 WHERE id = '" . $id_catalog . "' LIMIT 1" );
			mysql_query( "DELETE FROM like_catalog_temp WHERE iduser = '".$iduser."' AND id_catalog = '".$id_catalog."'" );
			echo 1;
			exit();
		} else {
			mysql_query( "UPDATE catalog_mes SET likes = likes + 1 WHERE id = '" . $id_catalog . "' LIMIT 1" );
			mysql_query( "INSERT INTO like_catalog_temp SET id_catalog = '".$id_catalog."', iduser = '".$iduser."'" );
			echo 1;
			exit();
		}
			
	}
}

### Новое сообщение в глобальном чате
if ( $_GET['func'] == 'newchat' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $_POST['text'] = trim( $_POST['text'] );
	
	$text = check_text( $_POST['text'] );
    $text = parce_bb_code( $text, 'chat' );
    
    $checkBan = mysql_query( "SELECT id FROM chat_ban WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
	if ( mysql_num_rows( $checkBan ) < 1 ) {
	  
	  #Задержка при создании
      $pr_forum_mes = mysql_query( "SELECT data FROM chat_mess WHERE from_id = '" . $_SESSION['iduser'] . "' ORDER BY id DESC LIMIT 1" );
      if ( mysql_num_rows( $pr_forum_mes ) > 0 ) {
        $pr_forum_mes_row = mysql_fetch_array( $pr_forum_mes );
        if ( $pr_forum_mes_row['data'] + $config['timeout_chat'] > time() ) {
		  echo 'Нельзя так часто слать сообщения!';
          exit();
        }
      } 
	  if ( empty( $_POST['text'] ) ) {
        echo 2;
        exit();
      } else {
        mysql_query( "INSERT INTO chat_mess SET from_id = '" . $_SESSION['iduser'] . "', text = '" . substr( $text, 0, 1000 ) . "', data = '" . time() . "' " );
        echo 1;
        exit();
      }
	
	} else {
	  echo 'Вы не можете отправлять сообщения в чате!';
	  exit();
	}
}

### Удалить сообщение (админ, арбитр, юзер)
if ( $_GET['func'] == 'dellchat' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    if ( $config_user['account'] == 2 or $config_user['account'] == 5 ) {
	  $checkDellchat = mysql_query( "SELECT id FROM chat_mess WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
	  if ( mysql_num_rows( $checkDellchat ) > 0 ) {
		mysql_query( "DELETE FROM chat_mess WHERE id = '" . ( int ) $_POST['id'] . "'" );
		echo 1;
		exit();
	  } else {
	    echo 'Сообщение не найдено или удалено!';
	    exit();
	  }
    } else {
	  $checkDellchat = mysql_query( "SELECT id FROM chat_mess WHERE id = '" . ( int ) $_POST['id'] . "' AND from_id = '" . $_SESSION['iduser'] . "' LIMIT 1" );
	  if ( mysql_num_rows( $checkDellchat ) > 0 ) {
		mysql_query( "DELETE FROM chat_mess WHERE id = '" . ( int ) $_POST['id'] . "'" );
		echo 1;
		exit();
	  } else {
	    echo 'Сообщение не пренадлежит вам!';
	    exit();
	  }
	}
 
}

### Кто онлай в чате
if ( $_GET['func'] == 'refreshonline' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $timeOnlyChat = (time())+60;
    mysql_query( "UPDATE chat_online SET time = '".$timeOnlyChat."' WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
	
	mysql_query( "DELETE FROM chat_online WHERE time < '".time(). "'" );
    
	$userOnlineChat = mysql_query( "SELECT iduser FROM chat_online" );
	if ( mysql_num_rows( $userOnlineChat ) > 0 ) {
	  while ( $userOnlineChatRow = mysql_fetch_array( $userOnlineChat ) ) {
		$userNameChat = mysql_fetch_array( mysql_query( "SELECT id, username, avatar, account FROM user WHERE id = '" . $userOnlineChatRow['iduser'] . "' LIMIT 1" ) );
		
		switch( $userNameChat['account'] ) {
		  case 0:
			$chatOnlineClass = 'chat_online_user';
			$nameStatus = 'Пользователь';
		  break;
		  case 2:
			$chatOnlineClass = 'chat_online_moder';
			$nameStatus = 'Модератор';
		  break;
		  case 5:
			$chatOnlineClass = 'chat_online_admin';
			$nameStatus = 'Администратор';
		  break;
		}
		
		$userBan = mysql_query( "SELECT iduser FROM chat_ban WHERE iduser = '" . $userNameChat['id'] . "' LIMIT 10" );
		if ( mysql_num_rows( $userBan ) > 0 ) {
		  $chatOnlineClass = 'chat_online_banfon';
		  if ( $config_user['account'] == 5 ) {
	        $chat_ban = '<i title="Разбанить в чате" onclick="delbanserg(' . $userNameChat['id'] . '); return false;" class="fa fa-ban color-red" aria-hidden="true"></i>';
		  } else {
		    $chat_ban = '';
	      }
		} else {
		  $chatOnlineClass = '';
		  if ( $config_user['account'] == 5 ) {
	        $chat_ban = '<i title="Забанить в чате" onclick="chat.Ban(' . $userNameChat['id'] . '); return false;" class="fa fa-ban color-red" aria-hidden="true"></i>';
		  } else {
		    $chat_ban = '';
	      }
		}
		
		echo '<div class="chat-online-block ' . $chatOnlineClass . '">
		  <a target="_blank" href="id' . $userNameChat['id'] . '">
			<img src="/temp/avatar/' . $userNameChat['avatar'] . '" width="24" height="24" class="img-circle" alt="" />
		  </a>
		  <div class="ch_online_name" onclick="toChat(this.innerHTML);">' . $userNameChat['username'] . '</div>
		  <div class="ch_online_ban">' . $chat_ban . '</div>
		</div>';
	  }
	}
}

### Разблокировка пользователя в чате
if ( $_GET['func'] == 'chatdel' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    if ( $config_user['account'] != 2 and $config_user['account'] != 3 and $config_user['account'] != 4 and $config_user['account'] != 5 ) {
	    exit();
    }  
	
    $checkUser = mysql_query( "SELECT account, username FROM user WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    if ( mysql_num_rows( $checkUser ) > 0 ) {
	  $checkUserRow = mysql_fetch_array( $checkUser );
	  $checkBan = mysql_query( "SELECT id FROM chat_ban WHERE iduser = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
	  if ( mysql_num_rows( $checkBan ) > 0 ) {
		
	    if ( $config_user['account'] <= $checkUserRow['account'] ) {
		  echo 'Вы не можете разблокировать пользователя с себе равным или выше административным статусом!';
		  exit();
	    }
	
	    mysql_query( "DELETE FROM chat_ban WHERE iduser = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
	    mysql_query( "UPDATE user SET chatblock = 0 WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
		$message = 'пользователь <span style="color:#4078CC">' . $checkUserRow['username'] . ' - разблокирован</span>';
	    mysql_query( "INSERT INTO chat_mess SET from_id = '" . $_SESSION['iduser'] . "', text = '" . $message . "', data = '" . time() . "'" );
	    echo 1;
	    exit();
	
	  } else {
		echo 'Пользователь уже разблокирован!';
		exit();
	  }
    }
} 

### Бан пользователя в чате
if ( $_GET['func'] == 'chatban' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    $id_ban_chat = ( int ) $_POST['id'];
	$date_tday = check_text( $_POST['date'] );
	$date_tday = strtotime( $date_tday );
	
	$coment_ban_chat = check_text($_POST['coment_ban_chat']);
	$coment_ban_chat = str_replace( 'коментарий к блокировке', '', $coment_ban_chat );
	
	if ( $config_user['account'] != 2 AND $config_user['account'] != 5 ) {
	  echo 'Ошибка прав доступа!';
	  exit();
    } else 
	if ( $date_tday < time() ) {
	  echo 'Дата блокировки не может быть меньше текущей!';
	  exit();
    } 
	
	$checkBan = mysql_query( "SELECT id FROM chat_ban WHERE iduser = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
	if ( mysql_num_rows( $checkBan ) > 0 ) {
	  echo 'Этот пользователь уже заблокирован!';
	  exit();
	}
    
	$checkUser_chat = mysql_query( "SELECT account, username FROM user WHERE id = '" . $id_ban_chat . "' LIMIT 1" );
    IF ( mysql_num_rows( $checkUser_chat ) > 0 ) {
	  $checkUserRow_chat = mysql_fetch_array( $checkUser_chat );
	    
	  IF ( $config_user['account'] <= $checkUserRow_chat['account'] ) {
		echo 'Вы не можете заблокировать пользователя с себе равным или выше административным статусом!';
		exit();
	  } ELSE  
	  IF ( $coment_ban_chat == '' ) {
		echo 'Коментарий не может быть пустым!';
		exit();
	  }  	    

	  if ( $date_tday <= ( time() + 31556926 ) ) {
	    mysql_query( "INSERT INTO chat_ban SET iduser = '" . $id_ban_chat . "', coment = '".$coment_ban_chat."', timeban = '".$date_tday."'" );
	    mysql_query( "UPDATE user SET chatblock = 1 WHERE id = '" . $id_ban_chat . "' LIMIT 1" );
		$message = 'пользователь <span style="color:#b41014">' . $checkUserRow_chat['username'] . ' - заблокирован</span>';
	    mysql_query( "INSERT INTO chat_mess SET from_id = '" . $_SESSION['iduser'] . "', text = '" . $message . "', data = '" . time() . "'" );
		
	    echo 1;
	    exit();
	
	  } ELSE {
	    echo 'Время блокировки не должно быть больше одного года';
	    exit();
	  }
		
	}
}

### Новый тикет
if ( $_GET['func'] == 'addtiks' ) {
	
	if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    $title = trim( $_POST['title'] );
    $text = trim( $_POST['text'] );
    $type = ( int ) $_POST['type'];
	
	if ( $title == "" ) {
		echo 'Тема запроса не может быть пустой!';
		exit();
	} else
	if ( $text == "" ) {
		echo 'Содержание запроса не может быть пустым!';
		exit();
	} else
	if ( $type != '0' AND $type != '1' AND $type != '2' AND $type != '3' AND $type != '4' AND $type != '5' AND $type != '6' ) {
		echo 'Выберите раздел запроса!';
		exit();
	} 
	
	$n1 = rand( 1, 100000 );
    $n2 = rand( 1, 100000 );
    $n3 = rand( 1, 100000 );
    $ident = $n1 + $n2 * $n2;
    $ident = md5($ident);
	
	$ident_tickets = mysql_query( "SELECT id FROM tickets WHERE ident = '" . $ident . "' " );
	$ident_tickets_row = mysql_fetch_array( $ident_tickets );
	
	if ($ident_tickets_row['id'] > 0) {
		echo 'Ошибка соеденения, попробуйте еще раз!';
		exit();
	}
	
	mysql_query( "
		INSERT INTO
			tickets 
		SET 
			ident = '" . $ident . "',
			iduser = '" . $_SESSION['iduser'] . "', 
			title = '" . substr( check_text( $title ), 0, 50 ) . "',
			time = '" . time() . "',
			type = '" . $type . "'
	" );
	
	mysql_query( "
		INSERT INTO
			tickets_dialog 
		SET 
			ident = '" . $ident . "', 
			iduser = '" . $_SESSION['iduser'] . "', 
			title = '" . substr( check_text( $title ), 0, 50 ) . "',
			message = '" . parce_bb_code ( substr( check_text( $text ), 0, 3000 ), 'msg' ) . "',
			time = '" . time() . "'
	" );
	
	echo 1;
	exit();
	
}

### Удаление тикетов
if ( $_GET['func'] == 'deltickets' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT * FROM tickets WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $proverka_row = mysql_fetch_array( $proverka );
        
        mysql_query( "DELETE FROM tickets WHERE ident = '" . $proverka_row['ident'] . "'" );
        mysql_query( "DELETE FROM tickets_dialog WHERE ident = '" . $proverka_row['ident'] . "'" );
        
        echo 1;
        exit();
    } else {
		echo 'Этот тикет не существует, или не пренадлежит Вам, удаление не возможно!';
		exit();
	}
}

### Ответ в тикете
if ( $_GET['func'] == 'mesagetiks' ) {
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
	$id = ( int ) $_POST['id'];
    $text = trim( $_POST['text'] );
    
    $proverka = mysql_query( "SELECT * FROM tickets WHERE id = '" . $id . "' and iduser = '" . $_SESSION['iduser'] . "'" );
    
	if ( $text == "" ) {
		echo 'Содержание запроса не может быть пустым!';
		exit();
	} else
    
	if ( mysql_num_rows( $proverka ) > 0 ) {
        $proverka_row = mysql_fetch_array( $proverka );
        
		$ident = $proverka_row['ident'];
		
        mysql_query( "
			INSERT INTO
				tickets_dialog 
			SET 
				ident = '" . $ident . "',
				iduser = '" . $_SESSION['iduser'] . "', 
				message = '" . parce_bb_code ( substr( check_text( $text ), 0, 3000 ), 'msg' ) . "',
				time = '" . time() . "'
			" );
		mysql_query( "UPDATE tickets SET status = '0' WHERE id = '" . $id . "'" );
        
        echo 1;
        exit();
    } else {
		echo 'Этот тикет не существует, или не пренадлежит вам, удаление не возможно!';
		exit();
	}
}


### Удаление события
if ( $_GET['func'] == 'delevents' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
    
    $proverka = mysql_query( "SELECT * FROM developments_user WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
    
    if ( mysql_num_rows( $proverka ) > 0 ) {
        $proverka_row = mysql_fetch_array( $proverka );
        
        mysql_query( "DELETE FROM developments_user WHERE id = '" . ( int ) $_POST['id'] . "' and iduser = '" . $_SESSION['iduser'] . "'" );
        
        echo 1;
        exit();
    } else {
		echo 'Этой записи не существует, или не пренадлежит вам, удаление не возможно!';
		exit();
	}
}


### Текстовый статус
if ( $_GET['func'] == 'text_status_w' ) {
    
    sleep(1);
    
    if ( !isset( $_SESSION['iduser'] ) ) exit();
    
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();
	
	$text = trim( $_POST['text'] );
    
    mysql_query( "UPDATE user SET text_status_wall = '" . substr( check_text( $text ), 0, 300 ) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
        
    echo 1;
    exit();
    
}









?>