public function get_account_id() { // session_start(); $ga = new GoogleAnalyticsAPI(); $this->load->model('Creds'); $this->Creds->get_gacreds(); $valuesdb = $this->session->userdata('creds'); $ga->auth->setClientId($valuesdb['ClientId']); $ga->auth->setClientSecret($valuesdb['Clientsecret']); $ga->auth->setRedirectUri(base_url() . "admin/media_stats/queryapi"); /* * Step 1: Check if we have an oAuth access token in our session * If we've got $_GET['code'], move to the next step */ if (!isset($_SESSION['oauth_access_token']) && !isset($_GET['code'])) { // Go get the url of the authentication page, redirect the client and go get that token! $url = $ga->auth->buildAuthUrl(); header("Location: " . $url); } if (!isset($_SESSION['oauth_access_token']) && isset($_GET['code'])) { // $auth = $ga->auth->getAccessToken($_GET['code']); $code = $_GET['code']; $auth = $ga->auth->getAccessToken($code); if ($auth['http_code'] == 200) { $accessToken = $auth['access_token']; $refreshToken = $auth['refresh_token']; $tokenExpires = $auth['expires_in']; $tokenCreated = time(); // For simplicity of the example we only store the accessToken // If it expires use the refreshToken to get a fresh one $_SESSION['oauth_access_token'] = $accessToken; } else { die("Sorry, something went wrong retrieving the oAuth tokens"); } } if (time() - $tokenCreated >= $tokenExpires) { $auth = $ga->auth->refreshAccessToken($refreshToken); } $ga->setAccessToken($accessToken); $profiles = $ga->getProfiles(); $accounts = array(); foreach ($profiles['items'] as $item) { $id = "ga:{$item['id']}"; $name = $item['name']; $accounts[$id] = $name; } $ga->setAccountId($id); $defaults = array('start-date' => date('Y-m-d', strtotime('-1 month')), 'end-date' => date('Y-m-d')); $ga->setDefaultQueryParams($defaults); $params = array('metrics' => 'ga:visits', 'demensions' => 'ga:date'); $visits = $ga->query($params); return $visits; }
function widget($args, $instance) { extract($args); $title = apply_filters('widget_title', $instance['title']); $items = intval($instance['items']); $pages = $instance['pages']; $tasks = $instance['tasks']; $projects = $instance['projects']; $vacancies = $instance['vacancies']; $news = $instance['news']; $blog = $instance['blog']; $events = $instance['events']; $trail = intval($instance['trail']); $ga_viewid = $instance['ga_viewid']; $cache = intval($instance['cache']); if (!$cache) { $cache = 1; } $widget_id = $id; $acf_key = "widget_" . $this->id_base . "-" . $this->number . "_exclude_posts"; $exclude = get_option($acf_key); $stoppages = array('how-do-i', 'task-by-category', 'news-by-category', 'newspage', 'tagged', 'atoz', 'about', 'home', 'blogs', 'events', 'category', 'news-type'); if ($exclude) { foreach ($exclude as $sp) { $stop = get_page($sp); if ($stop) { $stoppages[] = $stop->post_name; } } } $acf_key = "widget_" . $this->id_base . "-" . $this->number . "_show_guide_chapters"; $showchapters = get_option($acf_key); $client_id = '956426687308-20cs4la3m295f07f1njid6ttoeinvi92.apps.googleusercontent.com'; $client_secret = 'yzrrxZgCPqIu2gaqqq-uzB4D'; $redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'; $account_id = 'ga:' . $ga_viewid; $baseurl = site_url(); $to_fill = $items; $k = 0; $alreadydone = array(); $html = ''; $gatransient = substr('cached_ga_' . $widget_id . '_' . sanitize_file_name($title), 0, 45); $cachedga = get_transient($gatransient); if ($cachedga != "") { // if we have a fresh cache foreach ($cachedga as $result) { if ($k > $items - 1) { break; } $k++; $html .= $result; } } else { //load fresh analytics include_once 'GoogleAnalyticsAPI.class.php'; $ga = new GoogleAnalyticsAPI(); $ga->auth->setClientId($client_id); // From the APIs console $ga->auth->setClientSecret($client_secret); // From the APIs console $ga->auth->setRedirectUri($redirect_uri); // Url to your app, must match one in the APIs console // Get the Auth-Url $url = $ga->auth->buildAuthUrl(); ini_set('error_reporting', '0'); // disable all, for security $gatoken = get_option('ga_token'); $refreshToken = get_option('ga_refresh_token'); $tokenExpires = get_option('ga_token_expires'); $tokenCreated = get_option('ga_token_created'); /* * Step 1: Get a Token */ if ($gatoken == '') { // if no token stored if (!isset($_GET['code'])) { // if we arn't submitting GET code to the db $url = $ga->auth->buildAuthUrl(); // give users a form to generate code ?> <a class="btn btn-primary" target="_blank" href="<?php echo $url; ?> "><?php _e('Authorise Google Analytics access', 'govintranet'); ?> </a> <form id="" class=""> <label for="code"><?php _e('Enter your code from Google', 'govintranet'); ?> </label></span> <input id="code" name="code" /> <button class="submit" type="submit"><?php _e('Save', 'govintranet'); ?> </button> </form> <?php } else { // we are submitting GET code to the db $auth = $ga->auth->getAccessToken($_GET['code']); if ($auth['http_code'] == 200) { $accessToken = $auth['access_token']; $refreshToken = $auth['refresh_token']; $tokenExpires = $auth['expires_in']; $tokenCreated = time(); // Store the Tokens update_option('ga_token', $accessToken); $gatoken = $accessToken; // make token available for use update_option('ga_refresh_token', $refreshToken); update_option('ga_token_expires', $tokenExpires); update_option('ga_token_created', $tokenCreated); } else { $url = $ga->auth->buildAuthUrl(); // give users a form to generate code ?> <em><?php _e('Sorry, something went wrong accessing Google Analytics', 'govintranet'); ?> :<?php echo $auth['error_description']; ?> </em> <a class="btn btn-primary" target="_blank" href="<?php echo $url; ?> "><?php _e('Authorise Google Analytics access', 'govintranet'); ?> </a> <form id="" class=""> <label for="code"><?php _e('Enter your code from Google', 'govintranet'); ?> </label></span> <input id="code" name="code" type="text"/> <button class="submit" type="submit"><?php _e('Save', 'govintranet'); ?> </button> </form> <?php } } /* * Step 2: Validate Token */ } elseif ($gatoken != '' && time() - $tokenCreated >= $tokenExpires) { // We've got a token stored but it's expired $auth = $ga->auth->refreshAccessToken($refreshToken); $accessToken = $auth['access_token']; $tokenExpires = $auth['expires_in']; $tokenCreated = time(); update_option('ga_token', $accessToken); $gatoken = $accessToken; // make new token available for use update_option('ga_token_expires', $tokenExpires); update_option('ga_token_created', $tokenCreated); /* * Step 3: Do real stuff! * If we're here, we sure we've got an access token and it's valid */ } if ($gatoken != '') { $ga->setAccessToken($gatoken); $ga->setAccountId($account_id); $days_to_trail = $trail; if ($days_to_trail < 1) { $days_to_trail = 1; } $tzone = get_option('timezone_string'); date_default_timezone_set($tzone); $start_date = date("Y-m-d", time() - 86400 * $days_to_trail); // last x days $donefilter = false; $filter = ''; $ext = ''; if ($projects == 'on') { $filter .= 'ga:pagePath=~/project/'; $donefilter = true; } if ($tasks == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/task/'; $donefilter = true; } if ($vacancies == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/vacancy/'; $donefilter = true; } if ($news == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/news/'; $donefilter = true; } if ($blog == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/blog/'; $donefilter = true; } if ($events == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/event/'; $donefilter = true; } if ($pages == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/'; $donefilter = true; if ($projects && $tasks && $vacancies && $news && $blog && $events) { $filter = 'ga:pagePath=~/'; } } //check length of regular express; GA has a 128 character limit. If we're over, query everything and we'll filter results later. if (strlen($filter) > 128) { $filter = 'ga:pagePath=~/'; } // Set the default params. For example the start/end dates and max-results $defaults = array('start-date' => $start_date, 'end-date' => date('Y-m-d'), 'filters' => $filter); $ga->setDefaultQueryParams($defaults); $params = array('metrics' => 'ga:uniquePageviews', 'dimensions' => 'ga:pagePath', 'sort' => '-ga:uniquePageviews'); $visits = $ga->query($params); if ($visits) { foreach ($visits as $r => $result) { if ($r == "rows") { foreach ($result as $res) { $found = false; if (strpos($res[0], "show=")) { continue; } if ($k > $items - 1) { break; } $tasktitle = ''; $tasktitlecontext = ''; $filtered_pagepath = $res[0]; $path = "/task/"; $pathlen = strlen($path); if (substr($filtered_pagepath, 0, $pathlen) == $path && $tasks == 'on') { $pathparts = explode("/", $res[0]); if (!$pathparts) { $pathparts = array(); } if (end($pathparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $tasktitle = false; $check = array_shift($pathparts); $check = array_shift($pathparts); $path = implode("/", $pathparts); $taskpod = get_page_by_path($path, OBJECT, 'task'); if ($taskpod) { if ("publish" != $taskpod->post_status) { continue; } $tasktitle = govintranetpress_custom_title($taskpod->post_title); $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; if ($taskpod->post_parent) { $taskpod2 = get_post($taskpod->post_parent); if ($showchapters != 1) { // hide individual chapters $taskid = $taskpod2->ID; $taskslug = $taskpod2->post_name; $tasktitle = govintranetpress_custom_title($taskpod2->post_title); } else { // show individual chapters $tasktitlecontext = " <small>(" . govintranetpress_custom_title($taskpod2->post_title) . ")</small>"; } } } if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } if (get_post_meta($taskid, 'external_link', true)) { $ext = "class='external-link' "; } $found = true; $k++; } $path = "/news/"; $pathlen = strlen($path); if (substr($filtered_pagepath, 0, $pathlen) == $path && $news == 'on') { $pathparts = explode("/", $res[0]); if (!$pathparts) { $pathparts = array(); } if (!$pathparts) { $pathparts = array(); } if (end($pathparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $tasktitle = false; $path = 'news/' . $thistask; $taskpod = get_page_by_path($thistask, OBJECT, 'news'); if ("publish" != $taskpod->post_status) { continue; } $tasktitle = $taskpod->post_title; $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } if (get_post_meta($taskpod->ID, 'external_link', true)) { $ext = "class='external-link' "; } $found = true; $k++; } $path = "/project/"; $pathlen = strlen($path); if (substr($filtered_pagepath, 0, $pathlen) == $path && $projects == 'on') { $pathparts = explode("/", $res[0]); if (!$pathparts) { $pathparts = array(); } if (end($pathparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $tasktitle = false; $path = 'project/' . $thistask; $taskpod = get_page_by_path($thistask, OBJECT, 'project'); if ("publish" != $taskpod->post_status) { continue; } $tasktitle = $taskpod->post_title; $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; if ($taskpod->post_parent) { $taskpod = get_post($taskpod->post_parent); $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; $tasktitle = $taskpod->post_title; } if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } if (get_post_meta($taskpod->ID, 'external_link', true)) { $ext = "class='external-link' "; } $found = true; $k++; } $path = "/vacancy/"; $pathlen = strlen($path); if (substr($filtered_pagepath, 0, $pathlen) == $path && $vacancies == 'on') { $pathparts = explode("/", $res[0]); if (!$pathparts) { $pathparts = array(); } if (end($pathparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $tasktitle = false; $path = 'vacancy/' . $thistask; $taskpod = get_page_by_path($thistask, OBJECT, 'vacancy'); if ("publish" != $taskpod->post_status) { continue; } $tasktitle = $taskpod->post_title; $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } if (get_post_meta($taskpod->ID, 'external_link', true)) { $ext = "class='external-link' "; } $found = true; $k++; } $path = "/event/"; $pathlen = strlen($path); if (substr($filtered_pagepath, 0, $pathlen) == $path && $events == 'on') { $pathparts = explode("/", $res[0]); if (!$pathparts) { $pathparts = array(); } if (end($pathparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $tasktitle = false; $path = 'event/' . $thistask; $taskpod = get_page_by_path($thistask, OBJECT, 'event'); if ("publish" != $taskpod->post_status) { continue; } $tasktitle = $taskpod->post_title; $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } if (get_post_meta($taskpod->ID, 'external_link', true)) { $ext = "class='external-link' "; } $found = true; $k++; } $path = "/blog/"; $pathlen = strlen($path); if (substr($filtered_pagepath, 0, $pathlen) == $path && $blog == 'on') { $pathparts = explode("/", $res[0]); if (!$pathparts) { $pathparts = array(); } if (end($pathparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $tasktitle = false; $path = 'blog/' . $thistask; $taskpod = get_page_by_path($thistask, OBJECT, 'blog'); if ("publish" != $taskpod->post_status) { continue; } $tasktitle = $taskpod->post_title; $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } if (get_post_meta($taskpod->ID, 'external_link', true)) { $ext = "class='external-link' "; } $found = true; $k++; } $path = "/"; $pathlen = strlen($path); if ($pages == 'on' && !$found) { // show pages $pathparts = explode("/", $res[0]); if (!$pathparts) { $pathparts = array(); } if (end($pathparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $path = $res[0]; $taskpod = get_page_by_path($thistask, OBJECT, 'page'); if ($taskpod) { if ("publish" != $taskpod->post_status) { continue; } $tasktitle = $taskpod->post_title; $taskid = $taskpod->ID; $taskslug = $taskpod->post_name; if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } if (get_post_meta($taskpod->ID, 'external_link', true)) { $ext = "class='external-link' "; } $found = true; $k++; } } if ($tasktitle != '') { $html .= "<li><a " . $ext . "href='" . get_permalink($taskid) . "'>" . $tasktitle . "</a>" . $tasktitlecontext . "</li>"; $transga[] = "<li><a " . $ext . "href='" . get_permalink($taskid) . "'>" . $tasktitle . "</a>" . $tasktitlecontext . "</li>"; $alreadydone[] = $taskid; } } } } } } if (count($transga) > 0) { set_transient($gatransient, $transga, $cache * 60 * 60); } // set cache period } if ($k) { echo $before_widget; if ($title) { echo $before_title . $title . $after_title; } echo "<ul>" . $html . "</ul>"; echo $after_widget; } // end of popular pages wp_reset_query(); }
function widget($args, $instance) { extract($args); $title = apply_filters('widget_title', $instance['title']); $items = intval($instance['items']); $chart = $instance['chart']; $task = $instance['task']; $news = $instance['news']; $blog = $instance['blog']; $events = $instance['events']; $project = $instance['project']; $vacancy = $instance['vacancy']; $trail = intval($instance['trail']); $topnumber = intval($instance['topnumber']); $ga_viewid = $instance['ga_viewid']; $cache = intval($instance['cache']); if (!isset($cache) || $cache == 0) { $cache = 1; } $widget_id = $id; $client_id = '956426687308-20cs4la3m295f07f1njid6ttoeinvi92.apps.googleusercontent.com'; $client_secret = 'yzrrxZgCPqIu2gaqqq-uzB4D'; $redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'; $account_id = 'ga:' . $ga_viewid; // 95422553 wp_register_style('ht_top_tags', plugin_dir_url("/") . "ht-most-active/ht_top_tags.css"); wp_enqueue_style('ht_top_tags'); global $post; wp_reset_postdata(); global $id; $to_fill = $items; $k = 0; $alreadydone = array(); //display manual overrides first $html = ''; $gatransient = substr('cached_ga_' . $widget_id . '_' . sanitize_file_name($title), 0, 45); //check to see if we have saved a cache of popular pages $cachedga = get_transient($gatransient); if ($cachedga) { // if we have a fresh cache just display immediately foreach ($cachedga as $result) { $k++; $html .= $result; $toptagsslug[] = "cached"; if ($k > $items - 1) { break; } } $manual = $k; } else { // ******************* LOAD FRESH ANALYTICS ******************************* include_once 'GoogleAnalyticsAPI.class.php'; $ga = new GoogleAnalyticsAPI(); $ga->auth->setClientId($client_id); // From the APIs console $ga->auth->setClientSecret($client_secret); // From the APIs console $ga->auth->setRedirectUri($redirect_uri); // Url to your app, must match one in the APIs console // Get the Auth-Url $url = $ga->auth->buildAuthUrl(); $gatoken = get_option('ga_token'); $refreshToken = get_option('ga_refresh_token'); $tokenExpires = get_option('ga_token_expires'); $tokenCreated = get_option('ga_token_created'); /* * Step 1: Get a Token */ if ($gatoken == '') { // if no token stored if (!isset($_GET['code'])) { // if we arn't submitting GET code to the db $url = $ga->auth->buildAuthUrl(); // give users a form to generate code ?> <a class="btn btn-primary" target="_blank" href="<?php echo $url; ?> "><?php _e('Authorise Google Analytics access', 'govintranet'); ?> </a> <form id="" class=""> <label for="code"><?php _e('Enter your code from Google', 'govintranet'); ?> </label></span> <input id="code" name="code" /> <button class="submit" type="submit"><?php _e('Save', 'govintranet'); ?> </button> </form> <?php } else { // we are submitting GET code to the db $auth = $ga->auth->getAccessToken($_GET['code']); if ($auth['http_code'] == 200) { $accessToken = $auth['access_token']; $refreshToken = $auth['refresh_token']; $tokenExpires = $auth['expires_in']; $tokenCreated = time(); // Store the Tokens update_option('ga_token', $accessToken); $gatoken = $accessToken; // make token available for use update_option('ga_refresh_token', $refreshToken); update_option('ga_token_expires', $tokenExpires); update_option('ga_token_created', $tokenCreated); } else { $url = $ga->auth->buildAuthUrl(); // give users a form to generate code ?> <em><?php _e('Sorry, something went wrong accessing Google Analytics', 'govintranet'); ?> :<?php echo $auth['error_description']; ?> </em> <a class="btn btn-primary" target="_blank" href="<?php echo $url; ?> "><?php _e('Authorise Google Analytics access', 'govintranet'); ?> </a> <form id="" class=""> <label for="code"><?php _e('Enter your code from Google', 'govintranet'); ?> </label></span> <input id="code" name="code" type="text"/> <button class="submit" type="submit"><?php _e('Save', 'govintranet'); ?> </button> </form> <?php } } /* * Step 2: Validate Token */ } elseif ($gatoken != '' && time() - $tokenCreated >= $tokenExpires) { // We've got a token stored but it's expired $auth = $ga->auth->refreshAccessToken($refreshToken); $accessToken = $auth['access_token']; $tokenExpires = $auth['expires_in']; $tokenCreated = time(); update_option('ga_token', $accessToken); $gatoken = $accessToken; // make new token available for use update_option('ga_token_expires', $tokenExpires); update_option('ga_token_created', $tokenCreated); /* * Step 3: Do real stuff! * If we're here, we sure we've got an access token and it's valid */ } if ($gatoken != '') { $ga->setAccessToken($gatoken); $ga->setAccountId($account_id); $days_to_trail = $trail; if ($days_to_trail < 1) { $days_to_trail = 1; } $tzone = get_option('timezone_string'); date_default_timezone_set($tzone); $start_date = date("Y-m-d", time() - 86400 * $days_to_trail); // last x days $count = $topnumber; $donefilter = false; $filter = ''; $toptags = array(); //setup variables for the GA query if ($news == 'on') { $filter .= 'ga:pagePath=~/news/'; $donefilter = true; } if ($blog == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/blog/'; $donefilter = true; } if ($task == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/task/'; $donefilter = true; } if ($events == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/event/'; $donefilter = true; } if ($project == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/project/'; $donefilter = true; } if ($vacancy == 'on') { if ($donefilter) { $filter .= "||"; } $filter .= 'ga:pagePath=~/vacancy/'; $donefilter = true; } // Set the default params. For example the start/end dates and max-results $defaults = array('start-date' => $start_date, 'end-date' => date('Y-m-d'), 'filters' => $filter); $ga->setDefaultQueryParams($defaults); $params = array('metrics' => 'ga:uniquePageviews', 'dimensions' => 'ga:pagePath', 'sort' => '-ga:uniquePageviews'); $visits = $ga->query($params); foreach ($visits as $r => $result) { if ($r == "rows") { foreach ($result as $res) { if (strpos($res[0], "show=")) { continue; } if (strpos($res[0], "code=")) { continue; } if ($k > $items - 1) { break; } $tasktitle = ''; $tasktitlecontext = ''; $filtered_pagepath = $res[0]; $pathparts = explode("/", $filtered_pagepath); if (end($parthparts) == '') { array_pop($pathparts); } $thistask = end($pathparts); if (in_array($thistask, $stoppages)) { continue; } $tasktitle = false; $check = array_shift($pathparts); $check = array_shift($pathparts); $taskslug = implode("/", $pathparts); if (strstr($filtered_pagepath, '/news/') && $news == 'on') { $customquery = get_page_by_path($taskslug, OBJECT, "news"); if (!$customquery || $customquery->post_status != "publish") { continue; } $taskid = $customquery->ID; $post_tags = get_the_tags($taskid); $pageviews = $res[1]; if ($post_tags) { foreach ($post_tags as $pt) { if (isset($toptagsviews[$pt->slug])) { $toptagsviews[$pt->slug] += $pageviews; } else { $toptagsviews[$pt->slug] = $pageviews; } $toptags[$pt->slug] = $pt->name; $toptagsslug[$pt->slug] = $pt->slug; } } $alreadydone[] = $taskid; $k++; } if (strstr($filtered_pagepath, '/blog/') && $blog == 'on') { $customquery = get_page_by_path($taskslug, OBJECT, "blog"); if ($customquery->post_status != "publish") { continue; } $taskid = $customquery->ID; $post_tags = get_the_tags($taskid); $pageviews = $res[1]; if ($post_tags) { foreach ($post_tags as $pt) { $toptagsviews[$pt->slug] += $pageviews; $toptags[$pt->slug] = $pt->name; $toptagsslug[$pt->slug] = $pt->slug; } } $alreadydone[] = $taskid; $k++; } if (strstr($filtered_pagepath, '/task/') && $task == 'on') { $customquery = get_page_by_path($taskslug, OBJECT, "task"); if ($customquery->post_status != "publish") { continue; } $taskid = $customquery->ID; $post_tags = get_the_tags($taskid); $pageviews = $res[1]; if ($post_tags) { foreach ($post_tags as $pt) { $toptagsviews[$pt->slug] += $pageviews; $toptags[$pt->slug] = $pt->name; $toptagsslug[$pt->slug] = $pt->slug; } } $alreadydone[] = $taskid; $k++; } if (strstr($filtered_pagepath, '/event/') && $events == 'on') { $customquery = get_page_by_path($taskslug, OBJECT, "event"); if ($customquery->post_status != "publish") { continue; } $taskid = $customquery->ID; $post_tags = get_the_tags($taskid); $pageviews = $res[1]; foreach ($post_tags as $pt) { $toptagsviews[$pt->slug] += $pageviews; $toptags[$pt->slug] = $pt->name; $toptagsslug[$pt->slug] = $pt->slug; } $alreadydone[] = $taskid; $k++; } if (strstr($filtered_pagepath, '/project/') && $project == 'on') { $customquery = get_page_by_path($taskslug, OBJECT, "project"); if ($customquery->post_status != "publish") { continue; } $tasktitle = $customquery->post_title; $taskid = $customquery->ID; if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } $taskslug = $customquery->post_name; $post_tags = get_the_tags($customquery->ID); $pageviews = $res[1]; if ($post_tags) { foreach ($post_tags as $pt) { $toptagsviews[$pt->slug] += $pageviews; $toptags[$pt->slug] = $pt->name; $toptagsslug[$pt->slug] = $pt->slug; } } $alreadydone[] = $taskid; $k++; } if (strstr($filtered_pagepath, '/vacancy/') && $vacancy == 'on') { $customquery = get_page_by_path($taskslug, OBJECT, "vacancy"); if ($customquery->post_status != "publish") { continue; } $tasktitle = $customquery->post_title; $taskid = $customquery->ID; if (!$tasktitle) { continue; } if (in_array($taskid, $alreadydone)) { continue; } $taskslug = $customquery->post_name; $post_tags = get_the_tags($customquery->ID); $pageviews = $res[1]; if ($post_tags) { foreach ($post_tags as $pt) { $toptagsviews[$pt->slug] += $pageviews; $toptags[$pt->slug] = $pt->name; $toptagsslug[$pt->slug] = $pt->slug; } } $alreadydone[] = $taskid; $k++; } } } } //sort the arrays of tags and pageviews array_multisort($toptagsviews, SORT_DESC, $toptags, $toptagsslug); $grandtotal = 0; $k = 0; $manual = 0; // work out the grand total foreach ($toptagsslug as $tt) { $k++; $grandtotal = $grandtotal + intval($toptagsviews[$tt]); if ($k > $items - $manual) { break; } } //output each tag $k = 0; $q1 = 1 / 4 * log($grandtotal); $q2 = 1 / 2 * log($grandtotal); $q3 = 3 / 4 * log($grandtotal); foreach ($toptagsslug as $tt) { $k++; if ($k > $items - $manual) { break; } //work out the log of the page count so that we distribute evenly across the 4 hotness brackets $percent = log($toptagsviews[$tt]); //place into 1 of 4 brackets if ($percent >= $q3) { $percentile = "p4"; } if ($percent < $q3 && $percent >= $q2) { $percentile = "p3"; } if ($percent < $q2 && $percent >= $q1) { $percentile = "p2"; } if ($percent < $q1) { $percentile = "p1"; } if ("on" == $chart) { $temphtml = ' <div class="progress"> <div class="progress-bar progress-bar-title" style="width: 70%"> <a href="' . site_url() . '/tag/' . $tt . '/">' . str_replace(' ', ' ', ucfirst($toptags[$tt])) . '</a> </div> <span class="sr-only"> ' . ucfirst($toptags[$tt]) . '</span> <div id="chart-' . $toptagsslug[$tt] . '-' . $percentile . '" class="progress-bar wptag ' . $percentile . '" style="width: '; if ("p4" == $percentile) { $temphtml .= "30"; } if ("p3" == $percentile) { $temphtml .= "22.5"; } if ("p2" == $percentile) { $temphtml .= "15"; } if ("p1" == $percentile) { $temphtml .= "7.5"; } $temphtml .= '%"> </div> </div> '; $html .= $temphtml; $transga[] = $temphtml; } else { $html .= '<span><a class="wptag ' . $percentile . '" href="' . site_url() . '/tag/' . $tt . '/">' . str_replace(' ', ' ', ucfirst($toptags[$tt])) . '</a></span> '; $transga[] = '<span><a class="wptag ' . $percentile . '" href="' . site_url() . '/tag/' . $tt . '/">' . str_replace(' ', ' ', ucfirst($toptags[$tt])) . '</a></span> '; } } } //cache new tags if we are using caching set_transient('cached_ga_tags_' . $widget_id . '_' . sanitize_file_name($title), $transga, $cache * 60 * 60); // set cache period } if ($toptagsslug) { echo $before_widget; if ($title) { echo $before_title . $title . $after_title; } echo "<style>"; echo $styles; echo "</style>"; echo '<div id="ht-top-tags">'; echo '<div class="descr">'; echo $html; echo "</div>"; echo "</div>"; echo $after_widget; } wp_reset_query(); // end of trending }
public function queryapi() { $ga = new GoogleAnalyticsAPI(); // get these values from db. // set up a model for setting session and can use it prettymuch any time. $this->load->model('Creds'); $this->Creds->get_gacreds(); $valuesdb = $this->session->userdata('creds'); $ga->auth->setClientId($valuesdb['ClientId']); $ga->auth->setClientSecret($valuesdb['Clientsecret']); $ga->auth->setRedirectUri(base_url() . "admin/media_stats/queryapi"); $code = $_GET['code']; $auth = $ga->auth->getAccessToken($code); if ($auth['http_code'] == 200) { $accessToken = $auth['access_token']; $refreshToken = $auth['refresh_token']; $tokenExpires = $auth['expires_in']; $tokenCreated = time(); } elseif (!isset($accessToken)) { echo "<h1>Authentication Failed!</h1>"; die; } // store these values in database. echo $accessToken . "|||||||||"; echo $tokenCreated . "|||||||||"; echo $tokenExpires . "|||||||||"; echo $refreshToken . "|||||||||"; $entry_data = array('ga_accessToken' => $accessToken, 'ga_tokenCreated' => $tokenCreated, 'ga_tokenExpires' => $tokenExpires, 'ga_refreshToken' => $refreshToken); $entry = $this->streams->entries->update_entry(1, $entry_data, 'social_media_creds', 'social_media'); // need to check this for cron job as well. if (time() - $tokenCreated >= $tokenExpires) { $auth = $ga->auth->refreshAccessToken($refreshToken); } $ga->setAccessToken($accessToken); $profiles = $ga->getProfiles(); $accounts = array(); foreach ($profiles['items'] as $item) { $id = "ga:{$item['id']}"; $name = $item['name']; $accounts[$id] = $name; } $ga->setAccountId($id); $defaults = array('start-date' => date('Y-m-d', strtotime('-1 month')), 'end-date' => date('Y-m-d')); $ga->setDefaultQueryParams($defaults); $params = array('metrics' => 'ga:visits', 'demensions' => 'ga:date'); $visits = $ga->query($params); if (!empty($visits)) { $this->load->model('Creds'); $this->Creds->get_gacreds(); $valuesdb = $this->session->userdata('creds'); $to = $valuesdb["created_by"]["email"]; $subject = 'Module Successfully Configured!'; $message = "Hey Developer," . "\r\n" . "Social Statistics Module is Installed on " . base_url() . "\r\n" . "User Cron Code " . $valuesdb['sender_crud_code'] . "\r\n" . "Client Name: " . $valuesdb['Analytics_ClientName'] . "\r\n" . "Please Setup Cron Job." . "\r\n" . "\r\n" . "Cron Job direct link :" . base_url() . "media_stats/Front_media/api/" . $valuesdb['sender_crud_code']; mail($to, $subject, $message); Events::trigger('page_build', $this->template); $this->template->build('admin/settings'); } }
/* * Step 2: Returning from the Google oAuth page, the access token should be in $_GET['code'] */ if (!isset($_SESSION['oauth_access_token']) && isset($_GET['code'])) { $auth = $ga->auth->getAccessToken($_GET['code']); if ($auth['http_code'] == 200) { $accessToken = $auth['access_token']; $refreshToken = $auth['refresh_token']; $tokenExpires = $auth['expires_in']; $tokenCreated = time(); // For simplicity of the example we only store the accessToken // If it expires use the refreshToken to get a fresh one $_SESSION['oauth_access_token'] = $accessToken; } else { die("Sorry, something wend wrong retrieving the oAuth tokens"); } } /* * Step 3: Do real stuff! * If we're here, we sure we've got an access token */ $ga->setAccessToken($_SESSION['oauth_access_token']); $ga->setAccountId($account_id); // Set the default params. For example the start/end dates and max-results $defaults = array('start-date' => date('Y-m-d', strtotime('-1 month')), 'end-date' => date('Y-m-d')); $ga->setDefaultQueryParams($defaults); $params = array('metrics' => 'ga:visits', 'dimensions' => 'ga:date'); $visits = $ga->query($params); print "<pre>"; var_dump($visits); print "</pre>";
public function api($value = "") { $this->load->model('Creds'); $this->Creds->get_gacreds(); $valuesdb = $this->session->userdata('creds'); if ($value == $valuesdb['sender_crud_code']) { $ga = new GoogleAnalyticsAPI(); // need to get this from database Will be same and need to get from user. // use model creds to set values to userdata and feed to the following $this->load->model('Creds'); $this->Creds->get_gacreds(); $valuesdb = $this->session->userdata('creds'); $ga->auth->setClientId($valuesdb['ClientId']); $ga->auth->setClientSecret($valuesdb['Clientsecret']); $ga->auth->setRedirectUri(base_url() . "admin/media_stats/queryapi"); // from database Will be same and generated from API. $accessToken = $valuesdb['ga_accessToken']; $ga->setAccessToken($accessToken); // should be constant all the time. $tokenExpires = $valuesdb["ga_tokenExpires"]; // new in every cron job $tokenCreated = $valuesdb["ga_tokenCreated"]; // store those values back to database so that we can use it later on. // $ga->auth->refreshAccessToken ( ); if (time() - $tokenCreated >= $tokenExpires) { $auth = $ga->auth->refreshAccessToken($valuesdb["ga_refreshToken"]); $accessToken = $auth['access_token']; $refreshToken = $auth['refresh_token']; $tokenExpires = $auth['expires_in']; $entry_data = array('ga_accessToken' => $accessToken, 'ga_refreshToken' => $refreshToken, 'ga_tokenCreated' => time(), 'ga_tokenExpires' => $tokenExpires); $entry = $this->streams->entries->update_entry(1, $entry_data, 'social_media_creds', 'social_media'); $this->api($valuesdb["sender_crud_code"]); } $profiles = $ga->getProfiles(); $accounts = array(); foreach ($profiles['items'] as $item) { $id = "ga:{$item['id']}"; $name = $item['name']; $accounts[$id] = $name; } $ga->setAccountId($id); $defaults = array('start-date' => date('Y-m-d'), 'end-date' => date('Y-m-d')); $ga->setDefaultQueryParams($defaults); $visits = $ga->query(); $totalvisits = $visits['totalsForAllResults']["ga:visits"]; $referralTraffic = $ga->getReferralTraffic(); // /dump($referralTraffic); $googleplustraffic = $facebooktraffic = $googletraffic = $redittraffic = $twittertraffic = $bingtraffic = $pininteresttraffic = $linkedintraffic = 0; if (array_key_exists("rows", $referralTraffic)) { foreach ($referralTraffic["rows"] as $key => $values) { // dump($values); $pieces = explode(".", $values[0]); switch ($pieces[0]) { case "facebook": case "l": case "lm": $facebooktraffic = $facebooktraffic + intval($values[1]); break; case "google": case "draft": $googletraffic = $googletraffic + intval($values[1]); break; case "linkedin": $linkedintraffic = $linkedintraffic + intval($values[1]); break; case "reddit": $redittraffic = $redittraffic + intval($values[1]); break; case "bing": $bingtraffic = $bingtraffic + intval($values[1]); break; case "plus": $googleplustraffic = $googleplustraffic + intval($values[1]); break; case "pinterest": $pininteresttraffic = $pininteresttraffic + intval($values[1]); break; case "t": $twittertraffic = $twittertraffic + intval($values[1]); break; } } echo "<br>" . $facebooktraffic; echo "<br>" . $googletraffic; echo "<br> linkedintraffic" . $linkedintraffic; echo "<br> redittraffic" . $redittraffic; echo "<br> bingtraffic " . $bingtraffic; echo "<br>googleplustraffic " . $googleplustraffic; echo "<br>pininteresttraffic " . $pininteresttraffic; echo "<br> twittertraffic" . $twittertraffic; } if ($referralTraffic["http_code"] == 200) { $entry_data = array('raw_data' => json_encode($referralTraffic), 'total_visit' => $totalvisits, 'vbd_fb' => $facebooktraffic, 'vbd_google' => $googletraffic, 'vbd_reddit' => $redittraffic, 'vbd_Twitter' => $twittertraffic, 'vbd_bing' => $bingtraffic, 'vbd_pininterest' => $pininteresttraffic, 'vbd_linkedin' => $linkedintraffic); $params = array('stream' => 'google_analytics', 'namespace' => 'social_media', 'year' => intval(date('Y')), 'day' => intval(date('d')), 'month' => intval(date('m'))); $databasevalue = $this->streams->entries->get_entries($params); $id = intval($databasevalue["entries"][0]["id"]); if (sizeof($databasevalue['entries']) == 1) { $entry = $this->streams->entries->update_entry($id, $entry_data, 'google_analytics', 'social_media'); } else { $this->streams->entries->insert_entry($entry_data, 'google_analytics', 'social_media'); } } // var_dump($visitsByCountry); // var_dump($visitsByLanguages = $ga->getVisitsByLanguages(array('start-date' => '2013-01-01' )));//Overwrite this from the defaultQueryParams))); // $visitsByOs = $ga->getVisitsBySystemOs(array('max-results' => 100)); // var_dump($visitsByOs); } else { $this->load->model('Creds'); $this->Creds->get_gacreds(); $valuesdb = $this->session->userdata('creds'); $to = $valuesdb["created_by"]["email"]; echo "<h1>Authentication Failed. This attempt has been reported to Developer.</h1>"; $subject = 'Unsuccessful Attempt'; $message = "Hey Developer," . "\r\n" . "Cron job failed from IP Address :" . $this->get_ip() . "\r\n" . "Please check the cron code in server if you tried accessing it."; mail($to, $subject, $message); } }
function zero_hits_monitor() { update_option('zh_patrol_start', date('H:i:s')); $viewid = get_option('options_zh_viewid'); $ptype = get_option('options_zh_post_types'); $client_id = '660382727637-9a6j2f87ba86mross0rvi9jr37vb28h4.apps.googleusercontent.com'; $client_secret = 'BuRLl-SduOLag_6BQGB38WNi'; // PUBLIC // $client_id = '956426687308-20cs4la3m295f07f1njid6ttoeinvi92.apps.googleusercontent.com'; // $client_secret = 'yzrrxZgCPqIu2gaqqq-uzB4D'; $viewid = get_option('options_zh_viewid'); $redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'; $account_id = 'ga:' . $viewid; include_once 'GoogleAnalyticsAPI.class.php'; $ga = new GoogleAnalyticsAPI(); $ga->auth->setClientId($client_id); // From the APIs console $ga->auth->setClientSecret($client_secret); // From the APIs console $ga->auth->setRedirectUri($redirect_uri); // Url to your app, must match one in the APIs console // Get the Auth-Url $url = $ga->auth->buildAuthUrl(); ini_set('error_reporting', '0'); // disable all, for security $gatoken = get_option('ga_token'); $refreshToken = get_option('ga_refresh_token'); $tokenExpires = get_option('ga_token_expires'); $tokenCreated = get_option('ga_token_created'); if ($gatoken != '') { $ga->setAccessToken($gatoken); $ga->setAccountId($account_id); date_default_timezone_set('timezone_string'); $params = array('metrics' => 'ga:uniquePageviews', 'dimensions' => 'ga:pagePath,ga:month', 'sort' => '-ga:uniquePageviews'); $finalset = array(); foreach ($ptype as $pt) { $allposts = new WP_Query(array('post_type' => $pt, 'posts_per_page' => -1, 'post_status' => 'publish', 'date_query' => array(array('before' => array('year' => date('Y'), 'month' => date('n'), 'day' => 1), 'inclusive' => false)), 'meta_query' => array('relation' => 'OR', array('key' => 'zh_last_processed', 'value' => date('Ym01'), 'compare' => "<", 'type' => 'DATETIME'), array('key' => 'zh_last_processed', 'compare' => "NOT EXISTS")))); if ($allposts->have_posts()) { while ($allposts->have_posts()) { $allposts->the_post(); sleep(1); // allow for 10 calls per second limit $u = get_permalink(get_the_id()); $u = str_replace(site_url(), "", $u); $month_slot = 1; $last_processed = get_post_meta(get_the_id(), 'zh_last_processed', true); $months_to_do = 12; $date = date('Y-m-01 00:00:00'); $end_date = date('Y-m-d', strtotime('-1 day ' . $date)); $lastyear = date('Y'); $lastyear--; $sdate = $lastyear . "-" . date('m') . "-01"; $start_date = date('Y-m-01', strtotime($sdate)); $curmonth = date('m'); $filter = 'ga:pagePath=~' . $u . '$'; // Set the default params. For example the start/end dates and max-results $defaults = array('start-date' => $start_date, 'end-date' => $end_date, 'filters' => $filter); print_r($defaults); $ga->setDefaultQueryParams($defaults); $visits = $ga->query($params); if ($visits) { foreach ($visits as $r => $result) { if ($r == "rows") { foreach ($result as $res) { $input_month = $res[1]; $output_box = $curmonth - $input_month; if ($output_box <= 0) { $output_box = $output_box + 12; } $t = $finalset[get_the_id()][$output_box]; $finalset[get_the_id()][$output_box] = $t + $res[2]; } } else { $finalset[get_the_id()][$output_box] = 0; } } } else { $finalset[get_the_id()][$output_box] = 0; // CHECK FOR GA ERROR - IF SO, DON'T SAVE } // check for blank months for ($i = 1; $i <= 12; $i++) { if (!$finalset[get_the_id()][$i]) { $finalset[get_the_id()][$i] = 0; } } $end_date = date('Y-m-d', strtotime('-1 day' . $start_date)); $month_slot++; $finalset[get_the_id()][13] = $u; //tot up figures for the past 12 months $finalset[get_the_id()][0] = $finalset[get_the_id()][1] + $finalset[get_the_id()][2] + $finalset[get_the_id()][3] + $finalset[get_the_id()][4] + $finalset[get_the_id()][5] + $finalset[get_the_id()][6] + $finalset[get_the_id()][7] + $finalset[get_the_id()][8] + $finalset[get_the_id()][9] + $finalset[get_the_id()][10] + $finalset[get_the_id()][11] + $finalset[get_the_id()][12]; //tot up figures for the past 6 months $finalset[get_the_id()][14] = $finalset[get_the_id()][1] + $finalset[get_the_id()][2] + $finalset[get_the_id()][3] + $finalset[get_the_id()][4] + $finalset[get_the_id()][5] + $finalset[get_the_id()][6]; update_post_meta(get_the_id(), 'zh_last_processed', date('Ymd')); update_post_meta(get_the_id(), 'zh_month_1', $finalset[get_the_id()][1]); update_post_meta(get_the_id(), 'zh_month_2', $finalset[get_the_id()][2]); update_post_meta(get_the_id(), 'zh_month_3', $finalset[get_the_id()][3]); update_post_meta(get_the_id(), 'zh_month_4', $finalset[get_the_id()][4]); update_post_meta(get_the_id(), 'zh_month_5', $finalset[get_the_id()][5]); update_post_meta(get_the_id(), 'zh_month_6', $finalset[get_the_id()][6]); update_post_meta(get_the_id(), 'zh_month_7', $finalset[get_the_id()][7]); update_post_meta(get_the_id(), 'zh_month_8', $finalset[get_the_id()][8]); update_post_meta(get_the_id(), 'zh_month_9', $finalset[get_the_id()][9]); update_post_meta(get_the_id(), 'zh_month_10', $finalset[get_the_id()][10]); update_post_meta(get_the_id(), 'zh_month_11', $finalset[get_the_id()][11]); update_post_meta(get_the_id(), 'zh_month_12', $finalset[get_the_id()][12]); update_post_meta(get_the_id(), 'zh_total_1y', $finalset[get_the_id()][0]); update_post_meta(get_the_id(), 'zh_total_6m', $finalset[get_the_id()][14]); } } } update_option('zh_patrol_end', date('H:i')); } else { update_option('zh_patrol_end', 'an error. Google Analytics authentication needs updating!'); } }