Ejemplo n.º 1
0
 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));
 }
Ejemplo n.º 2
0
 function getAccounts()
 {
     $db =& JFactory::getDBO();
     $app =& JFactory::getApplication();
     $config = $app->getuserState('rsseoConfig');
     try {
         $ga = new gapi($config['analytics.username'], $config['analytics.password']);
         $token = $ga->getAuthToken();
         $db->setQuery("UPDATE #__rsseo_config SET ConfigValue = '" . $db->getEscaped($token) . "' WHERE ConfigName = 'ga.token' ");
         $db->query();
         $ga->requestAccountData();
         return $ga->getResults();
     } catch (Exception $e) {
         $app->redirect('index.php?option=com_rsseo', $e->getMessage(), 'error');
     }
 }
Ejemplo n.º 3
0
 /**
  * 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 settings_form($current)
 {
     // Initialize our variable array
     $vars = array();
     // Get current site
     $site = $this->EE->config->item('site_id');
     // This removes the current username/password
     if (isset($_GET['analytics_reset'])) {
         $settings = $this->get_settings(TRUE);
         $settings[$site]['user'] = '';
         $settings[$site]['password'] = '';
         $settings[$site]['profile'] = '';
         $settings[$site]['authenticated'] = '';
         $this->EE->db->where('class', ucfirst(get_class($this)));
         $this->EE->db->update('extensions', array('settings' => serialize($settings)));
         $this->EE->functions->redirect(BASE . AMP . 'C=addons_extensions' . AMP . 'M=extension_settings' . AMP . 'file=' . $this->slug);
         exit;
     }
     // Only grab settings for the current site
     $vars['current'] = isset($current[$site]) ? $current[$site] : $current;
     // We need our file name for the settings form
     $vars['file'] = $this->slug;
     // If we have a username and password, try and authenticate and fetch our profile list
     if (isset($vars['current']['authenticated']) && $vars['current']['authenticated'] == 'y') {
         require_once PATH_THIRD . 'cp_analytics/libraries/gapi.class.php';
         $ga_user = $vars['current']['user'];
         $ga_password = base64_decode($vars['current']['password']);
         $ga = new gapi($ga_user, $ga_password);
         $ga->requestAccountData(1, 100);
         if ($ga->getResults()) {
             $vars['ga_profiles'] = array('' => '--');
             foreach ($ga->getResults() as $result) {
                 $vars['ga_profiles'][$result->getProfileId()] = $result->getTitle();
             }
         }
     }
     // We have our vars set, so load and return the view file
     return $this->EE->load->view('settings', $vars, TRUE);
 }
Ejemplo n.º 5
0
 /**
  * Request account data from Google Analytics
  *
  * @param Int $start_index OPTIONAL: Start index of results
  * @param Int $max_results OPTIONAL: Max results returned
  */
 public function requestAccountData($start_index = 1, $max_results = 20)
 {
     if ($this->cacheManager) {
         $cacheKey = 'account-data-' . $start_index . '-to-' . $max_results;
         if ($this->cacheManager->getCache('gapi/request')->has($cacheKey)) {
             return $this->cacheManager->getCache('gapi/request')->get($cacheKey);
         }
     }
     try {
         $result = parent::requestAccountData($start_index, $max_results);
     } catch (Exception $e) {
         throw new dmGapiException($e->getMessage());
     }
     if ($this->cacheManager) {
         $this->cacheManager->getCache('gapi/request')->set($cacheKey, $result);
     }
     return $result;
 }
 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')) . ' &ndash; ' . 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) . '&hellip;' : $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

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 />";
}
Ejemplo n.º 8
0
function site_stats($site_name)
{
    global $lang, $config;
    if ($config['generate_statistics']) {
        $ga = new gapi($config['ga_email'], $config['ga_password']);
        //get profile ids
        $ga->requestAccountData();
        foreach ($ga->getResults() as $result) {
            $config[filename((string) $result)]['profile_id'] = $result->getProfileId();
        }
        if (isset($config[$site_name]['profile_id'])) {
            $profile_id = $config[$site_name]['profile_id'];
            //current week visits
            $arr['visits'] = get_visits($ga, $profile_id, $config['from'], $config['to']);
            $arr['prior_visits'] = get_visits($ga, $profile_id, $config['prior_from'], $config['prior_to']);
            $arr['st'] = get_stats($arr['visits'], $arr['prior_visits']);
            $arr['image_path'] = generate_image($lang[$site_name], $arr['visits']);
            $arr['image_name'] = basename($arr['image_path']);
            return $arr;
        }
    }
}
Ejemplo n.º 9
0
 private function changeProfileId($webPropertyId)
 {
     require "lib/gapi-1.3/gapi.class.php";
     $ga = new gapi($this->email, $this->password);
     $ga->requestAccountData();
     foreach ($ga->getResults() as $result) {
         $properties = $result->getProperties();
         if ($properties['webPropertyId'] == $webPropertyId) {
             $this->addConfiguration("profileId", $properties['profileId']);
             return;
         }
     }
 }