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; }
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; } }
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(); }
/** * */ 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(); } } }
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); }
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)); } }
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)); }
/** * 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); }
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])); } } }
/** * 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; } }
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; }
/** * 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 . '"'); }
/** * 透過帳密取得 GA 連結 * * @param String VW_GAPI::USER 登入帳號 * @param String VW_GAPI::PWD 登入密碼 * @return NULL success * @return String error message **/ private function connect_with_user() { try { parent::__construct(VW_GAPI::USER, VW_GAPI::PWD); $rep = $this->requestAccountData(); if (!empty($rep) && !empty($this->auth_token)) { // 成功 // 寫入 token 到檔案中 $file = dirname(__FILE__) . "/token.txt"; $resource = @fopen($file, "w"); @fwrite($resource, $this->auth_token); @fclose($resource); return null; } else { return "透過帳密取得帳號資料失敗"; } } catch (Exception $e) { return "GA 連結失敗: " . $e->getMessage(); } }
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(); } }
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 = ""; //получаем общее число посещений для всех стран $total_visits = $ga->getVisits(); //получаем и обрабатываем результаты foreach ($ga->getResults() as $result) { $city = $result->getCity(); //страна $visits = $result->getVisits(); //кол-во посещений //нот сет переводим на русский $city = str_replace("(not set)", "не определено", $city); //формируем строку $output .= $city . ";" . $visits . "\n"; } //пишем в файл self::writeToFile($path . $cityCSV, $output); } catch (Exception $e) { $SEVERITY = "WARNING"; $ERROR_TYPE = "STATGA_ERROR"; $MODULE_ID = "statga"; $ITEM_ID = "Get_StatGA"; $DESCRIPTION = $e->getMessage(); CEventLog::Add(array("SEVERITY" => $SEVERITY, "AUDIT_TYPE_ID" => $ERROR_TYPE, "MODULE_ID" => $MODULE_ID, "ITEM_ID" => $ITEM_ID, "DESCRIPTION" => $DESCRIPTION)); } return "statga::Get_StatGA();"; }
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; }
<?php require 'gapi.class.php'; define('ga_profile_id', 'your profile id'); $ga = new gapi("*****@*****.**", "key.p12"); $ga->requestReportData(ga_profile_id, array('browser', 'browserVersion'), array('pageviews', 'visits')); ?> <table> <tr> <th>Browser & Browser Version</th> <th>Pageviews</th> <th>Visits</th> </tr> <?php foreach ($ga->getResults() as $result) { ?> <tr> <td><?php echo $result; ?> </td> <td><?php echo $result->getPageviews(); ?> </td> <td><?php echo $result->getVisits(); ?> </td> </tr> <?php
<?php error_reporting(15); //конфиг //include("config.php"); //подключаем класс GA API include "gapi.class.php"; $ga = new gapi($u, $p); //////получаем пользователи/просмотры за все время $ga->requestReportData($id, array('month', 'year'), array('visitors', 'pageviews'), 'year', null, $datestart, $datefinish, 1, 1000); //переменная для записи резалта $output = ""; if ($addFile) { $add = file_get_contents($path . $addFile); $output .= trim($add) . "\n"; } //получаем и обрабатываем результаты foreach ($ga->getResults() as $result) { $m = $result; //месяц год $visitors = $result->getVisitors(); //посетители $pageviews = $result->getPageviews(); //просмотры //приводим дату к удобочитаемому виду ,мменяем пробелы на точки $m = str_replace(" ", ".", $m); //формируем строку $output .= $m . ";" . $visitors . ";" . $pageviews . "\n"; } //пишем в файл $fp = fopen($path . $visitorsCSV, "w");
<?php include 'header.php'; if (!isset($_SESSION['admin'])) { header("Location:index.php"); } $ga = new gapi($ga_email, $ga_password); $dimensions = array('visitCount'); //$metrics = array('pageviews','visits','timeOnPage'); $metrics = array('visits', 'pageviews', 'avgTimeOnSite', 'percentNewVisits', 'newVisits', 'pageviewsPerVisit', 'visitBounceRate'); //$filters = "country==India && pagePath==/broker_info.php?id=".$broker_id; $filters = ""; $start_date = date('Y-m-d', strtotime('1 month ago')); $end_date = date('Y-m-d'); $ga->requestReportData($ga_profile, $dimensions, $metrics, '-visits', $filters, $start_date, $end_date, 1, 50); ?> <div class="container-fluid"> <div class="row-fluid"> <div class="span3"> <?php include 'admin_menu.php'; ?> </div> <div class="span9"> <h2>Analytics-Visitors</h2> <div id="ajaxStatus"></div> <div id="visualization"></div> <div class="well"> <h3><?php echo $ga->getNewVisits(); ?>
public function actionGoogleAnalytics() { if (Yii::app()->user->checkAccess('viewGoogleAnalytics') == false) { throw new CHttpException(403); } require_once 'gapi.class.php'; header('Content-type: application/json'); try { $account = Setting::getValueByCode('google_analytics_account'); $password = Setting::getValueByCode('google_analytics_password'); $reportId = Setting::getValueByCode('google_analytics_report_id'); if (empty($account) || empty($password) || empty($password)) { throw new Exception('Google 分析帐号信息未设置'); } $ga = new gapi($account, $password); $ga->requestReportData($reportId, array('date'), array('pageviews', 'visits'), array('date', '-pageviews', '-visits')); $pageviews = array(); $visits = array(); foreach ($ga->getResults() as $result) { array_push($pageviews, array(date('Y-n-j', strtotime($result->getDate())), $result->getPageviews())); array_push($visits, array(date('Y-n-j', strtotime($result->getDate())), $result->getVisits())); } echo CJSON::encode(array('result' => true, 'data' => array($pageviews, $visits))); } catch (Exception $e) { echo CJSON::encode(array('result' => false, 'message' => $e->getMessage())); } Yii::app()->end(); }
function table($start_date = '2011-01-01', $end_date = '2011-12-31') { $dimensions = array('month'); $metrics = array('visits', 'newvisits', 'pageviews', 'timeonsite'); $sort = array('month'); $filter = ''; $ga = new gapi(MAIL, PASS . WORD); $ga->requestReportData(PROFILE_GA, $dimensions, $metrics, $sort, $filter, $start_date, $end_date, 1, 999); return $ga->getResults(); }
<?php define('ga_email', '*****@*****.**'); define('ga_password', 'your password'); require 'gapi.class.php'; $ga = new gapi(ga_email, ga_password); $ga->requestAccountData(); foreach ($ga->getResults() as $result) { echo $result . ' (' . $result->getProfileId() . ")<br />"; }
<?php define('ga_email', '*****@*****.**'); define('ga_password', 'your password'); require 'gapi.class.php'; $ga = new gapi(ga_email, ga_password, isset($_SESSION['ga_auth_token']) ? $_SESSION['ga_auth_token'] : null); $_SESSION['ga_auth_token'] = $ga->getAuthToken(); echo 'Token: ' . $_SESSION['ga_auth_token'];
function gaapi() { $this->load->library('ga_api'); $ga = new gapi('*****@*****.**', 'sumitkumarmunjal1'); $ga->requestReportData(60386809, array('browser', 'browserVersion'), array('pageviews', 'visits')); foreach ($ga->getResults() as $result) { echo '<strong>' . $result . '</strong><br />'; echo 'Pageviews: ' . $result->getPageviews() . ' '; echo 'Visits: ' . $result->getVisits() . '<br />'; } echo '<p>Total pageviews: ' . $ga->getPageviews() . ' total visits: ' . $ga->getVisits() . '</p>'; }
function annee($annee) { $layout = '<div id="print"><h2><a>Module de Statistiques</a> » <a class="active">Statistiques Annuelles (' . $annee . ')</h2> <a id="refPrint" href="javascript:PSR_imprimer()">Imprimer les statistiques</a><div id="main">'; define('ga_account', ''); define('ga_password', ''); define('ga_profile_id', ''); define('ga_start_date', $annee . '-01-01'); define('ga_end_date', $annee . '-12-31'); $ga = new gapi(ga_account, ga_password); $dimensions = array('month'); $metrics = array('pageviews', 'visits'); $sort = array('month'); $ga->requestReportData(ga_profile_id, $dimensions, $metrics, $sort, null, ga_start_date, ga_end_date, 1, 500); $results = $ga->getResults(); $layout .= '<fieldset style="margin-top:15px;"><h3>Fréquences des visites</h3>'; $layout .= '<table><tr><th width="33%">Mois</th><th width="33%">Nombres de visites</th><th width="33%">Pages visitées</th></tr>'; $i = 0; foreach ($results as $result) { $i++; if ($i % 2 != 0) { $layout .= '<tr><td>'; } else { $layout .= '<tr class="odd"><td>'; } switch ($result) { case "1": $layout .= "Janvier"; break; case "2": $layout .= "Février"; break; case "3": $layout .= "Mars"; break; case "4": $layout .= "Avril"; break; case "5": $layout .= "Mai"; break; case "6": $layout .= "Juin"; break; case "7": $layout .= "Juillet"; break; case "8": $layout .= "Août"; break; case "9": $layout .= "Septembre"; break; case "10": $layout .= "Octobre"; break; case "11": $layout .= "Novembre"; break; case "12": $layout .= "Décembre"; break; } $layout .= '</td><td>' . $result->getVisits() . '</td><td>' . $result->getPageviews() . '</td></tr>'; } $layout .= '</table><table style="margin-bottom:10px;"><tr><th width="75%">Total de visites</th><td width="25%">' . $ga->getVisits() . '</td></tr></table>'; $layout .= '</fieldset ><fieldset style="margin-top:15px;"><h3>Informations techniques</h3>'; $dimensions = array('operatingSystem'); $metrics = array('visits'); $sort = array('-visits'); $ga->requestReportData(ga_profile_id, $dimensions, $metrics, $sort, null, ga_start_date, ga_end_date, 1, 500); $results = $ga->getResults(); $layout .= '<table><tr><th width="50%">Sytème d'exploitation</th><th width="50%">Nombres de visites</th></tr>'; $i = 0; foreach ($results as $result) { $i++; if ($i % 2 != 0) { $layout .= '<tr><td>'; } else { $layout .= '<tr class="odd"><td>'; } $layout .= $result->getOperatingSystem() . '</td><td>' . $result->getVisits() . '</td></tr>'; } $layout .= '</table>'; $dimensions = array('browser'); $metrics = array('visits'); $sort = array('-visits'); $ga->requestReportData(ga_profile_id, $dimensions, $metrics, $sort, null, ga_start_date, ga_end_date, 1, 500); $results = $ga->getResults(); $layout .= '<table style="margin-top:10px;"><tr><th width="50%">Navigateurs web</th><th width="50%">Nombres de visites</th></tr>'; foreach ($results as $result) { $layout .= '<tr><td>' . $result->getBrowser() . '</td><td>' . $result->getVisits() . '</td></tr>'; } $layout .= '</table>'; $dimensions = array('screenResolution'); $metrics = array('visits'); $sort = array('-visits'); $filters = 'visits>5'; $ga->requestReportData(ga_profile_id, $dimensions, $metrics, $sort, $filters, ga_start_date, ga_end_date, 1, 500); $results = $ga->getResults(); $layout .= '<table style="margin-top:10px;margin-bottom:10px;"><tr><th width="50%">Résolution d'écrans</th><th width="50%">Nombres de visites</th></tr>'; $i = 0; foreach ($results as $result) { $i++; if ($i % 2 != 0) { $layout .= '<tr><td>'; } else { $layout .= '<tr class="odd"><td>'; } $layout .= $result->getScreenResolution() . '</td><td>' . $result->getVisits() . '</td></tr>'; } $layout .= '</table></fieldset><fieldset style="margin-top:15px;"><h3>Situations géographique</h3>'; $dimensions = array('country', 'city'); $metrics = array('visits'); $sort = array('-visits'); $ga->requestReportData(ga_profile_id, $dimensions, $metrics, $sort, null, ga_start_date, ga_end_date, 1, 500); $results = $ga->getResults(); $layout .= '<table style="margin-top:10px;margin-bottom:10px;"><tr><th width="33%">Pays</th><th width="33%">Villes</th><th width="33%">Nombres de visites</th></tr>'; $i = 0; foreach ($results as $result) { $i++; if ($i % 2 != 0) { $layout .= '<tr><td>'; } else { $layout .= '<tr class="odd"><td>'; } $layout .= $result->getCountry() . '</td><td>' . $result->getCity() . '</td><td>' . $result->getVisits() . '</td></tr>'; } $layout .= '</table>'; $layout .= '</table></fieldset><fieldset style="margin-top:15px;"><h3>Sites référents</h3>'; $dimensions = array('source'); $metrics = array('visits'); $sort = array('-visits'); $ga->requestReportData(ga_profile_id, $dimensions, $metrics, $sort, null, ga_start_date, ga_end_date, 1, 500); $results = $ga->getResults(); $layout .= '<table style="margin-top:10px;margin-bottom:10px;"><tr><th width="50%">Source</th><th width="50%">Nombres de visites</th></tr>'; $i = 0; foreach ($results as $result) { $i++; if ($i % 2 != 0) { $layout .= '<tr><td>'; } else { $layout .= '<tr class="odd"><td>'; } $layout .= $result->getSource() . '</td><td>' . $result->getVisits() . '</td></tr>'; } $layout .= '</table></fieldset><fieldset style="margin-top:15px;"><h3>Mots clés</h3>'; $dimensions = array('keyword'); $metrics = array('visits'); $sort = array('-visits'); $ga->requestReportData(ga_profile_id, $dimensions, $metrics, $sort, null, ga_start_date, ga_end_date, 1, 500); $results = $ga->getResults(); $layout .= '<table style="margin-top:10px;margin-bottom:10px;"><tr><th width="50%">Mot clés</th><th width="50%">Nombres de visites</th></tr>'; $i = 0; foreach ($results as $result) { $i++; if ($i % 2 != 0) { $layout .= '<tr><td>'; } else { $layout .= '<tr class="odd"><td>'; } $layout .= $result->getKeyword() . '</td><td>' . $result->getVisits() . '</td></tr>'; } $layout .= '</table></fieldset>'; $layout .= '</div></div>'; return $layout; }
<?php error_reporting(0); ini_set('display_errors', 1); $country = array('notset' => "(not set)", 'AF' => "Afghanistan", 'AX' => "Aland Islands", 'AL' => "Albania", 'DZ' => "Algeria", 'AS' => "American Samoa", 'AD' => "Andorra", 'AO' => "Angola", 'AI' => "Anguilla", 'AQ' => "Antarctica", 'AG' => "Antigua and Barbuda", 'AR' => "Argentina", 'AM' => "Armenia", 'AW' => "Aruba", 'AU' => "Australia", 'AT' => "Austria", 'AZ' => "Azerbaijan", 'BS' => "Bahamas", 'BH' => "Bahrain", 'BD' => "Bangladesh", 'BB' => "Barbados", 'BY' => "Belarus", 'BE' => "Belgium", 'BZ' => "Belize", 'BJ' => "Benin", 'BM' => "Bermuda", 'BT' => "Bhutan", 'BO' => "Bolivia, Plurinational State of", 'BA' => "Bosnia and Herzegovina", 'BW' => "Botswana", 'BV' => "Bouvet Island", 'BR' => "Brazil", 'IO' => "British Indian Ocean Territory", 'BN' => "Brunei Darussalam", 'BG' => "Bulgaria", 'BF' => "Burkina Faso", 'BI' => "Burundi", 'KH' => "Cambodia", 'CM' => "Cameroon", 'CA' => "Canada", 'CV' => "Cape Verde", 'KY' => "Cayman Islands", 'CF' => "Central African Republic", 'TD' => "Chad", 'CL' => "Chile", 'CN' => "China", 'CX' => "Christmas Island", 'CC' => "Cocos (Keeling) Islands", 'CO' => "Colombia", 'KM' => "Comoros", 'CG' => "Congo", 'CD' => "Congo, The Democratic Republic of the", 'CK' => "Cook Islands", 'CR' => "Costa Rica", 'CI' => "Côte d'Ivoire", 'HR' => "Croatia", 'CU' => "Cuba", 'CY' => "Cyprus", 'CZ' => "Czech Republic", 'DK' => "Denmark", 'DJ' => "Djibouti", 'DM' => "Dominica", 'DO' => "Dominican Republic", 'EC' => "Ecuador", 'EG' => "Egypt", 'SV' => "El Salvador", 'GQ' => "Equatorial Guinea", 'ER' => "Eritrea", 'EE' => "Estonia", 'ET' => "Ethiopia", 'FK' => "Falkland Islands [Islas Malvinas]", 'FO' => "Faroe Islands", 'FJ' => "Fiji", 'FI' => "Finland", 'FR' => "France", 'GF' => "French Guiana", 'PF' => "French Polynesia", 'TF' => "French Southern Territories", 'GA' => "Gabon", 'GM' => "Gambia", 'GE' => "Georgia", 'DE' => "Germany", 'GH' => "Ghana", 'GI' => "Gibraltar", 'GR' => "Greece", 'GL' => "Greenland", 'GD' => "Grenada", 'GP' => "Guadeloupe", 'GU' => "Guam", 'GT' => "Guatemala", 'GG' => "Guernsey", 'GN' => "Guinea", 'GW' => "Guinea-Bissau", 'GY' => "Guyana", 'HT' => "Haiti", 'HM' => "Heard Island and McDonald Islands", 'VA' => "Holy See (Vatican City State)", 'HN' => "Honduras", 'HK' => "Hong Kong", 'HU' => "Hungary", 'IS' => "Iceland", 'IN' => "India", 'ID' => "Indonesia", 'IR' => "Iran, Islamic Republic of", 'IQ' => "Iraq", 'IE' => "Ireland", 'IM' => "Isle of Man", 'IL' => "Israel", 'IT' => "Italy", 'JM' => "Jamaica", 'JP' => "Japan", 'JE' => "Jersey", 'JO' => "Jordan", 'KZ' => "Kazakhstan", 'KE' => "Kenya", 'KI' => "Kiribati", 'KP' => "South Korea", 'KR' => "North Korea", 'KW' => "Kuwait", 'KG' => "Kyrgyzstan", 'LA' => "Lao People's Democratic Republic", 'LV' => "Latvia", 'LB' => "Lebanon", 'LS' => "Lesotho", 'LR' => "Liberia", 'LY' => "Libya", 'LI' => "Liechtenstein", 'LT' => "Lithuania", 'LU' => "Luxembourg", 'MO' => "Macao", 'MK' => "Macedonia [FYROM]", 'MG' => "Madagascar", 'MW' => "Malawi", 'MY' => "Malaysia", 'MV' => "Maldives", 'ML' => "Mali", 'MT' => "Malta", 'MH' => "Marshall Islands", 'MQ' => "Martinique", 'MR' => "Mauritania", 'MU' => "Mauritius", 'YT' => "Mayotte", 'MX' => "Mexico", 'FM' => "Micronesia, Federated States of", 'MD' => "Moldova, Republic of", 'MC' => "Monaco", 'MN' => "Mongolia", 'ME' => "Serbia and Montenegro", 'MS' => "Montserrat", 'MA' => "Morocco", 'MZ' => "Mozambique", 'MM' => "Myanmar [Burma]", 'NA' => "Namibia", 'NR' => "Nauru", 'NP' => "Nepal", 'NL' => "Netherlands", 'AN' => "Netherlands Antilles", 'NC' => "New Caledonia", 'NZ' => "New Zealand", 'NI' => "Nicaragua", 'NE' => "Niger", 'NG' => "Nigeria", 'NU' => "Niue", 'NF' => "Norfolk Island", 'MP' => "Northern Mariana Islands", 'NO' => "Norway", 'OM' => "Oman", 'PK' => "Pakistan", 'PW' => "Palau", 'PS' => "Palestinian Territories", 'PA' => "Panama", 'PG' => "Papua New Guinea", 'PY' => "Paraguay", 'PE' => "Peru", 'PH' => "Philippines", 'PN' => "Pitcairn", 'PL' => "Poland", 'PT' => "Portugal", 'PR' => "Puerto Rico", 'QA' => "Qatar", 'RE' => "Réunion", 'RO' => "Romania", 'RU' => "Russia", 'RW' => "Rwanda", 'BL' => "Saint Barthélemy", 'SH' => "Saint Helena", 'KN' => "Saint Kitts and Nevis", 'LC' => "Saint Lucia", 'MF' => "Saint Martin", 'PM' => "Saint Pierre and Miquelon", 'VC' => "Saint Vincent and the Grenadines", 'WS' => "Samoa", 'SM' => "San Marino", 'ST' => "Sao Tome and Principe", 'SA' => "Saudi Arabia", 'SN' => "Senegal", 'RS' => "Serbia", 'SC' => "Seychelles", 'SL' => "Sierra Leone", 'SG' => "Singapore", 'SK' => "Slovakia", 'SI' => "Slovenia", 'SB' => "Solomon Islands", 'SO' => "Somalia", 'ZA' => "South Africa", 'GS' => "South Georgia and the South Sandwich Islands", 'ES' => "Spain", 'LK' => "Sri Lanka", 'SD' => "Sudan", 'SR' => "Suriname", 'SJ' => "Svalbard and Jan Mayen", 'SZ' => "Swaziland", 'SE' => "Sweden", 'CH' => "Switzerland", 'SY' => "Syrian Arab Republic", 'TW' => "Taiwan", 'TJ' => "Tajikistan", 'TZ' => "Tanzania, United Republic of", 'TH' => "Thailand", 'TL' => "Timor-Leste", 'TG' => "Togo", 'TK' => "Tokelau", 'TO' => "Tonga", 'TT' => "Trinidad and Tobago", 'TN' => "Tunisia", 'TR' => "Turkey", 'TM' => "Turkmenistan", 'TC' => "Turks and Caicos Islands", 'TV' => "Tuvalu", 'UG' => "Uganda", 'UA' => "Ukraine", 'AE' => "United Arab Emirates", 'GB' => "United Kingdom", 'US' => "United States", 'UM' => "United States Minor Outlying Islands", 'UY' => "Uruguay", 'UZ' => "Uzbekistan", 'VU' => "Vanuatu", 'VE' => "Venezuela, Bolivarian Republic of", 'VN' => "Viet Nam", 'VG' => "British Virgin Islands", 'VI' => "U.S. Virgin Islands", 'WF' => "Wallis and Futuna", 'EH' => "Western Sahara", 'YE' => "Yemen", 'ZM' => "Zambia", 'ZW' => "Zimbabwe"); require_once 'gapi.class.php'; define('ga_account', '*****@*****.**'); define('ga_password', 'elance987'); define('ga_profile_id', '85622792'); $ga = new gapi(ga_account, ga_password); /* We are using the 'source' dimension and the 'visits' metrics */ $dimensions = array('source'); $metrics = array('visits'); /* We will sort the result be desending order of visits, and hence the '-' sign before the 'visits' string */ $ga->requestReportData(ga_profile_id, array('year', 'month', 'country'), array('visits')); $gaResults = $ga->getResults(); $i = 1; $sampledata = ''; foreach ($ga->getResults() as $result) { $sampledata .= '"' . strtolower(array_search($result->getCountry(), $country)) . '":"' . $result->getVisits() . '",'; } $ga->requestReportData(ga_profile_id, array('year', 'month', 'day'), array('visits', 'pageviews'), 'year', '', date('Y-m-d', strtotime($Date . '-10 days')), date('Y-m-d')); $gaResults = $ga->getResults(); $i = 1; $visits = ''; foreach ($ga->getResults() as $result) { //echo '<pre>';print_r($result);echo '</pre>'; $visits .= '[gd(' . $result->getYear() . ', ' . $result->getMonth() . ', ' . $result->getDay() . ') , ' . $result->getVisits() . '] ,'; $pageviews .= '[gd(' . $result->getYear() . ', ' . $result->getMonth() . ', ' . $result->getDay() . ') , ' . $result->getPageviews() . '] ,'; } $fml = date('Y-m-d', strtotime("-4 months"));
function analyticsWidget() { // http://ga-dev-tools.appspot.com/explorer/ // http://code.google.com/p/gapi-google-analytics-php-interface/ // http://www.codediesel.com/php/reading-google-analytics-data-from-php/ // http://code.google.com/p/gapi-google-analytics-php-interface/wiki/UsingFilterControl $yamlparser = new \Symfony\Component\Yaml\Parser(); $this->config = $yamlparser->parse(file_get_contents(__DIR__ . '/config.yml')); if (empty($this->config['ga_email'])) { return "ga_email not set in config.yml."; } if (empty($this->config['ga_password'])) { return "ga_password not set in config.yml."; } if (empty($this->config['ga_profile_id'])) { return "ga_profile_id not set in config.yml."; } if (!empty($this->config['filter_referral'])) { $filter_referral = 'source !@ "' . $this->config['filter_referral'] . '"'; } else { $filter_referral = ''; } if (empty($this->config['number_of_days'])) { $this->config['number_of_days'] = 14; } require_once __DIR__ . '/gapi/gapi.class.php'; /* Create a new Google Analytics request and pull the results */ $ga = new \gapi($this->config['ga_email'], $this->config['ga_password']); $ga->requestReportData($this->config['ga_profile_id'], array('date'), array('pageviews', 'visitors', 'uniquePageviews', 'pageviewsPerVisit', 'exitRate', 'avgTimeOnPage', 'entranceBounceRate', 'newVisits'), 'date', '', date('Y-m-d', strtotime('-' . $this->config['number_of_days'] . ' day')), date('Y-m-d')); $pageviews = array(); $tempresults = $ga->getResults(); $aggr = array('pageviews' => 0, 'pageviewspervisit' => 0, 'visitors' => 0, 'uniquePageviews' => 0, 'timeonpage' => 0, 'bouncerate' => 0, 'exitrate' => 0); // aggregate data: foreach ($tempresults as $result) { $pageviews[] = array('date' => date('M j', strtotime($result->getDate())), 'pageviews' => $result->getPageviews(), 'visitors' => $result->getVisitors()); $aggr['pageviews'] += $result->getPageviews(); $aggr['pageviewspervisit'] += $result->getPageviewsPerVisit(); $aggr['visitors'] += $result->getVisitors(); $aggr['uniquePageviews'] += $result->getUniquepageviews(); $aggr['timeonpage'] += $result->getAvgtimeonpage(); $aggr['bouncerate'] += $result->getEntrancebouncerate(); $aggr['exitrate'] += $result->getExitrate(); } $aggr['pageviewspervisit'] = round($aggr['pageviewspervisit'] / count($tempresults), 1); $aggr['timeonpage'] = $this->secondMinute(round($aggr['timeonpage'] / count($tempresults), 1)); $aggr['bouncerate'] = round($aggr['bouncerate'] / count($tempresults), 1); $aggr['exitrate'] = round($aggr['exitrate'] / count($tempresults), 1); // Get the 'populair sources' $ga->requestReportData($this->config['ga_profile_id'], array('source', 'referralPath'), array('visits'), '-visits', $filter_referral, date('Y-m-d', strtotime('-' . $this->config['number_of_days'] . ' day')), date('Y-m-d'), 1, 12); $results = $ga->getResults(); $sources = array(); foreach ($results as $result) { if ($result->getReferralPath() == "(not set)") { $sources[] = array('link' => false, 'host' => $result->getSource(), 'visits' => $result->getVisits()); } else { $sources[] = array('link' => true, 'host' => $result->getSource() . $result->getReferralPath(), 'visits' => $result->getVisits()); } } // Get the 'popular pages' $ga->requestReportData($this->config['ga_profile_id'], array('hostname', 'pagePath'), array('visits'), '-visits', '', date('Y-m-d', strtotime('-' . $this->config['number_of_days'] . ' day')), date('Y-m-d'), 1, 12); $results = $ga->getResults(); $pages = array(); foreach ($results as $result) { $pages[] = array('host' => $result->gethostname() . $result->getPagePath(), 'visits' => $result->getVisits()); } $caption = sprintf("Google Analytics for %s - %s.", date('M d', strtotime('-' . $this->config['number_of_days'] . ' day')), date('M d')); $this->app['twig.loader.filesystem']->addPath(__DIR__, 'GoogleAnalytics'); $html = $this->app['render']->render("@GoogleAnalytics/widget.twig", array('caption' => $caption, 'aggr' => $aggr, 'pageviews' => $pageviews, 'sources' => $sources, 'pages' => $pages)); return new \Twig_Markup($html, 'UTF-8'); }
/** * Call method to find a matching metric or dimension to return * * @param $name String name of function called * @return String * @throws Exception if not a valid metric or dimensions, 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); $metric_key = gapi::array_key_exists_nc($name, $this->metrics); if ($metric_key) { return $this->metrics[$metric_key]; } $dimension_key = gapi::array_key_exists_nc($name, $this->dimensions); if ($dimension_key) { return $this->dimensions[$dimension_key]; } throw new Exception('No valid metric or dimesion called "' . $name . '"'); }
/** * Authenticate Google Account with Google * * @param String $email * @param String $password */ protected function authenticateUser($email, $password) { try { return parent::authenticateUser($email, $password); } catch (Exception $e) { throw new dmGapiException('GAPI: Failed to authenticate with email ' . $email . '. Please configure email and password in the admin configuration panel'); } }
<?php require 'gapi.class.php'; require 'config.php'; $ga = new gapi($my_email, $my_key); $id = $_POST['id']; $dataini = $_POST['dataini']; $datafim = $_POST['datafim']; $ga->requestReportData($id, 'date', array('1dayUsers'), 'date', null, $dataini, $datafim); $resultado = $ga->getResults(); $ga->requestReportData($id, 'date', array('7dayUsers'), 'date', null, $dataini, $datafim); $resultado2 = $ga->getResults(); $ga->requestReportData($id, 'date', array('14dayUsers'), 'date', null, $dataini, $datafim); $resultado3 = $ga->getResults(); $ga->requestReportData($id, 'date', array('30dayUsers'), 'date', null, $dataini, $datafim); $resultado4 = $ga->getResults(); $lista = array(); for ($i = 0; $i < count($resultado); $i++) { $lista['usuariosAtivos'][] = array('date' => $resultado[$i]->getDate(), 'users1Day' => $resultado[$i]->get1dayUsers(), 'users7Day' => $resultado2[$i]->get7dayUsers(), 'users14Day' => $resultado3[$i]->get14dayUsers(), 'users30Day' => $resultado4[$i]->get30dayUsers()); } echo json_encode($lista);