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)); } }
/** * 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 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; }
function getGASources() { $app =& JFactory::getApplication(); $config = $app->getuserState('rsseoConfig'); $filter1 = 'medium == (none)'; $filter2 = 'medium == organic'; $filter3 = 'medium == referral'; try { $ga = new gapi($config['analytics.username'], $config['analytics.password'], $config['ga.token']); $ga->requestReportData($config['ga.account'], array('source', 'medium'), array('visits', 'pageviewsPerVisit', 'avgTimeOnSite', 'visitBounceRate', 'percentNewVisits'), '-visits', null, $config['ga.start'], $config['ga.end'], 1, 20); $total = $ga->getVisits(); $return = array(); $results = $ga->getResults(); if (!empty($results)) { foreach ($results as $result) { $object = new stdClass(); $object->source = $result->getSource() . ' / ' . $result->getMedium(); $visits = $result->getVisits(); $visits = $visits == '' ? JText::_('RSSEO_NOT_AVAILABLE') : $visits; $bouncerate = $result->getVisitBounceRate(); $bouncerate = $bouncerate === '' ? JText::_('RSSEO_NOT_AVAILABLE') : number_format($bouncerate, 2) . ' %'; $avgtimesite = $result->getAvgTimeOnSite(); $avgtimesite = $avgtimesite === '' ? JText::_('RSSEO_NOT_AVAILABLE') : $this->convertseconds(number_format($avgtimesite, 0)); $pagesvisits = $result->getpageviewsPerVisit(); $pagesvisits = $pagesvisits === '' ? JText::_('RSSEO_NOT_AVAILABLE') : number_format($pagesvisits, 2); $newvisits = $result->getpercentNewVisits(); $newvisits = $newvisits === '' ? JText::_('RSSEO_NOT_AVAILABLE') : number_format($newvisits, 2) . ' %'; $object->visits = $visits; $object->bouncerate = $bouncerate; $object->avgtimesite = $avgtimesite; $object->pagesvisits = $pagesvisits; $object->newvisits = $newvisits; $return[] = $object; } } $ga->requestReportData($config['ga.account'], array('medium'), array('visits'), '-visits', $filter1, $config['ga.start'], $config['ga.end'], 1, 20); $directvisits = $ga->getVisits(); $directvisits = !empty($directvisits) ? $directvisits : '0'; $ga->requestReportData($config['ga.account'], array('medium'), array('visits'), '-visits', $filter2, $config['ga.start'], $config['ga.end'], 1, 20); $searchvisits = $ga->getVisits(); $searchvisits = !empty($searchvisits) ? $searchvisits : '0'; $ga->requestReportData($config['ga.account'], array('medium'), array('visits'), '-visits', $filter3, $config['ga.start'], $config['ga.end'], 1, 20); $refferingvisits = $ga->getVisits(); $refferingvisits = !empty($refferingvisits) ? $refferingvisits : '0'; $data['data'] = $return; $data['details'] = array($directvisits, $searchvisits, $refferingvisits); return $data; } catch (Exception $e) { return array('data' => $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; }
?> </td> </tr> <?php } ?> </table> <table> <tr> <th>Total Results</th> <td><?php echo $ga->getTotalResults(); ?> </td> </tr> <tr> <th>Total Pageviews</th> <td><?php echo $ga->getPageviews(); ?> </tr> <tr> <th>Total Visits</th> <td><?php echo $ga->getVisits(); ?> </td> </tr> </table>
//посещения //приводим дату к удобочитаемому виду ,мменяем пробелы на точки $d = str_replace(" ", ".", $d); //формируем строку $output .= $d . ";" . $visitors . ";" . $pageviews . ";" . $visits . "\n"; } //пишем в файл $fp = fopen($path . $visitors3CSV, "w"); fputs($fp, trim($output)); fclose($fp); //////получаем географию посещений за последний месяц $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"; } //пишем в файл $fp = fopen($path . $countryCSV, "w"); fputs($fp, trim($output)); fclose($fp);
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>'; }
$giorni_settimana = 7; $giorni_giorno = 1; $data_ricerca_anno = date("Y-m-d", time() - 86400 * $giorni_anno); $data_ricerca_mese = date("Y-m-d", time() - 86400 * $giorni_mese); $data_ricerca_settimana = date("Y-m-d", time() - 86400 * $giorni_settimana); $data_ricerca_giorno = date("Y-m-d", time() - 86400 * $giorni_giorno); $oggi = date("Y-m-d"); $ga = new gapi(ga_email, ga_password); ////////////// // GIORNO ////////////// $ga->requestReportData(ga_profile_id, array('visitorType'), array('visitors', 'pageviews', 'visits', 'timeOnSite', 'avgtimeOnsite', 'percentNewVisits', 'newVisits', 'pageviewsPerVisit', 'uniquePageviews'), '', '', $data_ricerca_giorno, date("Y-m-d"), 1, 1000); echo "<div class=\"gacounter\">"; echo "<h3>Periodo osservazione: ultimo giorno </h3>"; echo "<p> dal " . date("d-m-Y", time() - 86400 * $giorni_giorno) . " al " . date("d-m-Y") . "</p>"; echo "<ul><li>visite totali: " . $ga->getVisits() . "</li>"; echo "<li class=\"alternato\">visitatori totali: " . $ga->getVisitors() . "</li>"; echo "<li>nuovi visitatori: " . $ga->getnewVisits() . "</li>"; echo "<li class=\"alternato\">pagine viste: " . $ga->getPageviews() . "</li>"; echo "<li>pagine viste per visita: " . round($ga->getpageviewsPerVisit(), 2) . "</li>"; echo "<li class=\"alternato\">pagine uniche: " . $ga->getuniquePageviews() . "</li>"; $t_medio = tempo_medio($ga->getavgTimeOnSite()); echo "<li>tempo medio di permanenza sul sito: " . $t_medio . "</li></ul>"; echo "</div>"; ////////////// // SETTIMANA ////////////// $ga->requestReportData(ga_profile_id, array('visitorType'), array('visitors', 'pageviews', 'visits', 'timeOnSite', 'avgtimeOnsite', 'percentNewVisits', 'newVisits', 'pageviewsPerVisit', 'uniquePageviews'), '', '', $data_ricerca_settimana, date("Y-m-d"), 1, 1000); echo "<div class=\"gacounter\">"; echo "<h3>Periodo osservazione: ultimi 7 giorni</h3>"; echo "<p> dal " . date("d-m-Y", time() - 86400 * $giorni_settimana) . " al " . date("d-m-Y") . "</p>";
<?php // ajax_ga_mobile.php require_once 'includes/global.inc.php'; if (isset($_SESSION['user'])) { $broker = unserialize($_SESSION["user"]); $broker_id = $broker->m_BrokerID; // initialize the google analytics object $ga = new gapi($ga_email, $ga_password); $dimensions = array('browser', 'operatingSystem', 'source', 'segment=gaid::-11'); $metrics = array('visits', 'pageviews', 'timeOnSite'); $segments = ""; //$filters = "country==India && pagePath==/broker_info.php?id=".$broker_id; $filters = "country==India"; $ga->requestReportData($ga_profile, $dimensions, $metrics, '-visits', $filters, '2012-03-01', '2012-04-10', 1, 50); $html = "<table class='table table-striped table-bordered'>"; $html .= "<tr><th>Pageviews</th><th>Visits</th><th>Time On Page</th></tr>"; foreach ($ga->getResults() as $result) { $html .= print_r($result); /*$html .= "<tr>"; $html .= "<td>".$result->getPageviews()."</td>"; $html .= "<td>".$result->getVisits()."</td>"; $html .= "<td>".$result->getTimeOnPage()."</td>"; $html .= "</tr>";*/ } $html .= "</table>"; $html .= '<p>Total pageviews: ' . $ga->getPageviews() . ' total visits: ' . $ga->getVisits() . '</p>'; echo $html; }