<?php
#-----------------------------------------------------#
#          ********* ROTORCMS *********               #
#              Made by  :  VANTUZ                     #
#               E-mail  :  visavi.net@mail.ru         #
#                 Site  :  http://pizdec.ru           #
#             WAP-Site  :  http://visavi.net          #
#                  ICQ  :  36-44-66                   #
#  Вы не имеете право вносить изменения в код скрипта #
#        для его дальнейшего распространения          #
#-----------------------------------------------------#
if (!defined('BASEDIR')) {
  header('Location:../index.php');
  exit;
} 

if (isset($_SERVER['PHP_SELF'])) {
  $php_self = check(substr($_SERVER['PHP_SELF'], 1));
} 
if (isset($_SERVER['REQUEST_URI'])) {
  $request_uri = check(urldecode(substr(strtok($_SERVER['REQUEST_URI'], 'S'), 1)));
} 
if (isset($_SERVER['HTTP_REFERER'])) {
  $http_referer = check(urldecode(strtok($_SERVER['HTTP_REFERER'], 'S')));
} else {
  $http_referer = 'Не определено';
} 
if (empty($_SESSION['log'])) {
  $username = $config['guestsuser'];
} else {
  $username = $_SESSION['log'];
} 
if (empty($_SESSION['brow'])) {
  $_SESSION['brow'] = GetUserAgent();
} 
if (empty($request_uri)) {
  $request_uri = 'index.php';
} 
$brow = $_SESSION['brow'];
# ###########################################################################################
# #                            Сжатие и буферизация данныx                                 ##
# ###########################################################################################
if (!empty($config['gzip']) && extension_loaded('zlib') && ini_get('zlib.output_compression') != 'On' && ini_get('output_handler') != 'ob_gzhandler' && ini_get('output_handler') != 'zlib.output_compression') {
  if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
    $gzencode = $_SERVER['HTTP_ACCEPT_ENCODING'];
  } elseif (isset($_SERVER['HTTP_TE'])) {
    $gzencode = $_SERVER['HTTP_TE'];
  } else {
    $gzencode = false;
  } 

  $support_gzip = (strpos($gzencode, 'gzip') !== false);
  $support_deflate = (strpos($gzencode, 'deflate') !== false);

  if ($support_gzip) {
    header("Content-Encoding: gzip");
    ob_start("compress_output_gzip");
  } elseif ($support_deflate) {
    header("Content-Encoding: deflate");
    ob_start("compress_output_deflate");
  } 
} 

ob_start('ob_processing');
# ###########################################################################################
# #                                 Проверка на ip-бан                                     ##
# ###########################################################################################
if (file_exists(DATADIR . "temp/ipban.dat")) {
  $arrbanip = unserialize(file_get_contents(DATADIR . "temp/ipban.dat"));
} else {
  $querybanip = DB :: $dbh -> query("SELECT `ban_ip` FROM `ban`;");
  $arrbanip = $querybanip -> fetchAll();
} 

if (count($arrbanip) > 0) {
  foreach($arrbanip as $ipdata) {
    $ipmatch = 0;
    $ipsplit = explode('.', $ip);
    $dbsplit = explode('.', $ipdata['ban_ip']);

    for($i = 0;$i < 4;$i++) {
      if ($ipsplit[$i] == $dbsplit[$i] || $dbsplit[$i] == '*') {
        $ipmatch += 1;
      } 
    } 

    if ($ipmatch == 4) {
      if (!strstr($php_self, 'pages/banip.php')) {
        header ('Location: ' . $config['home'] . '/pages/banip.php?' . SID);
        exit;
      } 
    } //бан по IP
  } 
} 
# ###########################################################################################
# #                               Авторизация по cookies                                   ##
# ###########################################################################################
if (!empty($config['cookies'])) {
  if (empty($_SESSION['log']) && empty($_SESSION['par'])) {
    if (isset($_COOKIE['cooklog']) && isset($_COOKIE['cookpar'])) {
      $unlog = check(xoft_decode($_COOKIE['cooklog'], $config['keypass']));
      $unpar = xoft_decode($_COOKIE['cookpar'], $config['keypass']);

      $checkdata = DB :: $dbh -> queryFetch("SELECT * FROM `users` WHERE `users_login`=? LIMIT 1;", array($unlog));

      if (!empty($checkdata)) {
        if ($checkdata['users_login'] == $unlog && $checkdata['users_pass'] == md5(md5($unpar))) {
          session_regenerate_id(1);

          $_SESSION['log'] = $unlog;
          $_SESSION['par'] = $unpar;
          $_SESSION['my_ip'] = $ip;

          DB :: $dbh -> query("UPDATE `users` SET `users_visits`=`users_visits`+1, `users_timelastlogin`=? WHERE `users_login`=? LIMIT 1;", array(SITETIME, $unlog));
        } 
      } 
    } 
  } 
} 
// -------------------------------------------------------------//
if ($_SERVER['HTTP_HOST']) {
  $config['servername'] = $_SERVER['HTTP_HOST'];
} else {
  $config['servername'] = $_SERVER['SERVER_NAME'];
} 
if (substr($config['servername'], 0, 4) == 'www.') {
  $config['servername'] = preg_replace('#www\.#', '', $config['servername'], 1);
} 
if (substr($config['servername'], 0, 4) == 'wap.') {
  $config['servername'] = preg_replace('#wap\.#', '', $config['servername'], 1);
} 
// ---------------------- Установка сессионных переменных -----------------------//
$log = '';
if (empty($_SESSION['counton'])) {
  $_SESSION['counton'] = 0;
} 
if (empty($_SESSION['currs'])) {
  $_SESSION['currs'] = SITETIME;
} 
if (empty($_SESSION['token'])) {
  $_SESSION['token'] = generate_password(6);
} 
if (empty($_SESSION['protect'])) {
  $_SESSION['protect'] = mt_rand(1000, 9999);
} 
$_SESSION['timeon'] = maketime(SITETIME - $_SESSION['currs']);
# ###########################################################################################
# #                                     Авторизация                                        ##
# ###########################################################################################
if (is_user()) {
  $log = check($_SESSION['log']);

  $udata = DB :: $dbh -> queryFetch("SELECT * FROM `users` WHERE `users_login`=? LIMIT 1;", array($log)); 
  // ---------------------- Переопределение глобальных настроек -------------------------//
  $config['themes'] = $udata['users_themes']; # Скин/тема по умолчанию
  $config['bookpost'] = $udata['users_postguest']; # Вывод сообщений в гостевой
  $config['postnews'] = $udata['users_postnews']; # Новостей на страницу
  $config['forumpost'] = $udata['users_postforum']; # Вывод сообщение в форуме
  $config['forumtem'] = $udata['users_themesforum']; # Вывод тем в форуме
  $config['boardspost'] = $udata['users_postboard']; # Вывод объявлений
  $config['timeclocks'] = $udata['users_timezone']; # Временной сдвиг 
  $config['showtime'] = $udata['users_showtime']; # Вывод часов и дня недели
  $config['privatpost'] = $udata['users_postprivat']; # Вывод писем в привате
  $config['navigation'] = $udata['users_navigation']; # Быстрый переход

  if ($udata['users_ban'] == 1) {
    if (!strstr($php_self, 'pages/ban.php') && !strstr($php_self, 'pages/rules.php')) {
      header ('Location: ' . $config['home'] . '/pages/ban.php?log=' . $log . '&' . SID);
      exit;
    } 
  } 

  if ($config['regkeys'] > 0 && $udata['users_confirmreg'] > 0 && empty($udata['users_ban'])) {
    if (!strstr($php_self, 'pages/key.php') && !strstr($php_self, 'input.php')) {
      header ('Location: ' . $config['home'] . '/pages/key.php?log=' . $log . '&' . SID);
      exit;
    } 
  } 

  if ($udata['users_sumcredit'] > 0 && SITETIME > $udata['users_timecredit'] && empty($udata['users_ban'])) {
    if (!strstr($php_self, 'games/kredit.php')) {
      header ('Location: ' . $config['home'] . '/games/kredit.php?' . SID);
      exit;
    } 
  } 
  // ---------------------- функция проверки ip и браузера -----------------------//
  if (!empty($udata['users_ipbinding'])) {
    if ($_SESSION['my_ip'] != $ip) {
      $_SESSION = array();
      session_unset();
      setcookie(session_name(), '', 0, '/', '');
      session_destroy();
      header ('Location: ' . $config['home'] . '/' . $request_uri);
      exit;
    } 
  } 
  // ------------------------ Запись текущей страницы для админов -----------------------------//
  if (strstr($php_self, basename(ADMINDIR))) {
    DB :: $dbh -> query("INSERT INTO `admlog` (`admlog_user`, `admlog_request`, `admlog_referer`, `admlog_ip`, `admlog_brow`, `admlog_time`) VALUES (?, ?, ?, ?, ?, ?);", array($log, $request_uri, $http_referer, $ip, $brow, SITETIME));

    DB :: $dbh -> query("DELETE FROM `admlog` WHERE `admlog_time` < (SELECT MIN(`admlog_time`) FROM (SELECT `admlog_time` FROM `admlog` ORDER BY `admlog_time` DESC LIMIT 300) AS del);");
  } 
  // -------------------------- Дайджест ------------------------------------//
  $visits = DB :: $dbh -> queryFetch("SELECT * FROM `visit` WHERE `visit_user`=? LIMIT 1;", array($log));

  if (!empty($visits)) {
    $lifetime = SITETIME - $visits['visit_nowtime'];
    if ($lifetime > 5 && $lifetime < 300 && $_SESSION['counton'] < 300) {
      DB :: $dbh -> query("UPDATE `visit` SET `visit_self`=?, `visit_ip`=?, `visit_count`=?, `visit_allcount`=`visit_allcount`+1, `visit_nowtime`=?, `visit_alltime`=`visit_alltime`+? WHERE `visit_user`=? LIMIT 1;", array($php_self, $ip, $_SESSION['counton'], SITETIME, $lifetime, $log));
    } else {
      DB :: $dbh -> query("UPDATE `visit` SET `visit_nowtime`=? WHERE `visit_user`=? LIMIT 1;", array(SITETIME, $log));
    } 
  } else {
    DB :: $dbh -> query("INSERT INTO `visit` (`visit_user`, `visit_self`, `visit_ip`, `visit_nowtime`)  VALUES (?, ?, ?, ?);", array($log, $php_self, $ip, SITETIME));
  } 
} 
// ------------------------ Отключение кеширования -----------------------------//
if ($config['nocache'] == 0) {
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Expires: " . date("r"));
} else {
  header("Cache-Control: public");
  header("Expires: " . date("r", time() + 600));
} 
// ------------------------ Автоопределение системы -----------------------------//
if (!empty($_SERVER['HTTP_USER_AGENT']) && !empty($config['webthemes']) && empty($_SESSION['my_themes'])) {
  if (empty($_SESSION['log']) || empty($_SESSION['par'])) {
    if (stristr($_SERVER['HTTP_USER_AGENT'], 'windows') || stristr($_SERVER['HTTP_USER_AGENT'], 'linux') ||
        stristr($_SERVER['HTTP_USER_AGENT'], 'macintosh') || stristr($_SERVER['HTTP_USER_AGENT'], 'unix') ||
        stristr($_SERVER['HTTP_USER_AGENT'], 'macos') || stristr($_SERVER['HTTP_USER_AGENT'], 'bsd')) {
      $config['themes'] = $config['webthemes'];
    } 
  } 
} 

if (isset($_SESSION['my_themes'])) {
  $config['themes'] = $_SESSION['my_themes'];
} 
ob_start('mc');
if (!file_exists(BASEDIR . 'themes/' . $config['themes'] . '/index.php')) {
  $config['themes'] = 'default';
} 
if ($config['closedsite'] == 1 && !strstr($php_self, 'pages/closed.php') && !strstr($php_self, 'input.php') && $log != $config['nickname']) {
  header ('Location: ' . $config['home'] . '/pages/closed.php?' . SID);
  exit;
} 

?>