<?php 
/**
 * Check URLs against preroll blacklists from partners.
 * 
 * @author Roman
 */


class Preroll_blacklist{

	private $redis_read;
	private $redis_read_host = '192.168.17.177';
	private $redis_read_port = '6379';

	function __construct()
	{
		$this->redis_read = new Redis();
		$this->redis_read->pconnect($this->redis_read_host, $this->redis_read_port);
	}

	/**
	 * 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){
		$url = strtolower($url);

		preg_match('/(?:www\.)?((?:[a-z0-9]+(-*[a-z0-9]+)*\.)+[a-z]{2,})/', $url, $match);

		if (empty($match[1]))
			return '';

		$domain = $match[1];

		// Create array of possible subdomains
		$sub_domains = $this->getSubDomains($domain);

		// Get domains from Redis (to satisfy condition *.domain.com)
		try {
			$domains_listed = $this->redis_read->hMGet('preroll_blacklist', $sub_domains);
		} catch (RedisException $e) {
		}

		$domains_listed = array_filter($domains_listed, function($v){ return $v !== false; });

		// If one of the domains in the black list log it and return false
		if ($domains_listed) {
			return implode(',', $domains_listed);
		}

		return '';
	}

	private function getSubDomains($domain)
	{
		$res_arr = array();
		$domain = explode('.', $domain);

		do {
			$res_arr[] = implode('.', $domain);
			array_shift($domain);
		} while (count($domain) >= 2);

		return $res_arr;
	}
}


/*$url = "http://animetoon.tv/";
$url = "http://sdsd.bettermotorcarss.com?sdasd";
$pb = new Preroll_blacklist();
var_dump($pb->getTags($url, true));*/

