本文整理汇总了PHP中gapi类的典型用法代码示例。如果您正苦于以下问题:PHP gapi类的具体用法?PHP gapi怎么用?PHP gapi使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了gapi类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: GoogleAnalyticsPopularPosts_widget_output
function GoogleAnalyticsPopularPosts_widget_output()
{
$GAPP_usr = get_option('GoogleAnalyticsPopularPosts_username');
$GAPP_pwd = get_option('GoogleAnalyticsPopularPosts_password');
$GAPP_pID = get_option('GoogleAnalyticsPopularPosts_profileID');
$GAPP_mRs = get_option('GoogleAnalyticsPopularPosts_maxResults');
$GAPP_SDs = get_option('GoogleAnalyticsPopularPosts_statsSinceDays');
$GAPP_filter = get_option('GoogleAnalyticsPopularPosts_filter');
$GAPP_dDisp = get_option('GoogleAnalyticsPopularPosts_dateDispEnable');
$GAPP_pDisp = get_option('GoogleAnalyticsPopularPosts_postDateEnable');
$GAPP_cView = get_option('GoogleAnalyticsPopularPosts_contentsViewEnable');
if (is_numeric($GAPP_SDs)) {
$todays_year = date("Y");
$todays_month = date("m");
$todays_day = date("d");
$date = "{$todays_year}-{$todays_month}-{$todays_day}";
$newdate = strtotime("-{$GAPP_SDs} day", strtotime($date));
$newdate = date('Y-m-d', $newdate);
$From = $newdate;
}
define('ga_email', $GAPP_usr);
define('ga_password', $GAPP_pwd);
define('ga_profile_id', $GAPP_pID);
if (!ga_email || !ga_password || !ga_profile_id) {
$output = __('<b>Google Analytics Popular Posts Error :</b><br />Please enter your account details in the options page.', 'google-analytics-popular-posts');
return $output;
}
$GAPP_filter_fixed = 'ga:pagePath=~^/';
require 'gapi.class.php';
$ga = new gapi(ga_email, ga_password);
$ga->requestReportData(ga_profile_id, array('hostname', 'pagePath'), array('visits'), array('-visits'), $filter = $GAPP_filter_fixed . $GAPP_filter, $start_date = $From, $end_date = $date, $start_index = 1, $max_results = $GAPP_mRs);
if ($GAPP_dDisp == "yes") {
$output = '<p class="popular_stats_date">' . $From . ' ~ ' . $date . '</p>' . "\n";
}
foreach ($ga->getResults() as $result) {
$getHostname = $result->getHostname();
$getPagepath = $result->getPagepath();
$postPagepath = 'http://' . $getHostname . $getPagepath;
$getPostID = url_to_postid($postPagepath);
if ($getPostID <= 0) {
$titleStr = $postPagepath;
$output .= '<ul>' . "\n";
$output .= '<li>' . "\n";
$output .= '<div class="popular_post"><a href=' . $postPagepath . '>' . $titleStr . '</a></div>' . "\n";
$output .= '</li>' . "\n";
$output .= '</ul>' . "\n";
} else {
$titleStr = get_the_title($getPostID);
$post = get_post($getPostID);
$dateStr = mysql2date('Y-m-d', $post->post_date);
$contentStr = strip_tags(mb_substr($post->post_content, 0, 60));
$output .= '<ul>' . "\n";
$output .= '<li>' . "\n";
$output .= '<div class="popular_post"><a href=' . $postPagepath . '>' . $titleStr . '</a><br />' . "\n";
if ($GAPP_pDisp == "yes" and $GAPP_cView == "yes") {
$output .= '<div class="popular_post_date">' . $dateStr . '<br /></div>' . "\n";
$output .= '<div class="popular_post_contents">' . $contentStr . ' ...' . '</div>' . "\n";
} elseif ($GAPP_pDisp == "yes" and $GAPP_cView == "no") {
$output .= '<div class="popular_post_date">' . $dateStr . '<br /></div>' . "\n";
} elseif ($GAPP_pDisp == "no" and $GAPP_cView == "yes") {
$output .= '<div class="popular_post_contents">' . $contentStr . ' ...' . '</div>' . "\n";
} else {
}
$output .= '</div>' . "\n";
$output .= '</li>' . "\n";
$output .= '</ul>' . "\n";
}
}
return $output;
}
示例2: get_analytics_data
public function get_analytics_data()
{
$flot_datas_visits = array();
$analytics = Config::get('cms::settings.analytics.profile_id');
if (!empty($analytics)) {
$id = Config::get('cms::settings.analytics.id');
$account = Config::get('cms::settings.analytics.account');
$password = Config::get('cms::settings.analytics.password');
$pid = Config::get('cms::settings.analytics.profile_id');
//CACHE DATA
if (CACHE) {
$show_data = Cache::remember('analytics_' . $pid, function () use($pid, $account, $password) {
$ga = new gapi($account, $password);
$ga->requestReportData($pid, array('date'), array('visits'), array('date'), null, date("Y-m-d", strtotime("-30 days")), date("Y-m-d"));
$results = $ga->getResults();
foreach ($results as $result) {
$flot_datas_visits[] = '[' . strtotime($result->getDate()) * 1000 . ',' . $result->getVisits() . ']';
}
return $show_data = '[' . implode(',', $flot_datas_visits) . ']';
}, 1440);
//CACHE DISABLED
} else {
$ga = new gapi($account, $password);
$ga->requestReportData($pid, array('date'), array('visits'), array('date'), null, date("Y-m-d", strtotime("-30 days")), date("Y-m-d"));
$results = $ga->getResults();
foreach ($results as $result) {
$flot_datas_visits[] = '[' . strtotime($result->getDate()) * 1000 . ',' . $result->getVisits() . ']';
}
$show_data = '[' . implode(',', $flot_datas_visits) . ']';
}
return $show_data;
}
}
示例3: run
public function run()
{
class_exists('gapi') or (require dirname(__FILE__) . '/../../../vendor/gapi/gapi.class.php');
$ga = new gapi($this->email, $this->password);
$ga->requestReportData($this->profile_id, array('date'), array($this->metric), null, null, date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime('-' . $this->time)));
$methodName = 'get' . ucFirst($this->metric);
$this->result = $ga->{$methodName}();
return parent::afterConstruct();
}
示例4: get_dashboard_report
/**
*
*/
public function get_dashboard_report()
{
if (self::$should_access) {
try {
$dataRows = array();
$ga = new gapi(self::$ga_email, self::$ga_password);
// Main data
$ga->requestReportData(self::$ga_profile_id, 'pagePath', array('pageviews', 'uniquePageviews', 'exitRate', 'avgTimeOnPage', 'entranceBounceRate'), null, 'pagePath == /');
$mainData = $ga->getResults();
// Visits data
$ga->requestReportData(self::$ga_profile_id, 'date', array('visitors', 'newVisits', 'visits'), 'date');
$visitorData = $ga->getResults();
if (!empty($mainData[0])) {
$result = $mainData[0];
$data = array('pageViews' => number_format($result->getPageviews(), 0, null, ' '), 'uniquePageViews' => number_format($result->getUniquePageviews(), 0, null, ' '), 'avgTimeOnPage' => $this->secondMinute($result->getAvgtimeOnpage()), 'bounceRate' => round($result->getEntranceBounceRate(), 2) . '%');
$data['visitors'] = 0;
$data['visits'] = 0;
$data['newVisits'] = 0;
if (!empty($visitorData)) {
foreach ($visitorData as $vd) {
$data['visitors'] += $vd->getVisitors();
$data['visits'] += $vd->getVisits();
$data['newVisits'] += $vd->getNewVisits();
$dataRows[] = array(date('M j', strtotime($vd->getDate())), $vd->getVisits(), $vd->getNewVisits());
}
$data['visitors'] = number_format($data['visitors'], 0, null, ' ');
$data['visits'] = number_format($data['visits'], 0, null, ' ');
$data['newVisits'] = number_format($data['newVisits'], 0, null, ' ');
}
$this->template['data'] = $data;
}
// Get the Last 30 days data
/*
$ga->requestReportData(
self::$ga_profile_id,
array('date'),
array('pageviews','uniquePageviews'),
'date',
'pagePath == /'
);
$chartResults = $ga->getResults();
foreach($chartResults as $result)
{
$dataRows[] = array(
date('M j', strtotime($result->getDate())),
$result->getPageviews(),
$result->getUniquePageviews()
);
}
*/
$this->template['dataRows'] = json_encode($dataRows, true);
$this->output('google/dashboard_report');
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
示例5: listing
function listing()
{
$dimensions = array('month');
$metrics = array('visits', 'newvisits', 'pageviews', 'timeonsite');
$sort = array('month');
$filter = '';
$ga = new gapi('', '');
$d['full'] = $ga->requestReportData($_SESSION['cmsgaprofile'], $dimensions, $metrics, $sort, $filter, '2015-01-01', '2015-12-31', 1, 999);
$this->set($d);
}
示例6: __construct
function __construct($email, $password, $uid, $start_date = null, $end_date = null)
{
$filter = '';
$this->initialstartdate = date('M j Y', strtotime($start_date));
$this->initialenddate = date('M j Y', strtotime($end_date));
$start_index = 1;
$perdayCounts = $this->createDateRangeArray($start_date, $end_date);
$max_result = 1000000000;
$ga = new gapi($email, $password);
$ga->requestReportData($uid, array('date', 'source', 'medium', 'referralPath'), array('pageviews', 'visits', 'entranceBounceRate', 'timeOnSite', 'newVisits'), 'date', $filter, $start_date, $end_date, $start_index, $max_result);
$result = $ga->getResults();
$this->pageViews = $ga->getPageviews();
$this->visits = $ga->getVisits();
$this->bounceRate = $ga->getentranceBounceRate();
$this->timeOnSite = $ga->gettimeOnSite() / $this->visits / 60;
$this->newVisits = round($ga->getnewVisits() / $this->visits * 100, 2);
foreach ($result as $key => $value) {
$this->source[] = array('medium' => $value->getMedium(), 'visit' => $value->getVisits(), 'source' => $value->getSource());
$this->dateWise[] = array($value->getDate() => $value->getPageviews());
}
foreach ($perdayCounts as $day) {
$new_array = '';
foreach ($this->dateWise as $breakPoint) {
foreach ($breakPoint as $key => $value) {
if ($key == $day) {
$new_array[] = $value;
}
}
}
$this->valueCountsPerDay[] = array($day => array_sum($new_array));
}
}
示例7: getMetrics
public function getMetrics()
{
$json = array();
$keys = array('username', 'password', 'date_ini', 'date_end');
foreach ($keys as $key) {
if (isset($this->request->post[$key])) {
${$key} = $this->request->post[$key];
} else {
${$key} = '';
}
}
$this->load->model('account/api');
$api_info = $this->model_account_api->login($username, $password);
if ($api_info) {
if ($date_ini && $date_end) {
$json['quantity_email'] = (int) $this->model_account_api->getTotalEmails();
$json['quantity_product'] = (int) $this->model_account_api->getTotalProducts();
$json['quantity_billing'] = (double) $this->model_account_api->getBillingStore($date_ini, $date_end);
require_once DIR_SYSTEM . "library/gapi.php";
$key = DIR_APPLICATION . 'controller/api/key/' . $api_info['email'] . '.p12';
$ga = new gapi($api_info['email'], $key);
$results = $ga->requestAccountData();
$id = '';
foreach ($results['items'] as $perfil) {
for ($i = 0; $i < count($perfil['webProperties']); $i++) {
if ($perfil['webProperties'][$i]['id'] == $this->config->get('config_google_analytics')) {
$count = count($perfil['webProperties'][$i]['profiles']) - 1;
$id = $perfil['webProperties'][$i]['profiles'][$count]['id'];
}
}
}
if ($id) {
$ga->requestReportData($id, 'day', array('pageviews', 'visits'), 'day', null, $date_ini, $date_end, 1, 50);
$pageviews = 0;
foreach ($ga->getResults() as $dados) {
$pageviews += $dados->getPageviews();
}
$json['quantity_pageview'] = (int) $pageviews;
} else {
$json['quantity_pageview'] = 'A conta do usúario não foi encontrada no Google Analytics';
}
}
} else {
$json['error'] = 'Token Inválido';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
示例8: gAnalytics
/**
* Obter informações do Google Analytics
*
* @param string $dt_inicio Data de início da consulta
* @param string $dt_fim Data final da consulta
* @param string $dimensao Dimensão a ser utilizada para agrupar os resultados
* @param array $metricas
*
* @throws \DL3Exception
*/
public function gAnalytics($dt_inicio, $dt_fim, $dimensao = 'day', $metricas = ['visits'])
{
# Selecionar as configurações do Google Analytics
$m_ga = new WebM\GoogleAnalytics();
$m_ga->selecionarPrincipal();
# Conectar ao Google Analytics
$o_ga = new \gapi($m_ga->contaCompleta(), $m_ga->getP12());
# Retornar as informações
$o_ga->requestReportData($m_ga->getPerfilId(), $dimensao, !isset($metricas) ? ['visits'] : $metricas, null, null, \Funcoes::formatarDataHora($dt_inicio, 'Y-m-d'), \Funcoes::formatarDataHora($dt_fim, 'Y-m-d'));
# Visitas
$infos = [];
foreach ($o_ga->getResults() as $info) {
$infos[] = ['dimensao' => (string) $info, 'visitas' => $info->getVisits()];
}
// Fim foreach
echo json_encode($infos);
}
示例9: info
private function info($id)
{
$results = array();
if ($id == null) {
$results = SearchKeywords::getKeywords($this->url);
} else {
$ga = new gapi(config::ga_email, config::ga_password);
$start = date('Y-m-d', strtotime('-1 day'));
$end = date('Y-m-d', strtotime('-1 day'));
$ga->requestReportData($id, array('keyword'), array('visits'), '-visits', null, $start, $end);
foreach ($ga->getResults() as $r) {
$results[1][] = $r->getKeyword();
$results[2][] = $r->getVisits();
}
}
for ($j = 0; $j < count($results[1]); ++$j) {
if ($results[1][$j] != "(not set)") {
$this->keys[] = array("keyword" => $results[1][$j], "visits" => $results[2][$j], "pos" => $this->keywordPosition($results[1][$j]));
}
}
}
示例10: _monthPageViewsVisits
/**
* A temporary function to hold the first example of a chart data return.
* We can make this more robust and to handle more uses cases.
* @todo Make an entire analytics plugin to be part of the reports plugin.
*/
public function _monthPageViewsVisits()
{
if (!empty($instance) && defined('__REPORTS_ANALYTICS_' . $instance)) {
extract(unserialize(constant('__REPORTS_ANALYTICS_' . $instance)));
} else {
if (defined('__REPORTS_ANALYTICS')) {
extract(unserialize(__REPORTS_ANALYTICS));
}
}
if (!empty($userName) && !empty($password) && !empty($setAccount)) {
App::import('Vendor', 'Reports.gapi');
$ga = new gapi($userName, $password, isset($_SESSION['ga_auth_token']) ? $_SESSION['ga_auth_token'] : null);
$_SESSION['ga_auth_token'] = $ga->getAuthToken();
// $filter = 'country == United States && browser == Firefox || browser == Chrome';
// $report_id, $dimensions, $metrics, $sort_metric=null, $filter=null, $start_date=null, $end_date=null, $start_index=1, $max_results=30
// http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html#ga:visitors
foreach ($ga->requestAccountData() as $account) {
if (is_object($account)) {
if ($account->properties['webPropertyId'] == $setAccount) {
$reportId = $account->properties['profileId'];
}
}
}
$backMonth = date('Y-m-d', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")));
$ga->requestReportData(53475, array('date'), array('pageviews', 'visits'), 'date', null, $backMonth, date('Y-m-d'));
$i = 0;
foreach ($ga->getResults() as $result) {
#debug($result);
$chartData[$i]['pageviews'] = $result->getPageviews();
$chartData[$i]['visits'] = $result->getVisits();
$chartData[$i]['date'] = $result->getDate();
$i++;
}
$chartData['totalResults'] = $ga->getTotalResults();
$chartData['totalPageViews'] = $ga->getPageviews();
$chartData['totalVisits'] = $ga->getVisits();
$chartData['updated'] = $ga->getUpdated();
return $chartData;
} else {
// google analytics username and password must be set in settings (__REPORTS_ANALYTICS)
return;
}
}
示例11: save_settings
function save_settings()
{
// Get all settings
$settings = $this->get_settings(TRUE);
// Get current site
$site = $this->EE->config->item('site_id');
// print_r($settings); exit();
// If we're posting a username and password,
// check if they authenticate, and store them if they do.
// If not, discard and throw the authentication error flag
if (isset($_POST['user']) && isset($_POST['password'])) {
require_once PATH_THIRD . 'cp_analytics/libraries/gapi.class.php';
$ga_user = $_POST['user'];
$ga_password = $_POST['password'];
$ga = new gapi($ga_user, $ga_password);
if ($ga->getAuthToken() != FALSE) {
$settings[$site]['user'] = $_POST['user'];
$settings[$site]['password'] = base64_encode($_POST['password']);
$settings[$site]['authenticated'] = 'y';
} else {
// The credentials don't authenticate, so zero us out
$settings[$site]['user'] = '';
$settings[$site]['password'] = '';
$settings[$site]['profile'] = '';
$settings[$site]['authenticated'] = 'n';
}
}
if (isset($_POST['profile'])) {
$settings[$site]['profile'] = $_POST['profile'];
$settings[$site]['hourly_cache'] = '';
$settings[$site]['daily_cache'] = '';
}
$this->EE->db->where('class', ucfirst(get_class($this)));
$this->EE->db->update('extensions', array('settings' => serialize($settings)));
$this->EE->session->set_flashdata('message_success', $this->EE->lang->line('preferences_updated'));
$this->EE->functions->redirect(BASE . AMP . 'C=addons_extensions' . AMP . 'M=extension_settings' . AMP . 'file=' . $this->slug);
exit;
}
示例12: __call
/**
* Call method to find a matching parameter to return
*
* @param $name String name of function called
* @return String
* @throws Exception if not a valid parameter, or not a 'get' function
*/
public function __call($name,$parameters)
{
if(!preg_match('/^get/',$name))
{
throw new Exception('No such function "' . $name . '"');
}
$name = preg_replace('/^get/','',$name);
$property_key = gapi::array_key_exists_nc($name,$this->properties);
if($property_key)
{
return $this->properties[$property_key];
}
throw new Exception('No valid property called "' . $name . '"');
}
示例13: getGAContent
function getGAContent()
{
$app =& JFactory::getApplication();
$config = $app->getuserState('rsseoConfig');
try {
$ga = new gapi($config['analytics.username'], $config['analytics.password'], $config['ga.token']);
$ga->requestReportData($config['ga.account'], array('pagePath'), array('pageviews', 'uniquePageviews', 'exitRate', 'avgTimeOnPage', 'bounces', 'entrances', 'entranceBounceRate'), '-pageviews', null, $config['ga.start'], $config['ga.end'], 1, 20);
$return = array();
$results = $ga->getResults();
if (!empty($results)) {
foreach ($results as $result) {
$object = new stdClass();
$object->page = $result->getpagePath();
$pageviews = $result->getPageviews();
$pageviews = $pageviews == '' ? JText::_('RSSEO_NOT_AVAILABLE') : $pageviews;
$upageviews = $result->getUniquePageviews();
$upageviews = $upageviews == '' ? JText::_('RSSEO_NOT_AVAILABLE') : $upageviews;
$avgtimesite = $result->getavgTimeOnPage();
$avgtimesite = $avgtimesite === '' ? JText::_('RSSEO_NOT_AVAILABLE') : $this->convertseconds(number_format($avgtimesite, 0));
$bouncerate = $result->getentranceBounceRate();
$bouncerate = $bouncerate === '' ? JText::_('RSSEO_NOT_AVAILABLE') : number_format($bouncerate, 2) . ' %';
$exits = $result->getexitRate();
$exits = $exits === '' ? JText::_('RSSEO_NOT_AVAILABLE') : number_format($exits, 2) . ' %';
$object->pageviews = $pageviews;
$object->upageviews = $upageviews;
$object->avgtimesite = $avgtimesite;
$object->bouncerate = $bouncerate;
$object->exits = $exits;
$return[] = $object;
}
}
return $return;
} catch (Exception $e) {
return $e->getMessage();
}
}
示例14: Get_StatGA
function Get_StatGA()
{
$u = COption::GetOptionString('statga', 'ga_login');
$p = COption::GetOptionString('statga', 'ga_password');
$id = COption::GetOptionString('statga', 'ga_id');
//дата, начиная с которой необходимо получить данные из GA для отчета. Формат YYYY-MM-DD
//берем дату год назад
$datestart = mktime(0, 0, 0, date("m"), date("d"), date("Y") - 1);
//текущая дата
$currentdate = date("Ymd");
//дата, заканчивая которой
//$datefinish="";
//или вычисляем дату - конец предыдущего месяца
$currentday = date("d");
$currentmonth = date("m");
$currentyear = date("Y");
$datefinish = date("Y-m-d");
//дата 3 месяца назад
$date3MonthStart = date("Y-m-d", mktime(0, 0, 0, $currentmonth - 3, $currentday - 1, $currentyear));
$date3MonthFinish = date("Y-m-d", mktime(0, 0, 0, $currentmonth, $currentday - 1, $currentyear));
//дата месяц назад
$date1MonthStart = date("Y-m-d", mktime(0, 0, 0, $currentmonth - 1, $currentday - 1, $currentyear));
$date1MonthFinish = date("Y-m-d", mktime(0, 0, 0, $currentmonth, $currentday - 1, $currentyear));
//количество стран
$countryRows = 3;
//количество городов
$cityRows = 10;
//csv-файл для отчета Посетители
$visitorsCSV = "visitors.csv";
//csv-файл для отчета Посетители за посл. 3 месяца
$visitors3CSV = "visitors_3.csv";
//csv-файл для отчета География по странам
$countryCSV = "country.csv";
//csv-файл для отчета География по городам
$cityCSV = "city.csv";
//полный пусть к директории со скриптом (слэш в конце обязателен!)
$path = dirname(__FILE__) . "/../../../cache/" . SITE_ID . "/statga/";
try {
$ga = new gapi($u, $p);
//получаем пользователи/просмотры за все время
$ga->requestReportData($id, array('month', 'year'), array('visitors', 'pageviews'), 'year', null, $datestart, $datefinish, 1, 1000);
//получаем и обрабатываем результаты
foreach ($ga->getResults() as $result) {
$m = $result;
//месяц год
$visitors = $result->getVisitors();
//посетители
$pageviews = $result->getPageviews();
//просмотры
//приводим дату к удобочитаемому виду ,мменяем пробелы на точки
$m = str_replace(" ", ".", $m);
//формируем строку
$output .= $m . ";" . $visitors . ";" . $pageviews . "\n";
}
//пишем в файл
self::writeToFile($path . $visitorsCSV, $output);
//получаем пользователи/просмотры/посещения за последние 3 месяца
$ga->requestReportData($id, array('day', 'month', 'year'), array('visitors', 'visits', 'pageviews'), array('year', 'month'), null, $date3MonthStart, $date3MonthFinish, 1, 1000);
//переменная для записи резалта
$output = "";
//получаем и обрабатываем результаты
foreach ($ga->getResults() as $result) {
$d = $result;
//день
$visitors = $result->getVisitors();
//посетители
$pageviews = $result->getPageviews();
//просмотры
$visits = $result->getVisits();
//посещения
//приводим дату к удобочитаемому виду ,мменяем пробелы на точки
$d = str_replace(" ", ".", $d);
//формируем строку
$output .= $d . ";" . $visitors . ";" . $pageviews . ";" . $visits . "\n";
}
//пишем в файл
self::writeToFile($path . $visitors3CSV, $output);
//получаем географию посещений за последний месяц
$ga->requestReportData($id, array('country'), array('visits'), '-visits', null, $date1MonthStart, $date1MonthFinish, 1, $countryRows);
//переменная для записи резалта
$output = "";
//получаем общее число посещений для всех стран
$total_visits = $ga->getVisits();
//получаем и обрабатываем результаты
foreach ($ga->getResults() as $result) {
$country = $result->getCountry();
//страна
$visits = $result->getVisits();
//кол-во посещений
//нот сет переводим на русский
$country = str_replace("(not set)", "не определено", $country);
//формируем строку
$output .= $country . ";" . $visits . "\n";
}
//пишем в файл
self::writeToFile($path . $countryCSV, $output);
//////получаем ГОРОДА за последний месяц
$ga->requestReportData($id, array('city'), array('visits'), '-visits', null, $date1MonthStart, $date1MonthFinish, 1, $cityRows);
//переменная для записи резалта
$output = "";
//.........这里部分代码省略.........
示例15: fetch_daily_stats
function fetch_daily_stats($ga_user, $ga_password, $ga_profile_id)
{
global $LOC;
$data = array();
$data['cache_date'] = date('Y-m-d', $LOC->set_localized_time());
require_once PATH_LIB . 'analytics_panel/gapi.class.php';
// Compile yesterday's stats
$yesterday = new gapi($ga_user, $ga_password);
$ga_auth_token = $yesterday->getAuthToken();
$yesterday->requestReportData($ga_profile_id, array('date'), array('pageviews', 'visits', 'timeOnSite'), '', '', date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime('yesterday')));
// Get account data so we can store the profile info
$data['profile'] = array();
$yesterday->requestAccountData(1, 100);
foreach ($yesterday->getResults() as $result) {
if ($result->getProfileId() == $ga_profile_id) {
$data['profile']['id'] = $result->getProfileId();
$data['profile']['title'] = $result->getTitle();
}
}
$data['yesterday']['visits'] = number_format($yesterday->getVisits());
$data['yesterday']['pageviews'] = number_format($yesterday->getPageviews());
$data['yesterday']['pages_per_visit'] = $this->analytics_avg_pages($yesterday->getPageviews(), $yesterday->getVisits());
$data['yesterday']['avg_visit'] = $this->analytics_avg_visit($yesterday->getTimeOnSite(), $yesterday->getVisits());
// Compile last month's stats
$lastmonth = new gapi($ga_user, $ga_password, $ga_auth_token);
$lastmonth->requestReportData($ga_profile_id, array('date'), array('pageviews', 'visits', 'newVisits', 'timeOnSite', 'bounces', 'entrances'), 'date', '', date('Y-m-d', strtotime('31 days ago')), date('Y-m-d', strtotime('yesterday')));
$data['lastmonth']['date_span'] = date('F jS Y', strtotime('31 days ago')) . ' – ' . date('F jS Y', strtotime('yesterday'));
$data['lastmonth']['visits'] = number_format($lastmonth->getVisits());
$data['lastmonth']['visits_sparkline'] = $this->analytics_sparkline($lastmonth->getResults(), 'visits');
$data['lastmonth']['pageviews'] = number_format($lastmonth->getPageviews());
$data['lastmonth']['pageviews_sparkline'] = $this->analytics_sparkline($lastmonth->getResults(), 'pageviews');
$data['lastmonth']['pages_per_visit'] = $this->analytics_avg_pages($lastmonth->getPageviews(), $lastmonth->getVisits());
$data['lastmonth']['pages_per_visit_sparkline'] = $this->analytics_sparkline($lastmonth->getResults(), 'avgpages');
$data['lastmonth']['avg_visit'] = $this->analytics_avg_visit($lastmonth->getTimeOnSite(), $lastmonth->getVisits());
$data['lastmonth']['avg_visit_sparkline'] = $this->analytics_sparkline($lastmonth->getResults(), 'time');
$data['lastmonth']['bounce_rate'] = $lastmonth->getBounces() > 0 && $lastmonth->getBounces() > 0 ? round($lastmonth->getBounces() / $lastmonth->getEntrances() * 100, 2) . '%' : '0%';
$data['lastmonth']['bounce_rate_sparkline'] = $this->analytics_sparkline($lastmonth->getResults(), 'bouncerate');
$data['lastmonth']['new_visits'] = $lastmonth->getNewVisits() > 0 && $lastmonth->getVisits() > 0 ? round($lastmonth->getNewVisits() / $lastmonth->getVisits() * 100, 2) . '%' : '0%';
$data['lastmonth']['new_visits_sparkline'] = $this->analytics_sparkline($lastmonth->getResults(), 'newvisits');
// Compile last month's top content
$topcontent = new gapi($ga_user, $ga_password, $ga_auth_token);
$topcontent->requestReportData($ga_profile_id, array('hostname', 'pagePath'), array('pageviews'), '-pageviews', '', date('Y-m-d', strtotime('31 days ago')), date('Y-m-d', strtotime('yesterday')), null, 20);
$data['lastmonth']['content'] = array();
$i = 0;
// Make a temporary array to hold page paths
// (for checking dupes resulting from www vs non-www hostnames)
$paths = array();
foreach ($topcontent->getResults() as $result) {
// Do we already have this page path?
$dupe_key = array_search($result->getPagePath(), $paths);
if ($dupe_key !== FALSE) {
// Combine the pageviews of the dupes
$data['lastmonth']['content'][$dupe_key]['count'] = $result->getPageviews() + $data['lastmonth']['content'][$dupe_key]['count'];
} else {
$url = strlen($result->getPagePath()) > 30 ? substr($result->getPagePath(), 0, 30) . '…' : $result->getPagePath();
$data['lastmonth']['content'][$i]['title'] = '<a href="http://' . $result->getHostname() . $result->getPagePath() . '" target="_blank">' . $url . '</a>';
$data['lastmonth']['content'][$i]['count'] = $result->getPageviews();
// Store the page path at the same position so we can check for dupes
$paths[$i] = $result->getPagePath();
$i++;
}
}
// Slice down to 10 results
$data['lastmonth']['content'] = array_slice($data['lastmonth']['content'], 0, 10);
// Compile last month's top referrers
$referrers = new gapi($ga_user, $ga_password, $ga_auth_token);
$referrers->requestReportData($ga_profile_id, array('source', 'referralPath', 'medium'), array('visits'), '-visits', '', date('Y-m-d', strtotime('31 days ago')), date('Y-m-d', strtotime('yesterday')), null, 10);
$data['lastmonth']['referrers'] = array();
$i = 0;
foreach ($referrers->getResults() as $result) {
$data['lastmonth']['referrers'][$i]['title'] = $result->getMedium() == 'referral' ? '<a href="http://' . $result->getSource() . $result->getReferralPath() . '" target="_blank">' . $result->getSource() . '</a>' : $result->getSource();
$data['lastmonth']['referrers'][$i]['count'] = number_format($result->getVisits());
$i++;
}
return $data;
}