File size: 3.39Kb
<?php
/**
* NOTE: In order for tracking cookies to be set, the ads must be requested prior to any
* output going to the user
*
* Potential additional parameters:
* u.age - actual age
* u.ageLow and u.ageHigh - for age range
* u.lang - override language (default is 'en-us')
*/
class Adfonic {
static $adfonic_ad_base = 'http://adfonic.net/ad';
var $client_id;
function __construct($client_id=null){
if (isset($client_id)) {
$this->client_id = md5($client_id);
}
}
/**
* Primary interface. Pass the ad identifier, any extra targeting parameters and tags
* @param params - name value parameters for targeting, do not url encode
* @return Ad content to directly embed
*/
function get_ad_content($ad_id,$params=array(),$tags=array()){
$ad_url = $this->build_ad_url($ad_id,$params,$tags);
$ch = curl_init($ad_url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$adcontent = '';
if ($output == false || $info['http_code'] != 200){
$adcontent = '<!-- no ad available, received response '. $info['http_code'] . '-->';
}
else {
parse_str($output, $rvals);
// handle "magic" quote escaping
if (get_magic_quotes_gpc()){
$rvals = array_map('stripslashes',$rvals);
}
// WARNING: This will only work if the output hasn't started going to the user
if (isset($rvals['trackingId'])){
setcookie('adfonic-tracking-id',$rvals['trackingId'],time() + (3600 * 24 * 365 * 2)); // 2 years
}
if (isset($rvals['error'])){
$adcontent = '<!-- no ad available, Adfonic error: ' . $rvals['error'] . '-->';
}
else {
$adcontent = $rvals['adContent'];
}
}
curl_close($ch);
return $adcontent;
}
/**
* Retrieve url for the given id and any extra parameters (tags, etc)
*
*/
function build_ad_url($ad_id,$params=array(),$tags=array()){
$ad_url = self::$adfonic_ad_base. "/$ad_id?";
// url params as key=value
$u_params = array();
// copy the user-supplied parameters
foreach ($params as $k=>$v){
$u_params[] = '$k='.urlencode($v);
}
// tracking id
$rid = $this->get_tracking_id();
if (isset($rid)) {
$u_params[]= 'r.id='.$this->get_tracking_id();
}
// user's ip address
$u_params[] = 'r.ip='.$this->get_ip();
// pass on all the http headers
foreach ($_SERVER as $k=>$v) {
if (substr(strtolower($k),0,5) == 'http_') {
$k = str_replace('_','-', strtolower(substr($k,5)));
if ($k != 'cookie') {
$u_params[] = 'h.'.$k.'='.urlencode($v);
}
}
}
if (! empty($tags)){
$u_params[] = "p.tags=".urlencode(join(",",$tags));
}
$query_string = join("&",$u_params);
$ad_url .= $query_string;
return $ad_url;
}
/**
* Extract tracking id from request/cookies
*
*/
function get_tracking_id(){
if (isset($_COOKIE['adfonic-tracking-id'])){
return $_COOKIE['adfonic-tracking-id'];
}
else {
return $this->client_id;
}
}
function get_ip(){
if (isset($_SERVER['HTTP_CLIENT_IP'])){
return $_SERVER['HTTP_CLIENT_IP'];
}
return $_SERVER['REMOTE_ADDR'];
}
}
?>