<?php
  ///////////////////////////////////////////////////
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include_once("session_class.php");
$session = new Sessions;
if (!$session->is_session(session_id())) { die('Сначала зайдите в игру <a href=/chat.htm>enter</a>') ; }

include_once("persinfo_class.php");
$palinfo=new Persinfo($session->id_person);
if ($palinfo->level<2) {echo "Нельзя голосовать тем кто ниже второго левела";die;}
  ///////////////////////////////////////////////////
?>
<HTML><HEAD>
<link rel=stylesheet type="text/css" href="../i/main.css">
<meta content="text/html; charset=windows-1251" http-equiv=Content-type>
<META Http-Equiv=Cache-Control Content=no-cache>
<meta http-equiv=PRAGMA content=NO-CACHE>
<META Http-Equiv=Expires Content=0>
</HEAD>
<body bgcolor=e2e0e0>
<?php
  include_once('poll/pollconfig.inc');
  include_once("poll/lng/rus_lng.inc");
	include_once('poll/functions.inc');
  //Инициализация переменных
  $FileName = base64_decode($_POST['blague']);
  $FileName = "poll/txt/".$FileName;
  $Poll = file($FileName);
  $Time = base64_decode($_POST['time']);
  $EndPos = count($Poll)-1;

  //$Poll = '';
  if(!empty($_POST['Vote']))
  {
    //рассчитываем позицию файлов для хранения ip, паролей, пароля
  	//метод защиты от накрутки
	  $ProtectMode = trim(StripBBCode($Poll[($EndPos - 1)]));
	  //Файл, где хранятся IP
	  $IpFile = "poll/txt/ip".$Time;
	  //Файл, где хранится пароль (режим один пароль для всех)
	  $PswdFile = "poll/txt/pswd".$Time;
	  //Файл, где хранятся пароли (режим логин и пароль для каждого)
	  $PswdsFile = "poll/txt/pswds".$Time;
    //один пароль на всех
    if($ProtectMode == 'pswrdall')
    {
      if(file_exists($PswdFile))
      {
        $PasswordArr = file($PswdFile);

        if(count($PasswordArr) == 1)
          if($PasswordArr[0] != '')
          {
            $Password = $_POST['password'];
            if($Password == '')
              $Message = $Err_NoPassw;
            elseif(md5($Password) != $PasswordArr[0])
              $Message = $Err_IncorrPassw;
          }
      }
    }
    //логин и пароль для каждого
    if($ProtectMode == 'pswrdeach')
    {
      $Login = $_POST['login'];
      $Password = $_POST['password'];
      if($Login == '')
        $Message = $Err_NoLogin;
      if($Password == '')
        $Message .= $Err_NoPassw;
      $Participants = @file($PswdsFile);
      if((!empty($Participants)) && ($Message == ''))
      {
        for($i = 0; $i < count($Participants); $i = $i + 2)
          if(strpos($Participants[$i], $Login) !== false)
          {
            $UserStr = $Participants[$i];
            $PasswordComp = $Participants[($i+1)];
            break;
          }
        if(empty($PasswordComp))
          $Message = $Err_IncorrLogin;
        elseif(strpos($UserStr, "(%%%voted%%%)") !== false)
          $Message = $Err_DoubleVote;
        elseif(md5($Password) == trim($PasswordComp))
        {
          $UserStr = trim($UserStr);
          $UserStr .= " (%%%voted%%%)\n";
          $Participants[$i] = $UserStr;
          $Message = SaveStringInFile($PswdsFile, implode('', $Participants), 'w');
        } else $Message = $Err_IncorrPassw;
      } //if((!empty($Participants)) && ($Message == ''))
    } //if($ProtectMode == 'pswrdeach')
    //стандартная защита от накрутки
    if($Message == '')
    {
      if(($ProtectMode == 'ord') || ($ProtectMode == 'pswrdall'))
	    {
	      if(($ProtSession == 'yes') || ($ProtCookie == 'yes'))
	        include_once('poll/sessionstart.inc');
	        //сессии
	      if($ProtSession == 'yes')
	      {
	        if(strpos($_SESSION['SessionIdent'], $_POST['blague']) !== false)
	          $Message = $Err_DoubleVote;
	        else
	        {
	          $SessionIdent .= $_POST['blague'];
	          session_register('SessionIdent');
	        }
	      }
	        //cookie
	      if($ProtCookie == 'yes')
	      {
	        if(strpos($_COOKIE['poll'], $_POST['blague']) !== false)
	          $Message = $Err_DoubleVote;
	        else
	        {
	          $CookieIdent = $_COOKIE['poll'].$_POST['blague'];
	          setcookie('poll', $CookieIdent, (time()+($KeepCookieTmp*3600*24)));
	        }
	        /* foreach($_COOKIE as $key => $value)
	          Print $key.' - '.$value.'<br>'; */
	      } //cookie
	        //ip
	      if($ProtIp == 'yes')
	      {
	        $IpArr = @file($IpFile);

	        for($i = 0; $i < count($IpArr); $i = $i + 2)
	        {
	          $Tmp = (time() - $IpArr[($i+1)]);
	          //Print $Tmp.'<br>';
	          if($Tmp <= ($KeepIpTmp*60))
	          {
	            $IpArrChanged[] = $IpArr[$i];
	            $IpArrChanged[] = $IpArr[($i+1)];
	          }
	        }
	        if(@in_array($REMOTE_ADDR."\n", $IpArrChanged))
	        {
	          $Message = $Err_DoubleVote;
	        }
	        else {
	          $IpStr = @implode($IpArrChanged);
	          $IpStr = $REMOTE_ADDR."\n".time()."\n".$IpStr;
	          $Message = SaveStringInFile($IpFile, $IpStr, 'w');
	        }
	      } //ip
	    } //if(($ProtectMode == 'ord') || ($ProtectMode == 'pswrdall'))
	    /*foreach($_COOKIE as $key => $value)
	      Print $key.' - '.$value.'<br>'; */
    } //if($Message == '')
#echo "!!!!!!!!!!!!";
		$res=db_use('array',"select id_person from golos where id_person='".$session->id_person."' and golosov='".$FileName."'");
		if ($res['id_person']) {$Message = '<font color=red>'.$Err_DoubleVote.'</font>';echo $Message;}
	  
    if($Message == '')
    {
      $TypeFile = str_replace('cp', 'type', $FileName);
      $TypeArr  = @file($TypeFile);
      $Type = trim($TypeArr[0]);
      if($Type == '') $Type = 'radio';
      //checkbox
      if($Type == 'checkbox')
      {
        $Min = $TypeArr[1];
        $Max = $TypeArr[2];
        $Err_chkbx_Limit = str_replace('MIN', $_POST['MinChosenCount'], $Err_chkbx_Limit);
	      $Err_chkbx_Limit = str_replace('MAX', $_POST['MaxChosenCount'], $Err_chkbx_Limit);
        if(count($_POST['check']) < $Min)
          $Message = $Err_chkbx_Limit;
        if(count($_POST['check']) > $Max)
          $Message = $Err_chkbx_Limit;
        if(empty($Message))
        {
          foreach($_POST['check'] as $key => $value)
	        {
	          $Num = 1 + $key + 1;
	          //элемент Var для выбранного элемента
	          $VarX = $key/2;
	          $Poll[$Num] = StripBBCode($Poll[$Num]);
	          $Poll[$Num] = (int) $Poll[$Num];
	          $Poll[$Num] = $Poll[$Num]+1;
	          $Poll[$Num] = "[var{$VarX}voted]".$Poll[$Num]."[/var{$VarX}voted]\r\n";
	        }  //foreach($_POST['check'] as $key => $value)
        }   // if(empty($Message))
      } //if($Type == 'checkbox')
      //radio
      if($Type == 'radio')
      {
      	$Chosen = $_POST['variant'];
	      //Num - номер строки, в которой в которой храниться число проголосовавших за выбранный вариант
	      //+1 - элемент [quest], $Chosen - позиция [var{$Chosen}], +1 - [var{$Chosen}voted]
	      $Num = 1 + $Chosen + 1;
	      //элемент Var для выбранного элемента
	      $VarX = $Chosen/2;
	      $Poll[$Num] = StripBBCode($Poll[$Num]);
	      $Poll[$Num] = (int) $Poll[$Num];
	      $Poll[$Num] = $Poll[$Num]+1;
	      $Poll[$Num] = "[var{$VarX}voted]".$Poll[$Num]."[/var{$VarX}voted]\r\n";
      } //if($Type == 'radio')
      if(empty($Message))
      {
        $Str = implode('', $Poll);
	      if(file_exists($FileName))
	      {
	        $Message = SaveStringInFile($FileName, $Str, 'w');
	      }
	      else
	        $Message = $Err_Fopen;
	      if($Message == ''){
	        $Message = $Cpt_Accepted;
	db_use('query',"insert into golos(id_person,golosov) values ('".$session->id_person."','".$FileName."')");
			}
      }
    }
    include('showresults.php');
  }
  elseif(!empty($_POST['ShowResults']))
    include('showresults.php');
  elseif(!empty($_POST['PollArchive']))
    include('pollarchive.php');
  else
  {
    $Message = $Err_DontKnow;
    include('showresults.php');
  }
?>