init(); } public function __destruct() { //doesn't work, must destruct manually at end of settings page } public function activate() { //delete previous version settings, if exist if(isset($this->settings['google_client_id'])) { unset($this->settings['google_client_id']); $this->settings_dirty = true; } if(isset($this->settings['google_client_secret'])) { unset($this->settings['google_client_secret']); $this->settings_dirty = true; } if(isset($this->settings['google_access_token'])) { unset($this->settings['google_access_token']); $this->settings_dirty = true; } if(isset($this->settings['adsense_account_id'])) { unset($this->settings['adsense_account_id']); $this->settings_dirty = true; } if(isset($this->settings['adsense_adclient_id'])) { unset($this->settings['adsense_adclient_id']); $this->settings_dirty = true; } if(isset($this->settings['ir_enabled'])) { unset($this->settings['ir_enabled']); $this->settings_dirty = true; } if(isset($this->settings['ir_googleclientid'])) { unset($this->settings['ir_googleclientid']); $this->settings_dirty = true; } if(isset($this->settings['ir_googleclientsecret'])) { unset($this->settings['ir_googleclientsecret']); $this->settings_dirty = true; } if(isset($this->settings['ir_googleaccesstoken'])) { unset($this->settings['ir_googleaccesstoken']); $this->settings_dirty = true; } if(isset($this->settings['ads'])) { unset($this->settings['ads']); $this->settings_dirty = true; } if(isset($this->settings['lastchange'])) { unset($this->settings['lastchange']); $this->settings_dirty = true; } //go through each segment that doesn't have devices set, if mobile then set as mobile device, otherwise set to all devices if(isset($this->settings['segments'])) { foreach($this->settings['segments'] as $i=>$segment) { if(!isset($segment['devices'])) { if($segment['criteria']=='mobile') { //match all pages and posts for tablet and phones $this->settings['segments'][$i]['devices'] = 'tp'; $this->settings['segments'][$i]['criteria'] = 'default'; } else { //no preference of device, set to all $this->settings['segments'][$i]['devices'] = 'dtp'; } $this->settings_dirty = true; } } } //Save to db. Destructor doesn't work if($this->settings_dirty) { //save vars to db update_option('ampedsense_settings', $this->settings); } } public function deactivate() { //nothing to do, keep settings in case reactivate later } public function init() { //retrieve settings $this->settings = get_option('ampedsense_settings'); //set defaults if(!isset($this->settings['segments']) || count($this->settings['segments'])==0) { //init default segment $this->settings['segments']; $newsegment = array(); $newsegment['criteria'] = "default"; $newsegment['segmentname'] = "All Traffic"; $newsegment['devices'] = "dtp"; $this->settings['segments'][] = $newsegment; $this->settings_dirty = true; } if(!isset($this->settings['siteabbrev']) || $this->settings['siteabbrev']=='') { $sitename = str_replace(" ","",get_bloginfo('name')); //get rid of whitespace $this->settings['siteabbrev'] = substr($sitename,0,3); $this->settings_dirty = true; } $this->ip = $_SERVER['REMOTE_ADDR']; //admin menu add_action('admin_menu', array( $this, 'make_settings_menu') ); //sidebar widgets add_action('widgets_init', array( $this, 'registerSidebars') ); //shortcodes add_shortcode( 'AmpedSenseShortcodeA' , array( $this, 'shortcodeA') ); add_shortcode( 'AmpedSenseShortcodeB' , array( $this, 'shortcodeB') ); add_shortcode( 'AmpedSenseShortcodeC' , array( $this, 'shortcodeC') ); //add hook to check page type later add_action('wp', array( $this, 'run')); //we save the report fromdates and google access token to session if( !session_id()) session_start(); //Save to db. Destructor doesn't work if($this->settings_dirty) { //save vars to db update_option('ampedsense_settings', $this->settings); } } public function registerSidebars() { register_widget( 'AmpedSenseSidebarA' ); register_widget( 'AmpedSenseSidebarB' ); register_widget( 'AmpedSenseSidebarC' ); } public function run() { if(isset($this->settings['adsensepublisherid']) && $this->settings['adsensepublisherid']!='') { //pick recipe! if(isset($_GET['as_preview']) && $_GET['as_preview'] && current_user_can('read')) //only allow preview via get on logged in users, otherwise may allow js injection { //preview! //create array of ads from parameters $previewads = array(); for($i=1; $i<=$_GET['as_numads']; $i++) { if(isset($_GET['as_custom'][$i])) $previewad['custom'] = $this->cleanInput($_GET['as_custom'][$i]); if(isset($_GET['as_adsize'][$i])) $previewad['adsize'] = $this->cleanInput($_GET['as_adsize'][$i]); if(isset($_GET['as_adtype'][$i])) $previewad['adtype'] = $this->cleanInput($_GET['as_adtype'][$i]); if(isset($_GET['as_adlocation'][$i])) $previewad['adlocation'] = $this->cleanInput($_GET['as_adlocation'][$i]); if(isset($_GET['as_adpadding'][$i])) $previewad['adpadding'] = $this->cleanInput($_GET['as_adpadding'][$i]); if(isset($_GET['as_admargin'][$i])) $previewad['admargin'] = $this->cleanInput($_GET['as_admargin'][$i]); if(isset($_GET['as_color'][$i])) $previewad['color'] = $this->cleanInput($_GET['as_color'][$i]); if(isset($_GET['as_colorborder'][$i])) $previewad['color_border'] = $this->cleanInput($_GET['as_colorborder'][$i]); if(isset($_GET['as_colorbg'][$i])) $previewad['color_bg'] = $this->cleanInput($_GET['as_colorbg'][$i]); if(isset($_GET['as_colorlink'][$i])) $previewad['color_link'] = $this->cleanInput($_GET['as_colorlink'][$i]); if(isset($_GET['as_colortext'][$i])) $previewad['color_text'] = $this->cleanInput($_GET['as_colortext'][$i]); if(isset($_GET['as_colorurl'][$i])) $previewad['color_url'] = $this->cleanInput($_GET['as_colorurl'][$i]); //security risk, just show black box instead //if(isset($_GET['as_customcode'][$i])) $previewad['customcode'] = $this->cleanInput($_GET['as_customcode'][$i]); if(isset($_GET['as_custom'][$i]) && $_GET['as_custom'][$i]=='html') $previewad['customcode'] = "
settings['installid']))
{
//first time authenticating
//pass contact so can get install id and init training
$state = get_option('admin_email')."|||".$real_redirect_uri;
}
else
{
$state = $this->settings['installid']."|||".$real_redirect_uri;
}
$encodedstate = base64_encode($state);
return "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=$google_client_id&redirect_uri=$redirect_uri&scope=$scope&access_type=offline&approval_prompt=force&state=$encodedstate"; //force so that it always returns refresh token
}
public function get_segment_preview_url($segmenti)
{
$criteria = isset($this->settings['segments'][$segmenti]['criteria']) ? $this->settings['segments'][$segmenti]['criteria'] : null;
$criteriaparam = isset($this->settings['segments'][$segmenti]['criteriaparam']) ? $this->settings['segments'][$segmenti]['criteriaparam'] : null;
$nonefoundurl = "http://www.ampedsense.com/empty-segment";
if($criteria=="post")
{
return get_permalink($criteriaparam);
}
elseif($criteria=="page")
{
return get_permalink($criteriaparam);
}
elseif($criteria=="category")
{
$recent_posts = wp_get_recent_posts( array( 'numberposts' => '1', 'post_type' => 'post', 'post_status' => 'publish', 'category' => $criteriaparam ));
if(count($recent_posts)) return get_permalink($recent_posts[0]["ID"]);
else return $nonefoundurl;
}
elseif($criteria=="homepage")
{
return get_home_url();
}
elseif($criteria=="allposts")
{
$recent_posts = wp_get_recent_posts( array( 'numberposts' => '1', 'post_type' => 'post', 'post_status' => 'publish' ));
if(count($recent_posts)) return get_permalink($recent_posts[0]["ID"]);
else return $nonefoundurl;
}
elseif($criteria=="allpages")
{
$recent_posts = wp_get_recent_posts( array( 'numberposts' => '1', 'post_type' => 'page', 'post_status' => 'publish' ));
if(count($recent_posts)) return get_permalink($recent_posts[0]["ID"]);
else return $nonefoundurl;
}
else //mobile or default (all) segment
{
//return post or page
$recent_posts = wp_get_recent_posts( array( 'numberposts' => '1', 'post_type' => 'post', 'post_status' => 'publish' ));
if(count($recent_posts)) return get_permalink($recent_posts[0]["ID"]);
else
{
$recent_posts = wp_get_recent_posts( array( 'numberposts' => '1', 'post_type' => 'page', 'post_status' => 'publish' ));
if(count($recent_posts)) return get_permalink($recent_posts[0]["ID"]);
else return $nonefoundurl;
}
}
}
public function get_recipe_preview_qs($recipe)
{
//as_preview=1&as_numads=1&as_custom%5B1%5D=0&as_adsize%5B1%5D=300x250&as_adtype%5B1%5D=TI&as_adlocation%5B1%5D=AP&as_recipename=&as_channelname=&as_channelid=
$count = count($recipe['ads']);
$qs = "as_preview=1&as_numads=$count";
foreach($recipe['ads'] as $key=>$ad)
{
$i = $key+1;
if(isset($ad['custom'])) $qs .= "&as_custom[$i]=".$ad['custom'];
if(isset($ad['adsize'])) $qs .= "&as_adsize[$i]=".$ad['adsize'];
if(isset($ad['adtype'])) $qs .= "&as_adtype[$i]=".$ad['adtype'];
if(isset($ad['adlocation'])) $qs .= "&as_adlocation[$i]=".$ad['adlocation'];
if(isset($ad['adpadding'])) $qs .= "&as_adpadding[$i]=".urlencode($ad['adpadding']);
if(isset($ad['admargin'])) $qs .= "&as_admargin[$i]=".urlencode($ad['admargin']);
//don't put html into query string, for security
//if(isset($ad['customcode'])) $qs .= "&as_customcode[$i]=".urlencode($ad['customcode']);
if(isset($ad['color'])) $qs .= "&as_color[$i]=".urlencode($ad['color']);
if(isset($ad['color_border'])) $qs .= "&as_colorborder[$i]=".urlencode($ad['color_border']);
if(isset($ad['color_bg'])) $qs .= "&as_colorbg[$i]=".urlencode($ad['color_bg']);
if(isset($ad['color_link'])) $qs .= "&as_colorlink[$i]=".urlencode($ad['color_link']);
if(isset($ad['color_text'])) $qs .= "&as_colortext[$i]=".urlencode($ad['color_text']);
if(isset($ad['color_url'])) $qs .= "&as_colorurl[$i]=".urlencode($ad['color_url']);
}
return $qs;
}
public function get_ir_fromdate($segmenti)
{
if(isset($_SESSION['as_fromdate'][$segmenti]) && $_SESSION['as_fromdate'][$segmenti]!="")
{
return $_SESSION['as_fromdate'][$segmenti];
}
else
{
//go through each recipe, pick first date
$earliest = time()+1; //future
if(isset($this->settings['segments'][$segmenti]['recipes']) && count($this->settings['segments'][$segmenti]['recipes']))
{
foreach($this->settings['segments'][$segmenti]['recipes'] as $recipe)
{
//only do those that are active
if($recipe['active'])
{
if($recipe['whenstarted']<$earliest)
{
$earliest = $recipe['whenstarted'];
}
}
}
}
return date("m/d/Y",$earliest);
}
return "XX/XX/XX";
}
public function lookup_channels()
{
//don't need to see if any channelids are missing, they always will be on edit or on new, or whenever this function is called
//lookup custom channel ids if some are missing / new
if(isset($_SESSION['as_googleaccesstoken']) && $_SESSION['as_googleaccesstoken']!="")
{
//first need ad client ids
$adclientids = array();
$returnedjson = $this->getUrlContents("https://www.googleapis.com/adsense/v1.4/accounts/".urlencode($this->settings['adsensepublisherid'])."/adclients/?access_token=".urlencode($_SESSION['as_googleaccesstoken'])."&userIp=".$this->ip);
$apiresult = json_decode($returnedjson,true);
if(count($apiresult) && empty($apiresult["error"]))
{
//could be multiple, save them
if(count($apiresult['items']))
{
//like ca-pub-89204534XXXXXXXX and ca-mb-pub-XXXXXXXXXX
foreach($apiresult['items'] as $item)
{
$adclientids[] = $item['id'];
}
}
}
else echo "Error: $returnedjson";
if(count($adclientids))
{
//now get channels for each adclientid
$customchannels = array();
foreach($adclientids as $adclientid)
{
echo "Retrieving custom channels...";
$returnedjson = $this->getUrlContents("https://www.googleapis.com/adsense/v1.4/accounts/".urlencode($this->settings['adsensepublisherid'])."/adclients/".urlencode($adclientid)."/customchannels/?access_token=".urlencode($_SESSION['as_googleaccesstoken'])."&userIp=".$this->ip);
$apiresult = json_decode($returnedjson,true);
if(count($apiresult) && empty($apiresult["error"]))
{
//will be multiple, save them
if(isset($apiresult['items']) && count($apiresult['items']))
{
//like "kind": "adsense#customChannel","id": "ca-pub-892040000:00000009999","code": "000000009999", "name": "XXXXXXXXXXXX"
foreach($apiresult['items'] as $item)
{
$name = $item['name'];
$customchannels[$name] = $item['code'];
}
}
}
else echo "Error: $returnedjson";
usleep(100000); //.1 second delay for quota mgmt
}
//now have list of ALL custom channels, see which we need to set
if(count($customchannels))
{
foreach($this->settings['segments'] as $segmenti=>$segment)
{
if(isset($segment["recipes"]) && count($segment["recipes"]))
{
foreach($segment["recipes"] as $recipei=>$recipe)
{
if(!isset($recipe["channelid"]) || $recipe["channelid"]=="")
{
foreach($customchannels as $name=>$code)
{
if($recipe['channelname']==$name)
{
$this->settings['segments'][$segmenti]['recipes'][$recipei]['channelid'] = $code;
$this->settings_dirty = true;
}
}
}
}
}
}
}
}
}
}
public function deviceCriteriaToString($devices)
{
//d=desktop, t=tablet, p=phone
if($devices=='dtp') return "All Devices";
if($devices=='dt') return "Desktops & Tablets";
if($devices=='tp') return "Tablets & Phones";
if($devices=='d') return "Desktops";
if($devices=='t') return "Tablets";
if($devices=='p') return "Phones";
return "Unknown";
}
//Utility functions
public function toPercent($num)
{
return sprintf("%01.2f", ($num*100));
}
public function cleanInput( $string )
{
if(!isset($string)) return "";
$string = trim($string);
if(true) { //wordpress automatically escapes quotes, regardless of if get_magic_quotes_gpc() is on
return stripslashes($string);
} else {
return $string;
}
}
public function getUrlContents($url)
{
//abstract out retrieving url, since file_get_contents vs curl may not be supported depending on host
$response = wp_remote_get( $url );
return wp_remote_retrieve_body($response);
}
public $googleclientid = "832329400699-sp4npe7175l2td6gcc7ahou1h8sjav3l.apps.googleusercontent.com";
}
//need to make seperate class so can associate ad with callback
class AmpedSenseRenderer
{
public $ad = null;
public $publisherid = "";
public $channelid = "";
public $watermark = "";
public function inject_ad_in_content($thecontent)
{
$adhtml = $this->render_ad();
$padding = (isset($this->ad['adpadding']) && $this->ad['adpadding']!="") ? "padding: ".$this->ad['adpadding']."; " : "";
$margin = (isset($this->ad['admargin']) && $this->ad['admargin']!="") ? "margin: ".$this->ad['admargin']."; " : "";
if($this->ad['adlocation']=="AP")
{
//above post
$thecontent = $this->watermark."'s yet, still \n //$closingp = "\n\n"; //$paragrapharr = explode($closingp, $thecontent); //print_r($thecontent); $paragrapharr = preg_split('/(\n\s*\n|<\/p>)/', $thecontent, -1, PREG_SPLIT_NO_EMPTY); //this is what wpautop() uses, except I added the |
//figure out index $insertindex = 0; if($distance=="P") { //after p1 $insertindex = 1; } elseif($distance=="1") { // 1/4 way down $insertindex = round(count($paragrapharr)*.25); } elseif($distance=="2") { // 1/2 way down $insertindex = round(count($paragrapharr)*.5); } elseif($distance=="3") { // 3/4 way down $insertindex = round(count($paragrapharr)*.75); } //insert it array_splice($paragrapharr, $insertindex, 0, array($addiv)); //join it all back return implode("\n\n", $paragrapharr); } public function render_ad() { //return ad snippet if($this->ad['custom']=="resp" || $this->ad['custom']=="html") { //wordpress will auto paragraph newlines on all html content (won't do it if within "; } else { //generate dynamic adsense ad $width = 0; $height = 0; $format = ''; //in order excluding recommended if($this->ad['adsize']=="728x90") { $width = 728; $height = 90; $format = "728x90_as"; } elseif($this->ad['adsize']=="320x100") { $width = 320; $height = 100; $format = "320x100_as"; } elseif($this->ad['adsize']=="970x250") { $width = 970; $height = 250; $format = "970x250_as"; } elseif($this->ad['adsize']=="970x90") { $width = 970; $height = 90; $format = "970x90_as"; } elseif($this->ad['adsize']=="468x60") { $width = 468; $height = 60; $format = "468x60_as"; } elseif($this->ad['adsize']=="320x50") { $width = 320; $height = 50; $format = "320x50_as"; } elseif($this->ad['adsize']=="234x60") { $width = 234; $height = 60; $format = "234x60_as"; } elseif($this->ad['adsize']=="300x600") { $width = 300; $height = 600; $format = "300x600_as"; } elseif($this->ad['adsize']=="300x1050") { $width = 300; $height = 1050; $format = "300x1050_as"; } elseif($this->ad['adsize']=="160x600") { $width = 160; $height = 600; $format = "160x600_as"; } elseif($this->ad['adsize']=="120x600") { $width = 120; $height = 600; $format = "120x600_as"; } elseif($this->ad['adsize']=="120x240") { $width = 120; $height = 240; $format = "120x240_as"; } elseif($this->ad['adsize']=="336x280") { $width = 336; $height = 280; $format = "336x280_as"; } elseif($this->ad['adsize']=="300x250") { $width = 300; $height = 250; $format = "300x250_as"; } elseif($this->ad['adsize']=="250x250") { $width = 250; $height = 250; $format = "250x250_as"; } elseif($this->ad['adsize']=="200x200") { $width = 200; $height = 200; $format = "200x200_as"; } elseif($this->ad['adsize']=="180x150") { $width = 180; $height = 150; $format = "180x150_as"; } elseif($this->ad['adsize']=="125x125") { $width = 125; $height = 125; $format = "125x125_as"; } elseif($this->ad['adsize']=="728x15") { $width = 728; $height = 15; $format = "728x15_0ads_al"; } elseif($this->ad['adsize']=="468x15") { $width = 468; $height = 15; $format = "468x15_0ads_al"; } elseif($this->ad['adsize']=="200x90") { $width = 200; $height = 90; $format = "200x90_0ads_al"; } elseif($this->ad['adsize']=="180x90") { $width = 180; $height = 90; $format = "180x90_0ads_al"; } elseif($this->ad['adsize']=="160x90") { $width = 160; $height = 90; $format = "160x90_0ads_al"; } elseif($this->ad['adsize']=="120x90") { $width = 120; $height = 90; $format = "120x90_0ads_al"; } $type = 'text_image'; if($this->ad['adtype']=='T') $type = 'text'; elseif($this->ad['adtype']=='I') $type = 'image'; $colorsettings = ""; if(isset($this->ad['color']) && $this->ad['color']=='custom') { //dont put more newlines in here, wordpress puts$colorsettings = " google_color_border = '".$this->ad['color_border']."'; google_color_bg = '".$this->ad['color_bg']."'; google_color_link = '".$this->ad['color_link']."'; google_color_text = '".$this->ad['color_text']."'; google_color_url = '".$this->ad['color_url']."';"; } //clientid and channelid have already been confirmed set return ""; } } //static public function applyShortcodeRenderers($rendererarr) { $buffer = ""; if(count($rendererarr)) { foreach($rendererarr as $renderer) { $adhtml = $renderer->render_ad(); $padding = (isset($renderer->ad['adpadding']) && $renderer->ad['adpadding']!="") ? "padding: ".$renderer->ad['adpadding']."; " : ""; $margin = (isset($renderer->ad['admargin']) && $renderer->ad['admargin']!="") ? "margin: ".$renderer->ad['admargin']."; " : ""; $buffer .= $renderer->watermark."