<?php
session_start();
require_once 'config.php';
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///                                                 Веб-студия (Rostik-Soft) (c)(r) 2013-2013                                                                ///
///  Крон задач для чистки таблиц от мусора, по дате, и различнм условиям. Если вы являетесь администратором, при этом не розбираетесь в программирование    ///
///  советуем вам закрить этот файл и обратится в тех поддержку Ростикс ICQ 643780703, Skype morgan_rostik, Wmid 296118676167, Email rostiksss@ukr.net       ///
///                                                                                                                                                          ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$res=mysql_fetch_array(mysql_query("SELECT * FROM tb_config WHERE id=1"));
$payment = $res["payment"];
$maxautopay = $res["maxautopay"];
$finesummam = $res["fine"];
$refererbonus = $res["refererbonus"];
$timer5 = $res["timer5"];
$obperehod = $res["obperehod"];
$hits = $res["hits"];
$hits5 = $res["hits5"];
$hits10 = $res["hits10"];
$hldyn = $res["hldyn"];
$advstatlink = $res['advstatlink'];
$advcep = $res['advcep'];
$advbanner = $res['advbanner'];
$advbanner2 = $res['advbanner2'];
$advbanner3 = $res['advbanner3'];
$mprice = $res['mprice'];
$pmtimer = $res['mtimer'];
$pmobper = $res['mobper'];
$pmhighlight = $res['mhighlight'];
$payuser = mysql_fetch_array(mysql_query("SELECT * FROM tb_price WHERE id = 1"));
$sql1 = mysql_query("SELECT * FROM tb_site WHERE id='1'") or die(mysql_error());
$o = mysql_fetch_array($sql1);
$sitename = $o["sitename"];
$sitewmid = $o["wmid"];
$siteicq = $o["icq"];
$siteemail = $o["email"];
$sitepurse = $o["purse"];
$siteval = $o["valuta"];
$sitetak = $o["sitetak"];
$x2 = $o["x2"];
$x6=$o["x6"];
$rpass1 = $o["robopass1"];
$rpass2 = $o["robopass2"];
$rlogin = $o["robologin"];
$sitevalname = $o["valutaname"];
$sitestartdate = $o["startdate"];
$merchant = $o["merchant"];
$timerpay = $o["timerpay"];
$payvisits = $o["visits"];
$payforday = $o["payforday"];
$takclick = $o["takclick"];
$sitehost=$_SERVER["HTTP_HOST"];
$siteurl="http://$sitehost";
$paycomm = $o["comment"];
$modered = $o['modered'];

$ip = getrealip(); 

$res = mysql_query("select count(*) as kolvo from tb_accessblock where ip like '$ip%'");
$res = mysql_fetch_array($res);										 
if ($res["kolvo"] > 0) {													  
	echo "Вашему IP заблокирован доступ к сайту";    
	exit();												  
}													  	

if (isset($_SESSION["username"])) {
$sql2 = mysql_query("SELECT * FROM tb_users WHERE id='" . $_SESSION['iduser'] . "'");
$byme = mysql_fetch_array($sql2);
$username = $byme["username"];
$passwd = $byme["password"];
$pemail = $byme["pemail"];
$payeer = $byme["payeers"];
$referer = $byme["referer"];
$referer2 = $byme["referer2"];
$country = $byme["country"];
$forumblock_date = $byme["forumblock_date"];
$user_status = $byme["user_status"];
$visits = $byme["visits"];
$maccess = $byme['mailaccess'];
$family = $byme['family'];
$finestatus = $byme['finestatus'];
$fine_text = $byme['fine_text'];
$doing = $byme['doing'];
$lastpay = $byme["lastpay"];
$ref1 = mysql_fetch_array(mysql_query("SELECT count(*) as count FROM tb_users WHERE referer = '" . $_SESSION['iduser'] . "'"));
$ref2 = mysql_fetch_array(mysql_query("SELECT count(*) as count FROM tb_users WHERE referer2 = '" . $_SESSION['iduser'] . "'"));
$referals = $ref1['count'];
$referals2 = $ref2['count'];
$toref1 = mysql_fetch_array(mysql_query("SELECT sum(toref) as sum FROM tb_users WHERE referer = '" . $_SESSION['iduser'] . "'"));
$toref2 = mysql_fetch_array(mysql_query("SELECT sum(toref2) as sum FROM tb_users WHERE referer2 = '" . $_SESSION['iduser'] . "'"));
$toreferals1 = $toref1['sum'];
$toreferals2 = $toref2['sum'];
$money = $byme["money"];
$admoney = $byme["admoney"];
$blockpay = $byme["blockpay"];
$golos = $byme['golos'];
$paid = $byme["paid"];
$email = $byme["email"];
$joindate = $byme["joindate"];
$lastlogdate = $byme["lastlogdate"];
$lastiplog = $byme["lastiplog"];
$wmid = $byme["wmid"];
$blockip = $byme["blockip"];
$refbonuson = $byme["refbonuson"];
$avatar = $byme["avatar"];
$avatar = "avp/" . $avatar;
$mailaccess = $byme['mailaccess'];
$taskreyt = $byme['taskreyt'];
$reyting = $byme['reyting'];
$autoback = $byme['autoback'];
$autobonus = $byme['refbonus'];
$blockforum = $byme['blockforum'];
$actcode = $byme['actcode'];
$keyok = $byme['keyok'];
$refsite = $byme['refsite'];

if ($finestatus != '0') {
    $rey = 'Штрафник';
}
if ($pemail == '' AND $finestatus == '0') {
    $rey = 'Прохожий';
}
if ($reyting >= 1 AND $reyting < 10 AND $pemail != '' AND $finestatus == '0') {
    $rey = 'Стажер';
}
if ($reyting >= 10 AND $reyting < 100 AND $pemail != '' AND $finestatus == '0') {
    $rey = 'Рабочий';
}
if ($reyting >= 100 AND $reyting < 250 AND $pemail != '' AND $finestatus == '0') {
    $rey = 'Бригадир';
}
if ($reyting >= 250 AND $reyting < 600 AND $pemail != '' AND $finestatus == '0') {
    $rey = 'Мастер';
}
if ($reyting >= 600 AND $reyting < 1000 AND $pemail != '' AND $finestatus == '0') {
    $rey = 'Бизнесмен';
}
if ($reyting >= 1000 AND $pemail != '' AND $finestatus == '0') {
    $rey = 'Гуру';
}
}
$points = $byme['points'];
$podarki = 40;
/// ----------------------------------------------------------------------------------------------------------------

/// Удаление V.I.P задания*/
    mysql_query( "UPDATE seo_tasks SET inblock = '' WHERE inblock <= '" . time() . "'" );
/// ----------------------------------------------------------------------------------------------------------------

/// Удаление реферала из бронирования
    $idrefb = mysql_query("SELECT ident FROM seo_basket WHERE time < '" . time() . "' - 3600 and type = 4");
    while ($refrow = mysql_fetch_array($idrefb)) {
    mysql_query("UPDATE seo_refbirj SET bron = 0 WHERE rid = '" . $refrow['ident'] . "'");
    mysql_query("DELETE FROM seo_basket WHERE ident = '" . $refrow['ident'] . "' and type = 4");
    }
/// ----------------------------------------------------------------------------------------------------------------

/// Удаление корзины
    mysql_query("DELETE FROM seo_basket WHERE time < '" . time() . "' - 86400 and type != 4");
/// ----------------------------------------------------------------------------------------------------------------

/// Автоматическая оплата задания
    $autask = mysql_query("SELECT id, ident, fromid FROM seo_taskstats WHERE anstime < '" . time() . "' - 86400 * 3 and status = 0");
    while ($aurow = mysql_fetch_array($autask)) {
    $bablotask = mysql_fetch_array(mysql_query("SELECT price, balance FROM seo_tasks WHERE id = '" . $aurow['ident'] . "'"));
    mysql_query("UPDATE seo_taskstats SET status = 1, anstime = '" . time() . "' WHERE  id = '" . $aurow['id'] . "'");
    if ($bablotask['balance'] >= $bablotask['price']){
        $moneytask = $bablotask['price'] * 5 / 6;
        mysql_query("UPDATE tb_users SET money = money + '$moneytask', taskreyt = taskreyt + 1 WHERE id = '" . $aurow['fromid'] . "'");
        mysql_query("UPDATE seo_tasks SET goods = goods + 1, waits = waits - 1, balance = balance - price WHERE id = '" . $aurow['ident'] . "'");
    $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 = '" . $aurow['fromid'] . "' and typ = 1");
    } else {
    mysql_query("UPDATE seo_tasks SET waits = waits - 1 WHERE id = '" . $aurow['ident'] . "'");
    mysql_query("UPDATE seo_taskstats SET status = 1, anstime = '" . time() . "' WHERE  id = '" . $aurow['id'] . "'");
    }
    }
/// ----------------------------------------------------------------------------------------------------------------

/// Удаление просроченных начатых заданий*/
    $gettaskstats = mysql_query("SELECT ident FROM seo_taskstats WHERE status = 3 and endtime < '" . time() . "'");
    while ($rowtask = mysql_fetch_array($gettaskstats)) {
    mysql_query("UPDATE seo_tasks SET works = works - 1 WHERE id = '$rowtask[ident]'");
    mysql_query("DELETE FROM seo_taskstats WHERE status = 3 and endtime < '" . time() . "'");
    }
/// ----------------------------------------------------------------------------------------------------------------

/// Удаление рассылки рефералов
    mysql_query("DELETE FROM masref WHERE active = 1 and date <= '" . time() . "'");
/// ----------------------------------------------------------------------------------------------------------------

/// Приостановление рекламных площадок
    mysql_query("UPDATE tb_ads SET paused = 1 WHERE balance < price and paused = 0");
    mysql_query("UPDATE seo_paymails SET paused = 1 WHERE balance < price and paused = 0");
    mysql_query("UPDATE seo_tasks SET paused = 1 WHERE balance < price and paused = 0");
    mysql_query("UPDATE tb_advban SET paused = 1 WHERE balance < price and paused = 0");
    mysql_query("UPDATE tb_advban_100 SET paused = 1 WHERE balance < price and paused = 0");
    mysql_query("UPDATE tb_advban_300 SET paused = 1 WHERE balance < price and paused = 0");
    mysql_query("UPDATE tb_statlinks SET paused = 1 WHERE balance < price and paused = 0");
	mysql_query("UPDATE cep_links SET paused = 1 WHERE balance < price and paused = 0");
/// ----------------------------------------------------------------------------------------------------------------

/// Удаляем кто онлайн
    mysql_query("DELETE FROM online WHERE date+150 < '".time()."' ");
/// ---------------------------------------------------------------------------------------------------------------	

/// Крон
    if ($user_status == 'admin') {
    $kron_if =  mysql_fetch_array( mysql_query( "SELECT timekron FROM tb_payx WHERE `id` = '1'" ));
	$dewff = $kron_if['timekron'];
    if ($dewff < (time()-86400)) { require_once 'cronxs.php'; } } else {  mysql_query("DELETE FROM online WHERE date+150 < '".time()."' "); }
/// ---------------------------------------------------------------------------------------------------------------	

/// Определяем победители доски почета и выдаем приз
    $fame_end = mysql_query("SELECT * FROM doska_status WHERE id = '1' and datestart < '".(time()-86400)."' ");
    if(mysql_num_rows($fame_end) > 0) {
        $fame_end_row = mysql_fetch_array($fame_end);
        if($fame_end_row['status'] == 1){
		  /// старт
	        $fame_endu = mysql_fetch_array(mysql_query("SELECT avatar, username, autoback, reyting FROM tb_users WHERE id = '".$fame_end_row['idlider']."'"));
	        $prizz = $fame_end_row['bank']*0.90;
	        mysql_query("UPDATE tb_users SET money = money+'$prizz' WHERE id = '".$fame_end_row['idlider']."'");
			$titx = "Поздравляем вы выиграли в конкурсе доски почета, вам зачислен приз в размере $prizz Руб.";
            mysql_query("INSERT INTO tb_allhistory (idus,data,doing,title) values ('".$fame_end_row['idlider']."','".time()."', '7', '$titx')");
			mysql_query("INSERT INTO doska_stat (status,namelider,dateend,banks,hislo_stavok) values ('1','".$fame_endu['username']."', '".time()."', '$prizz', '".$fame_end_row['hislo_stavok']."')");
			mysql_query("UPDATE doska_status SET status = '0', hislo_stavok= '0', bank='0', idlider='0', datestart='0'  WHERE id = '1'");
		  /// завершение
	    }
    } else {  mysql_query("DELETE FROM online WHERE date+150 < '".time()."' "); }
/// ----------------------------------------------------------------------------------------------------------------

/// Останавливаем акцию проекта по истечению даты
    $promotion_end = mysql_query("SELECT * FROM promotion_status WHERE id = '1' AND dateend < '".time()."' AND status = '1' ");
    if(mysql_num_rows($promotion_end) > 0) {
        $promotion_end_row = mysql_fetch_array($promotion_end);
	    if($promotion_end_row['status'] == 1){
	        mysql_query("UPDATE promotion_status SET description = '', texto = '', dateend = '0', prom1 = '0', prom2 = '0', prom3 = '0', prom4 = '0', status = '0', datestart = '0' WHERE id = '1'");
		    mysql_query("DELETE FROM promotion_temp WHERE date < '".time()."' ");
	    }
	}
/// ----------------------------------------------------------------------------------------------------------------

/// Статус штрафника
    if (isset($_SESSION["username"])) {
        $fine = mysql_query("SELECT finestatus, id, lastiplog, wmid FROM tb_users WHERE id = '" . $_SESSION['iduser'] . "'");
        if(mysql_num_rows($fine) > 0) {
            $fine_row = mysql_fetch_array($fine);
			if($fine_row['finestatus'] == 0) {
                #IP
			    $check_fine_ip = mysql_fetch_array( mysql_query( "SELECT count(*) as count FROM tb_users WHERE lastiplog = '".$fine_row['lastiplog']."' AND ban = '0' " ) );
                if($check_fine_ip['count'] > 1) {
		            mysql_query("UPDATE tb_users SET finestatus = '1', fine_text = 'Мультиаккаунтинг', datefine = '".time()."' WHERE id = '".$_SESSION['iduser']."'");
			        mysql_query("UPDATE tb_users SET ban = '1', fine_text = 'Мультиаккаунтинг' WHERE lastiplog = '".$fine_row['lastiplog']."' AND id != '".$_SESSION['iduser']."'");
			    }
		        #WMID
			    $check_fine_wmid = mysql_fetch_array( mysql_query( "SELECT count(*) as count FROM tb_users WHERE wmid = '".$fine_row['wmid']."' AND ban = '0' AND wmid != ''" ) );
                if($check_fine_wmid['count'] > 1) {
		            mysql_query("UPDATE tb_users SET finestatus = '1', fine_text = 'Мультиаккаунтинг', datefine = '".time()."' WHERE id = '".$_SESSION['iduser']."'");
			        mysql_query("UPDATE tb_users SET ban = '1', fine_text = 'Мультиаккаунтинг' WHERE wmid = '".$fine_row['wmid']."' AND id != '".$_SESSION['iduser']."'");
			    }
	        }
		}
	    #Создание корзины
	    if($finestatus == 1 OR $finestatus == 2 OR $finestatus == 3 OR $finestatus == 4 OR $finestatus == 5 ) {
		    $check_fine_bask = mysql_fetch_array( mysql_query( "SELECT count(*) as count FROM seo_basket WHERE fromid = '".$_SESSION['iduser']."' AND type = '8'" ) );
		    if($check_fine_bask['count'] == 0) {
			    mysql_query("INSERT INTO seo_basket (ident, price, fromid, time,type) values ('', '$finesummam', '$_SESSION[iduser]', '".time()."', '8')") or die(mysql_error());
			}
		}
	
	}
/// ----------------------------------------------------------------------------------------------------------------
?> 