* @copyright 2007-2013 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_VERSION_'))
exit;
class Gapi extends Module
{
public function __construct($type = null)
{
$this->name = 'gapi';
$this->tab = 'administration';
$this->version = 0.9;
$this->author = 'PrestaShop';
$this->need_instance = 0;
parent::__construct();
$this->displayName = $this->l('Google Analytics API');
}
public function getContent()
{
$html = '';
// Check configuration
$allow_url_fopen = ini_get('allow_url_fopen');
$openssl = extension_loaded('openssl');
$curl = extension_loaded('curl');
$ping = (($allow_url_fopen || $curl) && $openssl && Tools::file_get_contents('https://www.google.com/'));
$online = (in_array(Tools::getRemoteAddr(), array('127.0.0.1', '::1')) ? false : true);
if (!$ping || !$online)
{
$html .= $this->displayError('
'.(($curl && $allow_url_fopen) ? '' : '
'.$this->l('You are not allowed to open external URLs').'
').'
'.(($curl && $allow_url_fopen) ? '' : '
'.$this->l('cURL is not enabled').'
').'
'.($openssl ? '' : '
'.$this->l('OpenSSL is not enabled').'
').'
'.(($allow_url_fopen AND $openssl AND !$ping) ? '
'.$this->l('Google is unreachable').' ('.$this->l('check your firewall').')
' : '').'
'.($online ? '' : '
'.$this->l('Your store is not online').'
').'
');
}
// You can switch to the 1.3 API by replacing the following function call by $this->api_1_3_getContent()
return $html.$this->api_3_0_getContent();
}
public function requestReportData($dimensions, $metrics, $date_from, $date_to, $sort = null, $filters = null, $start = 1, $limit = 30)
{
// You can switch to the 1.3 API by replacing the following function call by $this->api_1_3_requestReportData()
return $this->api_3_0_requestReportData($dimensions, $metrics, $date_from, $date_to, $sort, $filters, $start, $limit);
}
public function api_3_0_authenticate()
{
// https://developers.google.com/accounts/docs/OAuth2WebServer
$params = array(
'response_type' => 'code',
'client_id' => Configuration::get('PS_GAPI30_CLIENT_ID_TMP'),
'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
'redirect_uri' => Tools::getShopDomain(true, false).__PS_BASE_URI__.'modules/'.$this->name.'/oauth2callback.php',
'state' => $this->context->employee->id.'-'.Tools::encrypt($this->context->employee->id.Configuration::get('PS_GAPI30_CLIENT_ID_TMP')),
'approval_prompt' => 'force',
'access_type' => 'offline'
);
Tools::redirectLink('https://accounts.google.com/o/oauth2/auth?'.http_build_query($params));
}
public function api_3_0_refreshtoken()
{
$params = array(
'client_id' => Configuration::get('PS_GAPI30_CLIENT_ID'),
'client_secret' => Configuration::get('PS_GAPI30_CLIENT_SECRET'),
'grant_type' => 'authorization_code'
);
// https://developers.google.com/accounts/docs/OAuth2WebServer#offline
if (Configuration::get('PS_GAPI30_REFRESH_TOKEN'))
$params['refresh_token'] = Configuration::get('PS_GAPI30_REFRESH_TOKEN');
else
{
$params['code'] = Configuration::get('PS_GAPI30_AUTHORIZATION_CODE');
$params['redirect_uri'] = Tools::getShopDomain(true, false).__PS_BASE_URI__.'modules/'.$this->name.'/oauth2callback.php';
}
$stream_context = stream_context_create(array(
'http' => array(
'method'=> 'POST',
'content' => http_build_query($params),
'header' => 'Content-type: application/x-www-form-urlencoded',
'timeout' => 5,
)
));
if (!$response_json = Tools::file_get_contents('https://accounts.google.com/o/oauth2/token', false, $stream_context))
return false;
$response = Tools::jsonDecode($response_json, true);
Configuration::updateValue('PS_GAPI30_ACCESS_TOKEN', $response['access_token']);
Configuration::updateValue('PS_GAPI30_TOKEN_EXPIRATION', time() + (int)$response['expires_in']);
if (isset($response['refresh_token']))
Configuration::updateValue('PS_GAPI30_REFRESH_TOKEN', $response['refresh_token']);
return true;
}
public function api_3_0_getContent()
{
$html = '';
if (Tools::getValue('PS_GAPI30_CLIENT_ID'))
{
Configuration::updateValue('PS_GAPI30_REQUEST_URI_TMP', dirname($_SERVER['REQUEST_URI']).'/'.AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
Configuration::updateValue('PS_GAPI30_CLIENT_ID_TMP', trim(Tools::getValue('PS_GAPI30_CLIENT_ID')));
Configuration::updateValue('PS_GAPI30_CLIENT_SECRET_TMP', trim(Tools::getValue('PS_GAPI30_CLIENT_SECRET')));
Configuration::updateValue('PS_GAPI30_PROFILE_TMP', trim(Tools::getValue('PS_GAPI30_PROFILE')));
// This will redirect the user to Google API authentication page
$this->api_3_0_authenticate();
}
elseif (Tools::getValue('oauth2callback') == 'error')
$html .= $this->displayError('Google API: Access denied');
elseif (Tools::getValue('oauth2callback') == 'undefined')
$html .= $this->displayError('Something wrong happened with Google API authorization');
elseif (Tools::getValue('oauth2callback') == 'success')
{
if ($this->api_3_0_refreshtoken())
$html .= $this->displayConfirmation('Google API Authorization granted');
else
$html .= $this->displayError('Google API Authorization granted but access token cannot be retrieved');
}
$display_slider = true;
if (Configuration::get('PS_GAPI30_CLIENT_ID') && Configuration::get('PS_GAPI30_CLIENT_SECRET') && Configuration::get('PS_GAPI30_PROFILE'))
{
$result_test = $this->api_3_0_requestReportData('', 'ga:visits,ga:uniquePageviews', date('Y-m-d', strtotime('-1 day')), date('Y-m-d', strtotime('-1 day')), null, null, 1, 1);
if (!$result_test)
$html .= $this->displayError('Cannot retrieve test results');
else
{
$display_slider = false;
$html .= $this->displayConfirmation(sprintf($this->l('Yesterday, your store received the visit of %d people for a total of %d unique page views.'), $result_test[0]['metrics']['visits'], $result_test[0]['metrics']['uniquePageviews']));
}
}
if ($display_slider)
{
$slides = array(
'Google API - 01 - Start.png' => $this->l('Go to https://code.google.com/apis/console and click the "Create project..." button'),
'Google API - 02 - Services.png' => $this->l('In the "Services" tab, switch on the Analytics API'),
'Google API - 03 - Terms.png' => $this->l('You will be asked to agree to the Terms of Service of Google APIs'),
'Google API - 04 - Terms.png' => $this->l('And the Terms of Service of Analytics API'),
'Google API - 05 - Services OK.png' => $this->l('You should now have something like that'),
'Google API - 06 - API Access.png' => $this->l('In the "API Access" tab, click the big, blue, "Create an OAuth 2.0 client ID..." button'),
'Google API - 07 - Create Client ID.png' => $this->l('Fill in the form with the name of your store, the URL of your logo and the URL of your store then click "Next"'),
'Google API - 08 - Create Client ID.png' => sprintf($this->l('Keep "Web application" select and fill in the "Authorized Redirect URIs" area with the following URL: %s (you may have to click the "more options" link). Then validate by clicking the "Create client ID" button'), Tools::getShopDomain(true, false).__PS_BASE_URI__.'modules/'.$this->name.'/oauth2callback.php'),
'Google API - 09 - API Access created.png' => $this->l('You should now have the following screen. Copy/Paste the "Client ID" and "Client secret" into the form below'),
'Google API - 10 - Profile ID.png' => $this->l('Now you need the ID of the Analytics Profile you want to connect. In order to find you Profile ID, connect to the Analytics dashboard look at the URL in the address bar. Your Profile ID is the number following a "p", as shown underlined in red on the screenshot')
);
$first_slide = key($slides);
$html .= '