#!/usr/bin/perl -w
# wp_spam.pl
# Disables comment notification emails and ability to comment for unregistered users on a WordPress blog.
#
# Michael Karr
#
# Please send all errors/bugs to mkarr@hostgator.com

# 20110620 - original version - mkarr
# 20110622 - added remote database and mu support - mkarr
# 20110624 - added usage info - mkarr
# 20110707 - mu main options table detection fixed - mkarr
# 20110714 - recursive and specific config file options added - mkarr
# 20110817 - added disable of moderation messages - mkarr
# 20110817_2 - clean up code - mkarr

my $version = "20110817_2";

use strict;
use warnings;

use Cwd;
use FileHandle;
use File::stat;
use File::Find;
use Getopt::Long;
use DBI;

sub frexvalue;
sub disable;
sub disablenotificationmails;
sub disableunregcomments;
sub tableexist;
sub usage;

# begin maincode

print "wp_spam.pl - Version: $version - Michael Karr\n\n"; 

my $prefix = "wp_";
my $mu = "base";
my $help = 0;
my $recurs = 0;
my $wpconfig;

GetOptions ('prefix|p=s' => \$prefix,
            'mu|m=s' => \$mu,
            'help|h|usage|u' => \$help,
            'recursive|r' => \$recurs,
            'config|c=s' => \$wpconfig);

if ($help) {
    usage();
} elsif (exists $ARGV[0]) { # make sure we were given something to work with
    print "Wordpress database given.\n\n";
    
    my $db = $ARGV[0];
    my $server = "localhost";
    my $pass;

    if ($pass = frexvalue("/root/.my.cnf", 'pass\s*?=\s*?[\'"]([^\"\']*)[\'"]')) {
        print "Cpanel detected.\n";
        my $user = "root";

	disable($db, $server, $user, $pass, $prefix, $mu);
    } elsif ($pass = frexvalue("/etc/psa/.psa.shadow", '^(.*?)$')) {
        print "Plesk detected.\n";
        my $user = "admin";

	disable($db, $server, $user, $pass, $prefix, $mu);
    } else {
        print "No MySQL password detected.\n";
    }
} elsif ($recurs) {
    find({
	no_chdir => 1,
	wanted => sub {
	    if (/^.*?\/wp-config\.php\z/s) {
		print("Wordpress configuration found at: $File::Find::name\n");
		disablewpconfig($File::Find::name);
		print "\n";
	    }
	}
    }, '.');
} elsif ($wpconfig) {
    if (stat($wpconfig)) {
        print "WordPress configuration file given.\n\n";
        disablewpconfig($wpconfig);
    } else {
        print "File \"$wpconfig\" not found.\n";
    }
} elsif (stat(my $file = cwd() . "/wp-config.php")) {
    print "WordPress configuration file detected.\n\n";
    disablewpconfig($file);
} else {
    print "No WordPress installation detected in CWD or given.\n";
}

print "\nDone.\n";
exit 0;

# end maincode

sub frexvalue {
    my ($file, $rex) = @_;
    my $value = undef;

    my $fh = new FileHandle;

    if ($fh->open("<$file")) {
        while(my $line = <$fh>) {
            if ($line =~ /$rex/) {
                $value = $1;
                last    
            }       
        }
    
        $fh->close();
    }

    return $value;
}

sub disable {
    my ($db, $server, $user, $pass, $prefix) = @_;

    print "Server: $server\n";
    print "Database: $db\n";
    print "Prefix: $prefix\n";
    print "User: $user\n";
    # print "Password: $pass\n";
    print "\n";
    
    if (my $dbh = DBI->connect("dbi:mysql:database=$db;host=$server", $user, $pass, {PrintError => 0})) {
        print "MySQL connection opened successfully.\n";
	
	my @options_tables;
        
        if (tableexist($dbh, $prefix."blogs")) {
            print "Wordpress MU detected.\n\n";

            if (($mu eq "base") || ($mu eq "all")) { # add main tables
                if (tableexist($dbh, $prefix."options")) {
                    push (@options_tables, $prefix."options");
                }    
                if (tableexist($dbh, $prefix."1_options")) {
                    push (@options_tables, $prefix."1_options");
                }
		
		if ($mu eq "all") { # add all sub-blog tables
		    my $sth = $dbh->prepare("SELECT blog_id FROM ".$prefix."blogs WHERE blog_id>1;");
		    $sth->execute();
		    
		    while (my @result = $sth->fetchrow_array()) { 
			push (@options_tables, $prefix.$result[0]."_options");
		    }
		}
            } else { # add specific sub-blog table
		push (@options_tables, $prefix.$mu ."_options");
            }
        } else {
            print "Plain Wordpress detected.\n\n";
            
            push (@options_tables, $prefix."options");
        }
	
	for my $table (@options_tables) {
	    print "Processing table '$table'\n";
	    disabl_email_options($dbh, $table);
	}
	
        $dbh->disconnect();
    } else {
        print "MySQL connection failed: $DBI::errstr\n\n";
    }
}

sub set_option {
    my ($dbh, $table, $option, $value) = @_;
    
    my $sth = $dbh->prepare("UPDATE ".$table." SET option_value=? WHERE option_name=?");
    
    if ($sth->execute($value, $option)) {
        return "Success.\n";
    } else {
        return "Fail: $DBI::errstr\n";
    }
}

sub disabl_email_options {
    my ($dbh, $table) = @_;
    
    print "Disabling comment notification emails. ";
    print set_option($dbh, $table, 'comments_notify', '');
    
    print "Disabling comments for unregistered users. ";
    print set_option($dbh, $table, 'comment_registration', '1');
    
    print "Disabling moderation messages. ";
    print set_option($dbh, $table, 'moderation_notify', '');
}

sub tableexist {
    my ($dbh, $table) = @_;    
    my $exists = 0;
    
    my $sth = $dbh->prepare("SHOW TABLES LIKE '$table';");

    if ($sth->execute()) {
        if ($sth->rows > 0) {
            $exists = 1;
        }
        
        $sth->finish;
    } else {
        print "Fail: $DBI::errstr\n\n";
    }
    
    return $exists;
}

sub usage {
    print "wp_spam.pl\n".
          "----------\n".
          "Disables comment notification emails and ability to comment for unregistered\n".
          "users on a WordPress blog.\n\n".
          "Usage:\n\n".
          "Run from within the a base WordPress directory. Script will automatically pull\n".
          "relevant info from the wp-config.php file:\n\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl\n\n".
          "Run against a database:\n\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - <database>\n\n".
          "Run against a database with a custom table prefix:\n\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -p <prefix> <database>\n\n".
          "Run against a specific config file: \n\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -c <file> \n\n".
          "Run against all wordpress installations found within a certain directory (recursively): \n\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -r\n\n".
          "Examples:\n\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - blah_wrdp1\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - wp2_ blah_wrdp1\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -c wp-config.php\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -r\n\n".
          "Usage with MU:\n\n".
          "By default, if wp_spam detects a MU installation, it will only perform changes\n".
          "against the base/main blog. This can be changed with the -m option. This will\n".
          "take the values all, base, or the number of the blog you want to make changes\n".
          "against.\n\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -m all\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -m base\n". 
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -m 15\n".
          "    GET scripts.hostgator.com/~sec/wp_spam | perl - -m 3054\n";
}

sub disablewpconfig {
    my ($file) = @_;
    
    my $server =  frexvalue($file, 'define\s*?\(\s*?["\']DB_HOST["\']\s*?,\s*?["\']([^"\']*)["\']\s*?\);'); 
    my $db = frexvalue($file, 'define\s*?\(\s*?["\']DB_NAME["\']\s*?,\s*?["\']([^"\']*)["\']\s*?\);');
    my $user = frexvalue($file, 'define\s*?\(\s*?["\']DB_USER["\']\s*?,\s*?["\']([^"\']*)["\']\s*?\);');
    my $pass = frexvalue($file, 'define\s*?\(\s*?["\']DB_PASSWORD["\']\s*?,\s*?["\']([^"\']*)["\']\s*?\);');
    my $prefix =  frexvalue($file, '\$table_prefix  = ["\']([^"\']*)["\'];');
    
    disable($db, $server, $user, $pass, $prefix);
}