<?php
/**
 * Moved from adinteractivemedia banners/functions.php and banners/memcache.php
 * @author janaki
 * 02/13/2018
 */

include_once 'lib/php/include/db.php';

class mCache extends Memcache {
    static private $instance = null;
    static private $port = 11211;
    //static private $port = 22123;
    static function mGet() {
        if(self::$instance == null) {
            self::$instance = new Memcache;
            self::$instance->addServer('192.168.30.104', self::$port);
            self::$instance->addServer('192.168.30.105', self::$port);
            //self::$instance->addServer('127.0.0.1', self::$port);
        }
        return self::$instance;
    }
}

function getLocation()
{
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];

    $mkey = "uip_getTags_gbanner2_".$ipaddress;
    $expire = 43200; // 12 hours
    if (!$location = mCache::mGet()->get($mkey))
    {
        $db = connectToReadProxy();

        $location_sql = "select country, country3, city, state from envoyip4 where ".ip2long($ipaddress)." <= endip limit 1";
        $res = mysql_query($location_sql, $db);
        if($res){
            $location = mysql_fetch_assoc($res);
        }
        if (is_array($location) && count($location)>0){
            mCache::mGet()->set($mkey, $location, 0, $expire);
        } else {
            mCache::mGet()->set($mkey, "NONE000", 0, $expire);
        }
    }

    return $location;
}

function getDomain($url)
{
    if(!trim($url)){
        return "";
    }

    if(stripos($url, "apps://") === 0)
        return $url;

    $url = urldecode($url);
    if(stripos($url, "http://") === false && stripos($url, "https://") === false)
        $url = "http://".$url;
    $host = parse_url($url,PHP_URL_HOST);
    if($host){
        return $host;
    }
    else{
        return $url;
    }
}

function getAffiliate($aff_id)
{
    $aff_id = (int)$aff_id;
    $mkey = "abanner_affiliate_".$aff_id;
    $expire = 60*30; // 30 minutes
    if (!$affiliate = mCache::mGet()->get($mkey))
    {
        $db = connectToReadProxy();

        $sql = "SELECT a.banner_floor_bid,  a.looping_preroll, ai.Affiliate, ai.rev_share, a.adnet_qps
                FROM AffiliateIDs aid
                  JOIN Affiliate_info ai ON ai.Affiliate=aid.Affiliate
                  JOIN  Affiliate a ON a.name=aid.Affiliate
                WHERE aid.id=$aff_id";
        $res = mysql_query($sql, $db);

        $affiliate = mysql_fetch_assoc($res);

        if ($affiliate)
            mCache::mGet()->set($mkey, $affiliate, 0, $expire);
    }

    return $affiliate;
}


function get_approved_domains($aid){
    $mkey = "aff_approved_domains_".$aid;
    $expire = 60*30;
    if (!$domains_arr = mCache::mGet()->get($mkey)){
        $db_new = ConnectToAdmin2();
    
        $domains_arr = array();
        $sql = "select domain from rep_affiliate_domains where aid=$aid and status=1";
        $res = mysql_query($sql, $db_new);
        while($row = mysql_fetch_array($res)){
            $domains_arr[] = $row['domain'];
        }
    
        if (is_array($domains_arr) && count($domains_arr)>0){
            mCache::mGet()->set($mkey, $domains_arr, 0, $expire);
        } else {
            mCache::mGet()->set($mkey, "NONE000", 0, $expire);
        }
    
        mysql_close($db_new);
    }
    
    return $domains_arr;
}

/**
 * @param $aid int Affiliate id
 * @param $location array GEO data
 * @param $width int Ad width
 * @param $height int Ad height
 * @param $main_domain string using domain
 * @param bool|true $stacking stack or not
 * @param $app array with store url and bundle for apps -- keys matching ssp get params
 * @param $device array of device parameters -- keys matching ssp get params
 * @return string
 */
function admedia_rtb($aid, $location, $width, $height, $referrer, $main_domain, $stacking = true, $demo = false, $app = array(), $device = array(), $rtb_source_str = "")
{
    $result   = '';
    $price    = '';
    $cat_str  = '';
    $rtb_ref  = '';
    $floor_bid_string = '';
    $aff = getAffiliate($aid);
	$aidForDetail = '';							// For logging the SSP for detailed wins (smart routing)
	if(isset($_GET['ssp']) && trim($_GET['ssp']) != '')
	{
		$aidForDetail = $_GET['ssp'];
	}
	
    if(!isset($device['cat']) && isset($_GET['cat']) && $_GET['cat'] != '')
        $cat_str = "&cat=".urlencode($_GET['cat']);
    if(isset($_GET['ref']) && $_GET['ref'] != '')
        $rtb_ref = $_GET['ref'];

    if(!empty($app)){
        foreach ($app as $param=>$value){
            $page_url_string .= "&{$param}=".urlencode($value);
        }
    }
    else{ 
        $ref_enc = urlencode($referrer);
        $domain = parse_url($referrer, PHP_URL_HOST);
        $page_url_string = "&page_url=$ref_enc";
    }
    
    if(!empty($device)){
        foreach ($device as $param=>$value){
            $device_string .= "&{$param}=".urlencode($value);
        }
    }
    if(!isset($device['ip']))
        $ip_string = "&ip=".urlencode($_SERVER['HTTP_X_FORWARDED_FOR']);
    
    if(!isset($device['ua']))
        $ua_string = "&ua=".urlencode($_SERVER['HTTP_USER_AGENT']);
    
    if(!isset($device['country']) && isset($location['country3']) && trim($location['country3']) != ''){
        $country_str = "&country=".$location['country3'];;
    }

    if($aff && $aff['banner_floor_bid'] > 0)
    {
        $floor_bid = round($aff['banner_floor_bid'] / $aff['rev_share'], 3);
        $floor_bid_string = '&floor='.$floor_bid;
    }


    if(trim($_GET['rtbuid'])){  //dynamic uid from arb creatives. Do look up on rtb for buyer uid
        $cookie_str .= "&buyer_uid=".urlencode($_GET['rtbuid']);
        $cookie_str .= "&user_id=".urlencode(md5($_GET['rtbuid']));
    }
    else if(trim($_COOKIE['admRtbUidCkey34334Ssp245'])){  //user sync stores cookie on .admedia.com.
        $cookie_str .= "&buyer_uid=".urlencode($_COOKIE['admRtbUidCkey34334Ssp245']);
        $cookie_str .= "&user_id=".urlencode(md5($_COOKIE['admRtbUidCkey34334Ssp245']));
    }
    else{
        //cookie sync for bidswitch. Currently bidswitch id is passed to all rtb partners which is not correct. FIX this on rtb to include partner specific ids/
        $bidswitch_cookie = $_COOKIE["rtb_ssp_userKey_bidswitch"];
        $cookie_str = "&buyer_uid=".urlencode($bidswitch_cookie);
        $bidswitch_cookie_md5 = md5($bidswitch_cookie);
        $cookie_str .= "&user_id={$bidswitch_cookie_md5}";
    }
    

    //call bidswitch and other rtb partners here.
    $ssp_host = "204.44.79.8";
    //if(rand(1,10)%2 == 0)
    $ssp_host = "rtbg.$main_domain";
	
    $ssp_str = '';
    if($_GET['ssp'] && $_GET['ssp'] != '')
        $ssp_str = '&ssp='.$_GET['ssp'];
    if(isset($_GET['ssp_pub']) && $_GET['ssp_pub'] != '')
        $ssp_str .= '&ssp_pubid='.$_GET['ssp_pub'];

    $secure = 0;
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
        // SSL connection
        $secure = 1;
    }

    // 'app' params
    $app_params = '';
    if(!empty($_GET['app_name']))
        $app_params .= '&app_name='.urlencode($_GET['app_name']);
    if(!empty($_GET['app_store_url']))
        $app_params .= '&store_url='.urlencode($_GET['app_store_url']);
    if(!empty($_GET['app_bundle']))
        $app_params .= '&bundle='.urlencode($_GET['app_bundle']);
    if(!empty($_GET['app_ver'])){
        $app_params .= '&app_ver='.urlencode($_GET['app_ver']);
    }
    if(!empty($_GET['app_store_id'])){
        $app_params .= '&app_store_id='.urlencode($_GET['app_store_id']);
    }
    if(!empty($_GET['app_category'])){
        $app_params .= '&app_category='.urlencode($_GET['app_category']);
    }
    
    //below params are not just for apps, though they are added to $app_params variable
    if(!empty($_GET['country']) && !$country_str){
        $app_params .= '&country='.urlencode($_GET['country']);
    }
    if(!empty($_GET['loclong'])){
        $app_params .= '&lon='.urlencode($_GET['loclong']);
    }
    if(!empty($_GET['loclat'])){
        $app_params .= '&lat='.urlencode($_GET['loclat']);
    }
    if(!empty($_GET['ifa'])){
        $app_params .= '&ifa='.urlencode($_GET['ifa']);
    }
    if(!empty($_GET['didsha1'])){
        $app_params .= '&didsha1='.urlencode($_GET['didsha1']);
    }
    if(!empty($_GET['didmd5'])){
        $app_params .= '&didmd5='.urlencode($_GET['didmd5']);
    }
    if(!empty($_GET['dpidsha1'])){
        $app_params .= '&dpidsha1='.urlencode($_GET['dpidsha1']);
    }
    if(!empty($_GET['dpidmd5'])){
        $app_params .= '&dpidmd5='.urlencode($_GET['dpidmd5']);
    }
    if(!empty($_GET['macsha1'])){
        $app_params .= '&macsha1='.urlencode($_GET['macsha1']);
    }
    if(!empty($_GET['macmd5'])){
        $app_params .= '&macmd5='.urlencode($_GET['macmd5']);
    }
    if(!empty($_GET['os'])){
        $app_params .= '&os='.urlencode($_GET['os']);
    }
    if(!empty($_GET['osv'])){
        $app_params .= '&osv='.urlencode($_GET['osv']);
    }
    
    
    if($rtb_source_str){
        $src_str = "&src=".urlencode(trim($rtb_source_str));
    }
    else if(trim($_GET['src'])){
        $src_str = "&src=".urlencode(trim($_GET['src'])); 
    }

    $endpoint_url = "http://".$ssp_host."/ssp/?banner=1&stype=php&width=$width&height=$height".$ssp_str."&secure={$secure}{$page_url_string}&subid={$aid}{$country_str}{$cat_str}&ref=".urlencode($rtb_ref).$ip_string.$ua_string.$cookie_str.$device_string.$floor_bid_string.$app_params.$src_str; // &test_res=1  -  returns test data

    if($demo)
        $endpoint_url .= '&test_res=1';

    if($_GET['debug'] == 'ms123')
    {
        echo "RTB Endpoint: {$endpoint_url}<br>";
    }

    //$endpoint_url = "http://192.168.30.184/janaki/svn/rtb.admedia.com/trunk/html/ssp/?banner=1&width=$width&height=$height&page_url=$ref_enc&subid=$aid&ip=".urlencode($_SERVER['HTTP_X_FORWARDED_FOR'])."&ua=".urlencode($_SERVER['HTTP_USER_AGENT']);
    //echo $endpoint_url;
    $ch = curl_init($endpoint_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 3500 );
    //curl_setopt($ch, CURLOPT_TIMEOUT, $CurlData['timeout']);
    $response = curl_exec($ch);

    if(!curl_errno($ch)){
        $info = curl_getinfo($ch);
        if($_GET['debug'] == "ms123")
        {
            var_dump($info);
            echo "<br><br>";
        }
    }
    else{
        //curl error - log it
        //echo curl_error($ch);
        if($_GET['debug'] == 'ms123')
            echo "Curl error: ".curl_error($ch)."<br>";
    }
    curl_close($ch);

    $redis_array = array("192.168.30.121","192.168.30.122","192.168.30.124");
    $redis_port = 6379;
    shuffle($redis_array);
    $redis_server = $redis_array[0];


    if($info["http_code"] == 200 && $response){

        if($_GET['debug'] == 'ms123')
        {
            echo "Ad Stacking: ";
            var_dump($stacking);
            echo "<br>";
            echo "RTB Response: ".$response."<br>";
            //die;
        }

        $data = json_decode($response);
        if($data && is_array($data) && count($data) > 0)
        {
            $all_wins_arr = array();
            $non_stacked_ad = null;
            $max_cpm = 0;

            foreach ($data as $ad_arr){
                $partner_id = $ad_arr->partner_id;
                $ad = $ad_arr->creative;
                $win_notice = $ad_arr->win_notice;
				
                if(!$stacking && trim($ad) != '')	// Only load one ad, register win and die
                {
                    if($_GET['debug'] == 'ms123')
                        echo "No Stacking: ".$partner_id."<br>";

                    if($ad_arr->price && $ad_arr->price > $max_cpm)
                    {
                        if($_GET['debug'] == 'ms123')
                            echo "Found non-stacked ad from {$partner_id} at {$ad_arr->price} over {$max_cpm}";
                        $non_stacked_ad = $ad_arr;
                        $max_cpm = $ad_arr->price;
                    }
                }
                else if($stacking)
                {
                    if($_GET['debug'] == 'ms123')
                        echo "Stacking: ".$partner_id."<br>";

                    //display all the ads
                    $result .=  "<!-- s:rtbssp: $partner_id -->";
                    //create a fake call to track
                    $qstr = urlencode(json_encode(array("pid"=>$partner_id, "crid"=>$ad_arr->crid, "cid"=>$ad_arr->cid, "ad"=>$ad)));
                    $result .=  "<img width='1' height='1' style='display:none' src='//b.$main_domain/_adlog_/?q=$qstr' />";
                    $result .=  $ad;

                    if($win_notice)
                    {
                        $ch = curl_init($win_notice);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 200);
                        curl_exec($ch);
                        curl_close($ch);
                    }

                    $win_arr = array("request_id" => $ad_arr->request_id,"bid_id" => $ad_arr->bid_id, "aid" => $ad_arr->aid, "partner_id" => $partner_id, "price" => $ad_arr->price, "domain"=>$ad_arr->domain, "size" => $ad_arr->size, "isSmartRoutedReq" => $ad_arr->isSmartRoutedReq);
					// Enter SSP as aid for detail as SSP ID is logged for detailed smart routing //
					if($aidForDetail != '')
						$win_arr['aidForDetail'] = $aidForDetail;
					
					$all_wins_arr[] = $win_arr;		// Store win in array, insert all wins when done
                }
            }

            // Load non stacked ad, register win and die if (stacking == false) OR Register all wins (stacking == true)
            $list = "rtb_wins_" . date("Ymd");
            if($non_stacked_ad)
            {
                $partner_id = $non_stacked_ad->partner_id;
                $ad = $non_stacked_ad->creative;
                $win_notice = $non_stacked_ad->win_notice;
                $price = $non_stacked_ad->price;

                if($_GET['debug'] == 'ms123')
                    echo "Loading non-stacked ad from {$partner_id} at {$non_stacked_ad->price}<br>";

                $result .= "<!-- ns:rtbssp: $partner_id -->";
                $qstr = urlencode(json_encode(array("pid"=>$partner_id, "crid"=>$non_stacked_ad->crid, "cid"=>$non_stacked_ad->cid, "ad"=>$ad)));
                $result .=  "<img width='1' height='1' style='display:none' src='//b.$main_domain/_adlog_/?q=$qstr' />";
                $result .=  $ad;

                if($win_notice)
                {
                    $ch = curl_init($win_notice);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 200);
                    curl_exec($ch);
                    curl_close($ch);
                }

                $redis = new Redis();
                $redis->connect($redis_server, $redis_port);

                $win_arr = array("request_id" => $non_stacked_ad->request_id,"bid_id" => $non_stacked_ad->bid_id, "aid" => $non_stacked_ad->aid, "partner_id" => $partner_id, "price" => $non_stacked_ad->price, "domain"=>$non_stacked_ad->domain, "size" => $non_stacked_ad->size, "isSmartRoutedReq" => $non_stacked_ad->isSmartRoutedReq);
                // Enter SSP as aid for detail as SSP ID is logged for detailed smart routing //
				if($aidForDetail != '')
					$win_arr['aidForDetail'] = $aidForDetail;
				
				$redis->rpush($list, json_encode($win_arr));
            }
            else if(is_array($all_wins_arr) && count($all_wins_arr) > 0)
            {
                $redis = new Redis();
                $redis->connect($redis_server, $redis_port);

                $ret = $redis->multi();

                foreach($all_wins_arr as $win_data)
                {
                    if($_GET['debug'] == "ms123")
                        echo "Log win: ".json_encode($win_data)."<br>";
                    $ret->rpush($list, json_encode($win_data));
                }
                $ret->exec();
            }
        }
    }

    return array('bid' => $price, 'tag' => $result);

}



function getPartnersTags($aff, $location, $width, $height, $main_domain)
{
    require('lib/php/include/simple_mobile_detect.php');

    $isMobile = is_mobile();
    $psbid = (int)$_GET['psbid'];
    $cookie_key = md5($_GET['pageUrl'].$width.$height);
    $country = '';
    if(isset($location['country']))
        $country = $location['country'];

    if (!empty($_COOKIE[$cookie_key]))
        $showed_tags = explode(':', $_COOKIE[$cookie_key]);
    else
        $showed_tags = array();

    if($isMobile) $whereDevice = 'AND device_type IN(0,2)';
    else          $whereDevice = 'AND device_type IN(0,1)';

    $wherePartnername = '';
    if($psbid != 54) $wherePartnername = "AND partnername != (SELECT name FROM rep_banner_partners WHERE id=$psbid )";


    $urls_to_check = array();
    $url = parse_url($_GET['pageUrl'], PHP_URL_HOST);
    if ($url) {
        $urls_to_check[] = $url;
    }
    $url = parse_url($_GET['pageReferer'], PHP_URL_HOST);
    if ($url) {
        $urls_to_check[] = $url;
    }
    $url = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
    if ($url) {
        $urls_to_check[] = $url;
    }

    $urls_to_check = array_unique($urls_to_check);

    if (count($urls_to_check)) {
        $urls_to_check_str = "'" . implode("','", $urls_to_check) . "'";
        $blacklist_clause = "partnername NOT IN(SELECT partner_name FROM rep_bannerTags_blacklist WHERE domain in ($urls_to_check_str))";
        $whitelist_clause = "wl.domain in ($urls_to_check_str)";
    }
    else {
        $blacklist_clause = "true";
        $whitelist_clause = "false";
    }

    $sql = "SELECT distinct rbtn.id, tag, LOWER(partnername) as partnername, countries FROM rep_BannerTags_new rbtn
				LEFT OUTER JOIN rep_bannerTags_whitelist wl on rbtn.id = wl.id
				WHERE width=$width
				AND height=$height
				AND (countries LIKE '%$country%' OR countries='')
				$whereDevice
				$wherePartnername
				AND $blacklist_clause
				AND ((wl.id is NULL) OR ($whitelist_clause))
				AND del=0
				AND tag_status=1
				AND cap_status=0 ";

    $mkey = md5($sql);

    if(!$tags = mCache::mGet()->get($mkey)){

        $db = connectToReadProxy();

        $res = mysql_query($sql, $db);

        while($r = mysql_fetch_assoc($res)){
            $tags[] = $r;
        }
        mCache::mGet()->set($mkey, $tags, 0, 60*60*2);
    }

    if(!is_array($tags))
        return '';

    //Trick to keep tags with country targeting and remove tags without country targeting from same partner
    usort($tags, function($a, $b){
        return strcasecmp($b['countries'], $a['countries']);
    });

    $tagFilter = array();
    foreach ($tags as $i => $tag) {

        if(isset($tagFilter[$tag['partnername']]) && $tagFilter[$tag['partnername']] && !$tag['countries'])
            unset($tags[$i]);

        $tagFilter[$tag['partnername']] = $tag['countries'];

    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////

    shuffle($tags);

    if (!$showed_tags) {
        // Load:
        // adkarma_pubvantage - 60%
        // gamut - 20%
        // Others - 20%
        $rand = rand(1,10);
        if($rand <= 6) $partner = 'adkarma_pubvantage';
        elseif($rand ==7 || $rand == 8) $partner = 'gamut';
        else $partner = false;

        $tags_filtered = array_filter($tags, function($var) use ($partner){
            if(!$partner)
                return $var['partnername'] != 'adkarma_pubvantage' && $var['partnername'] != 'gamut';
            else
                return $var['partnername'] == $partner;
        });

        //Get first tag
        if($tags_filtered)
            $tag = array_shift($tags_filtered);
        else
            $tag = array_shift($tags);
    } else {
        $tags_filtered = array_filter($tags, function($var) use ($showed_tags){
            return !in_array($var['id'], $showed_tags);
        });

        if($tags_filtered)
            $tag = array_shift($tags_filtered);
        else
            return '';
    }

    $showed_tags[] = $tag['id'];
    setcookie($cookie_key, implode(':', $showed_tags), time() + 15, '/');

    $redis = new Redis();
    $redis->pconnect("192.168.30.121", 6379);
    $key = $aff.'_'.$tag['id'];
    $redis->hincrby('gbanner_tags:'.date('Ymd'), $key, 1);
    $redis->hincrby('partner_tags_counter_'.date('Ymd'), $tag['id'], 1);

    $tag['tag'] = str_ireplace(array('[page_url]', '[cachebuster]', '[timestamp]'), array(urlencode(@$urls_to_check[0]), rand(), time()), $tag['tag']);
    $adlog =  '<img width="1" height="1" style="display:none" src="//b.'.$main_domain.'/_adlog_/?q='.urlencode(json_encode(array("gbnr" => $tag['id']))).'" />';

    return $tag['tag']."\n".$adlog;

}

