install();
$akpc->upgrade();
$akpc->mine_gap_data();
}
// -- MAIN FUNCTIONALITY
class ak_popularity_contest {
var $feed_value;
var $home_value;
var $archive_value;
var $category_value;
var $single_value;
var $comment_value;
var $pingback_value;
var $trackback_value;
var $searcher_names;
var $logged;
var $options;
var $top_ranked;
var $current_posts;
var $show_pop;
var $show_help;
var $ignore_authors;
var $show_rank_in_widget;
var $report_types;
function ak_popularity_contest() {
$this->options = array(
'feed_value'
,'home_value'
,'archive_value'
,'category_value'
,'tag_value'
,'single_value'
,'searcher_value'
,'comment_value'
,'pingback_value'
,'trackback_value'
,'searcher_names'
,'show_pop'
,'show_help'
,'ignore_authors'
,'show_rank_in_widget'
);
$this->feed_value = 1;
$this->home_value = 2;
$this->archive_value = 4;
$this->category_value = 6;
$this->tag_value = 6;
$this->single_value = 10;
$this->searcher_value = 2;
$this->comment_value = 20;
$this->pingback_value = 50;
$this->trackback_value = 80;
$this->searcher_names = 'google.com yahoo.com bing.com';
$this->logged = 0;
$this->show_pop = 1;
$this->show_help = 1;
$this->ignore_authors = 1;
$this->show_rank_in_widget = 0;
$this->top_ranked = array();
$this->current_posts = array();
}
function get_settings() {
global $wpdb;
if (AKPC_CONFIG_FILE == 1) { // use hard coded settings
global $akpc_settings;
foreach($akpc_settings as $key => $value) {
if (in_array($key, $this->options)) {
$this->$key = $value;
}
}
}
else { // pull settings from db
// This checks to see if the tables are in the DB for this blog
$settings = $this->query_settings();
// If the DB tables are not in place, lets check to see if we can install
if (!count($settings)) {
// This checks to see if we need to install, then checks if we can install
// For the can install to work in MU the AKPC_MU_AUTOINSTALL variable must be set to 1
if (!$this->check_install() && $this->can_autoinstall()) {
$this->install();
}
if (!$this->check_install()) {
$error = __('
Popularity Contest Installation Failed
Sorry, Popularity Contest was not successfully installed. Please try again, or try one of the following options for support:
If you are having trouble and need to disable Popularity Contest immediately, simply delete the popularity-contest.php file from within your wp-content/plugins directory.
', 'popularity-contest');
wp_die($error);
}
else {
$settings = $this->query_settings();
}
}
if (count($settings)) {
foreach ($settings as $setting) {
if (in_array($setting->option_name, $this->options)) {
$this->{$setting->option_name} = $setting->option_value;
}
}
}
}
return true;
}
function query_settings() {
global $wpdb;
return @$wpdb->get_results("
SELECT *
FROM $wpdb->ak_popularity_options
");
}
/**
* check_install - This function checks to see if the proper tables have been added to the DB for the blog the plugin is being activated for
*
* @return void
*/
function check_install() {
global $wpdb;
$result = mysql_query("SHOW TABLES LIKE '{$wpdb->prefix}ak_popularity%'", $wpdb->dbh);
return mysql_num_rows($result) == 2;
}
/**
* can_autoinstall - This function checks to see whether the tables can be installed
*
* @return void - Checks to see if the blog is MU, if not returns true
* - Checks to see if the blog is MU, if it is also checks to see if the function can install and returns true if it can
* - (For the second condition to work: ie. if the plugin is installed in MU: AKPC_MU_AUTOINSTALL must be set to 1)
*/
function can_autoinstall() {
global $wpmu_version;
return (is_null($wpmu_version) || (!is_null($wpmu_version) && AKPC_MU_AUTOINSTALL == 1));
}
/**
* install - This function installs the proper tables in the DB for handling popularity contest items
*
* @return void - Returns whether the table creation was successful
*/
function install() {
global $wpdb;
if ($this->check_install()) {
return;
}
akpc_wpdb_init();
$result = mysql_query("
CREATE TABLE `$wpdb->ak_popularity_options` (
`option_name` VARCHAR( 50 ) NOT NULL,
`option_value` VARCHAR( 255 ) NOT NULL
)
", $wpdb->dbh) or die(mysql_error().' on line: '.__LINE__);
if (!$result) {
return false;
}
$this->default_values();
$result = mysql_query("
CREATE TABLE `$wpdb->ak_popularity` (
`post_id` INT( 11 ) NOT NULL ,
`total` INT( 11 ) NOT NULL ,
`feed_views` INT( 11 ) NOT NULL ,
`home_views` INT( 11 ) NOT NULL ,
`archive_views` INT( 11 ) NOT NULL ,
`category_views` INT( 11 ) NOT NULL ,
`tag_views` INT( 11 ) NOT NULL ,
`single_views` INT( 11 ) NOT NULL ,
`searcher_views` INT( 11 ) NOT NULL ,
`comments` INT( 11 ) NOT NULL ,
`pingbacks` INT( 11 ) NOT NULL ,
`trackbacks` INT( 11 ) NOT NULL ,
`last_modified` DATETIME NOT NULL ,
KEY `post_id` ( `post_id` )
)
", $wpdb->dbh) or die(mysql_error().' on line: '.__LINE__);
if (!$result) {
return false;
}
$this->mine_data();
return true;
}
function upgrade() {
akpc_wpdb_init();
$this->upgrade_20();
}
function upgrade_20() {
global $wpdb;
$wpdb->query("
ALTER TABLE `$wpdb->ak_popularity_options`
CHANGE `option_value` `option_value` VARCHAR( 255 ) NULL
");
$cols = $wpdb->get_col("
SHOW COLUMNS FROM $wpdb->ak_popularity
");
//2.0 Schema
if (!in_array('tag_views', $cols)) {
$wpdb->query("
ALTER TABLE `$wpdb->ak_popularity`
ADD `tag_views` INT( 11 ) NOT NULL
AFTER `category_views`
");
}
if (!in_array('searcher_views', $cols)) {
$wpdb->query("
ALTER TABLE `$wpdb->ak_popularity`
ADD `searcher_views` INT( 11 ) NOT NULL
AFTER `single_views`
");
}
$temp = new ak_popularity_contest;
$cols = $wpdb->get_col("
SELECT `option_name`
FROM `$wpdb->ak_popularity_options`
");
if (!in_array('searcher_names', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'searcher_names',
'$temp->searcher_names'
)
");
}
if (!in_array('show_pop', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'show_pop',
'$temp->show_pop'
)
");
}
if (!in_array('show_help', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'show_help',
'$temp->show_help'
)
");
}
if (!in_array('ignore_authors', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'ignore_authors',
'$temp->ignore_authors'
)
");
}
if (!in_array('show_rank_in_widget', $cols)) {
$wpdb->query("
INSERT
INTO `$wpdb->ak_popularity_options` (
`option_name`,
`option_value`
)
VALUES (
'show_rank_in_widget',
'$temp->show_rank_in_widget'
)
");
}
}
function default_values() {
global $wpdb;
foreach ($this->options as $option) {
$result = $wpdb->query("
INSERT
INTO $wpdb->ak_popularity_options
VALUES (
'$option',
'{$this->$option}'
)
");
if (!$result) {
return false;
}
}
return true;
}
function update_settings() {
if (!current_user_can('manage_options')) { wp_die('Unauthorized.'); }
global $wpdb;
$this->upgrade();
foreach ($this->options as $option) {
if (isset($_POST[$option])) {
$option != 'searcher_names' ? $this->$option = intval($_POST[$option]) : $this->$option = stripslashes($_POST[$option]);
$wpdb->query("
UPDATE $wpdb->ak_popularity_options
SET option_value = '{$this->$option}'
WHERE option_name = '".$wpdb->escape($option)."'
");
}
}
$this->recalculate_popularity();
$this->mine_gap_data();
header('Location: '.get_bloginfo('wpurl').'/wp-admin/options-general.php?page='.basename(__FILE__).'&updated=true');
die();
}
function recalculate_popularity() {
global $wpdb;
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET total = (home_views * $this->home_value)
+ (feed_views * $this->feed_value)
+ (archive_views * $this->archive_value)
+ (category_views * $this->category_value)
+ (tag_views * $this->tag_value)
+ (single_views * $this->single_value)
+ (searcher_views * $this->searcher_value)
+ (comments * $this->comment_value)
+ (pingbacks * $this->pingback_value)
+ (trackbacks * $this->trackback_value)
");
}
function reset_data() {
global $wpdb;
$result = $wpdb->query("
TRUNCATE $wpdb->ak_popularity
");
if (!$result) {
return false;
}
$result = $wpdb->query("
TRUNCATE $wpdb->ak_popularity_options
");
if (!$result) {
return false;
}
$this->default_values();
return true;
}
function create_post_record($post_id = -1) {
global $wpdb;
if ($post_id == -1) {
global $post_id;
}
$post_id = intval($post_id);
$count = $wpdb->get_var("
SELECT COUNT(post_id)
FROM $wpdb->ak_popularity
WHERE post_id = '$post_id'
");
if (!intval($count)) {
$result = $wpdb->query("
INSERT
INTO $wpdb->ak_popularity (
`post_id`,
`last_modified`
)
VALUES (
'$post_id',
'".date('Y-m-d H:i:s')."'
)
");
}
}
function delete_post_record($post_id = -1) {
global $wpdb;
if ($post_id == -1) {
global $post_id;
}
$result = $wpdb->query("
DELETE
FROM $wpdb->ak_popularity
WHERE post_id = '$post_id'
");
}
function mine_data() {
global $wpdb;
$posts = $wpdb->get_results("
SELECT ID
FROM $wpdb->posts
WHERE post_status = 'publish'
");
if ($posts && count($posts) > 0) {
foreach ($posts as $post) {
$this->create_post_record($post->ID);
$this->populate_post_data($post->ID);
}
}
return true;
}
function mine_gap_data() {
global $wpdb;
$posts = $wpdb->get_results("
SELECT p.ID
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE pop.post_id IS NULL
AND (
p.post_type = 'post'
OR p.post_type = 'page'
)
AND p.post_status = 'publish'
");
if ($posts && count($posts) > 0) {
foreach ($posts as $post) {
$this->create_post_record($post->ID);
$this->populate_post_data($post->ID);
}
}
}
function populate_post_data($post_id) {
global $wpdb;
// grab existing comments
$count = intval($wpdb->get_var("
SELECT COUNT(*)
FROM $wpdb->comments
WHERE comment_post_ID = '$post_id'
AND comment_type = ''
AND comment_approved = '1'
"));
if ($count > 0) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET comments = comments + $count
, total = total + ".($this->comment_value * $count)."
WHERE post_id = '$post_id'
");
if (!$result) {
return false;
}
}
// grab existing trackbacks
$count = intval($wpdb->get_var("
SELECT COUNT(*)
FROM $wpdb->comments
WHERE comment_post_ID = '$post_id'
AND comment_type = 'trackback'
AND comment_approved = '1'
"));
if ($count > 0) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET trackbacks = trackbacks + $count
, total = total + ".($this->trackback_value * $count)."
WHERE post_id = '$post_id'
");
if (!$result) {
return false;
}
}
// grab existing pingbacks
$count = intval($wpdb->get_var("
SELECT COUNT(*)
FROM $wpdb->comments
WHERE comment_post_ID = '$post_id'
AND comment_type = 'pingback'
AND comment_approved = '1'
"));
if ($count > 0) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET pingbacks = pingbacks + $count
, total = total + ".($this->pingback_value * $count)."
WHERE post_id = '$post_id'
");
if (!$result) {
return false;
}
}
}
function record_view($api = false, $ids = false, $type = false) {
if ($this->logged > 0 || ($this->ignore_authors && current_user_can('publish_posts'))) {
return true;
}
global $wpdb;
if ($api == false) {
global $posts;
if (!isset($posts) || !is_array($posts) || count($posts) == 0 || is_admin()) {
return;
}
$ids = array();
$ak_posts = $posts;
foreach ($ak_posts as $post) {
$ids[] = $post->ID;
}
}
if (!$ids || !count($ids)) {
return;
}
if (($api && $type == 'feed') || is_feed()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET feed_views = feed_views + 1
, total = total + $this->feed_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && $type == 'archive') || (is_archive() && !is_category())) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET archive_views = archive_views + 1
, total = total + $this->archive_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && $type == 'category') || is_category()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET category_views = category_views + 1
, total = total + $this->category_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && $type == 'tag') || is_tag()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET tag_views = tag_views + 1
, total = total + $this->tag_views
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
else if (($api && in_array($type, array('single', 'page'))) || is_single() || is_singular() || is_page()) {
if (($api && $type == 'searcher') || akpc_is_searcher()) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET searcher_views = searcher_views + 1
, total = total + $this->searcher_value
WHERE post_id = '".$ids[0]."'
");
if (!$result) {
return false;
}
}
else {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET single_views = single_views + 1
, total = total + $this->single_value
WHERE post_id = '".$ids[0]."'
");
if (!$result) {
return false;
}
}
}
else {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET home_views = home_views + 1
, total = total + $this->home_value
WHERE post_id IN (".implode(',', $ids).")
");
if (!$result) {
return false;
}
}
$this->logged++;
return true;
}
function record_feedback($type, $action = '+', $comment_id = null) {
global $wpdb, $comment_post_ID;
if ($comment_id) {
$comment_post_ID = $comment_id;
}
switch ($type) {
case 'trackback':
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET trackbacks = trackbacks $action 1
, total = total $action $this->trackback_value
WHERE post_id = '$comment_post_ID'
");
if (!$result) {
return false;
}
break;
case 'pingback':
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET pingbacks = pingbacks $action 1
, total = total $action $this->pingback_value
WHERE post_id = '$comment_post_ID'
");
if (!$result) {
return false;
}
break;
default:
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET comments = comments $action 1
, total = total $action $this->comment_value
WHERE post_id = '$comment_post_ID'
");
if (!$result) {
return false;
}
break;
}
return true;
}
function edit_feedback($comment_id, $action, $status = null) {
$comment = get_comment($comment_id);
switch ($action) {
case 'delete':
$this->record_feedback($comment->comment_type, '-', $comment_id);
break;
case 'status':
if ($status == 'spam') {
$this->record_feedback($comment->comment_type, '-', $comment_id);
return;
}
break;
}
}
function recount_feedback() {
global $wpdb;
$post_ids = $wpdb->get_results("
SELECT ID
FROM $wpdb->posts
WHERE post_status = 'publish'
OR post_status = 'static'
");
if (count($post_ids)) {
$result = $wpdb->query("
UPDATE $wpdb->ak_popularity
SET comments = 0
, trackbacks = 0
, pingbacks = 0
");
foreach ($post_ids as $post_id) {
$this->populate_post_data($post_id);
}
}
$this->recalculate_popularity();
header('Location: '.get_bloginfo('wpurl').'/wp-admin/options-general.php?page='.basename(__FILE__).'&updated=true');
die();
}
function options_form() {
if (!AKPC_CONFIG_FILE) { // don't show options update functions if we're running from a config file
$temp = new ak_popularity_contest;
print('
'.__('Put this tag within The Loop to show the popularity of the post being shown. The popularity is shown as a percentage of your most popular post. For example, if the popularity total for Post #1 is 500 and your popular post has a total of 1000, this tag will show a value of 50%.', 'popularity-contest').'
Example:
<?php if (function_exists(\'akpc_the_popularity\')) { akpc_the_popularity(); } ?>
'.__('Put this tag outside of The Loop (perhaps in your sidebar?) to show a list (like the archives/categories/links list) of your most popular posts. All arguments are optional, the defaults are included in the example above.', 'popularity-contest').'
Examples:
<?php if (function_exists(\'akpc_most_popular\')) { akpc_most_popular(); } ?>
<?php if (function_exists(\'akpc_most_popular\')) { ?>
<li><h2>Most Popular Posts</h2>
<ul>
<?php akpc_most_popular(); ?>
</ul>
</li>
<?php } ?>
'.__('Put this tag outside of The Loop (perhaps in your sidebar?) to show a list of the most popular posts in a specific category. You may want to use this on category archive pages. All arguments are', 'popularity-contest').'
Examples:
<?php if (function_exists(\'akpc_most_popular_in_cat\')) { akpc_most_popular_in_cat(); } ?>
<php if (is_category() && function_exists(\'akpc_most_popular_in_cat\')) { akpc_most_popular_in_cat(); } ?>
<?php if (is_category() && function_exists(\'akpc_most_popular_in_cat\')) { ?>
<li><h2>Most Popular in \'<?php single_cat_title(); ?>\'</h2>
<ul>
<?php akpc_most_popular_in_cat(); ?>
</ul>
</li>
<?php } ?>
'.__('Put this tag outside of The Loop (perhaps in your sidebar?) to show a list of the most popular posts in a specific month. You may want to use this on monthly archive pages.', 'popularity-contest').'
Examples:
<?php if (function_exists(\'akpc_most_popular_in_month\')) { akpc_most_popular_in_month(); } ?>
'.__('Put this tag outside of The Loop (perhaps in your sidebar?) to show a list of the most popular posts in the last (your chosen number, default = 45) days.', 'popularity-contest').'
Examples:
<?php if (function_exists(\'akpc_most_popular_in_last_days\')) { akpc_most_popular_in_last_days(); } ?>
<?php if (function_exists(\'akpc_most_popular_in_last_days\')) { ?>
<li><h2>Recent Popular Posts</h2>
<ul>
<?php akpc_most_popular_in_last_days(); ?>
</ul>
</li>
<?php } ?>
');
}
function get_popular_posts($type = 'popular', $limit = 50, $exclude_pages = 'yes', $custom = array()) {
global $wpdb;
$items = array();
switch($type) {
case 'category':
$temp = "
SELECT p.ID AS ID, p.post_title AS post_title, pop.total AS total
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
LEFT JOIN $wpdb->term_relationships tr
ON p.ID = tr.object_id
LEFT JOIN $wpdb->term_taxonomy tt
ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tt.term_id = ".$custom['cat_ID']."
AND p.post_status = 'publish'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
ORDER BY pop.total DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'tag':
$temp = "
SELECT p.ID AS ID, p.post_title AS post_title, pop.total AS total
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
LEFT JOIN $wpdb->term_relationships tr
ON p.ID = tr.object_id
LEFT JOIN $wpdb->term_taxonomy tt
ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tt.term_id = ".$custom['term_id']."
AND p.post_status = 'publish'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
ORDER BY pop.total DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'category_popularity':
$temp = "
SELECT DISTINCT name, AVG(pop.total) AS avg
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
LEFT JOIN $wpdb->term_relationships tr
ON p.ID = tr.object_id
LEFT JOIN $wpdb->term_taxonomy tt
ON tr.term_taxonomy_id = tt.term_taxonomy_id
LEFT JOIN $wpdb->terms t
ON tt.term_id = t.term_id
WHERE tt.taxonomy = 'category'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
GROUP BY name
ORDER BY avg DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'tag_popularity':
$temp = "
SELECT DISTINCT name, AVG(pop.total) AS avg
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
LEFT JOIN $wpdb->term_relationships tr
ON p.ID = tr.object_id
LEFT JOIN $wpdb->term_taxonomy tt
ON tr.term_taxonomy_id = tt.term_taxonomy_id
LEFT JOIN $wpdb->terms t
ON tt.term_id = t.term_id
WHERE tt.taxonomy = 'post_tag'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
GROUP BY name
ORDER BY avg DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'year':
$temp = "
SELECT MONTH(p.post_date) AS month, AVG(pop.total) AS avg
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE YEAR(p.post_date) = '".$custom['y']."'
AND p.post_status = 'publish'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
GROUP BY month
ORDER BY avg DESC
";
$items = $wpdb->get_results($temp);
break;
case 'views_wo_feedback':
$temp = "
SELECT p.ID AS ID, p.post_title AS post_title, pop.total AS total
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE pop.comments = 0
AND pop.pingbacks = 0
AND pop.trackbacks = 0
AND p.post_status = 'publish'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
ORDER BY pop.total DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'most_feedback':
// in progress, should probably be combination of comment, pingback & trackback scores
$temp = "
SELECT p.ID, p.post_title, p.comment_count
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop ON p.ID = pop.post_id
WHERE p.post_status = 'publish'
AND p.comment_count > 0";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp = "
ORDER BY p.comment_count DESC
LIMIT $limit;
";
$items = $wpdb->get_results($temp);
break;
case 'date':
$temp = "
SELECT p.ID AS ID, p.post_title AS post_title, pop.total AS total
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE DATE_ADD(p.post_date, INTERVAL ".intval($custom['days'])." DAY) {$custom['compare']} DATE_ADD(NOW(), INTERVAL ".intval($custom['offset'])." DAY)
AND p.post_status = 'publish'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
ORDER BY pop.total DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'most':
$temp = "
SELECT p.ID AS ID, p.post_title AS post_title, pop.{$custom['column']} AS {$custom['column']}
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE p.post_status = 'publish'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
ORDER BY pop.{$custom['column']} DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'popular':
$temp = "
SELECT p.ID AS ID, p.post_title AS post_title, pop.{$custom['column']} AS {$custom['column']}
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE p.post_status = 'publish'
";
if ($exclude_pages == 'yes') { $temp .= " AND p.post_type != 'page' "; }
$temp .= "
ORDER BY pop.{$custom['column']} DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
case 'popular_pages':
$temp = "
SELECT p.ID AS ID, p.post_title AS post_title, pop.single_views AS single_views
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE p.post_status = 'publish'
AND p.post_type = 'page'
ORDER BY pop.single_views DESC
LIMIT $limit
";
$items = $wpdb->get_results($temp);
break;
}
do_action('akpc_get_popular_posts',$items);
if (count($items)) {
return $items;
}
return false;
}
/**
* Show a popularity report
* @var string $type - type of report to show
* @var int $limit - num posts to show
* @var array $custom - pre-defined list of posts to show
* @var bool $hide_title - wether to echo the list title
*/
function show_report($type = 'popular', $limit = 10, $exclude_pages = 'yes', $custom = array(), $before_title = '
';
echo apply_filters('akpc_show_report', $html, $items);
}
}
/**
* create a list of popular items for a report
* @var array $items
* @return string - HTML
*/
function report_list_items($items, $before = '
get_results("
SELECT p.*, pop.*
FROM $wpdb->posts p
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
WHERE p.post_status = 'publish'
ORDER BY pop.total DESC
LIMIT ".intval($limit)
);
if ($posts) {
$bgcolor = '';
foreach ($posts as $post) {
$class = ('alternate' == $class) ? '' : 'alternate';
?>
$column_display_name) {
switch($column_name) {
case 'popularity':
?>
');
?>
current_posts['id_'.$post_id])) {
$this->get_current_posts(array($post_id));
}
return $this->current_posts['id_'.$post_id];
}
function get_rank($item, $total = null) {
if (is_null($total)) {
$total = $this->top_rank();
}
return ceil(($item/$total) * 100).'%';
}
function get_post_rank($post_id = null, $total = -1) {
if (count($this->top_ranked) == 0) {
$this->get_top_ranked();
}
if ($total > -1 && !$post_id) {
return ceil(($total/$this->top_rank()) * 100).'%';
}
if (isset($this->top_ranked['id_'.$post_id])) {
$rank = $this->top_ranked['id_'.$post_id];
}
else {
$rank = $this->get_post_total($post_id);
}
$show_help = apply_filters('akpc_show_help', $this->show_help, $post_id);
if ($show_help) {
$suffix = ' [?]';
}
else {
$suffix = '';
}
if (isset($rank) && $rank != false) {
return __('Popularity:', 'popularity-contest').' '.$this->get_rank($rank).$suffix;
}
else {
return __('Popularity:', 'popularity-contest').' '.__('unranked', 'popularity-contest').$suffix;
}
}
function show_post_rank($post_id = -1, $total = -1) {
print($this->get_post_rank($post_id, $total));
}
function top_rank() {
if (count($this->top_ranked) == 0) {
$this->get_top_ranked();
}
foreach ($this->top_ranked as $id => $rank) {
$top = $rank;
break;
}
// handle edge case - div by zero
if (intval($top) == 0) {
$top = 1;
}
return $top;
}
function get_current_posts($post_ids = array()) {
global $wpdb, $wp_query;
$posts = $wp_query->get_posts();
$ids = array();
foreach ($posts as $post) {
$ids[] = $post->ID;
}
$ids = array_unique(array_merge($ids, $post_ids));
if (count($ids)) {
$result = $wpdb->get_results("
SELECT post_id, total
FROM $wpdb->ak_popularity
WHERE post_id IN (".implode(',', $ids).")
");
if (count($result)) {
foreach ($result as $data) {
$this->current_posts['id_'.$data->post_id] = $data->total;
}
}
}
return true;
}
function get_top_ranked() {
global $wpdb;
$result = $wpdb->get_results("
SELECT post_id, total
FROM $wpdb->ak_popularity
ORDER BY total DESC
LIMIT 10
");
if (!count($result)) {
return false;
}
foreach ($result as $data) {
$this->top_ranked['id_'.$data->post_id] = $data->total;
}
return true;
}
function show_top_ranked($limit, $before, $after) {
if ($posts=$this->get_top_ranked_posts($limit)) {
foreach ($posts as $post) {
print(
$before.''
.$post->post_title.''.$after
);
}
}
else {
print($before.'(none)'.$after);
}
}
function get_top_ranked_posts($limit) {
global $wpdb;
$temp = $wpdb;
$join = apply_filters('posts_join', '');
$where = apply_filters('posts_where', '');
$groupby = apply_filters('posts_groupby', '');
if (!empty($groupby)) {
$groupby = ' GROUP BY '.$groupby;
}
else {
$groupby = ' GROUP BY '.$wpdb->posts.'.ID ';
}
$posts = $wpdb->get_results("
SELECT ID, post_title
FROM $wpdb->posts
LEFT JOIN $wpdb->ak_popularity pop
ON $wpdb->posts.ID = pop.post_id
$join
WHERE post_status = 'publish'
AND post_date < NOW()
$where
$groupby
ORDER BY pop.total DESC
LIMIT ".intval($limit)
);
$wpdb = $temp;
return $posts;
}
function show_top_ranked_in_cat($limit, $before, $after, $cat_ID = '') {
if (empty($cat_ID) && is_category()) {
global $cat;
$cat_ID = $cat;
}
if (empty($cat_ID)) {
return;
}
global $wpdb;
$temp = $wpdb;
// $join = apply_filters('posts_join', '');
// $where = apply_filters('posts_where', '');
// $groupby = apply_filters('posts_groupby', '');
if (!empty($groupby)) {
$groupby = ' GROUP BY '.$groupby;
}
else {
$groupby = ' GROUP BY p.ID ';
}
$posts = $wpdb->get_results("
SELECT ID, post_title
FROM $wpdb->posts p
LEFT JOIN $wpdb->term_relationships tr
ON p.ID = tr.object_id
LEFT JOIN $wpdb->term_taxonomy tt
ON tr.term_taxonomy_id = tt.term_taxonomy_id
LEFT JOIN $wpdb->ak_popularity pop
ON p.ID = pop.post_id
$join
WHERE tt.term_id = '".intval($cat_ID)."'
AND tt.taxonomy = 'category'
AND post_status = 'publish'
AND post_type = 'post'
AND post_date < NOW()
$where
$groupby
ORDER BY pop.total DESC
LIMIT ".intval($limit)
);
if ($posts) {
foreach ($posts as $post) {
print(
$before.''
.$post->post_title.''.$after
);
}
}
else {
print($before.'(none)'.$after);
}
$wpdb = $temp;
}
function show_top_ranked_in_month($limit, $before, $after, $m = '') {
if (empty($m) && is_archive()) {
global $m;
}
if (empty($m)) {
global $post;
$m = get_the_time('Ym');
}
if (empty($m)) {
return;
}
$year = substr($m, 0, 4);
$month = substr($m, 4, 2);
global $wpdb;
$temp = $wpdb;
$join = apply_filters('posts_join', '');
$where = apply_filters('posts_where', '');
$groupby = apply_filters('posts_groupby', '');
if (!empty($groupby)) {
$groupby = ' GROUP BY '.$groupby;
}
else {
$groupby = ' GROUP BY '.$wpdb->posts.'.ID ';
}
$posts = $wpdb->get_results("
SELECT ID, post_title
FROM $wpdb->posts
LEFT JOIN $wpdb->ak_popularity pop
ON $wpdb->posts.ID = pop.post_id
$join
WHERE YEAR(post_date) = '$year'
AND MONTH(post_date) = '$month'
AND post_status = 'publish'
AND post_date < NOW()
$where
$groupby
ORDER BY pop.total DESC
LIMIT ".intval($limit)
);
if ($posts) {
foreach ($posts as $post) {
print(
$before.''
.$post->post_title.''.$after
);
}
}
else {
print($before.'(none)'.$after);
}
$wpdb = $temp;
}
function show_top_ranked_in_last_days($limit, $before, $after, $days = 45) {
global $wpdb;
$temp = $wpdb;
$join = apply_filters('posts_join', '');
$where = apply_filters('posts_where', '');
$groupby = apply_filters('posts_groupby', '');
if (!empty($groupby)) { $groupby = ' GROUP BY '.$groupby; }
$offset = 0;
$compare = '>';
$posts = $wpdb->get_results("
SELECT ID, post_title
FROM $wpdb->posts
LEFT JOIN $wpdb->ak_popularity pop
ON $wpdb->posts.ID = pop.post_id
$join
WHERE DATE_ADD($wpdb->posts.post_date, INTERVAL $days DAY) $compare DATE_ADD(NOW(), INTERVAL $offset DAY)
AND post_status = 'publish'
AND post_date < NOW()
$where
$groupby
ORDER BY pop.total DESC
LIMIT ".intval($limit)
);
if ($posts) {
foreach ($posts as $post) {
print(
$before.''
.$post->post_title.''.$after
);
}
}
else {
print($before.'(none)'.$after);
}
$wpdb = $temp;
}
}
function akpc_wpdb_init() {
global $wpdb;
if (!isset($wpdb->ak_popularity) || !isset($wpdb->ak_popularity_options)) {
$wpdb->ak_popularity = $wpdb->prefix.'ak_popularity';
$wpdb->ak_popularity_options = $wpdb->prefix.'ak_popularity_options';
}
}
// -- "HOOKABLE" FUNCTIONS
function akpc_init() {
global $akpc;
akpc_wpdb_init();
$akpc = new ak_popularity_contest;
$akpc->get_settings();
}
function akpc_view($content) {
global $akpc;
$akpc->record_view();
return $content;
}
function akpc_feedback_comment() {
global $akpc;
$akpc->record_feedback('comment');
}
function akpc_comment_status($comment_id, $status = 'approved') {
global $akpc;
$akpc->edit_feedback($comment_id, 'status', $status);
}
function akpc_comment_delete($comment_id) {
global $akpc;
$akpc->edit_feedback($comment_id, 'delete');
}
function akpc_feedback_pingback() {
global $akpc;
$akpc->record_feedback('pingback');
}
function akpc_feedback_trackback() {
global $akpc;
$akpc->record_feedback('trackback');
}
function akpc_publish($post_id) {
global $akpc;
$akpc->create_post_record($post_id);
}
function akpc_post_delete($post_id) {
global $akpc;
$akpc->delete_post_record($post_id);
}
function akpc_options_form() {
global $akpc;
$akpc->options_form();
}
function akpc_view_stats() {
global $akpc;
$akpc->view_stats();
}
function akpc_plugin_action_links($links, $file) {
$plugin_file = basename(__FILE__);
if (basename($file) == $plugin_file) {
$settings_link = ''.__('Settings', 'popularity-contest').'';
array_unshift($links, $settings_link);
$reports_link = ''.__('Reports', 'popularity-contest').'';
array_unshift($links, $reports_link);
}
return $links;
}
add_filter('plugin_action_links', 'akpc_plugin_action_links', 10, 2);
function akpc_options() {
if (function_exists('add_options_page')) {
add_options_page(
__('Popularity Contest Options', 'popularity-contest')
, __('Popularity', 'popularity-contest')
, 10
, basename(__FILE__)
, 'akpc_options_form'
);
}
if (function_exists('add_submenu_page')) {
add_submenu_page(
'index.php'
, __('Most Popular Posts', 'popularity-contest')
, __('Most Popular Posts', 'popularity-contest')
, 0
, basename(__FILE__)
, 'akpc_view_stats'
);
}
}
function akpc_options_css() {
print('');
}
function akpc_widget_js() {
echo '';
}
// -- TEMPLATE FUNCTIONS
function akpc_the_popularity($post_id = null) {
global $akpc;
if (!$post_id) {
global $post;
$post_id = $post->ID;
}
$akpc->show_post_rank($post_id);
}
function akpc_most_popular($limit = 10, $before = '
', $after = '
', $report = false, $echo = true) {
global $akpc;
if(!$report) {
$akpc->show_top_ranked($limit, $before, $after);
}
else {
return $akpc->show_report($report, $limit);
}
}
/**
* Show a single report
* @var string $type - type of report to show
* @var int $limit - number of results to display
* @return mixed echo/array
*/
function akpc_show_report($type = 'popular', $limit = 10, $exclude_pages = 'no', $custom = array(), $before_title = '
', $after_title = '
', $hide_title = false) {
global $akpc;
return $akpc->show_report($type, $limit, $exclude_pages, $custom, $before_title, $after_title, $hide_title);
}
/**
* Get raw post data for a report type
* @var string $type - type of report to show
* @var int $limit - number of posts to display
* @var array $custom - any custom report attributes needed
* @return bool/array - returns false if no posts in report
*/
function akpc_get_popular_posts_array($type, $limit, $custom = array()) {
global $akpc;
return $akpc->get_popular_posts($type, $limit, $custom);
}
function akpc_most_popular_in_cat($limit = 10, $before = '
', $after = '
', $cat_ID = '') {
global $akpc;
$akpc->show_top_ranked_in_cat($limit, $before, $after, $cat_ID);
}
function akpc_most_popular_in_month($limit = 10, $before = '
', $after = '
', $m = '') {
global $akpc;
$akpc->show_top_ranked_in_month($limit, $before, $after, $m);
}
function akpc_most_popular_in_last_days($limit = 10, $before = '
', $after = '
', $days = 45) {
global $akpc;
$akpc->show_top_ranked_in_last_days($limit, $before, $after, $days);
}
function akpc_content_pop($str) {
global $akpc, $post;
if (is_admin()) {
return $str;
}
else if (is_feed()) {
$str .= '';
}
else {
if (AKPC_USE_API) {
$str .= '';
}
$show = apply_filters('akpc_display_popularity', $akpc->show_pop, $post);
if (!get_post_meta($post->ID, 'hide_popularity', true) && $show) {
$str .= '
'.$akpc->get_post_rank($post->ID).'
';
}
}
return $str;
}
function akpc_excerpt_compat_pre($output) {
remove_filter('the_content', 'akpc_content_pop');
return $output;
}
add_filter('get_the_excerpt', 'akpc_excerpt_compat_pre', 1);
function akpc_excerpt_compat_post($output) {
add_filter('the_content', 'akpc_content_pop');
return $output;
}
add_filter('get_the_excerpt', 'akpc_excerpt_compat_post', 999);
// -- WIDGET
/**
* do widget init functionality
*/
function akpc_widget_init() {
if(!function_exists('register_sidebar_widget') || !function_exists('register_widget_control')) { return; }
// get existing widget options
$options = maybe_unserialize(get_option('akpc_widget_options'));
// if no existing widgets, fake one
if(!is_array($options)) { $options[-1] = array('title'=>'','type'=>'','limit'=>''); }
// base set of options for widget type
$base_options = array('classname' => 'akpc-widget', 'description' => __('Show popular posts as ranked by Popularity Contest', 'popularity-contest'));
$widget_name = __('Popularity Contest', 'popularity-contest');
// register widgets & controls for each existing widget
foreach($options as $number => $option) {
$widget_id = 'akpc-widget-'.($number === -1 ? 1 : $number); // not needed, but avoids duplicate dashes for new widgets
wp_register_sidebar_widget($widget_id, $widget_name,'akpc_widget', $base_options, array('number' => $number));
wp_register_widget_control($widget_id, $widget_name,'akpc_widget_control', array('id_base' => 'akpc-widget'), array('number' => $number));
}
}
/**
* Widget display
*/
function akpc_widget($args, $widget_args = 1) {
// find out which widget we're working on
if(is_numeric($widget_args)) {
$widget_args = array('number' => $widget_args);
}
$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
extract($widget_args, EXTR_SKIP);
// get passed args
extract($args);
// get saved options
$options = maybe_unserialize(get_option('akpc_widget_options'));
extract($options[$number]);
$type = (!isset($type) || empty($type)) ? 'popular' : $type;
$days = (!isset($days) || empty($days)) ? '' : intval($days);
$limit = (!isset($limit) || empty($limit)) ? 10 : intval($limit);
$title_string = (!isset($title) || empty($title)) ? '' : $before_title.htmlspecialchars(stripslashes($title)).$after_title;
$exclude_pages = (!isset($exclude_pages) || empty($exclude_pages)) ? 'no' : $exclude_pages;
$custom = array();
// Check to see if we have the custom type of "last_n" and pass the day amount in the custom array
if ($type == 'last_n') {
$custom['days'] = $days;
}
// output
echo $before_widget.$title_string;
akpc_show_report($type, $limit, $exclude_pages, $custom, '
', '
', true);
echo $after_widget;
global $akpc;
if (!$akpc->show_rank_in_widget) {
echo '';
}
}
/**
* Controls for creating and saving multiple PC widgets
*/
function akpc_widget_control($widget_args = 1) {
global $wp_registered_widgets;
static $updated = false; // set this after updating so update only happens once
// get individual widget ID
if(is_numeric($widget_args)) {
$widget_args = array('number' => $widget_args);
}
$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
extract( $widget_args, EXTR_SKIP );
// get existing widget options
$options = maybe_unserialize(get_option('akpc_widget_options'));
/* UPDATE OPTIONS ON PRESENCE OF POST DATA */
if(isset($_POST['akpc']) && isset($_POST['sidebar'])) {
// get current sidebar data
$sidebar = strval($_POST['sidebar']);
$sidebar_widgets = wp_get_sidebars_widgets();
$this_sidebar = isset($sidebar_widgets[$sidebar]) ? $sidebar_widgets[$sidebar] : array();
// check to see if this sidebar item needs to be deleted
// code pulled directly from the Plain Text widget native to wordpress
foreach ($this_sidebar as $_widget_id) {
if ('akpc_widget' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number'])) {
$widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number'];
// if we had a previously registered widget ID but nothing in the post args, the widget was removed, so kill it
if(!in_array("akpc-widget-$widget_number", $_POST['widget-id'])) {
unset($options[$widget_number]);
}
}
}
// save this widget's options
foreach((array) $_POST['akpc'] as $widget_number => $widget_options) {
$options[$widget_number]['title'] = $widget_options['title'];
$options[$widget_number]['type'] = $widget_options['type'];
$options[$widget_number]['days'] = intval($widget_options['days']);
$options[$widget_number]['limit'] = intval($widget_options['limit']);
$options[$widget_number]['exclude_pages'] = $widget_options['exclude_pages'];
}
update_option('akpc_widget_options',serialize($options));
$updated = true;
}
// new widget prep
if($number == -1) {
$options[$number] = array('title'=>'','type'=>'','days'=>'','limit'=>'');
$number = '%i%'; // required for new widgets so WP auto-generates a new ID
}
/* START CONTROLS OUTPUT */
// Widget Title
echo '
'.PHP_EOL;
// Number of days to get data from
$hide_days = '';
if ($options[$number]['type'] != 'last_n' || (!is_int($options[$number]['days']) && $options[$number]['days'] != 0)) {
$hide_days = ' style="display:none;"';
}
echo '
'.PHP_EOL;
// number of posts to display
echo '
'.PHP_EOL;
// exclude pages
echo '
'.PHP_EOL;
// submit hidden field, really necessary? may be needed for legacy compatability
echo '';
}
function akpc_show_error($type, $info = null) {
switch ($type) {
case 'tag_report_not_found':
echo '
'.sprintf(__('Sorry, could not find the requested tag: %s', 'popularity-contest'), htmlspecialchars($info)).'
';
break;
case 'tag_report_already_added':
echo '
'.sprintf(__('Looks like you already have a report for tag: %s', 'popularity-contest'), htmlspecialchars($info)).'