<?php

// include the GAPI class from http://code.google.com/p/gapi-google-analytics-php-interface/
require_once 'gapi.class.php';

// login details for the account that has access to analytics reports.
define('ga_web_email', 'you@email.com');
define('ga_web_pass', 'password');

// use our caching function above to get some results in a nice array
// change 123456789 to your google analytics id.
$data = get_analytics_data('123456789',array('date'),array('newVisits','visits'));
// output the image:
output_image($data);

function get_analytics_data(
		$profile_id,
		$dimensions=array('browser'),
		$metrics=array('pageviews','visits','UniquePageviews'),
		$sort=null,
		$start_date=null,
		$end_date=null
	){
	$cache_id = md5(serialize(func_get_args()));
	$return = false;
	// check if the cache item exists.
	$temp_folder = '/tmp/ga/';
	if(!is_dir($temp_folder))mkdir($temp_folder);
	$filename = $temp_folder.$cache_id;
	if(is_file($filename)){ // if cache entry exists
		if(filemtime($filename) > (time() - 172800)){ // check if it's older than 2 days
			$return = unserialize(file_get_contents($filename)); // grab the cached content.
		}
	}
	if(!$return){
		// no cache item found, so we grab it via gapi class.
		$ga = new gapi(ga_web_email,ga_web_pass);
		if(!$sort)$sort = current($dimensions);
		ini_set('display_errors',true);
		$ga->requestReportData($profile_id,$dimensions,$metrics,$sort,null,$start_date,$end_date,null,100);
		$return = array();
		$return['data'] = array();
		foreach($ga->getResults() as $result){
			$data = array();
			foreach($dimensions as $d){
				$data[$d] = (string)$result;
				foreach($metrics as $m){
					$data[$m] = $result->{'get'.$m}();
				}
			}
			$return['data'][] = $data;
		}
		$return['total'] = $ga->getTotalResults();
		foreach($metrics as $m){
			$return[$m] = $ga->{'get'.$m}();
		}
		$return['timestamp'] =  $ga->getUpdated();
	}
	// save cache item.
	file_put_contents($filename,serialize($return));
	return $return;
}

function output_image($data){
	$max_y = 500;
	$width = 640;
	$height = 200;
	$attr=array();
	$days = count($data['data'])-1;
	// work out the width of 1 day
	$day_width_percent = round((100 / $days)/100,4); // 15% will be 0.15  1% will be 0.01
	$half_day_width = round($day_width_percent/2,4);
	$attr['chxl'] = '1:'; // the data point label text.
	$attr['chxp'] = '1'; // the data point label positions.
	$attr['chxr'] = '0,0,'.$max_y.'|1,0,'.$days; // the min/max data range to graph over the space of the image.
	$attr['chxt'] = 'y,x'; // ?
	$attr['chs'] = $width.'x'.$height; // width x height of the image.
	$attr['cht'] = 'lc'; // type of graph
	$attr['chco'] = '3D7930,FF9900'; // colors of the graph lines.
	$attr['chds'] = '0,'.$max_y.',0,'.$max_y.''; // data range of each data set (0 to 500 each)
	$attr['chdl'] = 'Visits|New Visits'; // labels for each data set
	$attr['chg'] =  (100/$days) . ',' . ((100/$max_y)*100) . ',4,1,-'.($half_day_width*100).',0'; // (vert,horiz) how many step lines.
	$attr['chls'] = '2,4,0|1'; // ?something about size of lines maybe?
	$attr['chtt'] = 'Visits vs New Visits over past '.$data['total'].' days.'; // graph label at the top.
	// graph stripes. every saturday and sunday ?
	// work out what day the graph starts on.
	$first = current($data['data']);
	$start_day = date('N',strtotime($first['date']));
	// how big is the first bar?
	// highlight white from first bar to first Saturday (6)
	$attr['chf'] = 'c,ls,0';
	$number_of_days = 6 - $start_day;
	if($number_of_days>0){
		// we start with a white bar, because we're starting graph during the week.
		$color='FFFFFF';
		$attr['chf'] .= ','.$color.','.(round($number_of_days*$day_width_percent,5)-$half_day_width);
	}else{
		// we're starting graph on a saturday or sunday.
		$color='EFEFEF';
		$attr['chf'] .= ','.$color.','.(round((8-6)*$day_width_percent,5)-$half_day_width);
		// then we do 5 days white.
		$attr['chf'] .= ',FFFFFF,'.round(5*$day_width_percent,5);
	}
	// loop over for the remaining days, every 7 days different colour.
	for($x=0;$x<=$days;$x+=7){
		// we're doing 2 days dark for weekend.
		$attr['chf'] .= ',EFEFEF,'.round(2*$day_width_percent,5);
		// we're doing 5 days white.
		$attr['chf'] .= ',FFFFFF,'.round(5*$day_width_percent,5);
	}

	$p = $start_day;

	$x=0;
	$points1 = $points2 = '';
	foreach($data['data'] as $d){
		if($p%7==1){
			// every monday put a date.
			$attr['chxl'] .= '|Mon' . date('jM',strtotime($d['date']));
			$attr['chxp'] .= ',' . $x;
		}
		$points1 .= $d['visits'].',';
		$points2 .= $d['newVisits'].',';
		$x++;
		$p++;
	}

	$attr['chd'] = 't:' . rtrim($points1,',') . '|' . rtrim($points2,',');
	?>
	<img src="http://chart.apis.google.com/chart?<?php foreach($attr as $k=>$v) echo $k .'='.urlencode($v).'&
	';?>" width="<?php echo $width;?>"
		 height="<?php echo $height;?>" alt="<?php echo $attr['chtt'];?>" />
<?php
}
?>
Advertisements