<?php 
/**
 * Check URLs against preroll blacklists from partners.
 * 
 * @author Janaki
 */

include_once "lib/php/include/db.php";

class prBlklst_mCachedb extends Memcache {
	static private $instance = null;
	static private $port = 11211;
	static function mGet() {
		if (self::$instance == null) {
			self::$instance = new Memcache;
			self::$instance->addServer("192.168.30.51", self::$port);
		}
		return self::$instance;
	}
}

class Preroll_blacklist{
	
	function __construct()
	{
	}
	
	function _filer($value){
		return $value !== 'www';
	}
	
	function get_domain($domain, $debug = false)
	{
		$original = $domain = strtolower($domain);
	
		if (filter_var($domain, FILTER_VALIDATE_IP)) {
			return $domain;
		}
	
		$debug ? print('<strong style="color:green">&raquo;</strong> Parsing: '.$original) : false;
	
	
		$arr = array_slice(array_filter(explode('.', $domain, 4), array($this, "_filer")), 0); //rebuild array indexes
	
		if (count($arr) > 2)
		{
			$count = count($arr);
			$_sub = explode('.', $count === 4 ? $arr[3] : $arr[2]);
	
			$debug ? print(" (parts count: {$count})") : false;
	
			if (count($_sub) === 2) // two level TLD
			{
				$removed = array_shift($arr);
				if ($count === 4) // got a subdomain acting as a domain
				{
					$removed = array_shift($arr);
				}
				$debug ? print("<br>\n" . '[*] Two level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
			}
			elseif (count($_sub) === 1) // one level TLD
			{
				$removed = array_shift($arr); //remove the subdomain
	
				if (strlen($_sub[0]) === 2 && $count === 3) // TLD domain must be 2 letters
				{
					array_unshift($arr, $removed);
				}
				else
				{
					// non country TLD according to IANA
					$tlds = array(
							'aero',
							'arpa',
							'asia',
							'biz',
							'cat',
							'com',
							'coop',
							'edu',
							'gov',
							'info',
							'jobs',
							'mil',
							'mobi',
							'museum',
							'name',
							'net',
							'org',
							'post',
							'pro',
							'tel',
							'travel',
							'xxx'
					);
	
					if (count($arr) > 2 && in_array($_sub[0], $tlds) !== false) //special TLD don't have a country
					{
						array_shift($arr);
					}
				}
				$debug ? print("<br>\n" .'[*] One level TLD: <strong>'.join('.', $_sub).'</strong> ') : false;
			}
			else // more than 3 levels, something is wrong
			{
				for ($i = count($_sub); $i > 1; $i--)
				{
				$removed = array_shift($arr);
				}
				$debug ? print("<br>\n" . '[*] Three level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
			}
		}
		else if (count($arr) === 2)
		{
		$arr0 = array_shift($arr);
	
		if (strpos(join('.', $arr), '.') === false	&& in_array($arr[0], array('localhost','test','invalid')) === false) // not a reserved domain
		{
		$debug ? print("<br>\n" .'Seems invalid domain: <strong>'.join('.', $arr).'</strong> re-adding: <strong>'.$arr0.'</strong> ') : false;
		// seems invalid domain, restore it
		array_unshift($arr, $arr0);
		}
		}
	
		$debug ? print("<br>\n".'<strong style="color:gray">&laquo;</strong> Done parsing: <span style="color:red">' . $original . '</span> as <span style="color:blue">'. join('.', $arr) ."</span><br>\n") : false;
	
		return join('.', $arr);
	}
	
	/**
	 * Check against preroll blocklists from various partners and return the corresponding LR_TAGS values for blocking.
	 * 
	 */
	function getTags($url, $skip_cache=false, $log_info=false){
		if(trim($url)==""){
			return "";
		}
		
		$CACHE_RESET = "xzy";	//change to reset cache keys
		$CACHE_EXPIRY = 12*60*60;
				
		if(stripos($url, "http%3A%2F%2F") === 0 || stripos($url, "https%3A%2F%2F") === 0)
			$url = urldecode($url);
		
		$url_host = parse_url($url, PHP_URL_HOST);
		if(!$url_host){
			$url_host_temp = explode("/", $url);
			$url_host = $url_host_temp[0];	//get the string before first /
		}
		
		//check master cache
		$master_cache_key = md5($CACHE_RESET."PR_BLK".$url_host);	
		
		if(!$skip_cache && $lr_tags = prBlklst_mCachedb::mGet()->get($master_cache_key)){
			if($log_info)
				echo "<h4 style='color:blue'>Log: Hit master cache.</h4>";
			if($lr_tags == "FALSE")
				return "";
			else
				return $lr_tags;
		}
		
		//check for blacklists
		$url_host_mod = str_ireplace("www.", "", $url_host);	
		//get top level domain when url is a subdomain
		$url_dom = $this->get_domain($url_host);
		$lr_tags_arr = array();
		$db = ConnectToRead();
		$sql = "SELECT * from rep_preroll_blacklists";
		$res = mysql_query($sql, $db);
		while ($row = mysql_fetch_array($res)){
			$table = $row['table'];
			$tag = $row['tag'];
			
			$sql = "SELECT * from $table where url like '$url_host%' OR url like '$url_host_mod%' OR url LIKE '$url_dom%' limit 1";
			$res1 = mysql_query($sql,$db);
			if(mysql_num_rows($res1)>0){
				//check for blank entries
				$row1 = mysql_fetch_array($res1);
				if(trim($row1['url']) != ""){
					if($log_info)
						echo "<h4 style='color:blue'>$sql :: $row1[url]</h4>";
					$lr_tags_arr[] = $tag;
				}
			}
		}
		mysql_close($db);
		
		if(empty($lr_tags_arr)){
			prBlklst_mCachedb::mGet()->set($master_cache_key, "FALSE", 0, $CACHE_EXPIRY);
			return "";
		}
		else{
			$lr_tags = implode(",", $lr_tags_arr);
			prBlklst_mCachedb::mGet()->set($master_cache_key, $lr_tags, 0, $CACHE_EXPIRY);
			return $lr_tags;
		}
		
	}
}

/* 
$url = "http://animetoon.tv/";
$url = "http://www.cured.com";
$pb = new Preroll_blacklist();
var_dump($pb->getTags($url));
 */
?>