├── Analytics.php ├── AnalyticsAsset.php ├── README.md ├── assets ├── css │ └── analytics.css └── js │ ├── analytics.js │ └── main.js ├── composer.json ├── messages ├── en │ └── infoweb │ │ └── analytics.php ├── fr │ └── infoweb │ │ └── analytics.php ├── id │ └── infoweb │ │ └── analytics.php └── nl │ └── infoweb │ └── analytics.php ├── models └── Connect.php └── views ├── average_session_length.php ├── countries.php ├── sessions.php ├── total_page_views.php ├── total_sessions.php ├── total_users.php └── visitors.php /Analytics.php: -------------------------------------------------------------------------------- 1 | getView(); 35 | 36 | $connection = new Connect; 37 | 38 | // Set default values 39 | // @todo Find a better way to do this 40 | if (!isset($this->startDate)) { 41 | $connection->startDate = date('Y-m-d', strtotime('-1 month')); 42 | } else { 43 | $connection->startDate = $this->startDate; 44 | } 45 | 46 | if (!isset($this->endDate)) { 47 | $connection->endDate = date('Y-m-d'); 48 | } else { 49 | $connection->endDate = $this->endDate; 50 | } 51 | 52 | // Get analytics data 53 | switch ($this->dataType) { 54 | 55 | case Analytics::SESSIONS: 56 | $data = $connection->getSessions(); 57 | 58 | // Set javascript variable 59 | // @todo Find a better way to do this 60 | $view->registerJs("var sessionsData = {$data}", \yii\web\View::POS_HEAD); 61 | 62 | break; 63 | 64 | case Analytics::VISITORS: 65 | $data = $connection->getVisitors(); 66 | 67 | // Set javascript variable 68 | // @todo Find a better way to do this 69 | $view->registerJs("var visitorsData = {$data}", \yii\web\View::POS_HEAD); 70 | 71 | break; 72 | 73 | case Analytics::COUNTRIES: 74 | $data = $connection->getCountries(); 75 | 76 | // Set javascript variable 77 | // @todo Find a better way to do this 78 | $view->registerJs("var countriesData = {$data}", \yii\web\View::POS_HEAD); 79 | 80 | break; 81 | 82 | case Analytics::TOTAl_SESSIONS: 83 | $data = $connection->getTotalSessions(); 84 | 85 | // Set javascript variable 86 | // @todo Find a better way to do this 87 | $view->registerJs("var totalSessionsData = {$data}", \yii\web\View::POS_HEAD); 88 | 89 | break; 90 | 91 | case Analytics::TOTAL_USERS: 92 | $data = $connection->getTotalUsers(); 93 | 94 | // Set javascript variable 95 | // @todo Find a better way to do this 96 | $view->registerJs("var totalUsersData = {$data}", \yii\web\View::POS_HEAD); 97 | 98 | break; 99 | 100 | case Analytics::TOTAL_PAGE_VIEWS: 101 | $data = $connection->getTotalPageViews(); 102 | 103 | // Set javascript variable 104 | // @todo Find a better way to do this 105 | $view->registerJs("var totalPageViewsData = {$data}", \yii\web\View::POS_HEAD); 106 | 107 | break; 108 | 109 | case Analytics::AVERAGE_SESSION_LENGTH: 110 | $data = $connection->getAverageSessionLength(); 111 | 112 | // Set javascript variable 113 | // @todo Find a better way to do this 114 | $view->registerJs("var averageSessionLengthData = {$data}", \yii\web\View::POS_HEAD); 115 | 116 | break; 117 | } 118 | 119 | // Register asssets 120 | AnalyticsAsset::register($this->view); 121 | 122 | } 123 | 124 | /** 125 | * Run the widget 126 | * 127 | * @return string 128 | */ 129 | public function run() 130 | { 131 | return $this->render($this->dataType); 132 | 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /AnalyticsAsset.php: -------------------------------------------------------------------------------- 1 | API's' and enable the 'Analytics API' 33 | 34 | Go to 'API & Auth -> Credentials' and under 'OAuth' click 'Create new Client ID' 35 | 36 | Choose 'Service account' and click 'Create client id' 37 | 38 | Save the certificate to 'backend\assets\certificate\certificate.p12' (don't forget to rename the file) 39 | 40 | Write down the 'private key's password' somewhere 41 | 42 | Add the credentials to your backend params 43 | 44 | ```php 45 | return [ 46 | ... 47 | 'analytics' => [ 48 | 'developerKey' => '', // Public key fingerprints 49 | 'serviceAccountName' => 'xxx@developer.gserviceaccount.com', // Email address 50 | 'clientId' => 'xxx.apps.googleusercontent.com', // Client ID 51 | ], 52 | ]; 53 | ``` 54 | 55 | Go to [Google analytics](https://www.google.com/analytics/), open your property and get your 'Profile ID' 56 | 57 | (It is the number at the end of the URL starting with p: https://www.google.com/analytics/web/#home/a11345062w43527078pXXXXXXXX/) 58 | 59 | Add the 'Profile ID' to your params 60 | 61 | ```php 62 | return [ 63 | ... 64 | 'analytics' => [ 65 | ... 66 | 'analyticsId' => 'ga:XXXXXXXX', 67 | ], 68 | ]; 69 | ``` 70 | 71 | 72 | Add the serviceAccountName (xxx@developer.gserviceaccount.com) as a new user to your Analyics property 73 | 74 | 75 | Create the alias '@google/api' in the bootstrap file in common/config like so: 76 | ```php 77 | Yii::setAlias('google/api', dirname(dirname(__DIR__)) . '/vendor/google/apiclient/src'); 78 | ``` 79 | 80 | Import the translations and use category 'infoweb/analytics': 81 | ``` 82 | yii i18n/import @infoweb/analytics/messages 83 | ``` 84 | 85 | If you can't access the `/tmp` folder on your server (shared hosting), change line 94 in `vendor\google\apiclient\src\Google\` 86 | ```php 87 | 'directory' => dirname(Yii::getAlias('@webroot')) . '/runtime/Google_Client' 88 | ``` 89 | 90 | Usage 91 | ----- 92 | 93 | Once the extension is installed, replace the contents of `backend/views/site/index.php` with the following: 94 | 95 | ```php 96 | title = Yii::$app->name; 100 | ?> 101 | ``` 102 | 103 | ```php 104 |
105 |
106 |
107 |
108 |

109 | 110 | 111 | formatter->asDate(date('d-m-Y', strtotime('-1 month')), 'medium'); ?> - formatter->asDate(date('d-m-Y'), 'medium'); ?> 112 | 113 |

114 |
115 |
116 | 117 |
118 | Analytics::TOTAl_SESSIONS]); ?> 119 | Analytics::TOTAL_USERS]); ?> 120 | Analytics::TOTAL_PAGE_VIEWS]); ?> 121 | Analytics::AVERAGE_SESSION_LENGTH]); ?> 122 |
123 | 124 |
125 | Analytics::SESSIONS]); ?> 126 |
127 |
128 | Analytics::VISITORS]); ?> 129 | Analytics::COUNTRIES]); ?> 130 |
131 |
132 |
133 | ``` 134 | 135 | Useful links 136 | ------------ 137 | 138 | [Google Analytics Query Explorer 2](https://ga-dev-tools.appspot.com/explorer/) 139 | [Google API Php Client](https://github.com/google/google-api-php-client) 140 | [Developer Documentation](https://developers.google.com/api-client-library/php) 141 | [Google Charts](https://developers.google.com/chart/?hl=nl) 142 | -------------------------------------------------------------------------------- /assets/css/analytics.css: -------------------------------------------------------------------------------- 1 | 2 | #analytics-sessions { 3 | width: 100%; 4 | height: 170px; 5 | } 6 | 7 | #analytics-visitors { 8 | width: 100%; 9 | height: 260px; 10 | } 11 | 12 | /** 13 | * Countries table 14 | */ 15 | 16 | .google-visualization-table-tr-head .gradient, 17 | .google-visualization-table-tr-head-nonstrict .gradient, 18 | .google-visualization-table-div-page .gradient { 19 | background: none !important; 20 | border: none; 21 | } 22 | 23 | .google-visualization-table-tr-head, 24 | .google-visualization-table-tr-head td, 25 | .google-visualization-table-tr-head-nonstrict { 26 | text-align: left !important; 27 | } 28 | 29 | .google-visualization-table-td { 30 | padding: 8px 8px 7px !important; 31 | } 32 | 33 | .google-visualization-table-tr-over, 34 | .google-visualization-table-tr-over td, 35 | .google-visualization-table-tr-over-nonstrict { 36 | background-color: #ffffcc !important; 37 | } 38 | 39 | .google-visualization-table-tr-head .google-visualization-table-th:first-child { 40 | width: 5%; 41 | } 42 | 43 | .page-header .report-period { 44 | font-size: 15px; 45 | } 46 | 47 | .google-visualization-table, 48 | .google-visualization-table-table { 49 | width: 100%; 50 | } 51 | 52 | .panel .title { 53 | font-weight: bold; 54 | margin-left: 10px; 55 | font-size: 15px; 56 | position: relative; 57 | bottom: 3px; 58 | } 59 | -------------------------------------------------------------------------------- /assets/js/analytics.js: -------------------------------------------------------------------------------- 1 | (function (root, factory) { 2 | if (typeof define === 'function' && define.amd) { 3 | define(factory); 4 | } else if (typeof exports === 'object') { 5 | module.exports = factory; 6 | } else { 7 | root.Analytics = factory(); 8 | } 9 | })(this, function () { 10 | 11 | 'use strict'; 12 | 13 | var Analytics = {}; 14 | 15 | Analytics.settings = { 16 | render: [] 17 | }; 18 | 19 | // Module initialization 20 | Analytics.init = function(settings) { 21 | 22 | var settings = settings || {}; 23 | 24 | $.extend(Analytics.settings, settings); 25 | 26 | // Load analytics 27 | google.load("visualization", "1", {packages: ["corechart", "table"]}); 28 | google.setOnLoadCallback(Analytics.renderData); 29 | 30 | }; 31 | 32 | Analytics.renderData = function() { 33 | 34 | $.each(Analytics.settings.render, function() { 35 | var func = 'render'+this; 36 | 37 | if (typeof Analytics[func] === 'function') { 38 | Analytics[func](); 39 | } 40 | 41 | }); 42 | }; 43 | 44 | Analytics.renderSessionsGraph = function() { 45 | 46 | var google = window.google; 47 | 48 | var data = google.visualization.arrayToDataTable(window.sessionsData); 49 | 50 | var options = { 51 | hAxis: { 52 | textStyle: { 53 | fontName: 'Arial', 54 | fontSize: '11', 55 | color: '#444444' 56 | }, 57 | slantedText: false, 58 | showTextEvery: 7, 59 | //minValue: new Date('2014-09-07') 60 | textPosition: 'out' 61 | }, 62 | vAxis: { 63 | minValue: 0, 64 | //ticks: [20, 40], 65 | textPosition: 'in', 66 | textStyle: { 67 | fontName: 'Arial', 68 | fontSize: '11', 69 | color: '#444444' 70 | }, 71 | gridlines: { 72 | color: '#f1f1f1' 73 | } 74 | }, 75 | series: { 76 | 0: { areaOpacity: 0.1, color: '#058dc7'} 77 | }, 78 | legend: 'none', 79 | pointSize: 7, 80 | lineWidth: 4, 81 | chartArea: { 82 | width: '100%', 83 | height: '80%' 84 | }, 85 | titleTextStyle: { 86 | fontName: 'Arial, sans-serif', 87 | fontSize: '13', 88 | color: '#444444', 89 | bold: false 90 | }, 91 | tooltip: { 92 | textStyle: { 93 | fontName: 'Arial', 94 | color: '#444444', 95 | fontSize: '12' 96 | } 97 | } 98 | }; 99 | 100 | var chart = new google.visualization.AreaChart(document.getElementById('analytics-sessions')); 101 | chart.draw(data, options); 102 | }; 103 | 104 | Analytics.renderVisitorsGraph = function() { 105 | 106 | var google = window.google; 107 | 108 | var data = google.visualization.arrayToDataTable(window.visitorsData); 109 | 110 | var options = { 111 | alignment: 'center', 112 | legend: { 113 | position: 'top', 114 | textStyle: { 115 | fontName: 'Arial', 116 | fontSize: '13', 117 | color: '#444444' 118 | }, 119 | alignment: 'center' 120 | }, 121 | pieSliceTextStyle: { 122 | textStyle: { 123 | fontName: 'Arial', 124 | fontSize: '13', 125 | color: '#444444' 126 | } 127 | }, 128 | tooltip: { 129 | textStyle: { 130 | fontName: 'Arial', 131 | color: '#444444', 132 | fontSize: '12' 133 | } 134 | }, 135 | chartArea: { 136 | width: '100%', 137 | height: '80%', 138 | top: 40 139 | }, 140 | slices: { 141 | 0: { color: '#058dc7' }, 142 | 1: { color: '#50b432' } 143 | } 144 | }; 145 | 146 | var chart = new google.visualization.PieChart(document.getElementById('analytics-visitors')); 147 | 148 | chart.draw(data, options); 149 | }; 150 | 151 | Analytics.renderCountriesTable = function() { 152 | 153 | var data = new google.visualization.DataTable(window.countriesData); 154 | /* 155 | //$flag_img = ' '; 156 | */ 157 | 158 | var options = { 159 | showRowNumber: true, 160 | allowHtml: true 161 | }; 162 | 163 | var table = new google.visualization.Table(document.getElementById('analytics-countries')); 164 | 165 | table.draw(data, options); 166 | 167 | }; 168 | 169 | Analytics.renderTotalSessions = function() { 170 | document.getElementById('totalSessions').innerHTML = window.totalSessionsData; 171 | }; 172 | 173 | Analytics.renderTotalUsers = function() { 174 | document.getElementById('totalUsers').innerHTML = window.totalUsersData; 175 | }; 176 | 177 | Analytics.renderTotalPageViews = function() { 178 | document.getElementById('totalPageViews').innerHTML = window.totalPageViewsData; 179 | }; 180 | 181 | /* 182 | Analytics.renderTotalPagesSession = function() { 183 | document.getElementById('totalPagesSession').innerHTML = window.totalPagesSession; 184 | }; 185 | */ 186 | 187 | Analytics.renderAverageSessionLength = function() { 188 | document.getElementById('averageSessionLength').innerHTML = window.averageSessionLengthData; 189 | }; 190 | 191 | return Analytics; 192 | }); -------------------------------------------------------------------------------- /assets/js/main.js: -------------------------------------------------------------------------------- 1 | 2 | Analytics.init({ 3 | render: [ 4 | 'SessionsGraph', 5 | 'VisitorsGraph', 6 | 'CountriesTable', 7 | 'TotalSessions', 8 | 'TotalUsers', 9 | 'TotalPageViews', 10 | 'AverageSessionLength', 11 | ] 12 | }); -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "infoweb-internet-solutions/yii2-cms-analytics", 3 | "description": "Analytics module for Yii2", 4 | "keywords": ["yii2", "yii2-cms-analytics", "analytics", "infoweb"], 5 | "type": "yii2-extension", 6 | "license": "MIT", 7 | "support": { 8 | "issues": "https://github.com/infoweb-internet-solutions/yii2-cms-analytics/issues?state=open", 9 | "source": "https://github.com/infoweb-internet-solutions/yii2-cms-analytics" 10 | }, 11 | "authors": [ 12 | { 13 | "name": "Fabio Maggio", 14 | "email": "fabio@infoweb.be", 15 | "homepage": "http://www.infoweb.be/" 16 | }, 17 | { 18 | "name": "Ruben Heymans", 19 | "email": "ruben@infoweb.be", 20 | "homepage": "http://www.infoweb.be/" 21 | } 22 | ], 23 | "require": { 24 | "yiisoft/yii2": "@stable", 25 | "google/apiclient": "1.*" 26 | 27 | }, 28 | "autoload": { 29 | "psr-4": { 30 | "infoweb\\analytics\\": "" 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /messages/en/infoweb/analytics.php: -------------------------------------------------------------------------------- 1 | '', 5 | 'Average session length' => '', 6 | 'Countries' => '', 7 | 'Day' => '', 8 | 'From' => '', 9 | 'New visitor' => '', 10 | 'Pageviews' => '', 11 | 'Returning visitor' => '', 12 | 'Sessions' => '', 13 | 'Title' => '', 14 | 'Total' => '', 15 | 'Users' => '', 16 | 'Visitors' => '', 17 | 'to' => '', 18 | ]; 19 | -------------------------------------------------------------------------------- /messages/fr/infoweb/analytics.php: -------------------------------------------------------------------------------- 1 | '', 5 | 'Average session length' => '', 6 | 'Countries' => '', 7 | 'Day' => '', 8 | 'From' => '', 9 | 'New visitor' => '', 10 | 'Pageviews' => '', 11 | 'Returning visitor' => '', 12 | 'Sessions' => '', 13 | 'Title' => '', 14 | 'Total' => '', 15 | 'Users' => '', 16 | 'Visitors' => '', 17 | 'to' => '', 18 | ]; 19 | -------------------------------------------------------------------------------- /messages/id/infoweb/analytics.php: -------------------------------------------------------------------------------- 1 | '', 4 | 'Average session length' => 'Panjang session rata-rata', 5 | 'Countries' => 'Negara', 6 | 'Day' => 'Hari', 7 | 'From' => 'Dari', 8 | 'New visitor' => 'Pengunjung Baru', 9 | 'Pageviews' => '', 10 | 'Returning visitor' => 'Pengunjung Kembali', 11 | 'Sessions' => '', 12 | 'Title' => '', 13 | 'Total' => '', 14 | 'Users' => 'Pengguna', 15 | 'Visitors' => 'Pengunjung', 16 | 'to' => 'Sampai', 17 | ]; 18 | -------------------------------------------------------------------------------- /messages/nl/infoweb/analytics.php: -------------------------------------------------------------------------------- 1 | 'Analytics', 5 | 'Average session length' => 'Gemiddelde sessieduur', 6 | 'Countries' => 'Landen', 7 | 'Day' => 'Dag', 8 | 'From' => 'Van', 9 | 'New visitor' => 'Nieuwe bezoeker', 10 | 'Pageviews' => 'Pagina weergaven', 11 | 'Returning visitor' => 'Terugkerende bezoeker', 12 | 'Sessions' => 'Sessies', 13 | 'Title' => 'Titel', 14 | 'Total' => 'Totaal', 15 | 'Users' => 'Gebruikers', 16 | 'Visitors' => 'Bezoekers', 17 | 'to' => 'tot', 18 | ]; 19 | -------------------------------------------------------------------------------- /models/Connect.php: -------------------------------------------------------------------------------- 1 | readFromCache('infoweb/analytics/connection'); 27 | 28 | if (!$connection) { 29 | $this->connectToAnalytics(); 30 | } else { 31 | $this->connection = $connection; 32 | } 33 | } 34 | 35 | public function connectToAnalytics() 36 | { 37 | if ($this->connection == null) { 38 | require_once Yii::getAlias('@google/api') . '/Google/Client.php'; 39 | require_once Yii::getAlias('@google/api') . '/Google/Service/Analytics.php'; 40 | 41 | $client = new \Google_Client(); //'../config.php' 42 | $client->setApplicationName("API Project"); 43 | $client->setDeveloperKey(Yii::$app->params['analytics']['developerKey']); 44 | 45 | $cred = new \Google_Auth_AssertionCredentials( 46 | // Add this email address as a new user to your Google analytics property 47 | Yii::$app->params['analytics']['serviceAccountName'], 48 | ['https://www.googleapis.com/auth/analytics.readonly'], 49 | file_get_contents(Yii::getAlias('@app') . '/assets/certificate/certificate.p12') 50 | ); 51 | 52 | $client->setAssertionCredentials($cred); 53 | 54 | $client->setClientId(Yii::$app->params['analytics']['clientId']); 55 | $client->setAccessType('offline_access'); 56 | 57 | // Connect to the analytics api 58 | $analytics = new \Google_Service_Analytics($client); 59 | 60 | $this->connection = $analytics; 61 | 62 | // Cache the connection 63 | $this->cacheData('infoweb/analytics/connection', $this->connection); 64 | } 65 | 66 | return $this->connection; 67 | } 68 | 69 | /** 70 | * Get the sessions data 71 | * 72 | * @return string 73 | */ 74 | public function getSessions() 75 | { 76 | // Read the data from cache 77 | $data = $this->readFromCache('infoweb/analytics/data/sessions'); 78 | 79 | if (!$data) { 80 | try { 81 | // You can find your analytics profile id here: Admin -> Profile Settings -> Profile ID 82 | $results = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:sessions', ['dimensions' => 'ga:date']); 83 | 84 | $data[] = [Yii::t('infoweb/analytics', 'Day'), Yii::t('infoweb/analytics', 'Sessions')]; 85 | 86 | foreach ($results['rows'] as $result) 87 | { 88 | $data[] = [date('d-m-Y', strtotime($result[0])), (int)$result[1]]; 89 | } 90 | 91 | $this->cacheData('infoweb/analytics/data/sessions', $data); 92 | 93 | } catch(Exception $e) { 94 | throw new BaseException(Yii::t('infoweb/analytics', 'Error while fetching data from Google Analytics')); 95 | } 96 | } 97 | 98 | return json_encode($data); 99 | } 100 | 101 | /** 102 | * Get the visitors data 103 | * 104 | * @return string 105 | */ 106 | public function getVisitors() 107 | { 108 | // Read the data from cache 109 | $data = $this->readFromCache('infoweb/analytics/data/visitors'); 110 | 111 | if (!$data) { 112 | try { 113 | 114 | $results['returningVisitors'] = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:sessions', ['segment' => 'gaid::-3'])->getTotalsForAllResults(); 115 | $results['newVisitors'] = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:sessions', ['segment' => 'gaid::-2'])->getTotalsForAllResults(); 116 | 117 | $data[] = [Yii::t('infoweb/analytics', 'Title'), Yii::t('infoweb/analytics', 'Total')]; 118 | 119 | $data[] = [Yii::t('infoweb/analytics', 'Returning visitor'), (int)$results['returningVisitors']['ga:sessions']]; 120 | $data[] = [Yii::t('infoweb/analytics', 'New visitor'), (int)$results['newVisitors']['ga:sessions']]; 121 | 122 | $this->cacheData('infoweb/analytics/data/visitors', $data); 123 | } catch(Exception $e) { 124 | throw new BaseException(Yii::t('infoweb/analytics', 'Error while fetching data from Google Analytics')); 125 | } 126 | } 127 | 128 | return json_encode($data); 129 | } 130 | 131 | /** 132 | * Get the countries data 133 | * 134 | * @return string 135 | */ 136 | public function getCountries() 137 | { 138 | // Read the data from cache 139 | $data = $this->readFromCache('infoweb/analytics/data/countries'); 140 | 141 | if (!$data) { 142 | try { 143 | 144 | //$results = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:sessions', ['sort' => '-ga:sessions', 'max-results' => 10]); 145 | $results = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:sessions', ['dimensions' => 'ga:country', 'sort' => '-ga:sessions', 'max-results' => 10]); 146 | 147 | $data['cols'] = [ 148 | ['id' => 'countries', 'label' => Yii::t('infoweb/analytics', 'Countries'), 'type' => 'string'], 149 | ['id' => 'sessions', 'label' => Yii::t('infoweb/analytics', 'Sessions'), 'type' => 'number'], 150 | ]; 151 | 152 | if ($results['rows']) { 153 | foreach ($results['rows'] as $result) 154 | { 155 | $data['rows'][] = ['c' => [ 156 | ['v' => $result[0]], 157 | ['v' => (int)$result[1]]], 158 | ]; 159 | } 160 | } 161 | 162 | $this->cacheData('infoweb/analytics/data/countries', $data); 163 | 164 | } catch(Exception $e) { 165 | throw new BaseException(Yii::t('infoweb/analytics', 'Error while fetching data from Google Analytics')); 166 | } 167 | } 168 | 169 | return json_encode($data); 170 | } 171 | 172 | /** 173 | * Get total sessions data 174 | * 175 | * @return string 176 | */ 177 | public function getTotalSessions() 178 | { 179 | // Read the data from cache 180 | $data = $this->readFromCache('infoweb/analytics/data/totalSessions'); 181 | 182 | if (!$data) { 183 | try { 184 | $results = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:sessions')->getTotalsForAllResults(); 185 | 186 | $data = number_format($results['ga:sessions'], 0, ',', '.'); 187 | 188 | $this->cacheData('infoweb/analytics/data/totalSessions', $data); 189 | } catch(Exception $e) { 190 | throw new BaseException(Yii::t('infoweb/analytics', 'Error while fetching data from Google Analytics')); 191 | } 192 | } 193 | 194 | return json_encode($data); 195 | } 196 | 197 | /** 198 | * Get total users data 199 | * 200 | * @return string 201 | */ 202 | public function getTotalUsers() 203 | { 204 | // Read the data from cache 205 | $data = $this->readFromCache('infoweb/analytics/data/totalUsers'); 206 | 207 | if (!$data) { 208 | try { 209 | $results = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:users')->getTotalsForAllResults(); 210 | 211 | $data = number_format($results['ga:users'], 0, ',', '.'); 212 | 213 | $this->cacheData('infoweb/analytics/data/totalUsers', $data); 214 | } catch(Exception $e) { 215 | throw new BaseException(Yii::t('infoweb/analytics', 'Error while fetching data from Google Analytics')); 216 | } 217 | } 218 | 219 | return json_encode($data); 220 | } 221 | 222 | /** 223 | * Get total page views data 224 | * 225 | * @return string 226 | */ 227 | public function getTotalPageViews() 228 | { 229 | // Read the data from cache 230 | $data = $this->readFromCache('infoweb/analytics/data/totalPageViews'); 231 | 232 | if (!$data) { 233 | try { 234 | $results = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:pageviews')->getTotalsForAllResults(); 235 | 236 | $data = number_format($results['ga:pageviews'], 0, ',', '.'); 237 | 238 | $this->cacheData('infoweb/analytics/data/totalPageViews', $data); 239 | } catch(Exception $e) { 240 | throw new BaseException(Yii::t('infoweb/analytics', 'Error while fetching data from Google Analytics')); 241 | } 242 | } 243 | 244 | return json_encode($data); 245 | } 246 | 247 | /** 248 | * Get average session length data 249 | * 250 | * @return string 251 | */ 252 | public function getAverageSessionLength() 253 | { 254 | // Read the data from cache 255 | $data = $this->readFromCache('infoweb/analytics/data/averageSessionLength'); 256 | 257 | if (!$data) { 258 | try { 259 | $results = $this->connection->data_ga->get(Yii::$app->params['analytics']['analyticsId'], $this->startDate, $this->endDate, 'ga:avgSessionDuration')->getTotalsForAllResults(); 260 | 261 | $data = gmdate('H:i:m', $results['ga:avgSessionDuration']); 262 | 263 | $this->cacheData('infoweb/analytics/data/averageSessionLength', $data); 264 | } catch(Exception $e) { 265 | throw new BaseException(Yii::t('infoweb/analytics', 'Error while fetching data from Google Analytics')); 266 | } 267 | } 268 | 269 | return json_encode($data); 270 | } 271 | 272 | /** 273 | * Caches data in a session variable 274 | * 275 | * @param string $key The key that has to be used in the session var 276 | * @param mixed $data 277 | * @return boolean 278 | */ 279 | public function cacheData($key = '', $data = []) 280 | { 281 | $session = Yii::$app->session; 282 | 283 | $session[$key] = serialize($data); 284 | 285 | return true; 286 | } 287 | 288 | /** 289 | * Reads the data from cache 290 | * 291 | * @param string $key 292 | * @return mixed 293 | */ 294 | public function readFromCache($key) 295 | { 296 | $session = Yii::$app->session; 297 | 298 | return ($session->has($key)) ? unserialize($session[$key]) : []; 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /views/average_session_length.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
-------------------------------------------------------------------------------- /views/countries.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 5 |
6 |
7 |
8 |
9 |
10 |
-------------------------------------------------------------------------------- /views/sessions.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 5 |
6 |
7 |
8 |
9 |
10 |
-------------------------------------------------------------------------------- /views/total_page_views.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
-------------------------------------------------------------------------------- /views/total_sessions.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 | 8 |
9 | 10 |
11 |
12 |
13 |
14 |
15 |
16 | */ ?> 17 |
18 | 20 | 26 | 27 | */ ?> 28 |
29 | -------------------------------------------------------------------------------- /views/total_users.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
-------------------------------------------------------------------------------- /views/visitors.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------