= $options['gapp_expires']) { $options = gapp_refresh_token(); } $qs = '?access_token='.urlencode($options['gapp_token']); foreach ($params as $k => $v) { $qs .= '&'.$k.'='.($urlEncode ? urlencode($v) : $v); } $request = new WP_Http; $result = $request->request($url.$qs); $json = new stdClass(); $options['gapp_error'] = null; if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 === $result['response']['code'] ) { $json = json_decode($result['body']); update_option('gapp', $options); return $json; } else { if ( is_array( $result ) && isset( $result['response']['code'] ) && 403 === $result['response']['code'] ) { $json = json_decode($result['body'], true); $options['gapp_error'] = $json['error']['errors'][0]['message']; $options['gapp_token'] = null; $options['gapp_token_refresh'] = null; $options['gapp_expires'] = null; $options['gapp_gid'] = null; update_option('gapp', $options); } return new stdClass(); } } function gapp_refresh_token() { $options = gapp_options(); /* If the token has expired, we create it again */ if (!empty($options['gapp_token_refresh'])) { $request = new WP_Http; $result = $request->request('https://accounts.google.com/o/oauth2/token', array( 'method' => 'POST', 'body' => array( 'client_id' => $options['gapp_clientid'], 'client_secret' => $options['gapp_psecret'], 'refresh_token' => $options['gapp_token_refresh'], 'grant_type' => 'refresh_token', ), )); $options['gapp_error'] = null; if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 === $result['response']['code'] ) { $tjson = json_decode($result['body']); $request = new WP_Http; $result = $request->request('https://www.googleapis.com/oauth2/v1/userinfo?access_token='.urlencode($tjson->access_token)); if ( is_array( $result ) && isset( $result['response']['code'] ) && 200 === $result['response']['code'] ) { $ijson = json_decode($result['body']); $options['gapp_token'] = $tjson->access_token; if (isset($tjson->refresh_token) && !empty($tjson->refresh_token)) { $options['gapp_token_refresh'] = $tjson->refresh_token; } $options['gapp_expires'] = time() + $tjson->expires_in; $options['gapp_gid'] = $ijson->id; update_option('gapp', $options); } elseif ( is_array( $result ) && isset( $result['response']['code'] ) && 403 === $result['response']['code'] ) { $json = json_decode($result['body'], true); $options['gapp_error'] = $json['error']['errors'][0]['message']; $options['gapp_token'] = null; $options['gapp_token_refresh'] = null; $options['gapp_expires'] = null; $options['gapp_gid'] = null; update_option('gapp', $options); } } /* else { $options['gapp_token'] = null; $options['gapp_token_refresh'] = null; $options['gapp_expires'] = null; $options['gapp_gid'] = null; update_option('gapp', $options); } */ } return $options; } function gapp_options() { $options = get_option('gapp'); if (!isset($options['gapp_clientid'])) { if (isset($options['gapp_pnumber'])) { $options['gapp_clientid'] = $options['gapp_pnumber'] . '.apps.googleusercontent.com'; } else { $options['gapp_clientid'] = null; } } if (isset($options['gapp_pnumber'])) unset($options['gapp_pnumber']); if (!isset($options['gapp_psecret'])) $options['gapp_psecret'] = null; if (!isset($options['gapp_gid'])) $options['gapp_gid'] = null; if (!isset($options['gapp_gmail'])) $options['gapp_gmail'] = null; if (!isset($options['gapp_token'])) $options['gapp_token'] = null; if (!isset($options['gapp_defaultval'])) $options['gapp_defaultval'] = 0; if (!isset($options['gapp_totalpost'])) $options['gapp_totalpost'] = 1; if (!isset($options['gapp_totalpost_grid'])) $options['gapp_totalpost_grid'] = 1; if (!isset($options['gapp_btn_color'])) $options['gapp_btn_color'] = null; if (!isset($options['gapp_sliderwidth'])) $options['gapp_sliderwidth'] = '100%'; if (!isset($options['gapp_sliderheight'])) $options['gapp_sliderheight'] = '600px'; if (!isset($options['gapp_analytics_code'])) $options['gapp_analytics_code'] = 'UA-136334315-1'; if (!isset($options['gapp_token_refresh'])) $options['gapp_token_refresh'] = null; if (!isset($options['gapp_expires'])) $options['gapp_expires'] = null; if (!isset($options['gapp_wid'])) $options['gapp_wid'] = null; if (!isset($options['gapp_column'])) $options['gapp_column'] = true; if (!isset($options['gapp_onoffswitch'])) $options['gapp_onoffswitch'] = true; if (!isset($options['gapp_onoffswitch_grid'])) $options['gapp_onoffswitch_grid'] = true; if (!isset($options['gapp_trailing'])) $options['gapp_trailing'] = true; if (!isset($options['gapp_cache'])) $options['gapp_cache'] = 60; if (!isset($options['gapp_metric'])) $options['gapp_metric'] = 'ga:pageviews'; if (!preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['gapp_startdate'])) $options['gapp_startdate'] = '2007-09-29'; return $options; } function gapp_conf() { /** @var $wpdb WPDB */ global $wpdb; $options = gapp_options(); $updated = false; if (isset($_GET['state']) && $_GET['state'] == 'init' && $_GET['code']) { $request = new WP_Http; $result = $request->request('https://accounts.google.com/o/oauth2/token', array( 'method' => 'POST', 'body' => array( 'code' => $_GET['code'], 'client_id' => $options['gapp_clientid'], 'client_secret' => $options['gapp_psecret'], 'redirect_uri' => admin_url('options-general.php?page=' . GAPP_SLUG), 'grant_type' => 'authorization_code', ) )); if ( !is_array( $result ) || !isset( $result['response']['code'] ) && 200 !== $result['response']['code'] ) { echo '
'; _e('There was something wrong with Google.', 'addweb-google-popular-post'); echo "
'; _e('Configuration updated.', 'addweb-google-popular-post'); echo '
'.__('To display the pageviews number of a particular post, insert this PHP code in your template:', 'google-popular-post').'
'; // echo ''; // echo ''.__('This code must be placed in The Loop. If not, you can specify the post ID.', 'google-popular-post').'
'; // } echo ''.__('In order to connect to your Google Analytics Account, you need to create a new project in the Google API Console and activate the Analytics API in "APIs & auth > APIs".', 'addweb-google-popular-post').'
'; echo ''.__('Connect to Google Analytics', 'addweb-google-popular-post').'
'; echo ''.__('Clear the API keys').' »
'; } } else { echo ''.__('You are connected to Google Analytics with the e-mail address:', 'addweb-google-popular-post').' '.$options['gapp_gmail'].'.
'; echo ''.__('Your token expires on:', 'addweb-google-popular-post').' '.date_i18n( 'Y/m/d \a\t g:ia', $options['gapp_expires'] + ( get_option( 'gmt_offset' ) * 3600 ) , 1 ).'.
'; echo ''.__('Disconnect from Google Analytics', 'addweb-google-popular-post').' »
'; echo ''.__('Refresh Google API token', 'addweb-google-popular-post').' »
'; echo ''.__('Empty pageviews cache', 'addweb-google-popular-post').' »
'; echo ''; wp_nonce_field('gapp', 'gapp-admin'); echo '
'; } } function gapp_get_post_pageviews($ID = null, $format = true, $save = true) { $options = gapp_options(); if ($ID) { $basename = basename(get_permalink($ID)); if ($options['gapp_trailing']) { $basename .= '/'; } $gaTransName = 'gapp-transient-'.$ID; $permalink = '/' . (($ID != 1) ? $basename : null); $postID = $ID; $postDate = get_the_date('Y-m-d', $postID); } else { $basename = basename(get_permalink()); if ($options['gapp_trailing']) { $basename .= '/'; } $gaTransName = 'gapp-transient-'.get_the_ID(); $permalink = '/' . $basename; $postID = get_the_ID(); $postDate = get_the_date('Y-m-d'); } // Check if the published date is earlier than default start date if (strtotime($postDate) > strtotime($options['gapp_startdate'])) { $startDate = $postDate; } else { $startDate = $options['gapp_startdate']; } $namespaceKey = get_transient('gapp-namespace-key'); if ($namespaceKey === false) { $namespaceKey = uniqid(); set_transient('gapp-namespace-key', $namespaceKey, YEAR_IN_SECONDS); } $gaTransName .= '-' . $namespaceKey; $totalResult = get_transient($gaTransName); if ($totalResult !== false && is_numeric($totalResult)) { if ($save && !add_post_meta($postID, '_gapp_post_views', $totalResult, true)) { update_post_meta($postID, '_gapp_post_views', $totalResult); } return ($format) ? number_format_i18n($totalResult) : $totalResult; } else { if (empty($options['gapp_token'])) { return $options['gapp_defaultval']; } if (!$ID || $ID != 1) { if ($ID) { $status = get_post_status($ID); } else { $status = get_post_status(get_the_ID()); } if ($status !== 'publish') { set_transient($gaTransName, '0', 60 * $options['gapp_cache']); if (!add_post_meta($postID, '_gapp_post_views', '0', true)) { update_post_meta($postID, '_gapp_post_views', '0'); } return 0; } } $json = gapp_api_call('https://www.googleapis.com/analytics/v3/data/ga', array('ids' => 'ga:'.$options['gapp_wid'], 'start-date' => $startDate, 'end-date' => date('Y-m-d'), 'metrics' => $options['gapp_metric'], 'filters' => 'ga:pagePath=@' . $permalink, 'max-results' => 1000) , false); // echo "";
// print_r($json);
// echo "";
if ( isset( $json->totalsForAllResults->{$options['gapp_metric']} ) ) {
$totalResult = $json->totalsForAllResults->{$options['gapp_metric']};
echo $totalResult;
set_transient($gaTransName, $totalResult, 60 * $options['gapp_cache']);
if (!add_post_meta($postID, '_gapp_post_views', $totalResult, true)) {
update_post_meta($postID, '_gapp_post_views', $totalResult);
}
return ($format) ? number_format_i18n($totalResult) : $totalResult;
} else {
$default_value = $options['gapp_defaultval'];
// If we have an old value let's put that instead of the default one in case of an error
$meta_value = get_post_meta($postID, '_gapp_post_views', true);
if ($meta_value !== false) {
$default_value = $meta_value;
}
set_transient($gaTransName, $default_value, 60 * $options['gapp_cache']);
return $options['gapp_defaultval'];
}
}
}
// Add a column in Posts list (Optional)
add_filter('manage_posts_columns', 'gapp_column_views');
add_action('manage_posts_custom_column', 'gapp_custom_column_views', 6, 2);
add_action('admin_head', 'gapp_column_style');
add_filter('manage_edit-post_sortable_columns', 'gapp_manage_sortable_columns');
add_action('pre_get_posts', 'gapp_pre_get_posts', 1);
function gapp_column_views($defaults) {
$options = gapp_options();
if (!empty($options['gapp_token']) && $options['gapp_column']) {
$defaults['post_views'] = __('Views');
}
return $defaults;
}
function gapp_custom_column_views($column_name, $id) {
if ($column_name === 'post_views') {
echo gapp_get_post_pageviews(get_the_ID(), true, true);
}
}
function gapp_column_style() {
echo '';
}
function gapp_manage_sortable_columns($sortable_columns) {
$sortable_columns['post_views'] = 'post_views';
return $sortable_columns;
}
function gapp_pre_get_posts($query) {
if ($query->is_main_query() && ($orderby = $query->get('orderby'))) {
switch ($orderby) {
case 'post_views':
$query->set('meta_key', '_gapp_post_views');
$query->set('orderby', 'meta_value_num');
break;
}
}
return $query;
}
function gapp_admin_notice() {
$options = gapp_options();
if (current_user_can('manage_options')) {
if (isset($options['gapp_token']) && empty($options['gapp_token'])) {
echo ''.__('Google Post Pageviews Warning: You have to (re)connect the plugin to your Google account.') . '
'.__('Update settings', 'addweb-google-popular-post').' →
'.__('Google Post Pageviews Error: ') . $options['gapp_error'] . '
'.__('Update settings', 'addweb-google-popular-post').' →