Просмотр файла includes/header.php

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

$php_self = (isset($_SERVER['PHP_SELF'])) ? check(substr($_SERVER['PHP_SELF'], 1)) : '';
$request_uri = (isset($_SERVER['REQUEST_URI'])) ? check(urldecode(substr(strtok($_SERVER['REQUEST_URI'], 'S'), 1))) : 'index.php';
$http_referer = (isset($_SERVER['HTTP_REFERER'])) ? check(urldecode(strtok($_SERVER['HTTP_REFERER'], 'S'))) : 'Не определено';
$username = (empty($_SESSION['log'])) ? $config['guestsuser'] : $_SESSION['log'];
$brow = (empty($_SESSION['brow'])) ? $_SESSION['brow'] = get_user_agent() : $_SESSION['brow'];
############################################################################################
##                                 Проверка на ip-бан                                     ##
############################################################################################
if (file_exists(DATADIR.'temp/ipban.dat')) {
	$arrbanip = unserialize(file_get_contents(DATADIR.'temp/ipban.dat'));
} else {
	save_ipban();
}

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

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

		if ($ipmatch == 4) {
			redirect($config['home'].'/pages/banip.php?'.SID);
		} //бан по IP
	}
}
############################################################################################
##                                 Счетчик запросов                                       ##
############################################################################################
if (!empty($config['doslimit'])) {
	if (is_writeable(DATADIR.'antidos')) {
		$dosfiles = glob(DATADIR.'antidos/*.dat');
		foreach ($dosfiles as $filename) {
			$array_filemtime = filemtime($filename);
			if ($array_filemtime < (time() - 60)) {
				@unlink($filename);
			}
		}
		// -------------------------- Проверка на время -----------------------------//
		if (file_exists(DATADIR.'antidos/'.$ip.'.dat')) {
			$file_dos = file(DATADIR.'antidos/'.$ip.'.dat');
			$file_str = explode('|', $file_dos[0]);
			if ($file_str[0] < (time() - 60)) {
				@unlink(DATADIR.'antidos/'.$ip.'.dat');
			}
		}
		// ------------------------------ Запись логов -------------------------------//
		$write = time().'|'.$request_uri.'|'.$http_referer.'|'.$brow.'|'.$username.'|';
		write_files(DATADIR.'antidos/'.$ip.'.dat', $write."\r\n", 0, 0666);
		// ----------------------- Автоматическая блокировка ------------------------//
		if (counter_string(DATADIR.'antidos/'.$ip.'.dat') > $config['doslimit']) {

			if (!empty($config['errorlog'])){
				$banip = DB::run() -> querySingle("SELECT `ban_id` FROM `ban` WHERE `ban_ip`=? LIMIT 1;", array($ip));
				if (empty($banip)) {
					DB::run() -> query("INSERT INTO `error` (`error_num`, `error_request`, `error_referer`, `error_username`, `error_ip`, `error_brow`, `error_time`) VALUES (?, ?, ?, ?, ?, ?, ?);", array(666, $request_uri, $http_referer, $username, $ip, $brow, SITETIME));

					DB::run() -> query("INSERT IGNORE INTO ban (`ban_ip`, `ban_time`) VALUES (?, ?);", array($ip, SITETIME));
					save_ipban();
				}
			}

			unlink(DATADIR.'antidos/'.$ip.'.dat');
		}
	}
}
############################################################################################
##                            Сжатие и буферизация данны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");
	}
}

############################################################################################
##                               Авторизация по cookies                                   ##
############################################################################################
if (empty($_SESSION['log']) && empty($_SESSION['par'])) {
	if (isset($_COOKIE['cooklog']) && isset($_COOKIE['cookpar'])) {
		$unlog = check($_COOKIE['cooklog']);
		$unpar = check($_COOKIE['cookpar']);

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

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

				$_SESSION['my_ip'] = $ip;
				$_SESSION['log'] = $unlog;
				$_SESSION['par'] = md5($config['keypass'].$checkuser['users_pass']);

				$authorization = DB::run() -> querySingle("SELECT `login_id` FROM `login` WHERE `login_user`=? AND `login_time`>? LIMIT 1;", array($unlog, SITETIME-30));

				if (empty($authorization)) {
					DB::run() -> query("INSERT INTO `login` (`login_user`, `login_ip`, `login_brow`, `login_time`) VALUES (?, ?, ?, ?);", array($unlog, $ip, $brow, SITETIME));
					DB::run() -> query("DELETE FROM `login` WHERE `login_user`=? AND `login_time` < (SELECT MIN(`login_time`) FROM (SELECT `login_time` FROM `login` WHERE `login_user`=? ORDER BY `login_time` DESC LIMIT 50) AS del);", array($unlog, $unlog));
				}

				DB::run() -> query("UPDATE `users` SET `users_visits`=`users_visits`+1, `users_timelastlogin`=? WHERE `users_login`=? LIMIT 1;", array(SITETIME, $unlog));
			}
		}
	}
}

// ---------------------- Установка сессионных переменных -----------------------//
$log = '';
if (empty($_SESSION['counton'])) {
	$_SESSION['counton'] = 0;
}
if (empty($_SESSION['currs'])) {
	$_SESSION['currs'] = SITETIME;
}
if (!isset($_SESSION['token'])) {
	if (!empty($config['session'])){
		$_SESSION['token'] = generate_password(6);
	} else {
		$_SESSION['token'] = 0;
	}
}
ob_start('mc');
ob_start('ob_processing');
$_SESSION['timeon'] = maketime(SITETIME - $_SESSION['currs']);
############################################################################################
##                                     Авторизация                                        ##
############################################################################################
if ($udata = is_user()) {

	$log = $udata['users_login'];
	// ---------------------- Переопределение глобальных настроек -------------------------//
	$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['timezone']   = $udata['users_timezone'];    # Временной сдвиг
	$config['privatpost'] = $udata['users_postprivat'];  # Вывод писем в привате
	$config['navigation'] = $udata['users_navigation'];  # Быстрый переход

	if ($udata['users_ban'] == 1) {
		if (!strsearch($php_self, array('pages/ban.php', 'pages/rules.php'))) {
			redirect($config['home'].'/pages/ban.php?log='.$log.'&'.SID);
		}
	}

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

	// ---------------------- функция проверки ip и браузера -----------------------//
	if (!empty($udata['users_ipbinding'])) {
		if ($_SESSION['my_ip'] != $ip) {
			$_SESSION = array();
			setcookie(session_name(), '', 0, '/', '');
			session_unset();
			session_destroy();
			redirect($config['home'].'/'.$request_uri);
		}
	}
	// ------------------------ Запись текущей страницы для админов -----------------------------//
	if (strstr($php_self, basename(ADMINDIR))) {
		DB::run() -> 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::run() -> query("DELETE FROM `admlog` WHERE `admlog_time` < (SELECT MIN(`admlog_time`) FROM (SELECT `admlog_time` FROM `admlog` ORDER BY `admlog_time` DESC LIMIT 500) AS del);");
	}
	// -------------------------- Дайджест ------------------------------------//
	DB::run() -> query("INSERT INTO `visit` (`visit_user`, `visit_self`, `visit_ip`, `visit_nowtime`)  VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `visit_self`=?, `visit_ip`=?, `visit_count`=?, `visit_nowtime`=?;", array($log, $php_self, $ip, SITETIME, $php_self, $ip, $_SESSION['counton'], SITETIME));
}
?>