= $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 "

"; var_dump($result); } $tjson = json_decode($result['body']); $options['gapp_token'] = $tjson->access_token; $options['gapp_token_refresh'] = $tjson->refresh_token; $options['gapp_expires'] = time() + $tjson->expires_in; update_option('gapp', $options); $ijson = gapp_api_call('https://www.googleapis.com/oauth2/v1/userinfo', array()); $options['gapp_gid'] = $ijson->id; $options['gapp_gmail'] = $ijson->email; update_option('gapp', $options); if (!empty($options['gapp_token']) && !empty($options['gapp_gmail'])) { echo ''; exit; } } elseif (isset($_GET['state']) && $_GET['state'] == 'reset') { if (current_user_can('manage_options')) { $options['gapp_gid'] = null; $options['gapp_gmail'] = null; $options['gapp_token'] = null; $options['gapp_token_refresh'] = null; $options['gapp_expires'] = null; $options['gapp_defaultval'] = 0; $options['gapp_totalpost'] = 1; $options['gapp_totalpost_grid'] = 1; $options['gapp_btn_color'] = null; $options['onoffswitch'] = 1; $options['gapp_sliderwidth'] = '100%'; $options['gapp_sliderheight'] = '600px'; $options['gapp_analytics_code'] = 'UA-136334315-1'; update_option('gapp', $options); $updated = true; } } elseif (isset($_GET['state']) && $_GET['state'] == 'clear') { $options['gapp_clientid'] = null; $options['gapp_psecret'] = null; update_option('gapp', $options); $updated = true; } elseif (isset($_GET['refresh'])) { gapp_refresh_token(); $options = gapp_options(); $updated = true; } elseif (isset($_GET['reset'])) { $wpdb->query("DELETE FROM `" . $wpdb->options . "` WHERE `option_name` LIKE '_transient_gapp-transient-%'"); $wpdb->query("DELETE FROM `" . $wpdb->options . "` WHERE `option_name` LIKE '_transient_timeout_gapp-transient-%'"); set_transient('gapp-namespace-key', uniqid(), 86400 * 365); $updated = true; } //if ('' != $_POST['submit'] || isset($_POST['submit'])) { if (isset($_REQUEST['submit'])) { check_admin_referer('gapp', 'gapp-admin'); if (current_user_can('manage_options')) { if (isset($_POST['gapp_clientid'])) { $options['gapp_clientid'] = sanitize_text_field($_POST['gapp_clientid']); } if (isset($_POST['gapp_psecret'])) { $options['gapp_psecret'] = sanitize_text_field($_POST['gapp_psecret']); } if (isset($_POST['gapp_wid'])) { $options['gapp_wid'] = sanitize_text_field($_POST['gapp_wid']); } if (isset($_POST['gapp_cache'])) { $options['gapp_cache'] = sanitize_text_field($_POST['gapp_cache']); } if (isset($_POST['gapp_startdate'])) { $options['gapp_startdate'] = sanitize_text_field($_POST['gapp_startdate']); } if (isset($_POST['gapp_defaultval'])) { $options['gapp_defaultval'] = sanitize_text_field($_POST['gapp_defaultval']); } if (isset($_POST['gapp_totalpost'])) { $options['gapp_totalpost'] = sanitize_text_field($_POST['gapp_totalpost']); } if (isset($_POST['gapp_totalpost_grid'])) { $options['gapp_totalpost_grid'] = sanitize_text_field($_POST['gapp_totalpost_grid']); } if (isset($_POST['gapp_btn_color'])) { $options['gapp_btn_color'] = sanitize_text_field($_POST['gapp_btn_color']); } if (isset($_POST['gapp_sliderwidth'])) { $options['gapp_sliderwidth'] = sanitize_text_field($_POST['gapp_sliderwidth']); } if (isset($_POST['gapp_sliderheight'])) { $options['gapp_sliderheight'] = sanitize_text_field($_POST['gapp_sliderheight']); } if (isset($_POST['gapp_analytics_code'])) { $options['gapp_analytics_code'] = sanitize_text_field($_POST['gapp_analytics_code']); } if (isset($_POST['gapp_metric'])) { $options['gapp_metric'] = sanitize_text_field($_POST['gapp_metric']); } //if (isset($_POST['gapp_onoffswitch'])) { $options['gapp_onoffswitch'] = (isset($_POST['gapp_onoffswitch'])); //} //if (isset($_POST['gapp_onoffswitch_grid'])) { $options['gapp_onoffswitch_grid'] = (isset($_POST['gapp_onoffswitch_grid'])); //} //if (isset($_POST['gapp_column'])) { $options['gapp_column'] = (isset($_POST['gapp_column'])); //} //if (isset($_POST['gapp_trailing'])) { $options['gapp_trailing'] = (isset($_POST['gapp_trailing'])); //} update_option('gapp', $options); $updated = true; } } echo '
'; if ($updated) { echo '

'; _e('Configuration updated.', 'addweb-google-popular-post'); echo '

'; } // if (!empty($options['gapp_token'])) { // echo '

'.__('Post Pageviews Usage', '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 '

'.__('Post Pageviews Settings', 'google-popular-post').'

'; if (empty($options['gapp_token'])) { if (empty($options['gapp_clientid']) || empty($options['gapp_psecret'])) { 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 '
'; echo '

'.__('Then, create an OAuth Client ID in "APIs & auth > Credentials". Enter this URL for the Redirect URI field:', 'addweb-google-popular-post').'
'; echo admin_url('options-general.php?page=' . GAPP_SLUG); echo '

'; echo '

'.__('You also have to fill the Product Name field in "APIs & auth" -> "Consent screen" — you need to select e-mail address as well.').'

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; wp_nonce_field('gapp', 'gapp-admin'); echo '

'; } else { $url_auth = 'https://accounts.google.com/o/oauth2/auth?client_id='.$options['gapp_clientid'].'&redirect_uri='; $url_auth .= admin_url('options-general.php?page=' . GAPP_SLUG); $url_auth .= '&scope=https://www.googleapis.com/auth/analytics.readonly+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile&response_type=code&access_type=offline&state=init&approval_prompt=force'; echo '

'.__('Connect to Google Analytics', 'addweb-google-popular-post').'

'; echo '

'.__('Clear the API keys').' »

'; } } else { echo '
'; echo '
'; 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 '
'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '
'; echo ''; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '

'; echo '
'; echo ''; echo '

'; echo '

'; echo '
'; echo '

'; echo '

'; echo '

'; echo '
'; 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').' →

'; } elseif (isset($options['gapp_error']) && !empty($options['gapp_error'])) { echo '

'.__('Google Post Pageviews Error: ') . $options['gapp_error'] . '
'.__('Update settings', 'addweb-google-popular-post').' →

'; } } } // Admin notice add_action('admin_notices', 'gapp_admin_notice'); function gapp_google_analytics_scipt() { wp_enqueue_style('jquery-ui-css', plugin_dir_url( __FILE__ ) . 'inc/css/admin/jquery-ui.css'); wp_enqueue_script( 'custom', plugin_dir_url( __FILE__ ) . 'inc/js/admin/tabs.js', array('jquery-ui-tabs'), '', true ); } add_action('admin_enqueue_scripts', 'gapp_google_analytics_scipt'); function gapp_add_googleanalytics() { $options = gapp_options(); if($options['gapp_analytics_code'] != ' ') { ?> '