<?php
/**
 * Minimalist version of video arb page for O&O sites. Display only the preroll player and nothing else.
 * The following must be defined before including this file. See clubmother.com>views>video_arb_wrapper.php for example.
 * 
 * Required to define before including this file:
	$site_id = "22009"; //affId to pass to player.admedia.com
	$anyclip //array containing video details passed from the controller 
 */ 

include_once("lib/php/include/db.php");
include_once('lib/php/include/encrypt.php');
class mCache_vam 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;
	}
}

$placementId = "";
// For pop on arb page, need to reco it to the affiliate we are popping it from
$aff_id = '';
if(isset($_GET['aff_id']) && trim($_GET['aff_id']) != '')
{
	$site_id = $_GET['aff_id'];

	// Get appnexus domain specific placement tag
	$sref = $_SERVER['HTTP_HOST'];
	$srefDomain = '';
	if($sref && $sref != '')
	{
		$srefUrl = str_replace("https", "http", $sref);
		preg_match('@^(?:http://)?([^/]+)@i',$srefUrl, $matches);
		$srefhost = $matches[1];
		preg_match('~^[^/]+~', $srefhost, $matches);
		$srefDomain=trim($matches[0]);
		$srefDomain = str_replace("www.", "", $srefDomain);
	}
	
	if($_SERVER['HTTP_X_FORWARDED_FOR'] == '199.27.174.35')
		echo "<!-- Aff_id ".$site_id." - Sref: ".$srefDomain." -->";

	$mkey = md5("domainLevelAid4527_".$site_id."_".$srefDomain);
    $expire = 1800;
    if(!$placementId = mCache_vam::mGet()->get($mkey))
    {
        $db = ConnectToRead();
        $mSql = "select pd.Placement from rep_placement_domains pd, AffiliateIDs ai where ai.appnexus_id = pd.id and ai.id = {$site_id} and pd.domain = '{$srefDomain}'";
        $mRes = mysql_query($mSql, $db);
        if($mRes)
        {
            $mRow = mysql_fetch_assoc($mRes);
            if($mRow && trim($mRow['Placement']) != '')
            {
                $placementId = trim($mRow['Placement']);
            }
        }

        if($placementId != '')
            mCache_vam::mGet()->set($mkey, $placementId, 0, $expire);
        else
            mCache_vam::mGet()->set($mkey, "NONE000", 0, $expire);
        mysql_close($db);
    }
	else
	{
		if($placementId == 'NONE000')
			$placementId = '';
	}
}

//override site for cpa arb
$cpa_page = false;
if(is_numeric(trim($_GET['sidcpa']))){
	$site_id = trim($_GET['sidcpa']);
	$cpa_page = true;
	$fire_cpa_pixel = false;
	
	//get yesterday's revenue
	$date = date("Y-m-d",strtotime("yesterday"));
	$mkey = md5("GrossRev $site_id $date");
	if(!$gross_rev = mCache_vam::mGet()->get($mkey))
	{
		$db = ConnectToRead();
		
		//get cpm and preroll accts.
		$sql = "SELECT a.* from Affiliate a, AffiliateIDs ai where a.name=ai.Affiliate and ai.id ='$site_id'";
		$res = mysql_query($sql, $db);
		while($row = mysql_fetch_array($res)){
			//affiliates to query in daily stats
			$daily_stats_aff[] = $row['cpm_account'];
			$daily_stats_aff[] = $row['cpm_banner'];
		}

		$aff_str = implode("','", $daily_stats_aff);
		$sql = "SELECT sum(avgcpc) as gross from from daily_stats_cpm where	affiliate in ('$aff_str') and creation='$date'";
		$res = mysql_query($sql, $db);
		$gross = -1;
		while($row = mysql_fetch_array($res)){
			$gross = $row['gross'];
		}
		mysql_close($db);
		mCache_vam::mGet()->set($mkey, $gross, 0, 60*60*2);
	}
	
	//fire pixel if gross rev is more than 10
	if($gross > 10){
		//fire the conv pixel only once. Check if it is already fired for the day
		$today = date("Y-m-d");
		$mkey = md5("CPA Pixel Cache $site_id $today");
		if(!$pixel_cache_check = mCache_vam::mGet()->get($mkey))
		{
			$pixel_cache_check = 1;
			
			$db = ConnectToRead();
			$sql = "SELECT * FROM `rep_cpa_arb_pixel` WHERE aid='$site_id' and date='$today'";
			$res = mysql_query($sql,$db);
			mysql_close($db);
			if(mysql_num_rows($res) == 0){
				//insert data
				$dbAdmin = ConnectToAdmin();
				$insert_sql = "INSERT INTO `rep_cpa_arb_pixel`(`aid`, `date`, `count`) VALUES ('$site_id','$today',1) ON DUPLICATE KEY UPDATE count=count+1";
				mysql_query($insert_sql, $dbAdmin);
				mysql_close($dbAdmin);
				$fire_cpa_pixel = true;
			}
			mCache_vam::mGet()->set($mkey, $pixel_cache_check, 0, 60*60*2);
			
		}
		
	}
}

$appnexusId = "";

if($placementId == '')
{
	$mkey = md5("videoArbMin_".$site_id);
	$expire = 1800;
	if(!$appnexusId = mCache_vam::mGet()->get($mkey))
	{
		if($_SERVER['HTTP_X_FORWARDED_FOR'] == '199.27.174.35')
			echo "<!-- No MC for ".$site_id." -->";

		$db = ConnectToRead();
		if($_SERVER['HTTP_X_FORWARDED_FOR'] == '199.27.174.35' && $db)
			echo "<!-- DB Connected -->";
		$sql = "select pp.Placements from AffiliateIDs ai, rep_publisher_placement pp where ai.appnexus_id = pp.id and ai.id = ".$site_id." limit 1";
		$res = mysql_query($sql, $db);
		if($res)
		{
			$row = mysql_fetch_assoc($res);
			if($row && trim($row['Placements']) != '')
				$appnexusId = $row['Placements'];
		}
		
		if($appnexusId != '')
			mCache_vam::mGet()->set($mkey, $appnexusId, 0, $expire);
		else
			mCache_vam::mGet()->set($mkey, "NONE000", 0, $expire);
		mysql_close($db);
	}
	else
	{
		if($_SERVER['HTTP_X_FORWARDED_FOR'] == '199.27.174.35')
			echo "<!-- Found in MC: ".$appnexusId." -->";
	}

	if($appnexusId != '' && $appnexusId != 'NONE000')
	{
		if(strpos($appnexusId, ",") !== false)
		{
			$appnexusEx = explode(",", $appnexusId);
			shuffle($appnexusEx);
			if($appnexusEx[0] != '')
				$placementId = $appnexusEx[0];
		}
		else
			$placementId = $appnexusId;
	}
}

if($_SERVER['HTTP_X_FORWARDED_FOR'] == '199.27.174.35')
	echo "<!-- Placement ID: ".$placementId." -->";

if(!(is_array($anyclip) && count($anyclip)>0) ){
	include_once 'lib/php/include/lib.php';
	$anyclip = getAnyclipVideoNonCI("cars");
}

//check if criteo is enabled
$domain = str_ireplace("www.", "", parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST));
if ($domain) {
    $sql = "SELECT * FROM `rep_criteo_tags` where enabled=1 and site='$domain'";
    $mkey = md5($sql);
    if (! $criteo_tags = mCache_vam::mGet()->get($mkey)) {
        $db = ConnectToRead();
        $res = mysql_fetch_array($res);
        if ($res && mysql_num_rows($res) > 0) {
            while ($row = mysql_fetch_array($res)) {
                $criteo_tags[$row['size']] = $row['tag'];
            }
        } else {
            $criteo_tags = "NONE";
        }
        mCache_vam::mGet()->set($mkey, $criteo_tags, 0, 30 * 60);
        mysql_close($db);
    }
}

$vArbCookieKey = "adVarbCookie224";
$vArbCookieVal = "";
if(!isset($_COOKIE[$vArbCookieKey]))
{
	$vArbCookieVal = md5($_SERVER['HTTP_X_FORWARDED_FOR']."_".time());
	setcookie($vArbCookieKey, $vArbCookieVal, time()+60*60*24*365*10);
}
else
	$vArbCookieVal = $_COOKIE[$vArbCookieKey];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<style type="text/css">
body {
	margin: 0px;
}

.ab_container {
	font-family: Arial, Helvetica, sans-serif;
	margin-top: 20px;
	margin-bottom: 20px;
	margin-left: auto;
	margin-right: auto;
	padding-left: 15px;
	padding-right: 15px;
	text-align: center;
}

@media ( min-width : 768px) {
	.ab_container {
		width: 750px;
	}
}

@media ( min-width : 992px) {
	.ab_container {
		width: 970px;
	}
}

@media ( min-width : 1200px) {
	.ab_container {
		width: 1170px;
	}
}

#codeigniter_profiler {
	position: absolute;
}

#col_left {
	float: left;
	width: 200px;
}

#col_center {
	display: inline-block;
}

#col_right {
	float: right;
	width: 200px;
}

#banner728 {
	margin-top: 50px;
}
</style>

<script type="text/javascript"
	src="http://player.admedia.com/?site=<?=$site_id?>&vam=1"></script>
<script type="text/javascript" src="//tag.1dehusw7.com/?partner=3e58680a-8584-49b0-be44-3f73e631f57d&user=<?=$vArbCookieVal?>" async="async"></script>
</head>

<body>

<?php
//disable it - danny: 7/24
if (0 && stristr(strtolower($_SERVER['HTTP_HOST']), 'sportsreviews.com')) { ?>
<script type="text/javascript"
		src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
	<div
		style="width: 655px; height: auto; margin-left: auto; margin-right: auto; position: relative;">
		<script>
            window.TOUT = {propertyUid: "466d95"};
        </script>
		<script src="http://platform.tout.com/sdk.js" async></script>
		<div class="tout-sdk tout-mid-article"></div>
	</div>
<?php } ?>

<div class="ab_container">
<?php if($cpa_page){?>
<h3>Content will resume shortly..</h3>
<?php }?>
</div>

	<div
		style="margin-left: auto; margin-right: auto; width: 90%; text-align: center">

		<div id="col_left">
			<?php if($criteo_tags['160x600']) 
			         echo $criteo_tags['160x600'];
			else{?>
			<iframe width="160" height="600" frameborder="0" scrolling="no"
				src="//b.admedia.com/banners/gbanner.php?d=1&aff=<?=$site_id?>&size=160x600&subid=&pageUrl=http://<?=urlencode($_SERVER['HTTP_HOST'])?>&pageReferer=&app=0"></iframe>
				<?php }?>
		</div>

		<div id="col_center">
			<div id="video"
				style="width: 705px; height: 397px; margin-left: auto; margin-right: auto;"></div>

			<div id="nativeunit" style="width: 800; height: 200px;">
				<div id="adm-nat-below-article"></div>
			</div>

			<div id="banner728">
			<?php if($criteo_tags['728x90']) 
			         echo $criteo_tags['728x90'];
			else{?>
				<iframe width="728" height="90" frameborder="0" scrolling="no"
					src="//b.admedia.com/banners/gbanner.php?d=1&aff=<?=$site_id?>&size=728x90&subid=&pageUrl=http://<?=urlencode($_SERVER['HTTP_HOST'])?>&pageReferer=&app=0"></iframe>
					<?php }?>
			</div>
		</div>
<?php /*if(rand()%2 != 0){ //50% of the time block clicks?>
<div id="vidloader" style="width:705px; height:397px; margin-left: auto;  margin-right: auto; position: relative; top: -397px;"></div>
<?php } */?>

<div id="col_right">
<?php if($criteo_tags['160x600']) 
			         echo $criteo_tags['160x600'];
			else{?>
			<iframe width="160" height="600" frameborder="0" scrolling="no"
				src="//b.admedia.com/banners/gbanner.php?d=1&aff=<?=$site_id?>&size=160x600&subid=&pageUrl=http://<?=urlencode($_SERVER['HTTP_HOST'])?>&pageReferer=&app=0"></iframe>
				<?php }?>
		</div>

	</div>


	<script>
window.onbeforeunload = confirmExit;
function confirmExit() {
	return 'Are you sure you want to exit this page?';
}
function inIframe() {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

  <?php 
  //load yume only 70% of the time
  if(rand()%3 == 0)
  	$skip_yume = 1;
  else
  	$skip_yume = 0;
  ?>
  if(!inIframe()){
		adm_player.init({player_id:'video',video_url:'http://s.colo.com/<?php echo $anyclip[0]['ID']; ?>.mp4', width:"705",height:"397",auto_play:true, title:<?=json_encode(trim(preg_replace('/\s+/', ' ',$anyclip[0]['Title'])))?>,description:<?=json_encode(trim(preg_replace('/\s+/', ' ',$anyclip[0]['Description'])))?>, skip_yume:"<?=$skip_yume?>", sav:"1"});
  }
  else{
	  <?php if($cpa_page){?>
	  (new Image()).src = "http://usadserver.com/if.php?s=<?=$_SERVER['HTTP_HOST']?>&cid=<?=$site_id?>";
	  <?php }
	  else{?>
	  (new Image()).src = "http://usadserver.com/if.php?s=<?=$_SERVER['HTTP_HOST']?>&cid=<?=$_GET['cid']?>";
	  <?php }?>
  }
</script>

<?php if($fire_cpa_pixel){?>
<img src="https://secure.adnxs.com/px?id=526157&t=2" width="1"
		height="1" />
<?php }?>
  
<?
if(0 && $placementId != '')
{
	echo '<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><div >';
	for($i=0; $i<4; $i++)
	{
		if($i < 2)
			$size = "728x90";
		else
			$size = "160x600";
		$sizeEx = explode("x", $size);
		$width = $sizeEx[0];
		$height = $sizeEx[1];
		?>
		<iframe
		src="http://ib.adnxs.com/tt?id=<?=$placementId?>&amp;size=<?=$size?>"
		width="<?=$width?>" height="<?=$height?>" frameborder="0"
		scrolling="no"></iframe>
		<?
	}
	echo '</div>';
}
?>
<?php
/* define('HASH_KEY', 'JhYoSkfdqO1hdD3');

$enc_str =  trim(encrypt_str($site_id)); */

?>
<script type="text/javascript"
		src="http://native.admedia.com/js/nat.js?aid=<?=$site_id?>&rtb=1"></script>

</body>
</html>