<?php
include_once("functions.php");
include_once("database.php");
include_once("game_functions.php");
class Sessions {
      var $session_expire_time;
      var $started_session;
      var $current_session;
      var $username;
      #var $userpass;
      var $userip;
      var $rq_param;
    var $id_user;
    var $id_person;

    function Sessions(){
            $this->session_expire_time = 60*2;      /*Длительность сессии в секундах.*/
            $this->started_session = null;
            $this->username = null;
            #$this->userpass = null;
            $this->userip = userip();
            $this->current_session = null;
     #       $this->rq_param = "sessid";
    }

    function clear_old_sessions(){   /*Удаление старых сессий*/
          $q="delete from sessions where userpass='' and session_time < ".(time()+$this->session_expire_time-2*60);
       db_use("query", $q);
    #   db_use("query","update paladins.abk_pals_sostav set ingame=NULL where id_person not in (select p.id_person from person p right join users u on u.id_person=p.id_person right join sessions s on s.username=u.login)");
    }


 #   function make_seed(){
  #                   list($usec, $sec) = explode(' ', microtime());
  #                   return (float) $sec + ((float) $usec * 100000);
  #  }

  #  function generate_session_id(){
  #                      srand($this->make_seed());
   #         $session_id = md5(uniqid(rand()));
   #         return($session_id);
    #}


    function start_session($username,$userpass,$cook){ /*Создать новую сессию*/
     session_start();
   $res=db_use("array","SELECT u.id_user,c.id_person FROM users u LEFT JOIN person c ON u.id_person=c.id_person where u.login='".$username."' AND u.pass='".$userpass."';");
  $id_user=$res['id_user'];$id_person=$res['id_person'];
  if (!$id_user OR !$id_person) {
    echo "Ошибка ".$id_user."входа. Персонаж не найден.".$id_person;
    $this->destroy_session($this->current_session);
    die;
  }

          if (!$this->is_session(session_id())) {
       $this->username = $username;
           #$this->userpass = $userpass;
       $this->id_user=$id_user;
       $this->id_person=$id_person;
            $this->clear_old_sessions();
           $this->started_session = session_id();#$this->generate_session_id();
       db_use('query',"delete from sessions where userpass='' and username='".clean_var($username)."'");
            $res = db_use('query', "insert into sessions (session_id,session_time, username, userip,cook)
            values ('".clean_var($this->started_session)."',".clean_var(time()+$this->session_expire_time).",'".clean_var($username)."','".clean_var($this->userip)."','".mysql_escape_string($cook)."')");
    #  $res = db_use('query', "insert into sessions (session_id,session_time, username, userip)           values ('".clean_var($this->started_session)."',".clean_var(time()+$this->session_expire_time).",'".clean_var($username)."','".clean_var($userpass)."','".clean_var($this->userip)."')");

    #  db_use("query","update paladins.abk_pals_sostav set ingame='".clean_var($this->userip)."',id_room=(select p.id_room from person p right join users u on u.id_person=p.id_person where u.login='".clean_var($username)."') where id_person=(select p.id_person from person p right join users u on u.id_person=p.id_person where u.login='".clean_var($username)."')");
       }
      $ip_login=$this->userip;
       $res = db_use('query',"INSERT INTO login_stat (id_user,login_time,ip_login,cook) VALUES ('".clean_var($id_user)."','".gmstrftime("%Y-%m-%d %H:%M:%S")."','".clean_var($ip_login)."','".mysql_escape_string($cook)."');");
       $res=db_use('array',"select p.id_room,r.roomname from users u left join person p on p.id_person=u.id_person left join room r on r.id_room=p.id_room and p.id_city=r.id_city where u.login='".$username."'");
      db_use('query',"insert into chat (timestamp,id_room,nick,text,color,type) values(".time().",'".$res['id_room']."','".$username."',' приветствует Вас.','','4')");
           return($this->started_session);
    }

    function is_session($session_id){ /*Проверки сесси на активность*/
               $this->clear_old_sessions();
               $this->current_session = "";
               $sess_ = false;
               if ($session_id){
        $res=db_use('array', "select p.blocked from sessions s
        left join users u on u.login=s.username
        left join person p on p.id_person=u.id_person
        where s.session_id='".clean_var($session_id)."'");
        if ($res['blocked']==1) {$error='Персонаж заблокирован.';
        $res=db_use('query', "delete from sessions where
        userpass='' and session_id='".clean_var($session_id)."'");
        echo' <html><head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<meta http-equiv="Content-Language" content="ru">
<TITLE>Произошла ошибка</TITLE></HEAD><BODY text="#FFFFFF"><p><font color=black>
Произошла ошибка: <pre>'.$error.'</pre>
<b><p><a href = "javascript:window.history.go(-1);">Назад</b></a>
<HR>
<p align="right">(c) <a href="/index.htm">АНТИБК Online</a></p>

</body></html>
';              $this->destroy_session($this->current_session);
              session_destroy();die;
        $session_id='';
        }
                 $res = db_use('query',
          "select session_id, userip,cook from sessions
          where session_id='".clean_var($session_id)."'");

                 if (mysql_numrows($res)>0){
                     $val = mysql_fetch_array($res);
          if ($val['session_id'] == $session_id && $val['userip'] == userip()  ) {
            if ($_COOKIE[cook]!=$val['cook']) {
             #echo "Ошибка входа. Неверный идентификатор компьютера для данной сессии. Повторите вход. Не получается войти 5 минут - напишите на icq251506<br />";
             #echo 'sessid='.clean_var($session_id).' idcomp='.$_COOKIE['cook'].' idcompsess='.$val['cook'];
             $this->destroy_session(clean_var($session_id));
             session_destroy();
            }else{
              $this->current_session = $session_id;
              $res = db_use('query', "update sessions set session_time  = ".clean_var(time()+$this->session_expire_time)." where session_id='".clean_var($session_id)."'");
              $val = db_use('array', "select username,userpass from sessions where session_id='".clean_var($session_id)."'");
              $this->username = $val['username'];
              #$this->userpass = $val['userpass'];
              $res=db_use("array","SELECT u.id_user,c.id_person FROM users u
              LEFT JOIN person c ON u.id_person=c.id_person where u.login='".($this->username)."' ");#AND u.pass='".$this->userpass."';");
              $id_user=$res['id_user'];$id_person=$res['id_person'];
              if (!$id_user OR !$id_person) {
                echo "Ошибка входа. Персонаж не найден.";
                $this->destroy_session($this->current_session);
                session_destroy();die;
              }
              $this->id_user=$id_user;
              $this->id_person=$id_person;
              $sess_ = true;
            }
                     } else{ # /f ($val['session_id'] == $session_id &
        #     echo "destroy";die;
              $this->destroy_session($this->current_session);
              session_destroy();
           }
                  } # /if (mysql_numrows($res)>0){
                 return($sess_);
               } #/if ($session_id){

    }# /function is_session($session_id)

   function destroy_session($session_id){ /*Принудительно закрыть сессию*/
      #return;
           $res = db_use('array', "select username from sessions where session_id = '".clean_var($session_id)."'");
           $q="delete from sessions where userpass='' and username = '".$res['username']."';";
           $res = db_use('query', $q);
    #   db_use("query","update paladins.abk_pals_sostav set ingame=NULL where id_person=(select p.id_person from person p right join users u on u.id_person=p.id_person where u.login='".$res['username']."')");
           $this->current_session = null;
   }
}


?>