<?
include_once 'lib/php/include/dbConstants.php';

function connect_Admin(){
	$mysql_host = MSACOMMON_DB_HOST_ADMIN;
    $mysql_user = MSACOMMON_DB_USER_ADMIN;
    $mysql_password = MSACOMMON_DB_PASS_ADMIN;
	$mysql_db = "Admin";
	$db = mysql_connect ( $mysql_host,   $mysql_user, $mysql_password );
	@mysql_select_db ($mysql_db, $db) or die ( "Error: Unable to select `$mysql_db` database.".mysql_error()); 
	return $db;
}

class msa_stdlib
{
    var $domain_values = false;
    var $hash_keys = array(
        'banners'  => 'ThkUbkfdgO1hdS7',
        'inline'   => 'JhYoSkfdqO1hdD3',
        'tagcloud' => 'FpkUCkfdgd4gTW4' );
    function get_domain_values()
    {
        if(!$this->domain_values){
            $brand = 1;
            $hostname = $_SERVER['HTTP_HOST'];
            if(stripos($hostname,'localpages') !== false) $brand = 1;
            if(stripos($hostname,'admedia') !== false) $brand = 2;
    
            switch($brand){
                case 1:
                    $this->domain_values = array(
                        'js_host'    => "js.localpages.com",
                        'ban_host'   => "js.localpages.com",
                        'base_host'  => "localpages.com",
                        'ref_domain' => "inline.localpages.com",
                        'lnk_domain' => "www.localpages.com",
                        'file_pref'  => "localpages",
                        'class_pref' => "localpages",
                        'blank_file' => "lpblank.png",
                        'dsp_domain' => "Localpages.com",
                        'dsp_name'   => "Localpages",
                        'big_logo'   => "images/localpages-logo.png",
                        'sml_logo'   => "localpages-logo.png"
                    );
                    break;
                case 2:
                    $this->domain_values = array(
                        'js_host'    => "admedia.com",
                        'ban_host'   => "admedia.com",
                        'base_host'  => "admedia.com",
                        'ref_domain' => "inline.admedia.com",
                        'lnk_domain' => "www.admedia.com",
                        'file_pref'  => "admedia",
                        'class_pref' => "admedia",
                        'blank_file' => "amblank.png",
                        'dsp_domain' => "AdMedia.com",
                        'dsp_name'   => "AdMedia",
                        'big_logo'   => "images/amblank.png",
                      //'sml_logo'   => "images/amblank.png"
                        'sml_logo'   => "images/blank.gif"
                    );
                    break;
            }
        }
        return $this->domain_values;
    }
    function strip_html_tags( $text )
    {
        $text = preg_replace(
            array('@<head[^>]*?>.*?</head>@siu',
                '@<style[^>]*?>.*?</style>@siu',
                '@<script[^>]*?.*?</script>@siu',
                '@<object[^>]*?.*?</object>@siu',
                '@<embed[^>]*?.*?</embed>@siu',
                '@<applet[^>]*?.*?</applet>@siu',
                '@<noframes[^>]*?.*?</noframes>@siu',
                '@<noscript[^>]*?.*?</noscript>@siu',
                '@<noembed[^>]*?.*?</noembed>@siu',
                '@<a[^>]*?.*?</a>@siu',
                '@<((br)|(hr))@iu',
                '@</?((address)|(blockquote)|(center)|(del))@iu',
                '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre)|(i)|(b)|(big)|(center)|(em)|(small)|(strike)|(u))@iu',
                '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
                '@</?((table)|(th)|(td)|(caption))@iu',
                '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
                '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
                '@</?((frameset)|(frame)|(iframe))@iu',
            ),
            array(
                ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
                "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",
                "\n\$0", "\n\$0",
            ),
            $text );
        // Remove all remaining tags and comments and return.
		//<p><i><b><big><center><em><h1><h2><h3><h4><h5><h6><small><strike><u>
        return strip_tags( $text );
    }
	function strip_html_tags_completely( $text )
    {
        $text = preg_replace(
            array('@<head[^>]*?>.*?</head>@siu',
                '@<style[^>]*?>.*?</style>@siu',
                '@<script[^>]*?.*?</script>@siu',
                '@<object[^>]*?.*?</object>@siu',
                '@<embed[^>]*?.*?</embed>@siu',
                '@<applet[^>]*?.*?</applet>@siu',
                '@<noframes[^>]*?.*?</noframes>@siu',
                '@<noscript[^>]*?.*?</noscript>@siu',
                '@<noembed[^>]*?.*?</noembed>@siu',
                '@<a[^>]*?.*?</a>@siu',
				'@<option[^>]*?.*?</option>@siu',
               
            ),
            array(
                ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
                
            ),
            $text );
        // Remove all remaining tags and comments and return.
        return strip_tags( $text, '<p><i><b><big><center><em><h1><h2><h3><h4><h5><h6><small><strike><u>' );
	   //return $text;
    }
    
/*	function strip_html_tags_partial( $text )
    {
        $text = preg_replace(
            array(
                '@<((br)|(hr))@iu',
                '@</?((address)|(blockquote)|(center)|(del))@iu',
                '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
                '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
                '@</?((table)|(th)|(td)|(caption))@iu',
                '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
                '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
                '@</?((frameset)|(frame)|(iframe))@iu',
            ),
            array(
                
                "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",
                "\n\$0", "\n\$0",
            ),
            $text );
        // Remove all remaining tags and comments and return.
        return strip_tags( $text );
    }*/
    function getMetaTagsFromString( $input_string )
    {
        $doc = new DOMDocument();
        $doc->strictErrorChecking = false;
        $doc->validateOnParse = false;
        @$doc->loadHTML($input_string);
        $metaTags = $doc->getElementsByTagName('meta');
        $metaTagA = array();
        for($i = 0; $metaTags->item($i); $i++){
            $metaTagA[$metaTags->item($i)->getAttribute("name")] = $metaTags->item($i)->getAttribute("content");
        }
        return $metaTagA;
    }
    function getPage($page_url)
    {
        $curl_handle=curl_init();
        curl_setopt($curl_handle,CURLOPT_URL,$page_url);
        curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
        curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl_handle,CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
        $page_text = curl_exec($curl_handle);
        curl_close($curl_handle);
        return $page_text;
    }
	function getRawText($url)
	{
        $raw_text = $this->getPage($url);
        $raw_text_copy=$raw_text;

		$ad_start_string = "google_ad_section_start";
		$ad_end_string = "google_ad_section_end";
		$google_start = stripos($raw_text, $ad_start_string);
		$google_end = stripos($raw_text, $ad_end_string);
		$google_start = $google_start?$google_start+strlen("google_ad_section_start -->"):"";
		$google_end = $google_end?$google_end-strlen("<!-- "):"";
		if ($google_start && $google_end){
			$raw_text = substr($raw_text,$google_start,$google_end-$google_start);
		}
	  
        preg_match( '@<meta\s+http-equiv="Content-Type"\s+content="([\w/]+)(;\s+charset=([^\s"]+))?@i',
            $raw_text, $matches );
        $encoding = $matches[3];
        //if($encoding != 'utf-8' && $encoding != 'UTF-8')
		{
			$utf8_text = iconv( $encoding, "utf-8", $raw_text );
		}
		//else
		{
		//	$utf8_text = $raw_text;
		}
			if($raw_text != "" && $utf8_text == "")
		{
			$utf8_text = $raw_text;
		}

		$temp = $utf8_text;
        $utf8_text_2 = $this->strip_html_tags_completely($utf8_text);
			
        $utf8_text = $this->strip_html_tags( $utf8_text );
		
		//$utf8_text = strip_html_tags($utf8_text);
        $buffer = html_entity_decode( $utf8_text, ENT_QUOTES, "UTF-8" ); 
return $utf8_text_2;
//		return $utf8_text_2;
		//return 1;
	}
    function getContextWords($url,$max_count)
    {
		$db_admin = connect_Admin();
        $raw_text = $this->getPage($url);
        $raw_text_copy=$raw_text;
		$ad_start_string = "google_ad_section_start";
		$ad_end_string = "google_ad_section_end";
		$google_start = stripos($raw_text, $ad_start_string);
		$google_end = stripos($raw_text, $ad_end_string);
		$google_start = $google_start?$google_start+strlen("google_ad_section_start -->"):"";
		$google_end = $google_end?$google_end-strlen("<!-- "):"";
		if ($google_start && $google_end){
			$raw_text = substr($raw_text,$google_start,$google_end-$google_start);
		}
		  
        preg_match( '@<meta\s+http-equiv="Content-Type"\s+content="([\w/]+)(;\s+charset=([^\s"]+))?@i',
            $raw_text, $matches );
        $encoding = $matches[3];
        /* Convert to UTF-8 before doing anything else */
		$utf8_text = iconv( $encoding, "utf-8", $raw_text );
		if($raw_text != "" && $utf8_text == "")
		{
			$utf8_text = $raw_text;
		}
        /* Strip HTML tags and invisible text */
        $utf8_text = $this->strip_html_tags( $utf8_text );
        /* Decode HTML entities */
        $buffer = html_entity_decode( $utf8_text, ENT_QUOTES, "UTF-8" ); 
//        $tags = get_meta_tags($URL);
        $tags = $this->getMetaTagsFromString( $raw_text_copy );
        $count=array();
        if(preg_match_all("/<h.>(.*?)<.h.>/i",str_replace("\n"," ",$raw_text_copy),$matches_x))
        {
            foreach($matches_x[1] as $temp2)
            {
                if (preg_match_all("/\\b".strip_tags($temp2)."\\b/i", $buffer, $matches)) 
                {
                    foreach ($matches[0] as $match)
                    {
                        $match=strtolower($match);
                        if(!isset($count[$match]['name']))
                        {
                            $count[$match]['count']=1;
                            $count[$match]['name']=$match;
                        }
                        else
                        {
                            $count[$match]['count']++;
                        }
                    }
                }
            }
        }

        $count=array();
//        $keyword=explode(",",$tags['keywords']);
        $keyword = preg_split("/[\\W]+/",$tags['keywords']);
        foreach ($keyword as $temp)
        {
            if($temp != '' && $temp != ' ')
            {
                if (preg_match_all("/\\b".$temp."\\b/i", $buffer, $matches)) 
                {
                    foreach ($matches[0] as $match)
                    {
                        $match=strtolower($match);
                        if(!isset($count[$match]['name']))
                        {
                            $count[$match]['count']=1;
                            $count[$match]['name']=$match;
                        }
                        else
                        {
                            $count[$match]['count']++;
                        }
                    }
                }
            }
        }
        $flag=0;
        foreach($count as $temp)
        {
            $flag++;
                if(!isset($word[$temp['name']]))
                {
                    $keyword_count++;
                    $word[$temp['name']]=1;
                }
                if($keyword_count == $max_count)
                {
                    break;
                }
            //echo "The keyword ".$temp['name']." was found ".$temp['count']." times\n";
        }
        $raw_words=array();
        if($keyword_count < $max_count)
        {
        //  $val=explode(" ",$buffer);
            $val = preg_split('/_|\W/', $buffer, NULL, PREG_SPLIT_NO_EMPTY);
            $c=0;
            $blacklist = array(
                'which' => 1,
                'where' => 1,
                'these' => 1,
                'known' => 1,
                'rather' => 1,
                'either' => 1,
                'being' => 1,
                'before' => 1,
                'because' => 1,
                'usually' => 1,
                'while' => 1,
                'shall' => 1,
                'whose' => 1,
                'would' => 1,
                'always' => 1,
                'across' => 1,
                'against' => 1,
                'within' => 1,
                'taken' => 1,
                'there' => 1,
                'along' => 1,
                'though' => 1,
                'through' => 1,
                'between' => 1,
                'after' => 1,
                'although' => 1,
                'having' => 1,
                'could' => 1,
                'again' => 1,
                'among' => 1,
                'cause' => 1,
                'about' => 1,
                'those' => 1,
                'their' => 1,
                'theirs' => 1,
                'yours' => 1,
                'without' => 1,
 				'username' => 1,
				'password' => 1
            );
            foreach($val as $temp)
            {
                $temp=strtolower(trim($temp));
                if( strlen($temp) > 5 && ctype_alpha($temp) && !isset($blacklist[$temp])) 
                {
                    $raw_words[]=$temp;
                    ;
                }
            }
        }
        $keywordCounts = array_count_values( $raw_words );
		$word_list="";
        foreach($keywordCounts as $kword=>$val){
            $cword = $kword;
			
            if(isset($keywordCounts[$cword]))
            {
                $keywordCounts[$cword] += $val;
				
				$word_list = $word_list."'".$cword."',";
            }
            else
            {
				$word_list = $word_list."'".$cword."',";
              
				$keywordCounts[$cword] = $val;
            }
        }
		$word_list=substr($word_list, 0, strlen($word_list) - 1);
		$query = "select * from inline_keyword where keyword IN (".$word_list.")";
		//echo "//".$query;
		$result = mysql_query($query, $db_admin);
		//print_r($keywordCounts);
		while ($row = mysql_fetch_assoc($result))
		{
		//	echo $row['keyword']." a ".$keywordCounts[$row['keyword']];
			$keywordCounts[$row['keyword']] = $keywordCounts[$row['keyword']] + 3;
		}
		//print_r($keywordCounts);
        arsort( $keywordCounts, SORT_NUMERIC );
        $keyword_count = 0;
        $output = "";
        $word = array();
        foreach($keywordCounts as $key => $value)
        {
            if($value > 1)
            {
                if(!isset($word[$key]))
                {
                    $keyword_count++;
                    $word[$key]=1;
                }
                //echo $key." was found $value times\n";
            }
            else
            {
		break;
            }
            if($keyword_count == $max_count)
            {
                break;
            }
        }
        return array_keys($word);
    }
    function get_contextual_keywords($url)
    {
        if (DEBUG) { $start = microtime(true); }
        if (DEBUG) { global $sql_reads,$cache_reads; }
        global $config;
        $url = strtolower($url);
        $sql = "SELECT pref_word,word_list FROM context_words WHERE url = '".$url."'";
        $mkey = 'context___'.md5($sql);
        //add_debug("get_contextual_keywords: $sql", 7);
        if (!$res = mCache::mGet()->get($mkey)) {
            $st = DB::get('s-devel-read')->prepare($sql);
            if (!$st->execute()) {
                if (DEBUG) { $err = $st->errorInfo(); }
                //add_debug('get_contextual_keywords db hit failed: '.$err[2]);
            } else {
                $res = $st->fetch(PDO::FETCH_ASSOC);
                if(is_array($res) and count($res) > 0){
                    $expire = 3600 * 24 * 3;
                    mCache::mGet()->set($mkey, $res, 0, $expire);
                }
            }
            $st->closeCursor();
            if (DEBUG) { ++$sql_reads; }
        } else {
            if (DEBUG) { ++$cache_reads; }
            //add_debug("get_contextual_keywords found value [".serialize($res)."] in cache for key, $mkey", 6);
        }
        if (DEBUG) { $elapsed = microtime(true) - $start; }
        //add_debug("get_contextual_keywords finished in $elapsed seconds", 4);
        return $res;
    }
    function set_contextual_keywords($url, $word_list, $keyword = "")
    {
        global $config;
        $url = strtolower($url);
        $sql = "INSERT INTO context_words (url,pref_word,word_list) VALUES ('$url','$keyword','$word_list')";
        $st = DB::get('s-devel-read')->exec($sql);
    }
    function record_impression($url)
    {
        $md5_url = md5($url);
        $sql = "INSERT INTO contextual_imp (url,impressions) VALUES ('".$md5_url."',1) ON DUPLICATE KEY UPDATE impressions = impressions + 1";
        $st = DB::get('s-devel-read')->exec($sql);
    }
    function getAffFromEncID( $idstr , $ktype = 'banners', $ToDecrypt = 1)
    {
		if ($ToDecrypt == 1)
			$idns = $this->decrypt_code($idstr, $this->hash_keys[$ktype]);
		else
			$idns = $idstr;
        if(!$idn = intval($idns)) return "";
		
		// replace ID changed ...
		if($idn == 7644)
			$idn = 9051;
		if($idn == 8888)
			$idn = 9052;
		if($idn == 4741 || $idn == 8941)
			$idn = 9053;
			
        $isql = "SELECT Affiliate FROM AffiliateIDs WHERE id = $idn";
        $mkey = 'affiliateID__'.md5($isql);
		if(stripos($_SERVER['HTTP_HOST'], "localadplatform") !== false){
			$mkey .= "__";
		}
		if (DEBUG) 
			echo "GetAffiliateName : ".$isql."<br>";
		if (!$aff = mCache::mGet()->get($mkey)) {
			if(stripos($_SERVER['HTTP_HOST'], "localadplatform") !== false){
				$st = DB::get('r31')->prepare($isql);
			} else {
				$st = DB::get('r7')->prepare($isql);
			}
            if (!$st->execute()) {
                if (DEBUG) { $err = $st->errorInfo(); }
            } else {
                $res = $st->fetch(PDO::FETCH_ASSOC);
                $aff = $res['Affiliate'];
                $expire = 3600 * 3;
                mCache::mGet()->set($mkey, $aff, 0, $expire);
            }
            $st->closeCursor();
        } else {
            if (DEBUG) 
	            echo "GetAffiliateName found value [".serialize($res)."] in cache for key, $mkey - Aff is $aff<br>";
        }
        return $aff;
    }
    function decrypt_code( $cstr, $ckey )
    {
        $uncleaned = strtr($cstr, '-_ ', '+/=');
        $unencoded = base64_decode($uncleaned);
        return $this->crypto($unencoded, $ckey);
    }
    function encrypt_code( $cstr, $ckey )
    {
        $ecd = $this->crypto($cstr, $ckey);
        $encoded = base64_encode($ecd);
        return trim(strtr($encoded, '+/=', '-_ '));
    }
    function crypto($str, $key) {
        $ky = str_replace(chr(32), '', $key);
        if (strlen($ky) < 8) exit('key error');
        $kl = strlen($ky) < 32 ? strlen($ky) : 32;
        $k = array();
        for ($i = 0; $i < $kl; ++$i) {
            $k[$i] = ord($ky{$i}) & 0x1F;
            
        }
        $j = 0;
        for ($i = 0; $i < strlen($str); ++$i) {
            $e = ord($str{$i});
            $str{$i} = $e & 0xE0 ? chr($e ^ $k[$j]) : chr($e);
        //  echo $str[$i]."<br>";
            ++$j;
            $j = $j == $kl ? 0 : $j;
        }
        return $str;
    }
}
// PDO singleton for handling multiple connections
// For method reference visit: 
//  http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
//  http://www.php.net/pdo
class DB {
    static private $db = array();
    static public $dsn = array(
		'read' => array('mysql:host=192.168.30.173;dbname=Live', 'web', 'RstG496urky2'),
        'write' => array('mysql:host=10.10.30.175;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		
		'w1' => array('mysql:host=192.168.16.214;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		'w2' => array('mysql:host=192.168.16.215;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		'w3' => array('mysql:host=192.168.16.216;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		'w4' => array('mysql:host=192.168.16.217;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		'w5' => array('mysql:host=192.168.16.218;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		'w6' => array('mysql:host=192.168.16.42;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		'r1' => array('mysql:host=192.168.16.219;dbname=Live', 'web', 'RstG496urky2'),
		'r2' => array('mysql:host=192.168.16.220;dbname=Live', 'web', 'RstG496urky2'),
		'r3' => array('mysql:host=192.168.16.221;dbname=Live', 'web', 'RstG496urky2'),
		'r4' => array('mysql:host=192.168.16.221;dbname=Live', 'web', 'RstG496urky2'),
		'r5' => array('mysql:host=192.168.16.223;dbname=Live', 'web', 'RstG496urky2'),
		'r6' => array('mysql:host=192.168.16.224;dbname=Live', 'web', 'RstG496urky2'),
		'r7' => array('mysql:host=192.168.16.225;dbname=Live', 'web', 'RstG496urky2'),
		'r8' => array('mysql:host=192.168.16.226;dbname=Live', 'web', 'RstG496urky2'),
		'r9' => array('mysql:host=192.168.16.227;dbname=Live', 'web', 'RstG496urky2'),
		'r10' => array('mysql:host=192.168.16.228;dbname=Live', 'web', 'RstG496urky2'),
		'r11' => array('mysql:host=192.168.16.229;dbname=Live', 'web', 'RstG496urky2'),
		'r12' => array('mysql:host=192.168.16.230;dbname=Live', 'web', 'RstG496urky2'),
		'r13' => array('mysql:host=192.168.16.231;dbname=Live', 'web', 'RstG496urky2'),
		'r14' => array('mysql:host=192.168.16.232;dbname=Live', 'web', 'RstG496urky2'),
		'r15' => array('mysql:host=192.168.16.233;dbname=Live', 'web', 'RstG496urky2'),
		'r31' => array('mysql:host=192.168.30.41;dbname=Live', 'web', 'RstG496urky2'), // Localadplatform
		'devel-read' => array('mysql:host=192.168.30.13;dbname=Live', 'web', 'RstG496urky2'),
		'devel-write' => array('mysql:host=192.168.30.104;dbname=Shorty', 'c3slave', 'RstG496urky2'),
		's-devel-read' => array('mysql:host=192.168.30.49;dbname=test', 'c3slave', 'RstG496urky2'),
    );

    final private function __construct() {}
    final private function __clone() {}
    static public function get($key) {
        if (!isset(self::$dsn[$key])) {
            throw new Exception("Unknown DSN: $key");
        }
        if (!isset(self::$db[$key])) {
			//add_debug("Making DB connection to '$key', ".self::$dsn[$key][0], 7);
            if (is_array(self::$dsn[$key])) {
            	$c = new ReflectionClass('PDO');
                self::$db[$key] = $c->newInstanceArgs(self::$dsn[$key]);
            } else {
                self::$db[$key] = new PDO(self::$dsn[$key]);
            }
        } 
        return self::$db[$key]; 
	}
	static public function close($key) {
		if (!isset(self::$dsn[$key])) {
			throw new Exception("Unknown DSN: $key");
		}
		if (isset(self::$db[$key])) {
		    self::$db[$key] = null;
		}
	}
}
if(stripos($_SERVER['HTTP_HOST'], "localadplatform") !== false){
	class mCache 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.16.229", self::$port);
			}
			return self::$instance;
		}
	}
} else {
	class mCache 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.16.230", self::$port);
							self::$instance->addServer("192.168.16.231", self::$port);
							self::$instance->addServer("192.168.16.232", self::$port);
							self::$instance->addServer("192.168.16.233", self::$port);
			}
			return self::$instance;
		}
	}
}
?>
