#!/usr/bin/env perl
# $Id: wp_comment_count.pl,v 1.3 2007/02/02 10:11:16 jaidev Exp jaidev $
# Copyright (c) 2006, Jaidev Krishna S
# Released under the GPL license
# http://www.gnu.org/copyleft/gpl.html

# Update following four lines from your wordpress config. Values can be found in your_blog_dir/wp-config.php
my $wp_db = 'WP_DATABASE';
my $wp_db_user = 'WP_DB_USER';
my $wp_db_pass = 'WP_DB_PASS';
my $wp_table_prefix = 'WP_TABLE_PREFIX';

my $posts = "$wp_table_prefix"."posts";
my $comments = "$wp_table_prefix"."comments";
use DBI;

my $dsn = "DBI:mysql:$wp_db:localhost";

my $dbh = DBI->connect ($dsn, $wp_db_user, $wp_db_pass);

my $sth = $dbh->prepare (qq{
	select ID, comment_count from $posts 
		where comment_count != (select count(*) from $comments where comment_post_ID=ID)
	});
$sth->execute ();
my $fix = 0;
while (my ($id, $count) = $sth->fetchrow_array()) 
{
	my $sth2 = $dbh->prepare (qq {
		select count(*) from $comments where comment_post_ID="$id"
	});
	$sth2->execute ();
	@expected = $sth2->fetchrow_array();
	if ($fix == 0) {
		printf ("Database inconsistent.\n    Post    Count Expected    Fixed\n");
	}
	printf ("%8d %8d %8d", $id, $count, $expected[0]);
	if ($ARGV != 1 && $ARGV[0] eq "fix") {
		$dbh->do ("update $posts set comment_count=$expected[0] where ID=$id");
		printf ("        Y");
		$fix = 1;
	}
	else {
		printf ("        N");
		$fix = 2;
	}
	printf ("\n");
	$sth2->finish ();
}
if ($fix == 2) {
	printf ("To fix database, run script with the argument 'fix'. i.e., 'wp_comment_count.pl fix'.\n");
}
if ($fix == 0) {
	printf ("Database is consistent.\n");
}
$sth->finish ();
$dbh->disconnect();



