#!/usr/bin/php -q
<?php

$api="http://www.facebook.com/ajax/inventory_estimator.php";
$referer="http://www.facebook.com/ads/create/";
$defaults=(array('country'=>'AO','country_name'=>'Portugal','education'=>'all','include_radius'=>'false','radius'=>'10','age_min'=>'0','age_max'=>'0','location_type'=>'everywhere','bid_estimate'=>'1'));

echo "Total Portuguese users: ".get_stats(array('country'=>'AO'))."\n";
echo "Total male users: ".get_stats(array('country'=>'AO','sex[male]'=>'male'))."\n";
echo "Total female users: ".get_stats(array('country'=>'AO','sex[female]'=>'female'))."\n";
echo "Total users from 0-20y: ".get_stats(array('country'=>'AO','age_max'=>'20'))."\n";
echo "Total users from 21-30y: ".get_stats(array('country'=>'AO','age_min'=>'21','age_max'=>'30'))."\n";
echo "Total users from 31-40y: ".get_stats(array('country'=>'AO','age_min'=>'31','age_max'=>'40'))."\n";
echo "Total with +41y: ".get_stats(array('country'=>'AO','age_min'=>'41'))."\n";
echo "Total male users interested in males: ".get_stats(array('country'=>'AO','sex[male]'=>'male','interested_in[men]'=>'men'))."\n";
echo "Total female users interested in females: ".get_stats(array('country'=>'AO','sex[female]'=>'female','interested_in[women]'=>'women'))."\n";

function get_stats($args) {
  GLOBAL $api,$referer,$fields,$defaults;
  $args=array_merge($defaults,$args);
  $params=array();
  $ch = curl_init($api);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  foreach(array_keys($args) as $f) {
    array_push($params,$f."=".$args[$f]);
    }
  curl_setopt($ch, CURLOPT_POSTFIELDS,implode("&",$params));
  curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, '1');
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14');
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_REFERER, $referer);
  $output=curl_exec($ch);
  curl_close($ch);
  preg_match_all('/\"UserCount\":\"([0-9,]+)\"/i',$output,$m);
  return(str_replace(",","",$m[1][0]));
  }


?>
