<?php
session_start();
header( 'Content-type: text/html; charset=windows-1251' );
error_reporting( 1 );
include 'guard.php';
include 'sfb.php';
include 'functiones.php';
include 'bbcode.class.php';

//-------------------------------------------------------------------------------------------------------------------------------------------
//Загрузка аватара
if ($_FILES['uploadfile']['name']):
    if(!isset($_SESSION["username"]) && !isset($_SESSION["password"])) {
        exit();
    }
    // Проверяем размер загружаемого файла
    if ($_FILES["uploadfile"]["size"] != 0 AND $_FILES["uploadfile"]["size"] <= 128 * 1024) {
        // Проверяем расширение1
        if ($_FILES["uploadfile"]["type"] == "image/jpg" or $_FILES["uploadfile"]["type"] == "image/jpeg" or $_FILES["uploadfile"]["type"] == "image/gif" or $_FILES["uploadfile"]["type"] == "image/png")  {      
		    // Проверяем расширение2
		    $type_im = array('image/gif','image/jpg','image/jpeg','image/png');
            if(in_array($_FILES['uploadfile']['type'],$type_im)){
                // Проверяем загружен ли файл на сервер
                if(is_uploaded_file($_FILES["uploadfile"]["tmp_name"])) {
                    $imgwh = GetImageSize($_FILES["uploadfile"]["tmp_name"]);
                    // Проверяем ширину и высоту файла
                    if ($imgwh[0] > 60 or $imgwh[1] > 60 or $imgwh[0] < 60 or $imgwh[1] < 60) {
                        echo "imgsize";
                    } else {
				        if(in_array($imgwh['mime'],$type_im)){
                            if(@imagecreatefromstring(file_get_contents($_FILES['uploadfile']['tmp_name'])) === false) {
						        echo "imgtype";
						    } else {
                                $type_file = str_replace("theme/tmp/", "", basename($_FILES['uploadfile']['type']));
                                // Переносим файл из временной папки в нашу
                                if(@move_uploaded_file($_FILES['uploadfile']['tmp_name'], "avp/" . $_SESSION["iduser"] . "avatar." . $type_file)) {
                                    $nowtime = time();
                                    $tit = "Пользователь изменил аватар";
                                    mysql_query("INSERT INTO tb_allhistory (idus,data,doing,title) values ('" . $_SESSION['iduser'] . "','$nowtime', '1', '$tit')");
                                    mysql_query("UPDATE tb_users SET avatar = '" . $_SESSION['iduser'] . "avatar." . $type_file . "' WHERE id='" . $_SESSION['iduser'] . "'");
                                    echo "ok";
                                } else {
                                    echo "erser1";
                                }
						    } 	
				        } else {
                            echo "imgtype";
                        }	
				    }
                } else {
                    echo "erser2";
                }
            } else {
                echo "imgtype";
            }
		} else {
            echo "imgtype";
        }
    } else {
        echo "imgs";
    }
endif;
//-------------------------------------------------------------------------------------------------------------------------------------------
if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) {
    exit();
}
//Регистраиця
if ($_GET['func'] == 'reg') {
    if(isset($_SESSION["username"]) && isset($_SESSION["password"])) {
    	exit();
    }
    
    $checkuser = mysql_query("SELECT username FROM tb_users WHERE username='" . check_text($_POST['regname']) . "'");
    $username_exist = mysql_num_rows($checkuser);
    
    $checkpemail = mysql_query("SELECT id FROM tb_users WHERE email='" . check_text($_POST['email']) . "'");
    $pemail_exist = mysql_num_rows($checkpemail);
    
    $laip = getRealIP();
    if($laip != "127.0.0.1") {
	   $checkip = mysql_query("SELECT ip FROM tb_users WHERE ip='$laip'");
	   $ip_exist = mysql_num_rows($checkip);
	}
    if ($ip_exist > 0) {
        echo 'С Вашего IP адреса уже была регистрация. Повторная регистрация невозможна!';
        exit();
    } else    
    if (empty($_POST['regname'])) {
        echo 'Укажите Ваш ник!';
        exit();
    } else
    if (strlen(iconv('UTF-8', 'windows-1251', $_POST['regname'])) < 5 or strlen(iconv('UTF-8', 'windows-1251', $_POST['regname'])) > 20) {
        echo 'Ник может состоят от 5 до 20 символов!';
        exit();
    } else
    if (preg_match("/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\:|\=|\{|\}|\@|\*|\s|\.]/is", $_POST['regname'])) {
        echo 'Недопустимые символы!';
        exit();
    } else
    if ($username_exist > 0) {
        echo 'Ваш ник уже кем-то используется!';
        exit();
    } else
    if (empty($_POST['regpass'])) {
        echo 'Вы не указали пароль!';
        exit();
    } else
    if (strlen(iconv('UTF-8', 'windows-1251', $_POST['regpass'])) < 5 or strlen(iconv('UTF-8', 'windows-1251', $_POST['regpass'])) > 50) {
        echo 'Пароль может состоят от 5 до 50 символов!';
        exit();
    } else
    if (preg_match("/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\:|\=|\{|\}|\@|\*|\s|\.]/is", $_POST['regpass'])) {
        echo 'Недопустимые символы в пароле!';
        exit();
    } else
    if (!preg_match("/^(?:[a-z0-9]+(?:[-_]?[a-z0-9\.\-\_]+)?@[a-z0-9]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i", substr($_POST['email'], 0, 50))) {
        echo 'Указан неверный email!';
        exit();
    } else
    if (empty($_POST['email'])) {
        echo 'Вы не указали email';
        exit();
    } else
    if ($pemail_exist > 0) {
        echo 'Ваш email уже кем-то используется!';
        exit();
    } else
    if (strtolower($_POST['code']) != strtolower($_SESSION['texto'])) {
        echo 'Неверно указано кол-во квадратов!';
        exit();
    } else {
        $buying = '0';
        if ($_COOKIE['referer'] != 0) {
            $checkref = mysql_query("SELECT id, referer, autoback, greeting FROM tb_users WHERE id='" . intval($_COOKIE['referer']) . "'");
            $referer_exist = mysql_num_rows($checkref);
            
            if ($referer_exist < 1) {
                $_COOKIE['referer'] = '';
            } else {
                $myrowz = mysql_fetch_array($checkref);
                $res = mysql_query("SELECT price FROM tb_config WHERE item='refmax' AND howmany='0'");
                $res = mysql_fetch_array($res);
                $refmax = $res["price"];
                $referer2 = $myrowz['referer'];
                $greeting = $myrowz['greeting'];
                if ($referer2 != 0) { $ref2rey = 0.2; } else { $ref2rey = 0; }
                $autoback = $myrowz['autoback'];
				
				//Конкурсы
                $prov_kon = mysql_query("SELECT id, end_date FROM konkurs WHERE type = 2 ORDER BY id DESC");
                if (mysql_num_rows($prov_kon) > 0) {
                    $prov_row = mysql_fetch_array($prov_kon);
                    $end_date = explode('.', $prov_row['end_date']);
                    $end_date = mktime(0, 0, 0, $end_date[1], $end_date[0], $end_date[2]);
                    if (time() < $end_date) {
                        $prov_user = mysql_query("SELECT id FROM konkurs_temp WHERE iduser = '" . intval($_COOKIE['referer']) . "' and type = 2");
                        if (mysql_num_rows($prov_user) > 0) {
                            mysql_query("UPDATE konkurs_temp SET summ = summ + '0', idkonkurs = '$prov_row[id]' WHERE iduser = '" . intval($_COOKIE['referer']) . "' AND type = 2");
                        } else {
                            mysql_query("INSERT INTO konkurs_temp (idkonkurs, iduser, type, summ) VALUES ('$prov_row[id]', '" . intval($_COOKIE['referer']) . "', 2, '0')");
                        }
                    }
                }
                                
                mysql_query("UPDATE tb_users SET money=money+'$refererbonus', reyting=reyting+1 WHERE id='" . intval($_COOKIE['referer']) . "'");
                mysql_query("UPDATE tb_users SET reyting = reyting+'$ref2rey' WHERE id = '$referer2'");
                }
            }
        }
    
    include 'geoip/GeoIP.php';
    $geoip = Net_GeoIP::getInstance('geoip/GeoIP.dat');
    try {
        $regcountry = $geoip->lookupCountryName($ip);
        $regcode = strtolower($geoip->lookupCountryCode($ip));
    }
    catch (Exception $e) {
    }
    
    //if ($regcountry == '') {$regcountry = 'Украина';}
    //if ($regcode == '') {$regcode = 'ua';}
    $fam = intval($_POST['fam']);
    if ($fam != 1 and $fam != 2) {
        $fam = 1;
    }
    
    $keyact = rand(100000, 999999);
    
    preg_match('/([a-z0-9aа-я\.])+([a-z0-9а-я\-])+(\.)([a-z0-9а-я]{2,5}\.)?([a-z0-9а-я]{2,5})/i', check_text($_COOKIE['rsite']), $out);
	
    
    $title="У Вас новый реферал ". iconv('UTF-8', 'windows-1251', $_POST['regname']) . ".Зачислен бонус $refererbonus $sitevalname";
    mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . intval($_COOKIE['referer']) . "', '$nowtime', '3', '$title')");
    	$query = "INSERT INTO tb_users (username, password, ip, email, referer, referer2, country, city_code, joindate, joindate2, mailaccess, autoproc, reyting, family, keyok, refsite, actcode) VALUES('" . iconv('UTF-8', 'windows-1251', $_POST['regname']) . "','" . iconv('UTF-8', 'windows-1251', md5($_POST['regpass'])) . "','$laip','" . $_POST['email'] . "', '" . intval($_COOKIE['referer']) . "', '" . $referer2 . "', '" . mb_convert_encoding($regcountry, 'CP1251', 'UTF8') . "', '" . $regcode . "', '" . time() . "', '" . time() . "', 0, '$autoback', 1, '$fam', 0, '$out[0]', '$keyact')";
    mysql_query($query) or die(mysql_error());
    
    //Приветствие на почту
    if ($greeting != '') {
        $userid = mysql_fetch_array(mysql_query("SELECT id FROM tb_users ORDER BY id DESC"));
        mysql_query( "INSERT INTO seo_mails (fromid, toid, subject, text, timemessage) VALUES ('$myrowz[id]', '$userid[id]', 'Приветственное письмо', '$greeting', '" . time() . "')" );
    }
    
    include 'mail.class.php';
    webmail_reg($_POST['email'], iconv('UTF-8', 'windows-1251', $_POST['regpass']), $siteemail, $keyact, $sitename);
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Авторизация
if ($_GET['func'] == 'log') {
    if(isset($_SESSION["username"]) && isset($_SESSION["password"])) {
    	exit();
    }
    $laip = getRealIP();
    $query = mysql_fetch_array(mysql_query("SELECT ban, blockip, id, count(*) as kolvo FROM tb_users WHERE email = '" . check_text($_POST['logusername']) . "' and password = '" . check_text(md5($_POST['logpassword'])) . "'"));
    if ($query['ban'] == 1) {
        echo 'Ваш аккаунт заблокирован';
        exit();
    } else
    if ($query["kolvo"] < 1) {
        echo 'Введены неверные данные. Вход невозможен!';
        exit();
    } else
    if (strtolower($_POST['code']) != strtolower($_SESSION['texto'])) {
        echo 'Неверно указано кол-во квадратов!';
        exit();
    } else  
    if ($query['blockip'] != '' and $query['blockip'] != $laip) {
        echo 'Ваш IP адрес не соответствует разрешенному для авторизации под данным логином!';
    } else {
        $_SESSION['iduser'] = intval($query['id']);
        
        include 'geoip/GeoIP.php';
        $geoip = Net_GeoIP::getInstance('geoip/GeoIP.dat');
        try {
            $regcountry = $geoip->lookupCountryName($laip);
            $regcode = strtolower($geoip->lookupCountryCode($laip));
        }
        catch (Exception $e) {
        }
        
        mysql_query("UPDATE tb_users SET lastiplog = '$laip', country = '" . mb_convert_encoding($regcountry, 'CP1251', 'UTF8') . "', lastlogdate = '" . time() . "' WHERE id = '" . $_SESSION['iduser'] . "'");
        $rres = mysql_fetch_assoc(mysql_query("SELECT username FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'"));
        $_SESSION['username'] = $rres['username'];
        $_SESSION["password"] = md5($_POST['logpassword']);
        $varstr=date('w');
        $row = mysql_query("select date from tb_statistic where typ = 0 and username = '" . $_SESSION['iduser'] . "'");
        if (mysql_num_rows($row) == 0) {
            mysql_query("INSERT INTO tb_statistic (date, username) values ('$varstr', '" . $_SESSION['iduser'] . "')") or die(mysql_error());
        }
        $row = mysql_fetch_array($row);
        if ($row['date'] != $varstr) {
            $day = '';
            if ($varstr == '1') $day = 'mon';
            if ($varstr == '2') $day = 'tue';
            if ($varstr == '3') $day = 'wed';
            if ($varstr == '4') $day = 'thu';
            if ($varstr == '5') $day = 'fri';
            if ($varstr == '6') $day = 'sat';
            if ($varstr == '0') $day = 'sun';    
            mysql_query("UPDATE tb_statistic SET date=" . $varstr . " , " . $day . " = 0 WHERE username='" . $_SESSION['iduser'] . "'");
        }
        
        if ($_POST['savelp'] == 'on') {
            setcookie('login', $_POST['logusername'], time() + 356 * 86400);
            setcookie('pass', $_POST['logpassword'], time() + 356 * 86400);
        } else {
            setcookie('login', '', time() - 1);
            setcookie('pass', '', time() - 1);
        }
		
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//восстановление пароля
if ($_GET['func'] == 'recpass') {
    $email = $_POST['recemail'];
    if (strtolower($_POST['code']) != strtolower($_SESSION['texto'])) {
        echo 'Неверно указано кол-во квадратов!';
        exit();
    } else
    if (!preg_match("/^(?:[a-z0-9]+(?:[-_]?[a-z0-9\.\-\_]+)?@[a-z0-9]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i", substr($email, 0, 50))) {
        echo 'Вы указали неправильный email';
        exit();
    } else
    if ($email == '') {
        echo 'Вы указали неправильный email';
        exit();
    } else {
        $sql = mysql_query("SELECT id FROM tb_users WHERE email = '$email' and user_status != 'admin'");
        if (mysql_num_rows($sql) < 1) {
            echo 'Указанный email не существует';
            exit();
        } else {
            $row = mysql_fetch_array($sql);
            $pass = generate_password(7);
            include_once 'mail.class.php';
            pasrec($email, iconv('UTF-8', 'windows-1251', $pass), $siteemail, $sitename);
            mysql_query("UPDATE tb_users SET password = '" . md5($pass) . "' WHERE id = '$row[id]'");
            echo 1;
            exit();
        }
    }
}

if (!isset($_SESSION['username']) && !isset($_SESSION['password'])) {
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Активация аккаунта
if ($_GET['func'] == 'actcode') {
    $code = intval($_POST['key']);
    
    if ($actcode != $code) {
        echo 'Неверный код активации!';
        exit();
    } else {
        mysql_query("UPDATE tb_users SET keyok = 1 WHERE id = '$_SESSION[iduser]'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Защита аккаунта по IP
if ($_GET['func'] == 'addblockip') {
    if ($blockip != '') {
        mysql_query("UPDATE tb_users SET blockip = '' WHERE id = '$_SESSION[iduser]'");
        echo 1;
        exit();
    } else {
        $laip = getRealIP();
        mysql_query("UPDATE tb_users SET blockip = '".$laip."' WHERE id = '$_SESSION[iduser]'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Редактирование профиля
if ($_GET['func'] == 'editprofile') {
    
	if (preg_match("/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\:|\=|\{|\}|\@|\*|\s]/is", $_POST['ask_pass'])) {
        echo 'Недопустимые символы';
        exit();
    } else
		
	if ($finestatus != 0) {
		echo 'На ваш аккаунт наложен штраф, изменение данных недоступно';
		exit();
	} else
		
	$ask_webmoney = check_text($_POST['ask_webmoney']);
	$ask_payeer = check_text($_POST['ask_payeer']);
	
	$ask_webmoney = str_replace('R', '', $ask_webmoney);
	$ask_payeer = str_replace('P', '', $ask_payeer);
	
	

	/// вебмани
    if ($ask_webmoney != '' AND $ask_payeer == '') {
		if ($wmid != '') {
			echo 'У Вас уже указан кошелек Webmoney';
			exit();
		}		
		
        if ($keyok != 1) {
			echo 'Вначале вы должны активировать аккаунт пин-кодом';
			exit();
		}	
        $gwmid = getwmid('R'.$ask_webmoney);
        if (strlen($ask_webmoney) != 12 or !is_numeric(substr($ask_webmoney, 1, 12)) or $gwmid == 1) {
            echo 'Неверно указан кошелек Webmoney. Будьте внимательны!';
            exit();
        } else
        if ($_POST['ask_pass'] != '' or $_POST['ask_pass2'] != '') {
            if ($_POST['ask_pass'] != $_POST['ask_pass2']) {
                echo 'Пароли не совпадают';
            } else {
                mysql_query( "UPDATE tb_users SET pemail = 'R" . $ask_webmoney . "', password = '" . check_text(substr(md5($_POST['ask_pass']), 0, 50)) . "', wmid = '$gwmid' WHERE id = '" . $_SESSION['iduser'] . "'" );
				
				//Конкурсы
				$getref = mysql_fetch_array(mysql_query("SELECT referer, wmid FROM tb_users WHERE id = '$_SESSION[iduser]'"));
				if ($getref['referer'] != 0) {
					$prkon = mysql_fetch_array(mysql_query("SELECT id, idkonkurs, summ FROM konkurs_temp WHERE type='2' and iduser = '$getref[referer]' ORDER BY id DESC"));
					$kon_date = mysql_fetch_array(mysql_query("SELECT start_date FROM konkurs WHERE id = '$prkon[idkonkurs]'"));
					$s_date = explode('.', $kon_date['start_date']);
					$s_date = mktime(0, 0, 0, $s_date[1], $s_date[0], $s_date[2]);
					if ($prkon['id'] != 0 and $kon_date['start_date'] < $s_date) {
						mysql_query("UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '$getref[referer]' and type = 2");
					}
				}
				
                unset($_SESSION["username"]);
                unset($_SESSION["password"]);
                unset($_SESSION["iduser"]);
                echo 1;
                exit();
            }
        } else {
            mysql_query( "UPDATE tb_users SET pemail = 'R" . $ask_webmoney . "', reyting = reyting + 1, wmid = '$gwmid' WHERE id = '" . $_SESSION['iduser'] . "'" );
			
			//Конкурсы
			$getref = mysql_fetch_array(mysql_query("SELECT referer, wmid FROM tb_users WHERE id = '$_SESSION[iduser]'"));
			if ($getref['referer'] != 0) {
				$prkon = mysql_fetch_array(mysql_query("SELECT id, idkonkurs, summ FROM konkurs_temp WHERE type='2' and iduser = '$getref[referer]' ORDER BY id DESC"));
				$kon_date = mysql_fetch_array(mysql_query("SELECT start_date FROM konkurs WHERE id = '$prkon[idkonkurs]'"));
				$s_date = explode('.', $kon_date['start_date']);
				$s_date = mktime(0, 0, 0, $s_date[1], $s_date[0], $s_date[2]);
				if ($prkon['id'] != 0 and $kon_date['start_date'] < $s_date) {
					mysql_query("UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '$getref[referer]' and type = 2");
				}
			}
			
            echo 1;
            exit();
        }
    } else
	
	///паер
	if($ask_payeer != '' AND $ask_webmoney == ''){
	
	if ($payeer != '') {
			echo 'У Вас уже указан кошелек Payeer';
			exit();
		}		
		
        if ($keyok != 1) {
			echo 'Вначале вы должны активировать аккаунт пин-кодом';
			exit();
		}

		if (strlen($ask_payeer) > 12 or strlen($ask_payeer) < 5) {
            echo 'Неверно указан кошелек Payeer. Будьте внимательны!';
            exit();
        } else
        
        if ($_POST['ask_pass'] != '' or $_POST['ask_pass2'] != '') {
            if ($_POST['ask_pass'] != $_POST['ask_pass2']) {
                echo 'Пароли не совпадают';
            } else {
                mysql_query( "UPDATE tb_users SET payeers = 'P" . $ask_payeer . "', password = '" . check_text(substr(md5($_POST['ask_pass']), 0, 50)) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
				
				//Конкурсы
				$getref = mysql_fetch_array(mysql_query("SELECT referer, wmid FROM tb_users WHERE id = '$_SESSION[iduser]'"));
				if ($getref['referer'] != 0) {
					$prkon = mysql_fetch_array(mysql_query("SELECT id, idkonkurs, summ FROM konkurs_temp WHERE type='2' and iduser = '$getref[referer]' ORDER BY id DESC"));
					$kon_date = mysql_fetch_array(mysql_query("SELECT start_date FROM konkurs WHERE id = '$prkon[idkonkurs]'"));
					$s_date = explode('.', $kon_date['start_date']);
					$s_date = mktime(0, 0, 0, $s_date[1], $s_date[0], $s_date[2]);
					if ($prkon['id'] != 0 and $kon_date['start_date'] < $s_date) {
						mysql_query("UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '$getref[referer]' and type = 2");
					}
				}
				
                unset($_SESSION["username"]);
                unset($_SESSION["password"]);
                unset($_SESSION["iduser"]);
                echo 1;
                exit();
            }
        } else {
            mysql_query( "UPDATE tb_users SET payeers = 'P" . $ask_payeer . "', reyting = reyting + 1 WHERE id = '" . $_SESSION['iduser'] . "'" );
			
			//Конкурсы
			$getref = mysql_fetch_array(mysql_query("SELECT referer, wmid FROM tb_users WHERE id = '$_SESSION[iduser]'"));
			if ($getref['referer'] != 0) {
				$prkon = mysql_fetch_array(mysql_query("SELECT id, idkonkurs, summ FROM konkurs_temp WHERE type='2' and iduser = '$getref[referer]' ORDER BY id DESC"));
				$kon_date = mysql_fetch_array(mysql_query("SELECT start_date FROM konkurs WHERE id = '$prkon[idkonkurs]'"));
				$s_date = explode('.', $kon_date['start_date']);
				$s_date = mktime(0, 0, 0, $s_date[1], $s_date[0], $s_date[2]);
				if ($prkon['id'] != 0 and $kon_date['start_date'] < $s_date) {
					mysql_query("UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '$getref[referer]' and type = 2");
				}
			}
			
            echo 1;
            exit();
        }


	
	} else
	
	///паер и вебмани
	if($ask_webmoney != '' AND $ask_payeer != '') {
	

		if ($wmid != '' or $payeer != '') {
			echo 'Ошибка ввода, свяжитесь с администрацией!';
			exit();
		}		
		
        if ($keyok != 1) {
			echo 'Вначале вы должны активировать аккаунт пин-кодом';
			exit();
		}	
        $gwmid = getwmid('R'.$ask_webmoney);
        if (strlen($ask_webmoney) != 12 or !is_numeric(substr($ask_webmoney, 1, 12)) or $gwmid == 1) {
            echo 'Неверно указан кошелек Webmoney. Будьте внимательны!';
            exit();
        } else
		if (strlen($ask_payeer) > 12 or strlen($ask_payeer) < 5) {
            echo 'Неверно указан кошелек Payeer. Будьте внимательны!';
            exit();
        } else
        if ($_POST['ask_pass'] != '' or $_POST['ask_pass2'] != '') {
            if ($_POST['ask_pass'] != $_POST['ask_pass2']) {
                echo 'Пароли не совпадают';
            } else {
                mysql_query( "UPDATE tb_users SET pemail = 'R" . $ask_webmoney . "', payeers = 'P" . $ask_payeer . "', password = '" . check_text(substr(md5($_POST['ask_pass']), 0, 50)) . "', wmid = '$gwmid' WHERE id = '" . $_SESSION['iduser'] . "'" );
				
				//Конкурсы
				$getref = mysql_fetch_array(mysql_query("SELECT referer, wmid FROM tb_users WHERE id = '$_SESSION[iduser]'"));
				if ($getref['referer'] != 0) {
					$prkon = mysql_fetch_array(mysql_query("SELECT id, idkonkurs, summ FROM konkurs_temp WHERE type='2' and iduser = '$getref[referer]' ORDER BY id DESC"));
					$kon_date = mysql_fetch_array(mysql_query("SELECT start_date FROM konkurs WHERE id = '$prkon[idkonkurs]'"));
					$s_date = explode('.', $kon_date['start_date']);
					$s_date = mktime(0, 0, 0, $s_date[1], $s_date[0], $s_date[2]);
					if ($prkon['id'] != 0 and $kon_date['start_date'] < $s_date) {
						mysql_query("UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '$getref[referer]' and type = 2");
					}
				}
				
                unset($_SESSION["username"]);
                unset($_SESSION["password"]);
                unset($_SESSION["iduser"]);
                echo 1;
                exit();
            }
        } else {
            mysql_query( "UPDATE tb_users SET pemail = 'R" . $ask_webmoney . "', payeers = 'P" . $ask_payeer . "', reyting = reyting + 1, wmid = '$gwmid' WHERE id = '" . $_SESSION['iduser'] . "'" );
			
			//Конкурсы
			$getref = mysql_fetch_array(mysql_query("SELECT referer, wmid FROM tb_users WHERE id = '$_SESSION[iduser]'"));
			if ($getref['referer'] != 0) {
				$prkon = mysql_fetch_array(mysql_query("SELECT id, idkonkurs, summ FROM konkurs_temp WHERE type='2' and iduser = '$getref[referer]' ORDER BY id DESC"));
				$kon_date = mysql_fetch_array(mysql_query("SELECT start_date FROM konkurs WHERE id = '$prkon[idkonkurs]'"));
				$s_date = explode('.', $kon_date['start_date']);
				$s_date = mktime(0, 0, 0, $s_date[1], $s_date[0], $s_date[2]);
				if ($prkon['id'] != 0 and $kon_date['start_date'] < $s_date) {
					mysql_query("UPDATE konkurs_temp SET summ = summ + 1 WHERE iduser = '$getref[referer]' and type = 2");
				}
			}
			
            echo 1;
            exit();
        }

	
		
	} else


	///пароль
	if($_POST['ask_pass'] != '' or $_POST['ask_pass2'] != '' AND $ask_webmoney == '' AND $ask_payeer == ''){
        if ($_POST['ask_pass'] != '' or $_POST['ask_pass2'] != '') {
            if ($_POST['ask_pass'] != $_POST['ask_pass2']) {
                echo 'Пароли не совпадают';
            } else {
                mysql_query( "UPDATE tb_users SET password = '" . check_text(substr(md5($_POST['ask_pass']), 0, 50)) . "' WHERE id = '" . $_SESSION['iduser'] . "'" );
                unset($_SESSION["username"]);
                unset($_SESSION["password"]);
                unset($_SESSION["iduser"]);
                echo 1;
                exit();
            }
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Установка рефбека
if ($_GET['func'] == 'refback') {
    $proc = intval($_POST['usproc']);
    $getus = mysql_fetch_array(mysql_query("SELECT autoproc, lastlogdate FROM tb_users WHERE id = '" . intval($_POST['usid']) . "' and referer='" . $_SESSION['iduser'] . "'"));
    if ($finestatus != '0') {
        echo 'Внимание! На ваш аккаунт наложен штраф! Работа с рефералами для вас не доступна!';
        exit();
    } else {
	    if ($proc > 0 or $proc < 90 and is_numeric($proc)) {
            if ($getus['autoproc'] > $proc and $getus['lastlogdate'] > time() - (7 * 86400)) {
                echo 'Рефбек не может быть меньше установленного';
                exit();
            } else {
                mysql_query("UPDATE tb_users set autoproc='" . $proc . "' WHERE id='" . intval($_POST['usid']) . "' and referer='" . $_SESSION['iduser'] . "'") or die(mysql_error());
                echo 1;
            }
	    }
	    exit();
	}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление реферала
if ($_GET['func'] == 'refdel') {
    if ($finestatus != '0') {
        echo 'Внимание! На ваш аккаунт наложен штраф! Работа с рефералами для вас не доступна!';
        exit();
    } else {
        $delid = intval($_POST['usid']);
	    mysql_query("UPDATE tb_users SET referer = 0, autoproc = 0 where id = '$delid' and referer = '$_SESSION[iduser]'");
        //mysql_query("UPDATE tb_users SET referer2 = 0 where id = '$delid' and referer2 = '$_SESSION[iduser]'");
        echo 1;
        exit();
	}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Вернуть реферала с ярмарки
if ($_GET['func'] == 'backref') {
    $ident = intval($_POST['usid']);
    $sql = mysql_fetch_array(mysql_query("SELECT bron FROM seo_refbirj WHERE rid='$ident' and trid='$_SESSION[iduser]'"));
    if ($finestatus != '0') {
        echo 'Внимание! На ваш аккаунт наложен штраф! Работа с рефералами для вас не доступна!';
        exit();
    } else {    
	    if ($sql['bron'] == 1) {
            echo 'Реферал забронирован';
            exit();
        } else {
    	    mysql_query("DELETE FROM seo_refbirj WHERE rid='$ident' and trid='$_SESSION[iduser]' and bron != 1");
            echo 1;
            exit();
        }
	}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Разрешить принимать почту или нет
if ($_GET['func'] == 'checkmail') {
    $mcheck = intval($_POST['mail']);
    if ($mcheck != 0 and $mcheck != 1) {
        exit();
    }
	mysql_query("UPDATE tb_users SET mailaccess = '$mcheck' WHERE id='$_SESSION[iduser]'");
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Ответ по почте
if ($_GET['func'] == 'reply') {
    $checkmail = mysql_fetch_array( mysql_query( "SELECT mailaccess FROM tb_users WHERE id = '" . intval($_POST['usid']) . "'" ) );
    if ($checkmail['mailaccess'] == 1 and $user_status != 'admin') {
        echo 'Пользователь запретил отправлять ему сообщения';
        exit();
    } else
    if ($_SESSION['mailuserid'] != intval($_POST['usid'])) {
        echo 'Пользователь не является вашим собеседником';
        exit();
    } else {
        $_POST['ussubject'] = check_text($_POST['ussubject']);
        if ($_POST['ussubject'] == '') $_POST['ussubject'] = 'Без темы';
        mysql_query( "INSERT INTO seo_mails (fromid, toid, subject, text, timemessage) VALUES ('" . $_SESSION['iduser'] . "', '" . intval($_POST['usid']) . "', '" . substr($_POST['ussubject'], 0, 50) . "', '" . iconv('UTF-8', 'windows-1251', substr(qcode_bb($_POST['text']), 0, 2000)) . "', '" . time() . "')" );
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Проверка пользователя по id
if ($_GET['func'] == 'checkid') {
    $mcheckus = mysql_fetch_array( mysql_query( "SELECT id, username, mailaccess FROM tb_users WHERE id = '" . intval($_POST['id']) . "' LIMIT 1" ) );
    if ($mcheckus['id'] == '') {
        echo '&nbsp;<font color="#800000">Пользователь несуществует</font>';
        exit();
    } else
    if ($mcheckus['mailaccess'] == 1 and $user_status != 'admin') {
        echo '&nbsp;<font color="#800000">Запретил отправлять сообщения</font>';
        exit();
    } else
    if ($mcheckus['id'] == $_SESSION['iduser']) {
        echo '&nbsp;<font color="#800000">Вы не можете отправить самому себе</font>';
        exit();
    } else {
        echo $mcheckus['username'];
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Новое сообщение
if ($_GET['func'] == 'newmail') {
    $mcheckus = mysql_fetch_array( mysql_query( "SELECT id, username, mailaccess FROM tb_users WHERE id = '" . intval($_POST['id']) . "'" ) );
    if ($mcheckus['id'] == '') {
        echo '<font color="#800000">Пользователь несуществует</font>';
        exit();
    } else
    if ($mcheckus['mailaccess'] == 1 and $user_status != 'admin') {
        echo '<font color="#800000">Пользователь запретил отправлять ему сообщения</font>';
        exit();
    } else
    if ($_POST['text'] == '') {
        echo '<font color="#800000">Введите текст сообщения</font>';
        exit();
    } else
    if ($mcheckus['id'] == $_SESSION['iduser']) {
        echo '<font color="#800000">Вы не можете отправить самому себе</font>';
        exit();
    } else {
        $_POST['subject'] = check_text($_POST['subject']);
        if ($_POST['subject'] == '') $_POST['subject'] = 'Без темы';
        mysql_query( "INSERT INTO seo_mails (text, subject, fromid, toid, timemessage) VALUES ('" . iconv('UTF-8', 'windows-1251', substr(qcode_bb($_POST['text']), 0, 2000)) . "', '" . substr($_POST['subject'], 0, 50) . "', '" . $_SESSION['iduser'] . "', '" . intval($_POST['id']) . "', '" . time() . "')" );
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ дин. ссылки
if ($_GET['func'] == 'adddyn') {
    $url1 = check_text($_POST["url"]);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    $description = check_text($_POST["description"]);
	$texto = check_text($_POST['texto']);

	$highlight = intval($_POST["highlight"]);
	if ($highlight != 1 and $highlight != 0) { 
        $highlight = 0; 
  	}

    $timer = intval($_POST["timer"]);
	if ($timer != 1 and $timer != 2 and $timer != 3 and $timer != 4 and $timer != 5 and $timer != 6 and $timer != 0) {
        echo "Ошибка ввода!!!";
        exit();
	} else
    $obper = intval($_POST["obper"]);
	if ($obper != 1 and $obper != 0) $obper = 0;
	
	if ($url1 == "") {echo '<div id="error">Вы не указали URL сайта</div>'; exit();} else
	if ($description == ""){echo '<div id="error">Вы не указали заголовок</div>'; exit();} else
	if ($texto == ""){echo '<div id="error">Вы не указали описание ссылки</div>'; exit();} else {
	
	if($timer == 6 ) { $precio = $hits5  + $hldyn * $highlight + $obper * $obperehod; } 
	if($timer == 5 ) { $precio = $hits10 + $hldyn * $highlight + $obper * $obperehod; } 
	
	if($timer == 0 or $timer == 1 or $timer == 2 or $timer == 3 or $timer == 4 ) { $precio = $hits + $timer * $timer5 + $hldyn * $highlight + $obper * $obperehod; } 
	
	if ($timer == 0) $payforad = $payuser['dyn20'];
	if ($timer == 1) $payforad = $payuser['dyn30'];
	if ($timer == 2) $payforad = $payuser['dyn40'];
	if ($timer == 3) $payforad = $payuser['dyn50'];
	if ($timer == 4) $payforad = $payuser['dyn60'];
	if ($timer == 5) $payforad = $payuser['dyn10'];
	if ($timer == 6) $payforad = $payuser['dyn5'];
    
    if ($modered == 1) $mod = 1; else $mod = 0;
    
    $nowtime = time();
    mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '" . $nowtime . "', 2, '" . substr($url1, 0, 300) . "')"); 
    mysql_query("INSERT INTO tb_ads (url, description, timer, obper, texto, highlight, price, fromus, payforad, modered) values ('" . substr($url1, 0, 300) . "', '" . substr($description, 0, 55). "', '" . $timer . "', '" . $obper . "', '" . substr($texto, 0, 55) . "', '" . $highlight . "', '" . $precio . "', '" . $_SESSION['iduser'] . "', '" . $payforad . "', '$mod')") or die(mysql_error());
    echo 1;
    exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Редактирование дин. ссылки
if ($_GET['func'] == 'updyn') {
    $url1 = check_text($_POST["url"]);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    $description = check_text($_POST["description"]);
	$texto = check_text($_POST['texto']);

	$highlight = intval($_POST["highlight"]);
	if ($highlight != 1 and $highlight != 0) { $highlight = 0; }

    $timer = intval($_POST["timer"]);
	if ($timer != 1 and $timer != 2 and $timer != 3 and $timer != 4 and $timer != 5 and $timer != 6 and $timer != 0) {
        echo "Ошибка ввода!!!";
        exit();
	}
    $get_link = mysql_fetch_array( mysql_query( "SELECT id, url, description, texto, modered FROM tb_ads WHERE id = '" . intval($_POST['id']) . "' and fromus = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    if ($get_link['id'] == '') {
        echo 'Вы не можете редактировать чужую ссылку';
        exit();
    } else
    $obper = intval($_POST["obper"]);
	if ($obper != 1 and $obper != 0) $obper = 0;
    
    if ($modered == 0 ) {
        $mod = 0;
    } else {
		if($get_link['modered'] == 2) {
			$mod = 0;
		} 
		elseif ($get_link['modered'] == 0){
			$mod = 0;
		}
		elseif ($get_link['modered'] != 0 AND $get_link['modered'] != 2 AND $get_link['modered'] == 1) {
			$mod = 1;
		}
	}
	
	if ($url1 == "") {echo '<div id="error">Вы не указали URL сайта</div>'; exit();} else
	if ($description == ""){echo '<div id="error">Вы не указали заголовок</div>'; exit();} else
	if ($texto == ""){echo '<div id="error">Вы не указали описание ссылки</div>'; exit();} else {
	if($timer == 6 ) { $precio = $hits5  + $hldyn * $highlight + $obper * $obperehod; } 
	if($timer == 5 ) { $precio = $hits10 + $hldyn * $highlight + $obper * $obperehod; } 
	if($timer == 0 or $timer == 1 or $timer == 2 or $timer == 3 or $timer == 4 ) { $precio = $hits + $timer * $timer5 + $hldyn * $highlight + $obper * $obperehod; } 
	if ($timer == 0) $payforad = $payuser['dyn20'];
	if ($timer == 1) $payforad = $payuser['dyn30'];
	if ($timer == 2) $payforad = $payuser['dyn40'];
	if ($timer == 3) $payforad = $payuser['dyn50'];
	if ($timer == 4) $payforad = $payuser['dyn60'];
	if ($timer == 5) $payforad = $payuser['dyn10'];
	if ($timer == 6) $payforad = $payuser['dyn5'];
    $nowtime = time();
    mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '" . $nowtime . "', 2, '" . substr($url1, 0, 300) . "')"); 
    mysql_query("UPDATE tb_ads SET url = '" . substr($url1, 0, 300) . "', description = '" . substr($description, 0, 55). "', timer = '" . $timer . "', obper = '" . $obper . "', texto = '" . substr($texto, 0, 55) . "', highlight = '" . $highlight . "', price = '" . $precio . "', payforad = '" . $payforad . "', modered = '$mod' WHERE id = '" . $get_link['id'] . "' and fromus = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
    echo 1;
    exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление дин. ссылки
if ($_GET['func'] == 'deladv') {
    $gg = intval($_POST['id']);
    $zzzz = mysql_query("SELECT balance FROM tb_ads WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'");
    if (mysql_num_rows($zzzz) > 0) {
        $balance = mysql_result($zzzz,0);
        if ($balance >= 0.5) {
            echo 'Вы не можете удалить ссылку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
            mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'");
            mysql_query("DELETE FROM tb_ads WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
            mysql_query("DELETE FROM tb_visits WHERE ident = '$gg'");
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сбросить статистику дин. ссылки
if ($_GET['func'] == 'clearadv') {
    $gg = intval($_POST['id']);
    mysql_query("UPDATE tb_ads SET plan = 0 where fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
    echo 1;
    exit();
}
//Включить дин. ссылки
if ($_GET['func'] == 'rundyn') {
    $pp = intval($_POST['id']);
    $paused = mysql_fetch_array(mysql_query("SELECT paused from tb_ads where id = '$pp' and modered = '1' and fromus = '" . $_SESSION['iduser'] . "'"));
    if ($paused['paused'] == 0) { $npaused = 1; } else { $npaused = 0; } 
    mysql_query("UPDATE tb_ads set paused='$npaused' where fromus = '" . $_SESSION['iduser'] . "' and id = '$pp' and modered = '1' and balance > price") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ платного письма
if ($_GET['func'] == 'addpmails') {
    $url1 = check_text($_POST["ask_url"]);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    $ask_title = check_text($_POST['ask_title']);
	$ask_desc = iconv('UTF-8', 'windows-1251', qcode_bb($_POST['ask_desc']));
    $ask_question = check_text($_POST['ask_question']);
    $ask_reply1 = check_text($_POST['ask_reply1']);
    $ask_reply2 = check_text($_POST['ask_reply2']);
    $ask_reply3 = check_text($_POST['ask_reply3']);
    $ask_mailmode = intval($_POST['ask_mailmode']);

	$highlight = intval($_POST["ask_high"]);
	if ($highlight != "1" and $highlight != "0") { 
        $highlight = "0"; 
  	}

    $timer = intval($_POST["ask_timer"]);
	if ($timer != 20 and $timer != 30 and $timer != 40 and $timer != 50 and $timer != 60) {
        echo "Ошибка ввода!!!";
        exit();
	} else
    $obper = intval($_POST["ask_move"]);
	if ($obper != 1 and $obper != 0) $obper = 0;
    if ($ask_mailmode != 1 and $ask_mailmode != 0) $ask_mailmode = 0;
    
    if ($modered == 1) $mod = 1; else $mod = 0;
	
	if ($url1 == "") {echo '<div id="error">Вы не указали URL сайта</div>'; exit();} else
	if ($ask_title == ""){echo '<div id="error">Вы не указали заголовок</div>'; exit();} else
	if ($ask_desc == ""){echo '<div id="error">Вы не указали содержание</div>'; exit();} else
    if ($ask_question == ""){echo '<div id="error">Вы не указали контрольный вопрос</div>'; exit();} else {
	$precio = $mprice + (($timer - 20) / 10) * $pmtimer + $pmhighlight * $highlight + $obper * $pmobper;

    $nowtime = time();
    mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '$nowtime', '2', '$url1')");
    mysql_query("INSERT INTO seo_paymails (url, description, timer, obper, name, highlight, price, fromid, quest, answer1, answer2, answer3, many, modered) values ('" . substr($url1, 0, 300) . "', '" . substr($ask_desc, 0, 3000). "', '" . $timer . "', '" . $obper . "', '" . substr($ask_title, 0, 55) . "', '" . $highlight . "', '" . $precio . "', '" . $_SESSION['iduser'] . "', '" . substr($ask_question, 0, 50) . "', '" . substr($ask_reply1, 0, 30) . "', '" . substr($ask_reply2, 0, 30) . "', '" . substr($ask_reply3, 0, 30) . "', '" . $ask_mailmode . "', '$mod')") or die(mysql_error());
    echo 1;
    exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Редактирование платного письма
if ($_GET['func'] == 'uppmails') {
    $url1 = check_text($_POST["ask_url"]);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    $ask_title = check_text($_POST['ask_title']);
	$ask_desc = iconv('UTF-8', 'windows-1251', qcode_bb($_POST['ask_desc']));
    $ask_question = check_text($_POST['ask_question']);
    $ask_reply1 = check_text($_POST['ask_reply1']);
    $ask_reply2 = check_text($_POST['ask_reply2']);
    $ask_reply3 = check_text($_POST['ask_reply3']);
    $ask_mailmode = intval($_POST['ask_mailmode']);

	$highlight = intval($_POST["ask_high"]);
	if ($highlight != "1" and $highlight != "0") { 
        $highlight = "0"; 
  	}

    $timer = intval($_POST["ask_timer"]);
	if ($timer != 20 and $timer != 30 and $timer != 40 and $timer != 50 and $timer != 60) {
        echo "Ошибка ввода!!!";
        exit();
	}
    $get_link = mysql_fetch_array( mysql_query( "SELECT id, url, description, name, modered FROM seo_paymails WHERE id = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    if ($get_link['id'] == '') {
        echo 'Вы не можете редактировать чужое письмо';
        exit();
    } else
    $obper = intval($_POST["ask_move"]);
	if ($obper != 1 and $obper != 0) $obper = 0;
    if ($ask_mailmode != 1 and $ask_mailmode != 0) $ask_mailmode = 0;
    
    if ($modered == 0 ) {
        $mod = 0;
    } else {
		if($get_link['modered'] == 2) {
			$mod = 0;
		} 
		elseif ($get_link['modered'] == 0){
			$mod = 0;
		}
		elseif ($get_link['modered'] != 0 AND $get_link['modered'] != 2 AND $get_link['modered'] == 1) {
			$mod = 1;
		}
	}
	
	if ($url1 == "") {echo '<div id="error">Вы не указали URL сайта</div>'; exit();} else
	if ($ask_title == ""){echo '<div id="error">Вы не указали заголовок</div>'; exit();} else
	if ($ask_desc == ""){echo '<div id="error">Вы не указали содержание</div>'; exit();} else
    if ($ask_question == ""){echo '<div id="error">Вы не указали контрольный вопрос</div>'; exit();} else {
	$precio = $mprice + (($timer - 20) / 10) * $pmtimer + $pmhighlight * $highlight + $obper * $pmobper;

    $nowtime = time();
    mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '$nowtime', '2', '$url1')");
    mysql_query("UPDATE seo_paymails SET url = '" . substr($url1, 0, 300) . "', description = '" . substr($ask_desc, 0, 3000). "', timer = '" . $timer . "', obper = '" . $obper . "', name = '" . substr($ask_title, 0, 55) . "', highlight = '" . $highlight . "', price = '" . $precio . "', quest = '" . substr($ask_question, 0, 50) . "', answer1 = '" . substr($ask_reply1, 0, 30) . "', answer2 = '" . substr($ask_reply2, 0, 30) . "', answer3 = '" . substr($ask_reply3, 0, 30) . "', many = '" . $ask_mailmode . "', modered = '$mod' WHERE id ='" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
    echo 1;
    exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление платного письма
if ($_GET['func'] == 'delpmails') {
    $gg = intval($_POST['id']);
    $zzzz = mysql_query("SELECT balance FROM seo_paymails WHERE fromid = '" . $_SESSION['iduser'] . "' and id = '$gg'");
    if (mysql_num_rows($zzzz) > 0) {
        $balance = mysql_result($zzzz,0);
        if ($balance > 0.5) {
            echo 'Вы не можете удалить ссылку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
            mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
            mysql_query("DELETE FROM seo_paymails WHERE fromid = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
            mysql_query("DELETE FROM seo_paymailsviews WHERE ident = '$gg'");
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сбросить статистику платного письма
if ($_GET['func'] == 'clearpmails') {
    $gg = intval($_POST['id']);
    mysql_query("UPDATE seo_paymails SET plan=0 where fromid = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление из корзины
if ($_GET['func'] == 'basketdel') {
    $iddel = intval($_POST['id']);
    $sql = mysql_fetch_array(mysql_query("SELECT * FROM seo_basket WHERE id='$iddel' AND fromid='$_SESSION[iduser]'"));
    if ($sql['type'] == 4) {
        mysql_query("UPDATE seo_refbirj SET bron = 0 WHERE rid = '$sql[ident]'");
    }
    mysql_query("DELETE FROM seo_basket WHERE id='$iddel' AND fromid='$_SESSION[iduser]'") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Включить платные письма
if ($_GET['func'] == 'runpmail') {
    $iduser = $_SESSION['iduser'];
    $pp = intval($_POST['id']);
    $paused = mysql_fetch_array(mysql_query("SELECT paused from seo_paymails where id='$pp' and modered='1' and fromid='$iduser'"));
    if ($paused['paused'] == 0) { $npaused = 1; }else{ $npaused = 0; } 
    mysql_query("UPDATE seo_paymails set paused='$npaused' where fromid='$iduser' and id='$pp' and modered='1' and balance>price") or die       (mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ задания
if ($_GET['func'] == 'addtask') {
    $url1 = check_text($_POST["ask_url"]);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    
    $ask_title = substr(check_text($_POST['ask_title']), 0, 55);
    $ask_desc = iconv('UTF-8', 'windows-1251', substr(qcode_bb($_POST['ask_desc']), 0, 3000));
    $ask_question = substr(check_text($_POST['ask_question']), 0, 3000);
    $ask_cat = intval($_POST['ask_cat']);
    $ask_taskmode = intval($_POST['ask_taskmode']);
    $ask_donate = $_POST['ask_donate'];
    $ask_days = intval($_POST['ask_days']);
    
    if ($ask_title == '') { echo 'Укажите заголовок задания'; exit(); } else
    if ($ask_desc == '') { echo 'Укажите описание задания'; exit(); } else
    if ($ask_question == '') { echo 'Укажите условия выполнения'; exit(); } else {
        if ($modered == 1) $mod = 1; else $mod = 0;
        if ($ask_cat > 10) { $ask_cat = 0; }
        if ($ask_taskmode != 1 and $ask_taskmode != 0) $ask_taskmode = 0;
        if ($ask_donate < 0.2 or !is_numeric($ask_donate)) { $ask_donate = 0.2; }
        if ($ask_donate <= 0) { $ask_donate = 0.2; }
        $price = round(floatval($ask_donate), 2);
        $price = $price * 1.2;
        if ($ask_days == '' and !is_numeric($ask_days)) {$ask_days == 86400 * 3;}
        mysql_query("INSERT INTO tb_allhistory (idus,data,doing,title) values ('$_SESSION[iduser]','$nowtime','2','$url1')");
        mysql_query("INSERT INTO seo_tasks (fromid, price, text, description, cat, url, many, maxtime, name, modered, time) VALUES ('" . $_SESSION['iduser'] . "', '$price', '$ask_desc', '$ask_question', '$ask_cat', '$url1', '$ask_taskmode', '$ask_days', '$ask_title', '$mod', '" . time() . "')");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Редактирование задания
if ($_GET['func'] == 'uptask') {
    $url1 = check_text($_POST["ask_url"]);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    $get_link = mysql_fetch_array( mysql_query( "SELECT id, url, description, name, text, modered FROM seo_tasks WHERE id = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    if ($get_link['id'] == '') {
        echo 'Вы не можете редактировать чужое задание';
        exit();
    } else
    $ask_title = substr(check_text($_POST['ask_title']), 0, 55);
    $ask_desc = iconv('UTF-8', 'windows-1251', substr(qcode_bb($_POST['ask_desc']), 0, 3000));
    $ask_question = substr(check_text($_POST['ask_question']), 0, 3000);
    $ask_cat = intval($_POST['ask_cat']);
    $ask_taskmode = intval($_POST['ask_taskmode']);
    $ask_donate = $_POST['ask_donate'];
    $ask_days = intval($_POST['ask_days']);
    
    if ($ask_title == '') { echo 'Укажите заголовок задания'; exit(); } else
    if ($ask_desc == '') { echo 'Укажите описание задания'; exit(); } else
    if ($ask_question == '') { echo 'Укажите условия выполнения'; exit(); } else {
        if ($ask_cat > 10) { $ask_cat = 0; }
        if ($ask_taskmode != 1 and $ask_taskmode != 0) $ask_taskmode = 0;
        if ($ask_donate < 0.2 or !is_numeric($ask_donate)) { $ask_donate = 0.2; }
        if ($ask_donate <= 0) { $ask_donate = 0.2; }
        $price = round(floatval($ask_donate), 2);
        $price = $price * 1.2;
        if ($ask_days == '' and !is_numeric($ask_days)) {$ask_days == 86400 * 3;}
        
		if ($modered == 0 ) {
			$mod = 0;
		} else {
			if($get_link['modered'] == 2) {
				$mod = 0;
			} 
			elseif ($get_link['modered'] == 0){
				$mod = 0;
			}
			elseif ($get_link['modered'] != 0 AND $get_link['modered'] != 2 AND $get_link['modered'] == 1) {
				$mod = 1;
			}
		}
        
        mysql_query("INSERT INTO tb_allhistory (idus,data,doing,title) values ('$_SESSION[iduser]','$nowtime','2','$url1')");
        mysql_query("UPDATE seo_tasks SET price = '$price', text = '$ask_desc', description = '$ask_question', cat = '$ask_cat', url = '$url1', many = '$ask_taskmode', maxtime = '$ask_days', name = '$ask_title', modered = '$mod' WHERE id = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Оплата выполненного задания
if ($_GET['func'] == 'taskpay') {
    $sql = mysql_query("SELECT id FROM seo_tasts WHERE id='" . intval($_POST['tident']) . "' and fromid = '" . $_SESSION['iduser'] . "' and balance <= price");
    if (mysql_num_rows($sql) > 0) {
        echo 'Для оплаты задания, недостаточно средств! Пополните счет';
        exit();
    }
    $chk=mysql_query("SELECT fromid FROM seo_taskstats WHERE id = '" . intval($_POST['tid']) . "' and status = 0 and ident IN(SELECT id FROM seo_tasks where fromid = '" . $_SESSION['iduser'] . "' and balance >= price)") or die(mysql_error());
    if (mysql_num_rows($chk) != 0) {
        $badus = mysql_result($chk, 0);
        mysql_query("UPDATE seo_tasks set waits = waits - 1, goods = goods + 1, balance = balance - price where id='" . intval($_POST['tident']) . "' and fromid = '" . $_SESSION['iduser'] . "'");
        mysql_query("UPDATE seo_taskstats set status = 1, anstime = '" . time() . "' + 86400 where id = '" . intval($_POST['tid']) . "' and ident IN(SELECT id FROM seo_tasks where fromid = '" . $_SESSION['iduser'] . "')");
        $pr = mysql_fetch_array( mysql_query( "SELECT price FROM seo_tasks WHERE id = '" . intval($_POST['tident']) . "' and fromid = '" . $_SESSION['iduser'] . "'" ) );
        
        $userd = mysql_fetch_array(mysql_query("SELECT referer FROM tb_users WHERE id = '$badus'"));
        
		if ($userd['referer'] != '') {
            $usref1 = mysql_fetch_array( mysql_query( "SELECT reyting, finestatus FROM tb_users WHERE id = '" . $userd['referer'] . "'" ) );
            $reyting = $usref1['reyting'];
            if($usref1['finestatus'] == 0){
                if ($reyting < 1) {
                    $prcr = 0;
                } else
                if ($reyting >= 1 and $reyting < 10) {
                    $prcr = ($pr['price'] - $pr['price'] * 5 / 6) * 0.01;
                } else
                if ($reyting >= 10 and $reyting < 100) {
                    $prcr = ($pr['price'] - $pr['price'] * 5 / 6) * 0.03;
                } else
                if ($reyting >= 100 and $reyting < 250) {
                    $prcr = ($pr['price'] - $pr['price'] * 5 / 6) * 0.03;
                } else
                if ($reyting >= 250 and $reyting < 600) {
                    $prcr = ($pr['price'] - $pr['price'] * 5 / 6) * 0.05;
                } else
                if ($reyting >= 600 and $reyting < 1000) {
                    $prcr = ($pr['price'] - $pr['price'] * 5 / 6) * 0.05;
                } else
                if ($reyting >= 1000) {
                    $prcr = ($pr['price'] - $pr['price'] * 5 / 6) * 0.07;
                }
                $autoproc = mysql_result(mysql_query("SELECT autoproc FROM tb_users WHERE id = '" . $badus . "'"), 0, 0);
                if ($autoproc != 100) $proc = "0.$autoproc";
                if ($autoproc == 100) $proc = 1;
                $plusautoback = $prcr * $proc; //авторефбек
                $elprecio1 = $prcr - $plusautoback;
			} else {
			    $elprecio1 = 0;
			}
            mysql_query("UPDATE tb_users SET money = money + '$elprecio1' WHERE id='" . $userd['referer'] . "'");
        }
        
		$montask = ($pr['price'] * 5 / 6) + $plusautoback;
        mysql_query("UPDATE tb_users SET taskreyt = taskreyt + 1, money = money + '$montask', toref = toref + '$elprecio1' WHERE id='" . $badus . "'");
        //Конкурсы (задания)
		if($montask > 0) {
			$ref_name_u = mysql_fetch_array( mysql_query( "SELECT referer FROM tb_users WHERE id = '" . $badus . "'" ) );
			if($ref_name_u['referer'] > 0) {
				$kon_ref_u = mysql_fetch_array(mysql_query("SELECT * FROM konkurs_ref WHERE status = '1' AND type = '3' AND referername = '".$ref_name_u['referer']."'"));
				if ($kon_ref_u['id'] > 0) {
					$ref_temp_u = mysql_fetch_array( mysql_query( "SELECT * FROM konkurs_ref_temp WHERE iduser = '" . $badus . "' AND idkonkurs = '" . $kon_ref_u['id'] . "' AND type = '3'" ) );
					if($ref_temp_u['id'] > 0) {
						///echo 'участвует';
						mysql_query("UPDATE konkurs_ref_temp SET summ = summ + '1' WHERE iduser = '" . $badus . "' AND idkonkurs = '" . $kon_ref_u['id'] . "' AND type = '3'");
					} else {
						///echo 'не участвует';
						mysql_query("INSERT INTO konkurs_ref_temp (iduser, idkonkurs, type, summ) VALUES ('" . $badus . "', '" . $kon_ref_u['id'] . "', '3', '1')");
					}
				}
			}
		}
        $varstr=date("w");
        $day="";
        if ($varstr == 1) $day = 'mon';
        if ($varstr == 2) $day = 'tue';
        if ($varstr == 3) $day = 'wed';
        if ($varstr == 4) $day = 'thu';
        if ($varstr == 5) $day = 'fri';
        if ($varstr == 6) $day = 'sat';
        if ($varstr == 0) $day = 'sun';
        $sqlstat= "UPDATE tb_statistic SET total = total + 1, " . $day . " = " . $day . " + 1 WHERE username = '$badus' and typ = 1"; 
        mysql_query($sqlstat);
        $viruchka = $pr['price'] - $pr['price'] * 5 / 6 - $elprecio1 - $plusautoback;
        mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (3, '$viruchka', '" . date('m', time()) . "', '" . date('Y', time()) . "')");
	
        echo 1;
        exit();
    } else {
        echo 'Для оплаты задания, недостаточно средств! Пополните счет';
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//На доработку задания
if ($_GET['func'] == 'taskrev') {
    $ident = intval($_POST['tident']);
    $tid = intval($_POST['tid']);
    $reason = substr(check_text($_POST['reason']), 0, 250);
    mysql_query("UPDATE seo_tasks set waits = waits - 1, works = works + 1 where id='$ident' and fromid = '" . $_SESSION['iduser'] . "'");
    mysql_query("UPDATE seo_taskstats set status = 3, anstime = '" . time() . "' where id = '$tid' and ident IN(SELECT id FROM seo_tasks where fromid = '" . $_SESSION['iduser'] . "')");
    $chk = mysql_query("SELECT fromid FROM seo_taskstats WHERE id = '$tid' and ident IN(SELECT id FROM seo_tasks where fromid = '" . $_SESSION['iduser'] . "')") or die(mysql_error());
        if (mysql_num_rows($chk) != 0) {
            $badus = mysql_result($chk, 0);
            mysql_query( "INSERT INTO seo_mails (fromid, toid, subject, text, timemessage) VALUES ('" . $_SESSION['iduser'] . "', '$badus', 'Задание №$ident', 'Уважаемый пользователь!<br />Выполненое Вами задание №$ident отправлено на доработку по причине:<br /><font color=#800000>$reason</font>', '" . time() . "' )" );
            }
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Поднять задание
if ($_GET['func'] == 'levelup') {
    $ident = intval($_POST['id']);
    $sql = mysql_fetch_array(mysql_query("SELECT levelup, balance FROM seo_tasks WHERE id = '$ident' and fromid = '$_SESSION[iduser]'"));
    if ($sql['levelup'] > time() - 86400) {
        echo 'Поднять задание можно только один раз в сутки';
        exit();
    } else
    if ($sql['balance'] <= 0.25) {
        echo 'На балансе недостаточно средств';
        exit();
    } else {
        mysql_query("UPDATE seo_tasks SET levelup = '" . time() . "', balance = balance - 0.25 WHERE id = '$ident' and fromid = '$_SESSION[iduser]'");
        mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (3, 0.25, '" . date('m', time()) . "', '" . date('Y', time()) . "')");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление задания
if ($_GET['func'] == 'deltask') {
	
    $iddel = intval($_POST['id']);
    $zzzz = mysql_fetch_array(mysql_query("SELECT id, balance, works, waits FROM seo_tasks WHERE fromid = '" . $_SESSION['iduser'] . "' and id = '$iddel'"));
	
	if ($zzzz['id'] > 0) {
        $balance = $zzzz['balance'];
        if ($balance > 0.5) {
            echo 'Вы не можете удалить площадку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
			if($zzzz['works'] == 0 AND $zzzz['waits'] == 0) {
				mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'");
				mysql_query("DELETE FROM seo_tasks WHERE fromid = '" . $_SESSION['iduser'] . "' and id = '$iddel'");
				mysql_query("DELETE FROM seo_favtasks WHERE ident = '$iddel'");
				mysql_query("DELETE FROM seo_taskstats WHERE ident = '$iddel'");
				mysql_query("DELETE FROM seo_taskcomms WHERE ident = '$iddel'");
				echo 1;
				exit();
			} else {
				echo 'Нельзя удалять задание когда кто то ведет над ним работу! ';
				exit();
			}
		}
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Размещение задания в V.I.P блоке
if ($_GET['func'] == 'viptask') {
    $idup = intval($_POST['id']);
    mysql_query("UPDATE seo_tasks SET balance = balance - 0.75, inblock = '" . time() . "' + 86400 where balance > 0.75 + price and fromid = '" . $_SESSION['iduser'] . "' and id = '$idup'") or die(mysql_error());
    mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (0.75, 0.75, '" . date('m', time()) . "', '" . date('Y', time()) . "')");
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Отклонение задания
if ($_GET['func'] == 'tasknopay') {
    $delstat = intval($_POST['tid']);
    $reason = substr(check_text($_POST['reason']), 0, 250);
    $ident = intval($_POST['tident']);
    if ($reason == '') {
        echo 'Укажите причину отказа';
        exit();
    } else {
        $chk = mysql_query("SELECT fromid FROM seo_taskstats WHERE id = '$delstat' and ident IN(SELECT id FROM seo_tasks where fromid = '" . $_SESSION['iduser'] . "')") or die(mysql_error());
        if (mysql_num_rows($chk) != 0) {
            $badus = mysql_result($chk, 0);
            mysql_query("UPDATE seo_taskstats SET status = 2, reason = '$reason' WHERE id = '$delstat' and ident = '$ident' and ident IN(SELECT id FROM seo_tasks WHERE fromid = '" . $_SESSION['iduser'] . "')") or die(mysql_error());
            mysql_query("UPDATE tb_users SET taskreyt = taskreyt - 1 WHERE id = '$badus'");
            mysql_query( "INSERT INTO seo_mails (fromid, toid, subject, text, timemessage) VALUES ('" . $_SESSION['iduser'] . "', '$badus', 'Задание №$ident', 'Уважаемый пользователь!<br />Выполненое Вами задание №$ident отклонено по причине:<br /><font color=#800000>$reason</font>', '" . time() . "' )" );
            mysql_query("UPDATE seo_tasks SET waits = waits - 1, no = no + 1 where id = '$ident' and fromid = '" . $_SESSION['iduser'] . "'");
            echo 1;
        } else {
            echo 'Возникла ошибка';
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Включить задания
if ($_GET['func'] == 'runtask') {
    $pp = intval($_POST['id']);
    $iduser = $_SESSION['iduser'];
    $paused = mysql_fetch_array(mysql_query("SELECT paused from seo_tasks where id='$pp' and modered='1' and fromid='$iduser'"));
    if ($paused['paused'] == 0) { $npaused = 1; }else{ $npaused = 0; }
    mysql_query("UPDATE seo_tasks set paused='$npaused' where fromid='$iduser' and id='$pp' and modered='1' and balance>=price") or die       (mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ контекстной рекламы
if ($_GET['func'] == 'addstatlink') {
    $url1 = substr(check_text($_POST["url"]), 0, 300);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    $description = substr(check_text($_POST['description']), 0, 55);
    $texto = substr(check_text($_POST['texto']), 0, 55);
    if ($description == '') {echo 'Укажите заголовок'; exit();} else
    if ($texto == '') {echo 'Укажите описание'; exit();} else
    if ($url1 == '') {echo 'Укажите URL'; exit();} else {
        if ($modered == 1) $mod = 1; else $mod = 0;
        mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '" . time() . "', 2,'$url1')");
        mysql_query("INSERT INTO tb_statlinks (fromus, price, url, description, texto, modered) values ('" . $_SESSION['iduser'] . "', '$advstatlink', '$url1', '$description', '$texto', '$mod')") or die(mysql_error());
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Редактирование контекстной рекламы
if ($_GET['func'] == 'upstatlink') {
    $url1 = substr(check_text($_POST["url"]), 0, 300);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    }
    $get_link = mysql_fetch_array( mysql_query( "SELECT id, url, description, texto, modered FROM tb_statlinks WHERE id = '" . intval($_POST['id']) . "' and fromus = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    if ($get_link['id'] == '') {
        echo 'Вы не можете редактировать чужую рекламу';
        exit();
    } else
    $description = substr(check_text($_POST['description']), 0, 55);
    $texto = substr(check_text($_POST['texto']), 0, 55);
		if ($modered == 0 ) {
			$mod = 0;
		} else {
			if($get_link['modered'] == 2) {
				$mod = 0;
			} 
			elseif ($get_link['modered'] == 0){
				$mod = 0;
			}
			elseif ($get_link['modered'] != 0 AND $get_link['modered'] != 2 AND $get_link['modered'] == 1) {
				$mod = 1;
			}
		}
    if ($description == '') {echo 'Укажите заголовок'; exit();} else
    if ($texto == '') {echo 'Укажите описание'; exit();} else
    if ($url1 == '') {echo 'Укажите URL'; exit();} else {
        mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '" . time() . "', 2,'$url1')");
        mysql_query("UPDATE tb_statlinks SET fromus = '" . $_SESSION['iduser'] . "', price = '$advstatlink', url = '$url1', description = '$description', texto =  '$texto', modered = '$mod' WHERE id = '" . intval($_POST['id']) . "' and fromus = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление контекстной рекламы
if ($_GET['func'] == 'delstat') {
    $gg = intval($_POST['id']);
    $zzzz = mysql_query("SELECT balance FROM tb_statlinks WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'");
    if (mysql_num_rows($zzzz) > 0) {
        $balance = mysql_result($zzzz,0);
        if ($balance > 0.5) {
            echo 'Вы не можете удалить ссылку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
            mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
            mysql_query("DELETE FROM tb_statlinks WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сбросить статистику контекстной рекламы
if ($_GET['func'] == 'clearstat') {
    $gg = intval($_POST['id']);
    mysql_query("UPDATE tb_statlinks SET views = 0 where fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Включить контекстную рекламу
if ($_GET['func'] == 'runstat') {
    $pp = intval($_POST['id']);
    $paused = mysql_fetch_array(mysql_query("SELECT paused from tb_statlinks where id = '$pp' and modered = '1' and fromus = '" . $_SESSION['iduser'] . "'"));
    if ($paused['paused'] == 0) { $npaused = 1; } else { $npaused = 0; } 
    mysql_query("UPDATE tb_statlinks set paused='$npaused' where fromus = '" . $_SESSION['iduser'] . "' and id = '$pp' and modered = '1' and balance > price") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ цепочки
if ($_GET['func'] == 'addcep') {
    $url1 = substr(check_text($_POST["url"]), 0, 300);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    } else
    $description = substr(check_text($_POST['description']), 0, 55);
    if ($description == '') {echo 'Укажите заголовок'; exit();} else
    if ($url1 == '') {echo 'Укажите URL'; exit();} else {
        if ($modered == 1) $mod = 1; else $mod = 0;
        mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '" . time() . "', 2,'$url1')");
        mysql_query("INSERT INTO cep_links (fromus, price, url, description, modered) values ('" . $_SESSION['iduser'] . "', '$advcep', '$url1', '$description', '$mod')") or die(mysql_error());
        echo 1;
        exit(); 
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Редактирование цепочки
if ($_GET['func'] == 'upcep') {
    $url1 = substr(check_text($_POST["url"]), 0, 300);
    function getHost($Address) {
        $parseUrl = parse_url(trim($Address));
        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
    }
    $site = getHost($url1);
    $site = str_ireplace("www.","",$site);
    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
    if (mysql_num_rows($bll) > 0) {
        $res34 = mysql_fetch_array($bll);
        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
        exit();
    }
    $get_link = mysql_fetch_array( mysql_query( "SELECT id, url, description, modered FROM cep_links WHERE id = '" . intval($_POST['id']) . "' and fromus = '" . $_SESSION['iduser'] . "' LIMIT 1" ) );
    if ($get_link['id'] == '') {
        echo 'Вы не можете редактировать чужую рекламу';
        exit();
    } else
    $description = substr(check_text($_POST['description']), 0, 55);
		if ($modered == 0 ) {
			$mod = 0;
		} else {
			if($get_link['modered'] == 2) {
				$mod = 0;
			} 
			elseif ($get_link['modered'] == 0){
				$mod = 0;
			}
			elseif ($get_link['modered'] != 0 AND $get_link['modered'] != 2 AND $get_link['modered'] == 1) {
				$mod = 1;
			}
		}
    if ($description == '') {echo 'Укажите заголовок'; exit();} else
    if ($url1 == '') {echo 'Укажите URL'; exit();} else {
        mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '" . time() . "', 2,'$url1')");
        mysql_query("UPDATE cep_links SET fromus = '" . $_SESSION['iduser'] . "', price = '$advcep', url = '$url1', description = '$description', modered = '$mod' WHERE id = '" . intval($_POST['id']) . "' and fromus = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление цепочки
if ($_GET['func'] == 'delcep') {
    $gg = intval($_POST['id']);
    $zzzz = mysql_query("SELECT balance FROM cep_links WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'");
    if (mysql_num_rows($zzzz) > 0) {
        $balance = mysql_result($zzzz,0);
        if ($balance > 0.5) {
            echo 'Вы не можете удалить ссылку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
            mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
            mysql_query("DELETE FROM cep_links WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сбросить статистику цепочки
if ($_GET['func'] == 'clearcep') {
    $gg = intval($_POST['id']);
    mysql_query("UPDATE cep_links SET views = 0 where fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Включить цепочки
if ($_GET['func'] == 'runcep') {
    $pp = intval($_POST['id']);
    $paused = mysql_fetch_array(mysql_query("SELECT paused from cep_links where id = '$pp' and modered = '1' and fromus = '" . $_SESSION['iduser'] . "'"));
    if ($paused['paused'] == 0) { $npaused = 1; } else { $npaused = 0; } 
    mysql_query("UPDATE cep_links set paused='$npaused' where fromus = '" . $_SESSION['iduser'] . "' and id = '$pp' and modered = '1' and balance > price") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ баннера 100x100
if ($_GET['func'] == 'addbanner_100') {
    if ($_FILES['file']['size'] <= 0 or $_FILES['file']['size'] > 409600) {
        echo 'Размер баннера превышает допустимое значение';
        exit();
    } else
    if ($_FILES['file']['type'] == "image/gif" OR $_FILES['file']['type'] == "image/png" OR $_FILES['file']['type'] == "image/jpeg" OR $_FILES['file']['type'] == "image/jpg") {
        if (is_uploaded_file($_FILES['file']['tmp_name'])) {
            $ssz = GetImageSize($_FILES['file']['tmp_name']);
            if ($ssz[0] != 100 or $ssz[1] != 100) {
                echo('Баннер должен быть размерами 100х100!');
                exit();
            } else {
			    if(@imagecreatefromstring(file_get_contents($_FILES['file']['tmp_name'])) === false) {
					echo "Неверный формат расширения";
				} else {
			        $url1 = substr(check_text($_POST["url"]), 0, 300);
                        function getHost($Address) {
                        $parseUrl = parse_url(trim($Address));
                        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
                    }
                    $site = getHost($url1);
                    $site = str_ireplace("www.","",$site);
                    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
                    if (mysql_num_rows($bll) > 0) {
                        $res34 = mysql_fetch_array($bll);
                        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
                        exit();
                    } else {
                        if ($modered == 1) $mod = 1; else $mod = 0;
                        $type_file = str_replace("theme/tmp/", "", basename($_FILES['file']['type']));
                        $nowtime = time();
                        if (@move_uploaded_file($_FILES['file']['tmp_name'], "banners/$nowtime." . $type_file)) {
                            mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '$nowtime', '2', '$url1')");
                            mysql_query("INSERT INTO tb_advban_100 (url, price, nametime, typeban, fromus, modered) values ('$url1', '$advbanner2', '$nowtime', '$type_file', '" . $_SESSION['iduser'] . "', '$mod')") or die(mysql_error());
                            echo 1;
                            exit();
                        }
                    }
                } 
		    }
        }
    } else {
        echo 'Неверный формат расширения';
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление баннера 100x100
if ($_GET['func'] == 'delban2') {
    $gg = intval($_POST['id']);
    $zzzz = mysql_query("SELECT balance FROM tb_advban_100 WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'");
    if (mysql_num_rows($zzzz) > 0) {
        $balance = mysql_result($zzzz,0);
        if ($balance > 0.5) {
            echo 'Вы не можете удалить ссылку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
            mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
            $get_ban = mysql_fetch_array( mysql_query( "SELECT nametime, typeban FROM tb_advban_100 WHERE id = '$gg'" ) );
            unlink('banners/' . $get_ban['nametime'] . '.' . $get_ban['typeban']);
            mysql_query("DELETE FROM tb_advban_100 WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сбросить статистику баннера 100x100
if ($_GET['func'] == 'clearban2') {
    $gg = intval($_POST['id']);
    mysql_query("UPDATE tb_advban_100 SET views = 0 where fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Включить баннер 100x100
if ($_GET['func'] == 'runban2') {
    $pp = intval($_POST['id']);
    $paused = mysql_fetch_array(mysql_query("SELECT paused from tb_advban_100 where id = '$pp' and modered = '1' and fromus = '" . $_SESSION['iduser'] . "'"));
    if ($paused['paused'] == 0) { $npaused = 1; } else { $npaused = 0; } 
    mysql_query("UPDATE tb_advban_100 set paused='$npaused' where fromus = '" . $_SESSION['iduser'] . "' and id = '$pp' and modered = '1' and balance > price") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ баннера 200х300
if ($_GET['func'] == 'addbanner_300') {
    if ($_FILES['file']['size'] <= 0 or $_FILES['file']['size'] > 409600) {
        echo 'Размер баннера превышает допустимое значение';
        exit();
    } else
    if ($_FILES['file']['type'] == "image/gif" OR $_FILES['file']['type'] == "image/png" OR $_FILES['file']['type'] == "image/jpeg" OR $_FILES['file']['type'] == "image/jpg") {
        if (is_uploaded_file($_FILES['file']['tmp_name'])) {
            $ssz = GetImageSize($_FILES['file']['tmp_name']);
            if ($ssz[0] != 200 or $ssz[1] != 300) {
                echo('Баннер должен быть размерами 200х300!');
                exit();
            } else {
			    if(@imagecreatefromstring(file_get_contents($_FILES['file']['tmp_name'])) === false) {
					echo "Неверный формат расширения";
				} else {
			        $url1 = substr(check_text($_POST["url"]), 0, 300);
                        function getHost($Address) {
                        $parseUrl = parse_url(trim($Address));
                        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
                    }
                    $site = getHost($url1);
                    $site = str_ireplace("www.","",$site);
                    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
                    if (mysql_num_rows($bll) > 0) {
                        $res34 = mysql_fetch_array($bll);
                        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
                        exit();
                    } else {
                        if ($modered == 1) $mod = 1; else $mod = 0;
                        $type_file = str_replace("theme/tmp/", "", basename($_FILES['file']['type']));
                        $nowtime = time();
                        if (@move_uploaded_file($_FILES['file']['tmp_name'], "banners/$nowtime." . $type_file)) {
                            mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '$nowtime', '2', '$url1')");
                            mysql_query("INSERT INTO tb_advban_300 (url, price, nametime, typeban, fromus, modered) values ('$url1', '$advbanner3', '$nowtime', '$type_file', '" . $_SESSION['iduser'] . "', '$mod')") or die(mysql_error());
                            echo 1;
                            exit();
                        }
                    }
                } 
		    }
        }
    } else {
        echo 'Неверный формат расширения';
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление баннера 200х300
if ($_GET['func'] == 'delban3') {
    $gg = intval($_POST['id']);
    $zzzz = mysql_query("SELECT balance FROM tb_advban_300 WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'");
    if (mysql_num_rows($zzzz) > 0) {
        $balance = mysql_result($zzzz,0);
        if ($balance > 0.5) {
            echo 'Вы не можете удалить ссылку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
            mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
            $get_ban = mysql_fetch_array( mysql_query( "SELECT nametime, typeban FROM tb_advban_300 WHERE id = '$gg'" ) );
            unlink('banners/' . $get_ban['nametime'] . '.' . $get_ban['typeban']);
            mysql_query("DELETE FROM tb_advban_300 WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сбросить статистику баннера 200х300
if ($_GET['func'] == 'clearban3') {
    $gg = intval($_POST['id']);
    mysql_query("UPDATE tb_advban_300 SET views = 0 where fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Включить баннер 200х300
if ($_GET['func'] == 'runban3') {
    $pp = intval($_POST['id']);
    $paused = mysql_fetch_array(mysql_query("SELECT paused from tb_advban_300 where id = '$pp' and modered = '1' and fromus = '" . $_SESSION['iduser'] . "'"));
    if ($paused['paused'] == 0) { $npaused = 1; } else { $npaused = 0; } 
    mysql_query("UPDATE tb_advban_300 set paused='$npaused' where fromus = '" . $_SESSION['iduser'] . "' and id = '$pp' and modered = '1' and balance > price") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ баннера 468x60
if ($_GET['func'] == 'addbanner1') {
    if ($_FILES['file']['size'] <= 0 or $_FILES['file']['size'] > 204800) {
        echo 'Размер баннера превышает допустимое значение';
        exit();
    } else
    if ($_FILES['file']['type'] == "image/gif" OR $_FILES['file']['type'] == "image/png" OR $_FILES['file']['type'] == "image/jpeg" OR $_FILES['file']['type'] == "image/jpg") {
        if (is_uploaded_file($_FILES['file']['tmp_name'])) {
            $ssz = GetImageSize($_FILES['file']['tmp_name']);
            if ($ssz[0] != 468 or $ssz[1] != 60) {
                echo('Баннер должен быть размерами 468х60!');
                exit();
            } else {
			    if(@imagecreatefromstring(file_get_contents($_FILES['file']['tmp_name'])) === false) {
					echo "Неверный формат расширения";
				} else {
			        $url1 = substr(check_text($_POST["url"]), 0, 300);
                        function getHost($Address) {
                        $parseUrl = parse_url(trim($Address));
                        return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2)));
                    }
                    $site = getHost($url1);
                    $site = str_ireplace("www.","",$site);
                    $bll = mysql_query("SELECT * FROM seo_blacklist WHERE site='$site' LIMIT 1");
                    if (mysql_num_rows($bll) > 0) {
                        $res34 = mysql_fetch_array($bll);
                        echo "Ваш сайт находится в чёрном списке. Причина: $res34[reason]";
                        exit();
                    } else {
                        if ($modered == 1) $mod = 1; else $mod = 0;
                        $type_file = str_replace("theme/tmp/", "", basename($_FILES['file']['type']));
                        $nowtime = time();
                        if (@move_uploaded_file($_FILES['file']['tmp_name'], "banners/$nowtime." . $type_file)) {
                            mysql_query("INSERT INTO tb_allhistory (idus, data, doing, title) values ('" . $_SESSION['iduser'] . "', '$nowtime', '2', '$url1')");
                            mysql_query("INSERT INTO tb_advban (url, price, nametime, typeban, fromus, modered) values ('$url1', '$advbanner', '$nowtime', '$type_file', '" . $_SESSION['iduser'] . "', '$mod')") or die(mysql_error());
                            echo 1;
                            exit();
                        }
                    }
                } 
		    }
        }
    } else {
        echo 'Неверный формат расширения';
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление баннера
if ($_GET['func'] == 'delban1') {
    $gg = intval($_POST['id']);
    $zzzz = mysql_query("SELECT balance FROM tb_advban WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'");
    if (mysql_num_rows($zzzz) > 0) {
        $balance = mysql_result($zzzz,0);
        if ($balance > 0.5) {
            echo 'Вы не можете удалить ссылку, пока на балансе не станет 0.5 руб';
            exit();
        } else {
            mysql_query("UPDATE tb_users set money = money + '$balance' where id = '" . $_SESSION['iduser'] . "'") or die(mysql_error());
            $get_ban = mysql_fetch_array( mysql_query( "SELECT nametime, typeban FROM tb_advban WHERE id = '$gg'" ) );
            unlink('banners/' . $get_ban['nametime'] . '.' . $get_ban['typeban']);
            mysql_query("DELETE FROM tb_advban WHERE fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сбросить статистику баннера
if ($_GET['func'] == 'clearban1') {
    $gg = intval($_POST['id']);
    mysql_query("UPDATE tb_advban SET views = 0 where fromus = '" . $_SESSION['iduser'] . "' and id = '$gg'") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Включить баннер
if ($_GET['func'] == 'runban1') {
    $pp = intval($_POST['id']);
    $paused = mysql_fetch_array(mysql_query("SELECT paused from tb_advban where id = '$pp' and modered = '1' and fromus = '" . $_SESSION['iduser'] . "'"));
    if ($paused['paused'] == 0) { $npaused = 1; } else { $npaused = 0; } 
    mysql_query("UPDATE tb_advban set paused='$npaused' where fromus = '" . $_SESSION['iduser'] . "' and id = '$pp' and modered = '1' and balance > price") or die(mysql_error());
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Просмотр дин. ссылки
if ($_GET['func'] == 'dynview') {
	if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Просмотр серфинга не доступный для вас!</font>';
        exit();
    } else
    if (strtolower($_POST['code']) != strtolower($_SESSION['texto'])) {
        echo '<font color="#800000">Просмотр не засчитан!</font>';
        exit();
    } else
    $getdyn = mysql_fetch_array( mysql_query( "SELECT id, timer, obper, highlight, price FROM tb_ads WHERE id = '" . intval($_POST['id']) . "' and balance >= price and modered = 1 and paused = 0" ) );
    if ((int)$getdyn['id'] == 0) {
        echo '<font color="#800000">Ссылка не существует!</font>';
        exit();
    } else
    $getvisit = mysql_num_rows( mysql_query( "SELECT id FROM tb_visits WHERE idus = '" . $_SESSION['iduser'] . "' and ident = '" . intval($_POST['id']) . "'" ) );
    if ($getvisit > 0 ) {
        echo '<font color="#800000">Вы уже просматривали эту ссылку!</font>';
        exit();
    } else {
        if($getdyn['timer'] == 0) $prc = $payuser['dyn20'];
        if($getdyn['timer'] == 1) $prc = $payuser['dyn30'];
        if($getdyn['timer'] == 2) $prc = $payuser['dyn40'];
        if($getdyn['timer'] == 3) $prc = $payuser['dyn50'];
        if($getdyn['timer'] == 4) $prc = $payuser['dyn60'];
		if($getdyn['timer'] == 5) $prc = $payuser['dyn10'];
        if($getdyn['timer'] == 6) $prc = $payuser['dyn5'];
        
		
		
        $userd = mysql_fetch_array( mysql_query( "SELECT referer, referer2 FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'" ) );
        
		if ($userd['referer'] != '') {
            $usref1 = mysql_fetch_array( mysql_query( "SELECT reyting, finestatus FROM tb_users WHERE id = '" . $userd['referer'] . "'" ) );
            $reyting = $usref1['reyting'];        
            ///проверяем если реферер штрафник, прибиль ему присваеваем к нулю
			if($usref1['finestatus'] == 0) {
                if ($reyting < 1) {
                    $prcr = 0;
                } else
                if ($reyting >= 1 and $reyting < 10) {
                    $prcr = $prc * $payuser['st1'];
                } else
                if ($reyting >= 10 and $reyting < 100) {
                    $prcr = $prc * $payuser['st2'];
                } else
                if ($reyting >= 100 and $reyting < 250) {
                    $prcr = $prc * $payuser['st3'];
                } else
                if ($reyting >= 250 and $reyting < 600) {
                    $prcr = $prc * $payuser['st4'];
                } else
                if ($reyting >= 600 and $reyting < 1000) {
                    $prcr = $prc * $payuser['st5'];
                } else
                if ($reyting >= 1000) {
                    $prcr = $prc * $payuser['st6'];
                }
                $autoproc = mysql_result(mysql_query("SELECT autoproc FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'"), 0, 0);
                if ($autoproc != 100) $proc = "0.$autoproc";
                if ($autoproc == 100) $proc = 1;
                $plusautoback = $prcr * $proc; //авторефбек
			    $elprecio1 = $prcr - $plusautoback;
            } else {
			    $elprecio1 = 0;
			}
			mysql_query("UPDATE tb_users SET money = money + '$elprecio1' WHERE id='" . $userd['referer'] . "'");
        }
		
        if ($userd['referer2'] != '') {
            $usref2 = mysql_fetch_array( mysql_query( "SELECT reyting, finestatus FROM tb_users WHERE id = '" . $userd['referer2'] . "'" ) );
            $reyting = $usref2['reyting'];
            
			/// Проверяем если реферер второго уровня штрафник, прибиль присваиваем ему к нулю
			if($usref2['finestatus'] == 0) {
			    if ($reyting < 1) {
                    $elprecio2 = 0;
                } else
                if ($reyting >= 1 and $reyting < 10) {
                    $elprecio2 = $payuser['st7'];
                } else
                if ($reyting >= 10 and $reyting < 100) {
                    $elprecio2 = $payuser['st8'];
                } else
                if ($reyting >= 100 and $reyting < 250) {
                    $elprecio2 = $payuser['st9'];
                } else
                if ($reyting >= 250 and $reyting < 600) {
                    $elprecio2 = $payuser['st10'];
                } else
                if ($reyting >= 600 and $reyting < 1000) {
                    $elprecio2 = $payuser['st11'];
                } else
                if ($reyting >= 1000) {
                    $elprecio2 = $payuser['st12'];
                }
			} else {
			    $elprecio2 = 0;
			}
			mysql_query("UPDATE tb_users SET money = money + '$elprecio2' WHERE id = '" . $userd['referer2'] . "'");
        }
		
        mysql_query("UPDATE tb_ads SET plan = plan + 1, balance = balance - price WHERE id = '" . intval($_POST['id']) . "'");
        mysql_query("UPDATE tb_users SET money = money + '$prc' + '$plusautoback', visits = visits + 1, toref = toref + '$elprecio1', toref2 = toref2 + '$elprecio2' WHERE id = '" . $_SESSION['iduser'] . "'");
        ///Конкурсы (серфинг)
		if($prc > 0) {
			$ref_name_u = mysql_fetch_array( mysql_query( "SELECT referer FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'" ) );
			if($ref_name_u['referer'] > 0) {
				$kon_ref_u = mysql_fetch_array(mysql_query("SELECT * FROM konkurs_ref WHERE status = '1' AND type = '1' AND referername = '".$ref_name_u['referer']."'"));
				if ($kon_ref_u['id'] > 0) {
					$ref_temp_u = mysql_fetch_array( mysql_query( "SELECT * FROM konkurs_ref_temp WHERE iduser = '" . $_SESSION['iduser'] . "' AND idkonkurs = '" . $kon_ref_u['id'] . "' AND type = '1'" ) );
					if($ref_temp_u['id'] > 0) {
						///echo 'участвует';
						mysql_query("UPDATE konkurs_ref_temp SET summ = summ + '1' WHERE iduser = '" . $_SESSION['iduser'] . "' AND idkonkurs = '" . $kon_ref_u['id'] . "' AND type = '1'");
					} else {
						///echo 'не участвует';
						mysql_query("INSERT INTO konkurs_ref_temp (iduser, idkonkurs, type, summ) VALUES ('" . $_SESSION['iduser'] . "', '" . $kon_ref_u['id'] . "', '1', '1')");
					}
				}
			}
		}
		$nowtime = time();
        $varstr = date("w");
        $day = "";
        if ($varstr == 1) $day = 'mon';
        if ($varstr == 2) $day = 'tue';
        if ($varstr == 3) $day = 'wed';
        if ($varstr == 4) $day = 'thu';
        if ($varstr == 5) $day = 'fri';
        if ($varstr == 6) $day = 'sat';
        if ($varstr == 0) $day = 'sun';
        mysql_query("UPDATE tb_statistic SET total=total+1, ".$day."=".$day."+1 WHERE username='" . $_SESSION['iduser'] . "' and typ=0");
        mysql_query("INSERT INTO tb_visits (idus, data, ident) VALUES ('" . $_SESSION['iduser'] . "', '$nowtime' + 86400, '" . intval($_POST['id']) . "')");
        if ($getdyn['obper'] == 1) {
            echo 2;
        } else {
            $vir1 = $getdyn['price'];//$hits + $getdyn['timer'] * $timer5 + $hldyn * $getdyn['highlight'] + $getdyn['obper'] * $obperehod;
            $viruchka = $vir1 - $prc - $plusautoback - $elprecio1 - $elprecio2;
            mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (1, '$viruchka', '" . date('m', time()) . "', '" . date('Y', time()) . "')");
            echo 1;
        }
    }
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Проверка ответа платного письма
if ($_GET['func'] == 'answerpmail') {
    $gg = intval($_POST['id']);
    $answer = check_text($_POST['answer']);
    $sql = mysql_fetch_array( mysql_query( "SELECT answer1 FROM seo_paymails WHERE id = '$gg'" ) );
    if ($answer != $sql['answer1']) {
        mysql_query( "INSERT INTO seo_paymailsviews (ident, fromid, time) VALUES ('" . $gg . "', '" . $_SESSION['iduser'] . "', '" . time() . "' + 86400)" );
        echo 2;
        exit();
    } else {
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Просмотр платного письма
if ($_GET['func'] == 'pmailsview') {
    if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Просмотр пл.писем не доступный для вас!</font>';
        exit();
    } else
    if (strtolower($_POST['code']) != strtolower($_SESSION['texto'])) {
        echo '<font color="#800000">Просмотр не засчитан!</font>';
        exit();
    } else
    $getpm = mysql_fetch_array( mysql_query( "SELECT id, timer, obper, many, price, highlight FROM seo_paymails WHERE id = '" . intval($_POST['id']) . "' and balance > price and modered = 1 and paused = 0" ) );
    if ($getpm['id'] == '') {
        echo '<font color="#800000">Ссылка не существует!</font>';
        exit();
    } else
    $pmvisit = mysql_fetch_array( mysql_query( "SELECT ident, time FROM seo_paymailsviews WHERE ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'" ) );
    if ($pmvisit['ident'] == intval($_POST['id']) and $getpm['many'] == 0 or $pmvisit['time'] > time()) {
        echo '<font color="#800000">Вы уже просматривали эту ссылку!</font>';
        exit();
    } else {
        if($getpm['timer'] == 20) $prc = $payuser['pm20'];
        if($getpm['timer'] == 30) $prc = $payuser['pm30'];
        if($getpm['timer'] == 40) $prc = $payuser['pm40'];
        if($getpm['timer'] == 50) $prc = $payuser['pm50'];
        if($getpm['timer'] == 60) $prc = $payuser['pm60'];
        
        $userd = mysql_fetch_array( mysql_query( "SELECT referer, referer2 FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'" ) );
        
		if ($userd['referer'] != '') {
            $usref1 = mysql_fetch_array( mysql_query( "SELECT reyting, finestatus FROM tb_users WHERE id = '" . $userd['referer'] . "'" ) );
            $reyting = $usref1['reyting'];           
            if($usref1['finestatus'] == 0) {
                if ($reyting < 1) {
                    $prcr = 0;
                } else
                if ($reyting >= 1 and $reyting < 10) {
                    $prcr = $prc * $payuser['st1'];
                } else
                if ($reyting >= 10 and $reyting < 100) {
                    $prcr = $prc * $payuser['st2'];
                } else
                if ($reyting >= 100 and $reyting < 250) {
                    $prcr = $prc * $payuser['st3'];
                } else
                if ($reyting >= 250 and $reyting < 600) {
                    $prcr = $prc * $payuser['st4'];
                } else
                if ($reyting >= 600 and $reyting < 1000) {
                    $prcr = $prc * $payuser['st5'];
                } else
                if ($reyting >= 1000) {
                    $prcr = $prc * $payuser['st6'];
                }
                $autoproc = mysql_result(mysql_query("SELECT autoproc FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'"), 0, 0);
                if ($autoproc != 100) $proc = "0.$autoproc";
                if ($autoproc == 100) $proc = 1;
                $plusautoback = $prcr * $proc; //авторефбек
                $elprecio1 = $prcr - $plusautoback;
		    } else {
			    $elprecio1 = 0;
			}
            mysql_query("UPDATE tb_users SET money = money + '$elprecio1' WHERE id='" . $userd['referer'] . "'");              
        }
		
        if ($userd['referer2'] != '') {
            $usref2 = mysql_fetch_array( mysql_query( "SELECT reyting, finestatus FROM tb_users WHERE id = '" . $userd['referer2'] . "'" ) );
			$reyting = $usref2['reyting'];           
            if($usref2['finestatus'] == 0) {
            if ($reyting < 1) {
                $elprecio2 = 0;
            } else
            if ($reyting >= 1 and $reyting < 10) {
                $elprecio2 = $payuser['st7'];
            } else
            if ($reyting >= 10 and $reyting < 100) {
                $elprecio2 = $payuser['st8'];
            } else
            if ($reyting >= 100 and $reyting < 250) {
                $elprecio2 = $payuser['st9'];
            } else
            if ($reyting >= 250 and $reyting < 600) {
                $elprecio2 = $payuser['st10'];
            } else
            if ($reyting >= 600 and $reyting < 1000) {
                $elprecio2 = $payuser['st11'];
            } else
            if ($reyting >= 1000) {
                $elprecio2 = $payuser['st12'];
            }
			} else {
			    $elprecio2 = 0;
			}
            
            mysql_query("UPDATE tb_users SET money = money + '$elprecio2' WHERE id = '" . $userd['referer2'] . "'");
        }
        mysql_query("UPDATE seo_paymails SET plan = plan + 1, balance = balance - price WHERE id = '" . intval($_POST['id']) . "'");
        
        mysql_query("UPDATE tb_users SET money = money + '$prc' + '$plusautoback', visits = visits + 1, toref = toref + '$elprecio1', toref2 = toref2 + '$elprecio2' WHERE id = '" . $_SESSION['iduser'] . "'");
        ///Конкурсы (письма)
		if($prc > 0) {
			$ref_name_u = mysql_fetch_array( mysql_query( "SELECT referer FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'" ) );
			if($ref_name_u['referer'] > 0) {
				$kon_ref_u = mysql_fetch_array(mysql_query("SELECT * FROM konkurs_ref WHERE status = '1' AND type = '2' AND referername = '".$ref_name_u['referer']."'"));
				if ($kon_ref_u['id'] > 0) {
					$ref_temp_u = mysql_fetch_array( mysql_query( "SELECT * FROM konkurs_ref_temp WHERE iduser = '" . $_SESSION['iduser'] . "' AND idkonkurs = '" . $kon_ref_u['id'] . "' AND type = '2'" ) );
					if($ref_temp_u['id'] > 0) {
						///echo 'участвует';
						mysql_query("UPDATE konkurs_ref_temp SET summ = summ + '1' WHERE iduser = '" . $_SESSION['iduser'] . "' AND idkonkurs = '" . $kon_ref_u['id'] . "' AND type = '2'");
					} else {
						///echo 'не участвует';
						mysql_query("INSERT INTO konkurs_ref_temp (iduser, idkonkurs, type, summ) VALUES ('" . $_SESSION['iduser'] . "', '" . $kon_ref_u['id'] . "', '2', '1')");
					}
				}
			}
		}
        $nowtime = time();
        $varstr = date("w");
        $day = "";
        if ($varstr == 1) $day = 'mon';
        if ($varstr == 2) $day = 'tue';
        if ($varstr == 3) $day = 'wed';
        if ($varstr == 4) $day = 'thu';
        if ($varstr == 5) $day = 'fri';
        if ($varstr == 6) $day = 'sat';
        if ($varstr == 0) $day = 'sun';
        mysql_query("UPDATE tb_statistic SET total=total+1, ".$day."=".$day."+1 WHERE username='" . $_SESSION['iduser'] . "' and typ=2");
        if ($getpm['many'] == 0 or $pmvisit['ident'] != intval($_POST['id'])) {
            mysql_query("INSERT INTO seo_paymailsviews (fromid, time, ident) VALUES ('" . $_SESSION['iduser'] . "', '$nowtime' + 86400, '" . intval($_POST['id']) . "')");
        } else {
            mysql_query("UPDATE seo_paymailsviews SET fromid = '" . $_SESSION['iduser'] . "', time = '$nowtime' + 86400 WHERE ident = '" . intval($_POST['id']) . "'");
        }
        
        if ($getdyn['obper'] == 1) {
            echo 2;
        } else {
            $vir1 = $getpm['price'];//$mprice + (($getpm['timer'] - 20) / 10) * $mtimer + $pmhighlight * $getpm['highlight'] + $getpm['obper'] * $pmobper;
            $viruchka = $vir1 - $prc - $plusautoback - $elprecio1 - $elprecio2;
            mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (2, '$viruchka', '" . date('m', time()) . "', '" . date('Y', time()) . "')");
            echo 1;
        }
    }
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Добавления комментария к заданию
if ($_GET['func'] == 'addcom') {
    if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Вы не можете оставить комментарий!</font>';
        exit();
    } else
    $getcom = mysql_num_rows( mysql_query( "SELECT id FROM seo_taskcomms WHERE fromid = '" . $_SESSION['iduser'] . "' and ident = '" . intval($_POST['id']) . "'" ) );
    $getus = mysql_num_rows( mysql_query( "SELECT id FROM seo_tasks WHERE fromid = '" . $_SESSION['iduser'] . "' and id = '" . intval($_POST['id']) . "'" ) );
    if ($getcom > 0) {
        echo '<div align="center" style="color:#800000; padding:5px">Вы уже оставляли комментарий к этому заданию</div>';
        exit();
    } else
    if ($getus > 0) {
        echo '<div align="center" style="color:#800000; padding:5px">Вы автор задания. Вы не можете оставить комментарий</div>';
        exit();
    } else
    if (check_text($_POST['comms'] == '')) {
        echo 'Вы не указали комментарий';
        exit();
    } else {
        $_POST['comms'] = check_text($_POST['comms']);
        $_POST['comms'] = substr($_POST['comms'], 0, 3000);
        if (intval($_POST['reyt']) < 0 and intval($_POST['reyt']) > 5) {
            $_POST['reyt'] = 0;
        }
        mysql_query("INSERT INTO seo_taskcomms (fromid, ident, time, text, reyt) VALUES ('" . $_SESSION['iduser'] . "', '" . intval($_POST['id']) . "', '" . time() . "', '" . $_POST['comms'] . "', '" . intval($_POST['reyt']) . "')");
        $allreyt = mysql_result(mysql_query("SELECT sum(reyt) FROM seo_taskcomms WHERE ident='" . intval($_POST['id']) . "'"), 0);
        $all = mysql_result(mysql_query("SELECT count(id) FROM seo_taskcomms WHERE ident='" . intval($_POST['id']) . "'"), 0);
        $srreyt = $allreyt / $all;
        $srreyt = round($srreyt, 2);
        mysql_query("UPDATE seo_tasks SET reyt = '$srreyt' WHERE id = '" . intval($_POST['id']) . "'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Начало выполнения задания
if ($_GET['func'] == 'taskadv') {
    if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Вы не можете выполнять задания!</font>';
        exit();
    } else
    $nowtime = time();
    $prov = mysql_fetch_array(mysql_query("SELECT id, paused, fromid, many, maxtime FROM seo_tasks WHERE id = '" . intval($_POST['id']) . "'"));
    $prov2 = mysql_query("SELECT id FROM seo_taskstats WHERE ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'");
    if ($prov['fromid'] == $_SESSION['iduser']) {
        exit();
    } else
    if ($prov['paused'] == 1) {
        exit();
    } else
    if ($prov['id'] == '') {
        exit();
    } else
    if ($prov['many'] == 0 and mysql_num_rows($prov2) > 0) {
        exit();
    } else {
        $endtime = $nowtime + $prov['maxtime'];
        mysql_query("INSERT INTO seo_taskstats (fromid, starttime, status, ident, anstime, endtime) values ('" . $_SESSION['iduser'] . "', '$nowtime', '3', '" . intval($_POST['id']) . "', '$nowtime', '$endtime')");
        mysql_query("UPDATE seo_tasks SET works = works + 1 WHERE id = '" . intval($_POST['id']) . "'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Начало выполнения задания заново
if ($_GET['func'] == 'taskadvup') {
    if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Вы не можете выполнять задания!</font>';
        exit();
    } else
    $nowtime = time();
    $prov = mysql_fetch_array(mysql_query("SELECT id, paused, fromid, many FROM seo_tasks WHERE id = '" . intval($_POST['id']) . "'"));
    $prov2 = mysql_query("SELECT id FROM seo_taskstats WHERE ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'");
    if ($prov['fromid'] == $_SESSION['iduser']) {
        exit();
    } else
    if ($prov['paused'] == 1) {
        exit();
    } else
    if ($prov['id'] == '') {
        exit();
    } else
    if ($prov['many'] == 0 and mysql_num_rows($prov2) > 0) {
        exit();
    } else {
        mysql_query("DELETE FROM seo_taskstats WHERE ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "' and status = 1");
        mysql_query("INSERT INTO seo_taskstats (fromid, starttime, status, ident, anstime) values ('" . $_SESSION['iduser'] . "', '$nowtime', '3', '" . intval($_POST['id']) . "', '$nowtime')");
        mysql_query("UPDATE seo_tasks SET works = works + 1 WHERE id = '" . intval($_POST['id']) . "'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Отказ от задания
if ($_GET['func'] == 'taskreset') {
    $prov = mysql_fetch_array(mysql_query("SELECT ident FROM seo_taskstats WHERE ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "' and status = 3"));
    if ($prov['ident'] != '') {
        mysql_query("UPDATE seo_tasks SET works = works - 1 WHERE id='" . intval($prov['ident']) . "'");
        mysql_query("DELETE FROM seo_taskstats WHERE ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "' and status = 3");
        echo 1;
        exit();
    } else {
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Отправка отчета выполненного задания
if ($_GET['func'] == 'tanswer') {
    if (mysql_num_rows(mysql_query("SELECT id FROM seo_taskstats WHERE status = 3 and ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'")) > 0) {
        $ntime = time();
        $myid = mysql_result(mysql_query("SELECT id FROM seo_taskstats WHERE status = 3 and ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'"), 0);
        $reply = check_text($_POST['answer']);
        $reply = substr($reply, 0, 1500);
        mysql_query("UPDATE seo_taskstats SET anstime = '$ntime', answer = '$reply', status = 0 where id = '$myid'");
        mysql_query("UPDATE seo_tasks SET waits = waits + 1, works = works - 1 WHERE id = '" . intval($_POST['id']) . "'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Добавление задания в избранное
if ($_GET['func'] == 'addfav') {
    $fav = mysql_query("SELECT id FROM seo_favtasks WHERE ident = '" . intval($_POST['id']) . "' and fromid = '" . $_SESSION['iduser'] . "'");
    if (mysql_num_rows($fav) > 0) {
        $idfav = mysql_fetch_array($fav);
        mysql_query("DELETE FROM seo_favtasks WHERE id = '" . $idfav['id'] . "'");
        exit();
    } else {
        mysql_query("INSERT INTO seo_favtasks (ident, fromid) VALUES ('" . intval($_POST['id']) . "', '" . $_SESSION['iduser'] . "')");
    }
    echo 1;
    exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Добавления комментария на стене
if ($_GET['func'] == 'addwall') {
    $id = intval($_POST['id']);
    $comms = check_text($_POST['comms']);
    $comms = substr($comms, 0, 228);
    
	if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Вы не можете оставить комментарий!</font>';
        exit();
    } else
    if ($comms == '') {
        echo 'Введите текст!';
        exit();
    } else
    $prwall = mysql_fetch_array(mysql_query("SELECT id FROM tb_wall WHERE tous = '$id' and fromus = '" . $_SESSION['iduser'] . "'"));
    if ($prwall != '') {
        echo 'Вы уже оставляли отзыв пользователю';
        exit();
    } else
    if ($reyting < 10) {
        echo 'Рейтинг маловат...';
        exit();
    } else
    if ($id == $_SESSION['iduser']) {
        echo 'Вы не можете оставить отзыв самому себе';
        exit();
    }
    mysql_query("INSERT INTO tb_wall (tous, fromus, date, comment) VALUES ('$id', '" . $_SESSION['iduser'] . "', '".time()."', '$comms')");
        echo 1;
        exit();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Подарок
if ($_GET['func'] == 'addgift') {
    $id = intval($_POST['id']);
    $gift = intval($_POST['gift']);
    $comms = check_text($_POST['comms']);
    $comms =substr($comms, 0, 55);
    
	if ($finestatus != '0') {
        echo 'Внимание! На ваш аккаунт наложен штраф! Вы не можете дарить подарки!';
        exit();
    } else
    if ($gift < 0 and $gift > $podarki) {
        echo 'Подарок не существует';
        exit();
    } else
    if ($golos < 5) {
        echo 'У Вас недостаточно голосов';
        exit();
    } else {
        mysql_query("UPDATE tb_users SET golos = golos - 5, reyting = reyting + 10 WHERE id = '" . $_SESSION['iduser'] . "'");
        mysql_query("INSERT INTO tb_gift (tous, fromus, date, gift, comms) VALUE ('$id', '" . $_SESSION['iduser'] . "', '" . time() . "', '$gift', '$comms')");
        echo 'Подарок успешно отправлен';
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Купить голос
if ($_GET['func'] == 'buygolos') {
    $buygolos = intval($_POST['golos']);
    if ($buygolos == 0 or $buygolos < 0) {
        echo 'Укажите правильное число голосов';
        exit();
    } else
    if ($buygolos > $admoney) {
        echo 'Недостаточно средств на счету';
        exit();
    } else {
        mysql_query("UPDATE tb_users SET admoney = admoney - '$buygolos', golos = golos + '$buygolos' WHERE id = '$_SESSION[iduser]'");
        mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (6, '$buygolos', '" . date('m', time()) . "', '" . date('Y', time()) . "')");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Стать рефералом
if ($_GET['func'] == 'addreferer') {
    $id = intval($_POST['id']);
    $us = mysql_query("SELECT id, autoback FROM tb_users WHERE id = '$id'");
    if (mysql_num_rows($us) < 1) {
        exit();
    } else
	if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Вы не можете стать чужим рефералом!</font>';
        exit();
    } else
	$reffine = mysql_fetch_array(mysql_query("SELECT finestatus, ban FROM tb_users WHERE id = '$id'"));
	if ($reffine['finestatus'] != '0') {
        echo '<font color="#800000">Внимание! Вы не можете стать рефералом штрафника!</font>';
        exit();
    } else
	if ($reffine['ban'] != '0') {
        echo '<font color="#800000">Внимание! Вы не можете стать рефералом заблокированного пользователя!</font>';
        exit();
    } else
	if ($id == $_SESSION['iduser']) {
        exit();
    } else
    if ($byme['referer'] != 0) {
        exit();
    } else {
        $row = mysql_fetch_array($us);
        mysql_query("UPDATE tb_users SET referer = '$id', autoproc = '" . $row['autoback'] . "' WHERE id = '" . $_SESSION['iduser'] . "'");
        mysql_query("UPDATE tb_users SET referer2 = '$id' WHERE referer = '" . $_SESSION['iduser'] . "' and id != '$id'");
        mysql_query("INSERT INTO seo_mails (text, subject, fromid, toid, `read`, timemessage) VALUES ('К вам присоединился реферал ID: " . $_SESSION['iduser'] . "', 'Что-то интересное произошло на вашей стене', '" . $_SESSION['iduser'] . "', '$id', '" . time() . "')");
        mysql_query("UPDATE tb_users SET reyting = reyting + 0.5 WHERE id = '" . $row['id'] . "'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Создание темы на форуме
if ($_GET['func'] == 'addtopic') {
    $id = intval($_POST['id']);
    $des = check_text($_POST['des']);
    $des = substr($des, 0, 55);
    $mess = iconv('UTF-8', 'windows-1251', substr(qcode_bb($_POST['mess']), 0, 5000));
	$mess = str_replace("	", '.d', $mess);
	$mess = preg_replace("#[j|J][a|A][v|V][a|A]#is", '', $mess);
    $mess = preg_replace("#[s|S][c|C][r|R][i|I][p|P][t|T]#is", '', $mess);
    $mess = preg_replace("#[d|D][o|O][c|C][u|U][m|M][e|E][n|N][t|T]#is", '', $mess);
    $mess = preg_replace("#[c|C][o|O][o|O][k|K][i|I][e|E]#is", '', $mess);
	$mess = preg_replace("#[u|U][n|N][i|I][o|O][n|N]#is", '', $mess); 
    $mess = preg_replace("#[f|F][r|R][o|O][m|M]#is", '', $mess); 
    $mess = preg_replace("#[w|W][h|H][e|E][r|R][e|E]#is", '', $mess); 
    $mess = preg_replace("#[s|S][e|E][l|L][e|E][c|C][t|T]#is", '', $mess); 
    $mess = preg_replace("#[i|I][n|N][s|S][e|E][r|R][t|T]#is", '', $mess);
    $mess = preg_replace("#[u|U][p|P][d|D][a|A][t|T][e|E]#is", '', $mess);
    $mess = preg_replace("#[d|D][e|E][l|L][e|E][t|T][e|E]#is", '', $mess);
 	$mess = str_replace('$', 'y.e', $mess);
    $mess = str_replace(';', '', $mess);
    $mess = str_replace('"', '', $mess);
    $mess = str_replace('\'', '', $mess);
    $mess = str_replace('`', '', $mess);
	$mess = str_replace("'", '', $mess);
    
    $gettopic = mysql_query("SELECT id FROM tb_forum_category WHERE id = '$id'");
    
	if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Вы не можете создавать темы на форуме!</font>';
        exit();
    } else
    if (mysql_num_rows($gettopic) < 1) {
        exit();
    } else
    if ($blockforum == 1) {
        echo 'Вам запрещено создавать темы';
        exit();
    } else
    if ($id == 1 and $user_status != 'admin') {
        echo 'Запрещено создавать темы';
        exit();
    } else
    if ($des == '') {
        echo 'Укажите заголовок темы';
        exit();
    } else
	if ($forumblock_date > time()-30) {
        echo 'Нельзя так часто создавать темы';
        exit();
    } else
    if ($mess == '') {
        echo 'Сообщение не может быть пустым';
        exit();
    } else {
        mysql_query("INSERT INTO tb_forum_topic (catid, topicname, avtor, date) VALUES ('$id', '$des', '" . $_SESSION['iduser'] . "', '" . time() . "')");
        $tc = mysql_fetch_array(mysql_query("SELECT id FROM tb_forum_topic WHERE catid = '$id' and avtor = '" . $_SESSION['iduser'] . "' ORDER BY id DESC"));
        mysql_query("INSERT INTO tb_forum_mes (tid, userid, mes, date) VALUES ('" . $tc['id'] . "', '" . $_SESSION['iduser'] . "', '$mess', '" . time() . "')");
		mysql_query("update tb_users set reyting=reyting+'0.5', forumblock_date = '" . time() . "' WHERE id='" . $_SESSION['iduser'] . "'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Сообщение на форуме
if ($_GET['func'] == 'addmess') {
    $id = intval($_POST['id']);
    $mess = iconv('UTF-8', 'windows-1251', substr(qcode_bb($_POST['mess']), 0, 5000));
    preg_match('/\[quote\](\d+)\[\/quote\]/i', $mess, $match);
    $match[1] = intval($match[1]);
    $sql = mysql_fetch_array(mysql_query("SELECT userid, mes FROM tb_forum_mes WHERE id='$match[1]'"));
    $sql['mes'] = preg_replace("#<fieldset class=\"(.+?)\">(.+?)<\/fieldset>#is", '', $sql['mes']);
    $sql2 = mysql_fetch_array(mysql_query("SELECT username FROM tb_users WHERE id='$sql[userid]'"));
    $mess = preg_replace("#\[quote\](\d+)\[\/quote\]#is","<fieldset class=\"quote\"><legend>$sql2[username]</legend>$sql[mes]</fieldset>", $mess);
    $mess = str_replace("	", '.d', $mess);
	$mess = preg_replace("#[j|J][a|A][v|V][a|A]#is", '', $mess);
    $mess = preg_replace("#[s|S][c|C][r|R][i|I][p|P][t|T]#is", '', $mess);
    $mess = preg_replace("#[d|D][o|O][c|C][u|U][m|M][e|E][n|N][t|T]#is", '', $mess);
    $mess = preg_replace("#[c|C][o|O][o|O][k|K][i|I][e|E]#is", '', $mess);
	$mess = preg_replace("#[u|U][n|N][i|I][o|O][n|N]#is", '', $mess); 
    $mess = preg_replace("#[f|F][r|R][o|O][m|M]#is", '', $mess); 
    $mess = preg_replace("#[w|W][h|H][e|E][r|R][e|E]#is", '', $mess); 
    $mess = preg_replace("#[s|S][e|E][l|L][e|E][c|C][t|T]#is", '', $mess); 
    $mess = preg_replace("#[i|I][n|N][s|S][e|E][r|R][t|T]#is", '', $mess);
    $mess = preg_replace("#[u|U][p|P][d|D][a|A][t|T][e|E]#is", '', $mess);
    $mess = preg_replace("#[d|D][e|E][l|L][e|E][t|T][e|E]#is", '', $mess);
 	$mess = str_replace('$', 'y.e', $mess);
    $mess = str_replace(';', '', $mess);
    $mess = str_replace('"', '', $mess);
    $mess = str_replace('\'', '', $mess);
    $mess = str_replace('`', '', $mess);
	$mess = str_replace("'", '', $mess); 
    
    $gettopic = mysql_query("SELECT id, topic_close FROM tb_forum_topic WHERE id = '$id'");
    $getrow = mysql_fetch_array($gettopic);
    
    if (mysql_num_rows($gettopic) < 1) {
        exit();
    } else
    if($getrow['topic_close'] == 1) {
        exit();
    } else
    if ($blockforum == 1) {
        echo 'Вам запрещено отвечать на темы';
        exit();
    } else
	if ($finestatus != '0') {
        echo '<font color="#800000">Внимание! На ваш аккаунт наложен штраф! Вы не можете оставить комментарий!</font>';
        exit();
    } else
	if ($forumblock_date > time()-30) {
        echo 'Нельзя так часто создавать сообщения';
        exit();
    } else	
    if ($mess == '') {
        echo 'Сообщение не может быть пустым';
        exit();
    } else {
        mysql_query("INSERT INTO tb_forum_mes (tid, userid, mes, date) VALUES ('$id', '" . $_SESSION['iduser'] . "', '$mess', '" . time() . "')");
		mysql_query("update tb_users set reyting=reyting+'0.1', forumblock_date ='" . time() . "' WHERE id='" . $_SESSION['iduser'] . "'");
        mysql_query("DELETE FROM forum_visit_status WHERE idtopic = '$id'");
		echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление поста
if ($_GET['func'] == 'delposts') {
    $id = intval($_POST['id']);
    $posts = intval($_POST['posts']);
    $usinfo = mysql_fetch_array(mysql_query("SELECT user_status FROM tb_users WHERE id = '$id'"));
    if (/*$id == $_SESSION['iduser'] or */$user_status == 'admin' or $user_status == 'moder' and $usinfo['user_status'] != 'admin') {
        mysql_query("DELETE FROM tb_forum_mes WHERE id = '$posts' and userid = '$id'");
		echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Бан на форуме
if ($_GET['func'] == 'banforum') {
    $id = intval($_POST['id']);
    $usinfo = mysql_fetch_array(mysql_query("SELECT blockforum, user_status FROM tb_users WHERE id = '$id'"));
    if ($user_status == 'admin' or $user_status == 'moder' and $usinfo['user_status'] != 'admin') {
        if ($usinfo['blockforum'] == 1) {
            mysql_query("UPDATE tb_users SET blockforum = 0 WHERE id = '$id'");
        } else {
            mysql_query("UPDATE tb_users SET blockforum = 1 WHERE id = '$id'");
        }
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Удаление топика
if ($_GET['func'] == 'delpotic') {
    if ($user_status == 'admin') {
        mysql_query("DELETE FROM tb_forum_mes WHERE tid = '" . intval($_POST['id']) . "'");
        mysql_query("DELETE FROM tb_forum_topic WHERE id = '" . intval($_POST['id']) . "'");
        echo 1;
        exit();
    } else {
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Открытие, закрытие топика
if ($_GET['func'] == 'closetopic') {
    if ($user_status == 'admin') {
        $topid = mysql_fetch_array(mysql_query("SELECT topic_close FROM tb_forum_topic WHERE id = '" . intval($_POST['id']) . "'"));
        if ($topid['topic_close'] == 1) {
            $tp = 0;
        } else {
            $tp = 1;
        }
        mysql_query("UPDATE tb_forum_topic SET topic_close = '$tp' WHERE id = '" . intval($_POST['id']) . "'");
        echo 1;
        exit();
    } else {
        exit();
    }
    
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Заказ выплаты
if ($_GET['func'] == 'payuser') {
    if ($finestatus != '0') {
        echo '<div class="erpay"><span>Вы не можете получить выплату. На ваш аккаунт наложен штраф! Пожалуйста, вам необходимо оплатить штраф за нарушение, если вы не согласны с этим, можете покинуть проект, ваш аккаунт будет удален в течение 10 суток.</span></div>';
        exit();
    } else
    if ($blockpay == 1) {
        echo '<div class="erpay"><span>Вы не можете получить выплату. Ваш аккаунт заблокирован на выплату заработанных средств. Пожалуйста, свяжитесь с администрацией сайта по внутренней почте для выяснения обстоятельств.</span></div>';
        exit();
    } else
    $sql2 = mysql_query("SELECT id, username, pemail, ip FROM tb_users WHERE pemail = '$pemail' and pemail != ''");
    if ($lastpay > time()) {
        echo '<div class="erpay"><span>Выплата производится раз в сутки.<br />Последний раз вы получали выплату <b>' . date('d.m.Y H:i', $lastpay-86400) . '</b></span></div>';
        exit();
    } else
    if ($pemail == '') {
        echo '<div class="erpay"><span>У Вас не указан WM кошелек. Пожалуйста, перейдите в личные данные и укажите WM кошелек.</span></div>';
        exit();
    } else {
        if ($reyting >= 1 and $reyting < 10) {
            $maxpay = 5;
        } else
        if ($reyting >= 10 and $reyting < 100) {
            $maxpay = 10;
        } else
        if ($reyting >= 100 and $reyting < 250) {
            $maxpay = 10;
        } else
        if ($reyting >= 250 and $reyting < 600) {
            $maxpay = 50;
        } else
        if ($reyting >= 600 and $reyting < 1000) {
            $maxpay = 100;
        } else
        if ($reyting >= 1000) {
            $maxpay = 200;
        }
        
        if ($money < $payment) {
            echo '<div class="erpay"><span>На вашем счету недостаточно средств. Минимальная сумма для снятия - <b>' . $payment . ' ' . $sitevalname .  '</b></span></div>';
        } else {
		if ($money >= $maxpay) {
            $moneyzakaz = moneyraund($maxpay * 0.992, 2);
            $minusmoney = $maxpay;
        } else {
            $moneyzakaz = moneyraund($money * 0.992, 2);
            $minusmoney = moneyraund($money, 2);
        }
            if ($x2 == 1) {
                require_once "x_2_pay/xml.php";
        		$nameus = $_SESSION["username"];
        
        		$tranid = time();
        		$pursesrc = $sitepurse;
        
        		$pursedest = $pemail;
        		$amount = $moneyzakaz;
        		$period = 0;
        		$pcode = "";
        		$username = $nameus;
        		
        		$comment = $paycomm;
        		$comment = str_ireplace(":sitename:", $sitename, $comment);
        		$desc = str_ireplace(":username:", $username, $comment);
        
        		$wminvid = 0;
                $response = $wmxi->X2(
            		intval($tranid),
            		$pursesrc,
            		$pursedest,
            		floatval($amount),
            		intval($period),
            		trim($pcode),
            		trim($desc),
            		intval($wminvid)
        		);
                $structure = $parser->Parse($response, DOC_ENCODING);
        		$transformed = $parser->Reindex($structure, true);
        		$status = @$transformed["w3s.response"]["retval"];
                $laip = getRealIP();
                mysql_query("INSERT INTO tb_payme (username, pemail, money, ip, datetime) VALUES('$_SESSION[iduser]','$pemail','$amount','$laip','" . time() . "')");
                if ($status == "0") {
                    if ($minusmoney >= 10) {
                        $addrey = 0.5;
                    }
                    $getrefrey = mysql_fetch_array(mysql_query("SELECT referer FROM tb_users WHERE id = '$_SESSION[iduser]'"));
                    if ($getrefrey['referer'] != 0 and $minusmoney >= 10) {
                        $reyref = 0.2;
                        mysql_query("UPDATE tb_users SET reyting = reyting + '$reyref' WHERE id = '$getrefrey[referer]'");
                    }
                    mysql_query("UPDATE tb_users SET paid = paid + '$amount', money = money - '$minusmoney', lastpay = '" . time() . "' + 86400, reyting = reyting + '$addrey' where id = '$_SESSION[iduser]'");
                    mysql_query("INSERT INTO tb_history (user, date, amount, method, status) VALUES('$_SESSION[iduser]','". time() . "','$amount','WebMoney','Выплата сделана')");
					mysql_query("UPDATE tb_payx SET sumpay = sumpay + '$amount' WHERE id = '1'");
                    mysql_query("INSERT INTO tb_allhistory (idus,data,doing,title) values ('$_SESSION[iduser]','" . time() . "','5','Выплата WebMoney на сумму <b>$amount $sitevalname</b>')");
                    mysql_query("DELETE FROM tb_payme WHERE username='$_SESSION[iduser]'");
                    echo '<div class="okpay">Выплата прошла успешно!</div>';
                    exit();
                } else {
                    mysql_query("UPDATE tb_users SET money = money - '$minusmoney', lastpay = '" . time() . "' + 86400 where id = '$_SESSION[iduser]'");
                    echo '<div class="erpay"><span>Произошла ошибка. Свяжитесь с администрацией сайта.</span></div>';
                    exit();
                }
            } else
            if ($minusmoney == 0 or $moneyzakaz == 0) {
                echo '<div class="erpay"><span>Произошла ошибка! Попробуйте еще раз</span></div>';
                exit();
            } else {
                $laip = getRealIP();
                mysql_query("UPDATE tb_users SET money = money - '$minusmoney' where id = '$_SESSION[iduser]'");
                mysql_query("INSERT INTO tb_payme (username, pemail, money, ip, datetime) VALUES('$_SESSION[iduser]','$pemail','$moneyzakaz','$laip','" . time() . "')");
                echo '<div class="okpay">Ваш заказ принят! Вы получите свои деньги после проверки Вашего аккаунта.</div>';
                exit();
            }
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Добавление сайта в каталог
if ($_GET['func'] == 'addcat') {
    $desc = check_text($_POST['description']);
    $desc = substr($desc, 0, 55);
    $url = check_text($_POST['url']);
    $ask_desc = check_text($_POST['ask_desc']);
    $ask_desc = substr($ask_desc, 0, 300);
    $prov = mysql_fetch_array(mysql_query("SELECT id, cat FROM catalog_id WHERE id = '" . intval($_POST['category']) . "'"));
    if ($points <= 0) {
        exit();
    } else
    if ($prov['id'] == '') {
        echo 'Каталог не существует';
        exit();
    } else
    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', $url)) {
        echo 'Указан неправильный URL';
        exit();
    } else
    if ($desc == '') {
        echo 'Укажите заголовок ссылки';
        exit();
    } else
    if ($ask_desc == '') {
        echo 'Укажите описание для сайта';
        exit();
    } else {
        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', $url, $out);
        mysql_query("INSERT INTO catalog_mes (cat, cat_id, data, full_text, description, url) VALUES ('$prov[cat]', '$prov[id]', '" . time() . "', '$ask_desc', '$desc', '$out[0]')") or die(mysql_error());
        mysql_query("UPDATE tb_users SET points = points - 1 WHERE id = '" . $_SESSION['iduser'] . "'");
        mysql_query("UPDATE catalog SET idcount = idcount + 1 WHERE id = '$prov[cat]'");
        mysql_query("UPDATE catalog_id SET idcount = idcount + 1 WHERE id = '$prov[id]'");
        echo 1;
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//перевод средств с одной площадки на другую
if ($_GET['func'] == 'sendbal') {
    $tid = intval($_POST['id']);
    $serf = intval($_POST['serf']);
    $idserf = intval($_POST['idserf']);
    $money = moneyraund($_POST['money'], 3);
    
    if ($serf == 1) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM tb_ads WHERE id = '$idserf' and fromus = '$_SESSION[iduser]'"));
        $ftype = 'tb_ads';
    } else
    if ($serf == 2) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM seo_paymails WHERE id = '$idserf' and fromid = '$_SESSION[iduser]'"));
        $ftype = 'seo_paymails';
    } else
    if ($serf == 3) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM seo_tasks WHERE id = '$idserf' and fromid = '$_SESSION[iduser]'"));
        $ftype = 'seo_tasks';
    } else
    if ($serf == 4) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM tb_statlinks WHERE id = '$idserf' and fromus = '$_SESSION[iduser]'"));
        $ftype = 'tb_statlinks';
    } else
    if ($serf == 5) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM tb_advban WHERE id = '$idserf' and fromus = '$_SESSION[iduser]'"));
        $ftype = 'tb_advban';
    } else    
	if ($serf == 6) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM tb_advban_100 WHERE id = '$idserf' and fromus = '$_SESSION[iduser]'"));
        $ftype = 'tb_advban_100';
    } else    
	if ($serf == 7) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM tb_advban_300 WHERE id = '$idserf' and fromus = '$_SESSION[iduser]'"));
        $ftype = 'tb_advban_300';
    } else 
	if ($serf == 8) {
        $type = mysql_fetch_array(mysql_query("SELECT id FROM cep_links WHERE id = '$idserf' and fromus = '$_SESSION[iduser]'"));
        $ftype = 'cep_links';
    } else {
        echo 'Ошибка';
        exit();
    }
    
    if ($_POST['functype'] == 'dyn') {
        $tidsql = mysql_query("SELECT balance FROM tb_ads WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE tb_ads SET balance = balance - '$money' WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    } else
    if ($_POST['functype'] == 'pm') {
        $tidsql = mysql_query("SELECT balance FROM seo_paymails WHERE id = '$tid' and fromid = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE seo_paymails SET balance = balance - '$money' WHERE id = '$tid' and fromid = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    } else
    if ($_POST['functype'] == 'task') {
        $tidsql = mysql_query("SELECT balance FROM seo_tasks WHERE id = '$tid' and fromid = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE seo_tasks SET balance = balance - '$money' WHERE id = '$tid' and fromid = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    } else
    if ($_POST['functype'] == 'statlink') {
        $tidsql = mysql_query("SELECT balance FROM tb_statlinks WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE tb_statlinks SET balance = balance - '$money' WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    } else
    if ($_POST['functype'] == 'ban1') {
        $tidsql = mysql_query("SELECT balance FROM tb_advban WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE tb_advban SET balance = balance - '$money' WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    } else
    if ($_POST['functype'] == 'ban2') {
        $tidsql = mysql_query("SELECT balance FROM tb_advban_100 WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE tb_advban_100 SET balance = balance - '$money' WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    } else
    if ($_POST['functype'] == 'ban3') {
        $tidsql = mysql_query("SELECT balance FROM tb_advban_300 WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE tb_advban_300 SET balance = balance - '$money' WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    } else   
	if ($_POST['functype'] == 'cep') {
        $tidsql = mysql_query("SELECT balance FROM cep_links WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
        $dynrow = mysql_fetch_array($tidsql);
        if (mysql_num_rows($tidsql) < 1) {
            echo 'Рекламная площадка не существует';
            exit();
        } else
        if ($type['id'] == '') {
            echo 'Рекламная площадка не существует или она не принадлежит Вам';
            exit();
        } else
        if (!is_numeric($money)) {
            echo 'Неверная сумма';
            exit();
        } else
        if ($money > $dynrow['balance'] or $money < 0) {
            echo 'На рекламной площадке нет такой суммы';
            exit();
        } else {
            mysql_query("UPDATE cep_links SET balance = balance - '$money' WHERE id = '$tid' and fromus = '$_SESSION[iduser]'");
            mysql_query("UPDATE $ftype SET balance = balance + '$money' WHERE id = '$type[id]'");
            echo 1;
            exit();
        }
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Приветствие рефералу
if ($_GET['func'] == 'addgreeting') {
    $mess = $_POST['mess'];
    $mess = check_text($mess);
    $mess = htmlspecialchars($mess);
    $mess = substr($mess, 0, 300);
    $autoback = intval($_POST['autoback']);
    if ($finestatus != '0') {
        echo 'На ваш аккаунт наложен штраф! Вы не можете редактировать привествие!';
        exit();
    } else
    if ($autoback < 0 or $autoback > 90) {
        echo 'Неверное значение';
        exit();
    } else {
        mysql_query("UPDATE tb_users SET autoback = '$autoback' WHERE id = '" . $_SESSION['iduser'] . "'");
        mysql_query("UPDATE tb_users SET greeting = '$mess' WHERE id = '$_SESSION[iduser]'");
        echo 'Данные сохранены';
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------
//Рассылка рефералам
if ($_GET['func'] == 'addmasref') {
    $mess = $_POST['mess'];
    $mess = iconv('UTF-8', 'windows-1251', $mess);
	$mess = check_text($mess);
    $mess = htmlspecialchars($mess);
    $mess = substr($mess, 0, 150);
    
    $sql = mysql_fetch_array(mysql_query("SELECT count(id) as count FROM tb_users WHERE referer = '$_SESSION[iduser]'"));
    $refmasmoney = $sql['count'] * 0.005;
    
    $sql2 = mysql_query("SELECT id FROM masref WHERE userid = '$_SESSION[iduser]'");
    
	if ($finestatus != '0') {
        echo 'На ваш аккаунт наложен штраф! Вы не можете делать рассылку!';
        exit();
    } else
    if (mysql_num_rows($sql2) > 0) {
        echo 'Еще не закончилась предыдущая рассылка';
        exit();
    } else
    if ($mess == '') {
        echo 'Не указан текст сообщения';
        exit();
    } else
    if ($refmasmoney > $admoney) {
        echo 'Недостаточно средст на балансе';
        exit();
    } else {
        $time = time() + (86400 * 2);
        mysql_query("INSERT INTO masref (userid, mess, date, money, active) VALUES ('$_SESSION[iduser]', '$mess', '$time', '$refmasmoney','0')");
        mysql_query("UPDATE tb_users SET admoney = admoney - '$refmasmoney' WHERE id = '$_SESSION[iduser]'");
        echo 'Рассылка будет размещена после модерации';
        exit();
    }
}
//-------------------------------------------------------------------------------------------------------------------------------------------

//Разбудить рефералов
if ($_GET['func'] == 'senwake') {
    $kol = intval($_POST['col']);
    $endday = time() - (86400 * 20);
    $wakeprice = 0.03;
    $moneywake = $kol * $wakeprice;

    $sql = mysql_fetch_array(mysql_query("SELECT count(id) as count FROM tb_users WHERE '$endday' > lastlogdate and referer = '$_SESSION[iduser]'"));

	if ($finestatus != '0') {
        echo 'На ваш аккаунт наложен штраф! Данная функция для вас заблокирована!';
        exit();
    } else    
    if ($kol <= 0 or $kol > $sql['count']) {
        echo 'Неверное кол-во рефералов';
        exit();
    } else
    if ($kol * $wakeprice > $admoney) {
        echo 'На Вашем балансе недосточно средств';
        exit();
    } else {
        $sql2 = mysql_query("SELECT username, email FROM tb_users WHERE '$endday' > lastlogdate and referer = '$_SESSION[iduser]' and wake = 0 LIMIT $kol");
        while ($row = mysql_fetch_array($sql2)) {

            $headers = "Reply-To: $siteemail\r\n";
        	//версия mime
        	$headers .= "MIME-Version: 1.0\r\n";
        	if (preg_match("/@[a-z0-9]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i", $row['email'])) {
                $headers  .= "Content-type: text/html; charset=UTF-8 \r\n";
            } else {
                $headers  .= "Content-type: text/html; charset=windows-1251 \r\n";
            }
        	//следует указать 8бит для русских символов
        	$headers .= "Content-Transfer-Encoding: 8bit\r\n";
            $headers .= "From: <$siteemail> \r\n";
            $subject = $sitename . ' - рассылка';
            $message = '
            <html>
            <head>
            <title>Информация ' . $sitename . '</title>
            <style type="text/css">
            html, body {
                margin:0;
                margin-left:5px;
                padding:0;
                font-size:14px;
            }
            p {
                margin:0;
                padding:3px;
            }
            </style>
            </head>
            <body>
            <p><b>Здравствуйте ' . $row["username"] . '</b>.</p>
            <p>--------------------------------------------------------------------------</p>
            <p>Вы давно не посещали сайт <a href="http://' . $_SERVER["HTTP_HOST"] . '">' . $sitename . '</a>. За время Вашего отсутсвия произошли значительные изменения и улучшения</p>
            <p>--------------------------------------------------------------------------</p>
            </body>
            </html>';
            if (mail($row['email'], $subject, $message, $headers)) {
                mysql_query("UPDATE tb_users SET wake = 1 WHERE email = '$row[email]'");
                mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (9, '$wakeprice', '" . date('m', time()) . "', '" . date('Y', time()) . "')");
                mysql_query("UPDATE tb_users SET admoney = admoney - '$wakeprice' WHERE id = '$_SESSION[iduser]'");
            }
        }
        echo 1;
        exit();
    }
}
///-------------------------------------------------------------------------------------------------------------------------------------------

///Яблоко рейтинга
if ($_GET['func'] == 'addreyting'){
    if ($finestatus != '0') {
        echo 'Внимание! На ваш аккаунт наложен штраф! Вы не можете получать бонус рейтинга!';
        exit();
    } else
    if(date("d.m.Y")!=@mysql_result(mysql_query("SELECT datere FROM tb_users WHERE id='$_SESSION[iduser]'"),0,0)){
        $ratingplus=1;
        mysql_query("update tb_users set reyting=reyting+'$ratingplus',datere='".date("d.m.Y",time())."' WHERE id='$_SESSION[iduser]'");
        echo 1;
        exit();
    } else {
	echo 'Ошибка, вы сегодня уже получали бонус!';
	exit();
	}
}
///-------------------------------------------------------------------------------------------------------------------------------------------

///Доска почета
if ($_GET['func'] == 'addhaloffamesx'){
    if ($finestatus != '0') {
        echo 'Внимание! На ваш аккаунт наложен штраф! Вы не можете участвовать в доске почета!';
        exit();
    } else
    if($_SESSION['iduser'] != @mysql_result(mysql_query("SELECT idlider FROM doska_status WHERE id='1'"),0,0)){
	    #Вытягиваем нужные данные
	    $ratingplus=1;
        $stavka_of_fame = mysql_fetch_array(mysql_query("SELECT stavka_of_fame FROM tb_config WHERE id = '1'"));
		$user_data = mysql_fetch_array(mysql_query("SELECT * FROM tb_users WHERE id = '$_SESSION[iduser]'"));
		$fame_x1 = mysql_fetch_array(mysql_query("SELECT * FROM doska_status WHERE id = '1'"));
		if ($stavka_of_fame['stavka_of_fame'] < $user_data['admoney'] ) 
		{
		    #Обновляем данные о конкурсе
			mysql_query("update tb_users set admoney=admoney-'".$stavka_of_fame['stavka_of_fame']."', reyting=reyting+'$ratingplus' WHERE id='$_SESSION[iduser]'");
		    mysql_query("update doska_status set idlider='".$_SESSION['iduser']."',idlider2='".$_SESSION['iduser']."',bank=bank+'".$stavka_of_fame['stavka_of_fame']."',status='1',hislo_stavok=hislo_stavok+'1' WHERE id='1'");
		    if ($fame_x1['datestart'] == 0) { mysql_query("update doska_status set datestart='".time()."' WHERE id='1'"); }
			#Сообщаем о том что процеc прошел успешно
		    echo 1; 
            exit();
		} else {
		    echo 'На вашем рекламном счету недостаточно средств!';
            exit();
		}
    } else {
		    echo 'Вы уже на доске почета!';
            exit();
	}
}
///-------------------------------------------------------------------------------------------------------------------------------------------

/// Перевод с рабочего на рекламный счет
if ($_GET['func'] == 'moneyexc'){
    $exmoney = floatval($_POST["excsum"]);
    if ($exmoney < 0.01) {
        echo 'Сумма указана не коректно, минимальная сумма пополнения 0.01 руб.';
        exit();
    } else
    if ($exmoney > $money) {
        echo 'Недостаточно средств на рабочем счету';
        exit();
    } else {
        mysql_query("update tb_users set money=money-'$exmoney', admoney=admoney+'$exmoney' WHERE id='$_SESSION[iduser]'");
		mysql_query("INSERT INTO tb_allhistory (idus,data,doing,title) values ('$_SESSION[iduser]','".time()."','4','Перевод средств с рабочего на рекламный счет, сумма $exmoney руб.')");
        echo 1;
        exit();
    }
}
///-------------------------------------------------------------------------------------------------------------------------------------------

/// Создание конкурса рефералов
if ($_GET['func'] == 'addrefcom') {
    #получаем данные и экранипуем их на запрещеные символы.
    $mess = $_POST['mess'];
    $mess = check_text($mess);
    $mess = htmlspecialchars($mess);
    $mess = substr($mess, 0, 300);    
	$tems = $_POST['tems'];
    $tems = check_text($tems);
    $tems = htmlspecialchars($tems);
    $tems = substr($tems, 0, 50);
    $comtype = intval($_POST['comtype']);
    $comdate = intval($_POST['comdate']);
    $commin = intval($_POST['commin']);
    $comrefprize1 = intval($_POST['comrefprize1']);
    $comrefprize2 = intval($_POST['comrefprize2']);
    $comrefprize3 = intval($_POST['comrefprize3']);
    #обьявляем переменые, делаем нужные вычисления.
	if($referals >=1) {
	$comrefdublicat = mysql_query("SELECT id FROM konkurs_ref WHERE type = '$comtype' AND status = '1' AND referername = '" . $_SESSION['iduser'] . "'");
    if($tems != '') {
	    if (mysql_num_rows($comrefdublicat) < 1) {
		    if($comtype == 1 OR $comtype == 2 OR $comtype == 3) {
				$comrefdateend = (($comdate*86400)+time());
				if($comrefdateend > time()+86300) {
					if($commin >= 1 AND $commin < 501) {
						if($comrefprize1 >= 1 AND $comrefprize2 >= 1 AND $comrefprize3 >= 1) {
							if($mess != '') {
								$comrefbalance = (($comrefprize1 + $comrefprize2 + $comrefprize3)* 1.05);
								$comrefbalance_d = ($comrefprize1 + $comrefprize2 + $comrefprize3);
								$comrefbalance_d_s = ($comrefbalance - $comrefbalance_d);
								$comrefbalance_d_s_v = check_text($comrefbalance);
								$comrefbalance_d_s_v = htmlspecialchars($comrefbalance);
								if($comrefbalance < $admoney) {
									mysql_query("update tb_users set admoney=admoney-'$comrefbalance' WHERE id='$_SESSION[iduser]'");
									mysql_query("INSERT INTO konkurs_ref (balance,name,description,type,start_date,end_date,min_type,comrefprice1,comrefprice2,comrefprice3,status,referername) values ('$comrefbalance_d','$tems','$mess','$comtype','".time()."','".$comrefdateend."','$commin','$comrefprize1','$comrefprize2','$comrefprize3','1','$_SESSION[iduser]')");
									mysql_query("INSERT INTO tb_viruchka (ident, money, month, year) VALUES (12, '$comrefbalance_d_s', '" . date('m', time()) . "', '" . date('Y', time()) . "')");
									echo 1;
									exit();
								} else {
									echo 'Недостаточно средств на рекламном счету! <br> У вас должна быть сумма '.$comrefbalance_d_s_v.' руб.';
									exit();
								}
							} else {
								echo 'Укажите описание конкурса!';
								exit();
							}	
						} else {
							echo 'Ошибка в заполнение призовых мест! Минимум 1 руб за каждое место.';
							exit();
						}
					} else {
						echo 'Минимум для участия 1, максимум 500! ';
						exit();
					}
				} else {
					echo 'Нарушение алгоритма функции, в доступе отказано!';
					exit();
				}														
			} else {
				echo 'Нарушение алгоритма функции, в доступе отказано!';
				exit();
			}		
		} else {
			echo 'Вы уже создавали конкурс такого типа, нельзя создавать конкурсы одинаковых типов одновремено! Дождитесь завершения ране созданого!';
			exit();
		}					
	} else {
		echo 'Укажите название конкурса!';
		exit();
	}	
	} else {
		echo 'У вас нет ни одного реферала, поэтому конкурс создавать не для кого!';
		exit();
	}
}			
//-------------------------------------------------------------------------------------------------------------------------------------------

//Заказ выплаты паеер
if ($_GET['func'] == 'payuserpr') { 
    if ($finestatus != '0') {
        echo '<div class="erpay"><span>Вы не можете получить выплату. На ваш аккаунт наложен штраф! Пожалуйста, вам необходимо оплатить штраф за нарушение, если вы не согласны с этим, можете покинуть проект, ваш аккаунт будет удален в течение 10 суток.</span></div>';
        exit();
    } else
    if ($blockpay == 1) {
        echo '<div class="erpay"><span>Вы не можете получить выплату. Ваш аккаунт заблокирован на выплату заработанных средств. Пожалуйста, свяжитесь с администрацией сайта по внутренней почте для выяснения обстоятельств.</span></div>';
        exit();
    } else
    $sql2 = mysql_query("SELECT id, username, payeers, ip FROM tb_users WHERE payeers = '$payeer' and payeers != ''");
    if ($lastpay > time()) {
        echo '<div class="erpay"><span>Выплата производится раз в сутки.<br />Последний раз вы получали выплату <b>' . date('d.m.Y H:i', $lastpay-86400) . '</b></span></div>';
        exit();
    } else
    if ($payeer == '') {
        echo '<div class="erpay"><span>У Вас не указан Payeer кошелек. Пожалуйста, перейдите в личные данные и укажите Payeer кошелек.</span></div>';
        exit();
    } else { 
        if ($reyting >= 1 and $reyting < 10) {
            $maxpay = 5;
        } else
        if ($reyting >= 10 and $reyting < 100) {
            $maxpay = 10;
        } else
        if ($reyting >= 100 and $reyting < 250) {
            $maxpay = 10;
        } else
        if ($reyting >= 250 and $reyting < 600) {
            $maxpay = 50;
        } else
        if ($reyting >= 600 and $reyting < 1000) {
            $maxpay = 100;
        } else
        if ($reyting >= 1000) {
            $maxpay = 200;
        }
        
        if ($money < $payment) {
            echo '<div class="erpay"><span>На вашем счету недостаточно средств. Минимальная сумма для снятия - <b>' . $payment . ' ' . $sitevalname .  '</b></span></div>';
        } else { 
		
			if ($money >= $maxpay) {
                $moneyzakaz = moneyraund($maxpay, 2);
                $minusmoney = $maxpay;
            } else {
                $moneyzakaz = moneyraund($money, 2);
                $minusmoney = $money;
            }
            
                if($moneyzakaz == '')  
				{  
					echo '<div class="erpay"><span> Некорректный ввод суммы выплаты! </span></div> </fieldset>';  
					exit();  
				} else { 
			
					if($money<=0)
					{
						echo '<div class="erpay"><span> Ваш рабочем счет пуст. Заказ выплаты невозможен!!!  </span></div> </fieldset>';
						exit();
					} else {
						if ($moneyzakaz<$payment)
						{
							echo '<div class="erpay"><span> На вашем рабочем не набрана минимальная для вывода сумма!!!  </span></div> </fieldset>';
							exit();
						} else {
							$checkuser = mysql_query("SELECT username FROM tb_payme WHERE username='$_SESSION[iduser]'");
							$username_exist = mysql_num_rows($checkuser);
							if ($username_exist>0) {
								echo '<div class="erpay"><span> Вы уже заказали выплату. После того как Ваш заказ будет выполнен, Вы сможете снова заказать выплату.  </span></div> </fieldset>';
								exit();
							} else {
								include('cpayeer.php'); /// ip 78.47.80.105
								$accountNumber = 'P10602939'; /// Кошелек пользователя
								$payer_user = $byme['payeers'];
								$apiId = '93979068';         /// API ID пользователя
								$apiKey = '4qzn1S06faSZlZmA';   /// Пароль пользовтаеля
								$payeer = new CPayeer($accountNumber, $apiId, $apiKey);
								///echo 1111111;
								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+1)) {
											$arTransfer = $payeer->transfer(array(
											'curIn' => 'RUB', // счет списания 
											'sum' => $moneyzakaz, // Сумма получения 
											'curOut' => 'RUB', // валюта получения  
											'to' => $payer_user,  // Получатель (Номер счета)
											'comment' => 'Payment to - '.$url.'',
											));
											if (!empty($arTransfer["historyId"]))
											{
												echo '<div class="okpay"><span>Выплата ID'.$arTransfer["historyId"].' успешно обработана, деньги выплачены! </span></div> </fieldset>';
												$laip=getRealIP();
												$dt=date("d.m.Y H:i:s");
												$dtsxc = time()+86400;
								
												mysql_query("UPDATE tb_users SET paid = paid + '$moneyzakaz', lastpay = '$dtsxc' WHERE id = '$_SESSION[iduser]'");
												mysql_query("INSERT INTO tb_payme (user, date, amount, method, status) VALUES('$_SESSION[username]','". time() . "','$moneyzakaz','PAYEER','Выплата сделана')");
												mysql_query("INSERT INTO tb_allhistory (idus,data,doing,title) values ('$_SESSION[iduser]','" . time() . "','5','Выплата PAYEER на сумму <b>$moneyzakaz $sitevalname</b>')");
												mysql_query("INSERT INTO tb_history (user, date, amount, method, status) VALUES('$_SESSION[iduser]','". time() . "','$moneyzakaz','Payeer','Выплата сделана')");
												mysql_query("UPDATE tb_payx SET sumpay = sumpay + '$moneyzakaz' WHERE id = '1'");
												$rating=$moneyzakaz*0.10; // рейтинг
												$sql="update tb_users set money=money-'$moneyzakaz',reyting=reyting+'$rating' where id='$_SESSION[iduser]'";
												mysql_query($sql) or die(mysql_error());$allsqls++;										
												exit();
											} else {
												echo '<div class="erpay"><span> Не верный кошелек, обратитесь к администрации! </span></div> -  - </fieldset>'; exit();		
											}
										} else { 
											echo '<div class="erpay"><span> Ошибка системы, обратитесь к администрации! </span></div> -  - </fieldset>'; exit(); 
										}
									} else {
										echo '<pre>'.print_r($payeer->getErrors(), true).'</pre>';
									}
									
								} else { 
									echo '<div class="erpay"><span> Внимание! Не вернный кошелек. Обратитесь в администрацию </span></div> -  - </fieldset>'; exit(); 
								}		
							}
						}
					}
				}
			
		}
	}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
?>