<?php

class cdnm_filter {
	public $config;
	public $dle_config;
	public $dle_db;
	
	public function __construct($dle_config, $dle_db) {
		// Подключаем конфигурацию модуля
		if (file_exists(ENGINE_DIR . '/data/cdnmconfig.php'))
			$this->configF = require_once ENGINE_DIR . '/data/cdnmconfig.php';
		else $this->configF = array ();
		
		// Подключаем конфигурацию скрипта
		$this->dle_config = $dle_config;
		
		// Подключение к базе
		$this->dle_db = $dle_db;
	}

	private function redirect_toSub ($redirect_code) {
		// redirect
		function cdnm_cache($cache_id, $cache_text = false) {
			$prefix = "cdnm";

			$key = $prefix . "_" . $cache_id;
			
			if( !is_dir( ENGINE_DIR . "/cache/cdnm" ) ) {
				@mkdir( ENGINE_DIR . "/cache/cdnm", 0777 );
				@chmod( ENGINE_DIR . "/cache/cdnm", 0777 );
			}
			
			if ( $cache_text === false) {
				$buffer = @file_get_contents( ENGINE_DIR . "/cache/cdnm/" . $key . ".tmp" );
				return $buffer;
			} else {
				file_put_contents (ENGINE_DIR . "/cache/cdnm/" . $key . ".tmp", $cache_text, LOCK_EX);
				@chmod( ENGINE_DIR . "/cache/cdnm/" . $key . ".tmp", 0666 );
				
				return true;
			}
		}
		
		$urls = explode(PHP_EOL, $this->configF['redirect']);
		$urls_count = count($urls);
		
		if ($urls_count > 1) {
			if ($this->configF['redirect_random'] == '0') $url = $urls[rand(0,$urls_count-1)];
			else {
				$time_period = 3600;
				if (intval($this->configF['redirect_random']) > 0 || empty($this->configF['redirect_random']))
					if (empty($this->configF['redirect_random'])) $redirect_random = 1440;
					else $redirect_random = intval($this->configF['redirect_random']);
					$time_period = $redirect_random * 60;
				
				$cache = cdnm_cache('filter');
				if ($cache === false) {
					$url = $urls[0];
					cdnm_cache('filter', time()+$time_period.'_1');
				} else {
					$cache = explode('_', $cache);
					if (time() <= $cache[0]) 
						$url = $urls[$cache[1]-1];
					else {
						if ($cache[1] >= $urls_count) $cache[1] = 0;
						else $cache[1] = $cache[1] = $cache[1] +1;
						
						cdnm_cache('filter', $cache[0]+$time_period.'_'.$cache[1]);
						$url = $urls[$cache[1]-1];
					}
				}
			}
		}
		else {
			$url = $urls[0];
		}

		if (strpos($url, '//') === false)
			$url = '//'.$url;
		
		// echo $url;

		// preg_match('/\{(.*)\}/', $url, $url_match);
		// if (!empty($url_match[0]))
			// $url = str_replace($url_match[0], date($url_match[1]), $url);
				
		header("HTTP/1.1 {$redirect_code}");
		header("Location: ".$url.$_SERVER['REQUEST_URI']);
		die('<meta http-equiv="refresh" content="0; url='.$url.$_SERVER['REQUEST_URI'].'">');
	}
	public function check () {
		if(!$this->configF['api_token']) return false;
		
		if (!empty($this->configF['good_bots']) && !preg_match('/('.$this->configF['good_bots'].')/',$_SERVER['HTTP_USER_AGENT'])) {
			
			$redirect_code = !empty($this->configF['redirect_code']) ? $this->configF['redirect_code'] : '302 Moved Temporarily';
			
			//echo '<!-- '.$_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'].'/'.' - '.$this->dle_config['http_home_url']."-->\r\n";
			if (
				!empty($this->configF['zaglush_norefer']) && empty($_SERVER['HTTP_REFERER']) 
				// &&
				// ('https://'. $_SERVER['HTTP_HOST'] .'/' == $this->dle_config['http_home_url'] ||
				// 'http://'. $_SERVER['HTTP_HOST'] .'/' == $this->dle_config['http_home_url'])
				) {
					// если страница
					$norefer_news = true;
					$norefer_zerkalo = true;
					
					if (!empty($this->configF['zaglush_norefer_news']) && strpos($_SERVER['QUERY_STRING'],'newsid=') === false)
						$norefer_news = false;
					
					if (!empty($this->configF['zaglush_norefer_zerkalo']) && strpos($this->dle_config['http_home_url'], $_SERVER['HTTP_HOST']) === false) 
						$norefer_zerkalo = false;
					
					if ( $norefer_news && $norefer_zerkalo ) {
						if (empty($this->configF['zaglush_norefer_code'])) $this->configF['zaglush_norefer_code'] = '404 Not Found';
						@header("HTTP/1.1 {$this->configF['zaglush_norefer_code']}");
						@header("Status: {$this->configF['zaglush_norefer_code']}");
						
						if (file_exists(ROOT_DIR . $this->configF['zaglush_norefer']))
							$content = include(ROOT_DIR . $this->configF['zaglush_norefer']);
						else {
							$content = <<<HTML
<html>
<head><title>{$this->configF['zaglush_norefer_code']}</title></head>
<body bgcolor="white">
<center><h1>{$this->configF['zaglush_norefer_code']}</h1></center>
<hr><center>nginx</center>
</html>
HTML;
						}
						die($content);
					}
					
			}
			
			if (
				!empty($this->configF['redirect']) && 
				('https://'. $_SERVER['HTTP_HOST'] .'/' == $this->dle_config['http_home_url'] ||
				'http://'. $_SERVER['HTTP_HOST'] .'/' == $this->dle_config['http_home_url'])
				) {
				// redirect
					$this->redirect_toSub($redirect_code);
				} // redirect
			
		} //nobots
		elseif (
			$this->configF['good_bots'] && preg_match('/('.$this->configF['good_bots'].')/',$_SERVER['HTTP_USER_AGENT']) && 
			$this->configF['redirect_poddomen'] &&
			('https://'. $_SERVER['HTTP_HOST'] .'/' != $this->dle_config['http_home_url'] &&
			'http://'. $_SERVER['HTTP_HOST'] .'/' != $this->dle_config['http_home_url'])
			) {
			// echo "<!-- ". $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST']. '/'." --> \r\n";
			// echo "<!-- ". $this->dle_config['http_home_url'] ." --> \r\n";
			$url = preg_replace('/\/$/', '', $this->dle_config['http_home_url']);
			
			header("HTTP/1.1 301 Moved Permanently");
			header("Location: ".$url.$_SERVER['REQUEST_URI']);
			die('<meta http-equiv="refresh" content="0; url='.$url.$_SERVER['REQUEST_URI'].'">');
		} //bots
		
		return 'ok';
	}
	
}