#!/usr/local/cpanel/3rdparty/bin/perl

use strict;
use warnings;
use lib '/usr/local/cpanel';
use Cpanel::DomainLookup;
use DBI;
use Sys::Hostname;
use LWP::Simple;
use LWP::UserAgent;
use HTTP::Request;
use JSON;
use YAML::Tiny;

# These need to be changed
our $debug = 0;
our $esocollector = 'https://eso-collect.hostgator.com/submit';

# Set some initial variables - Everything after this point shouldn't need changing
our $hostname = hostname;
our $mysqlpass = get_mysql_pass();

our %paths = %{ find_scripts() };
our %yamldata;

# Main loop
# This goes through every install path, determines the script version
foreach my $install_path (keys %paths) {
	my $pathhash = $paths{$install_path};

	# All users start with a letter, and have letters, numbers, dashes, and are maximum 16 chars. Also lowercase.
	next unless ( ($pathhash->{'user'} =~ /^[a-z][\-a-z0-9]{1,16}$/) 
			&& ($install_path =~ /^\/home\d?\/[a-z][\-a-z0-9]{1,16}\//) 
			&& (-f "$install_path/wp-includes/version.php") );

	print "Processing $install_path :: " if ($debug);

	my $version = get_wp_version( $install_path );
	next unless ($version);

	$paths{$install_path}->{'version'} = $version;

	my $data = {
		'hostname'   => "$hostname",
		'type'       => "wordpress",
		'user'       => "$pathhash->{'user'}",
		'version' => "$pathhash->{'version'}",
		'path'       => "$pathhash->{'path'}",
		'table'      => "$pathhash->{'options_table'}",
		'domain'     => "$pathhash->{'domain'}",
		'db'         => "$pathhash->{'db'}"
	};

	my $json = encode_json($data);

	my $ua = LWP::UserAgent->new();
	$ua->timeout( 3 );

	my $res = $ua->post($esocollector, { report => 'cscancollector', data => $json } );

	if ($res->{'_rc'} == 200 && $res->{'_msg'} eq 'OK') {
		print "Success: $hostname, $pathhash->{'domain'}, $pathhash->{'user'}, $pathhash->{'version'}\n" if ($debug);
	} else {
		print "Failed: $hostname, $pathhash->{'domain'}, $pathhash->{'user'}, $pathhash->{'version'}\n" if ($debug);
	}

	$yamldata{$pathhash->{'user'}}{$install_path} = $data;
}


foreach my $user (sort keys %yamldata) {
	my (undef, undef, $uid, $gid, undef, undef, undef, $homedir, undef) = getpwnam( $user );

	next unless ( -d "$homedir" );

	my $cs_version_file = $homedir . "/.cpanel/.cs_version_info";
	my $yaml = YAML::Tiny->new();

	foreach my $path (keys %{ $yamldata{$user} }) {
		$yaml->[0]->{$path} = $yamldata{$user}{$path};
	}

	print "Writing $cs_version_file\n" if ($debug);
	$yaml->write( $cs_version_file ) or warn "Could not write to \n";

	chown $uid, $gid, $cs_version_file or warn ( "Couldn't change ownership of $cs_version_file to $user\n" );
	chmod 0644, $cs_version_file or warn ( "Couldn't change permissions of $cs_version_file to 0644\n" );
}

sub get_mysql_pass {
	my $pass;

	open my $FH, '<', '/root/.my.cnf' or die "We can't operate unless we have the MySQL pass.\n";
	while (<$FH>) {
		if ($_ =~ /^password\s?=\s?"(\S+)"$/) {
			$pass = $1;
		} elsif ($_ =~ /^password\s?=\s?"?(\S+)"?$/) {
			$pass = $1;
		}
	}
	close $FH;

	die "Couldn't retrieve MySQL password\n" if (!$pass);
	return $pass;
}

sub find_scripts {
	my @dbs = @{ get_all_dbs() };
	my %path_list;

	for my $user ( get_all_users() ) {
		my $dbuser;
		if (length($user) > 8) {
			$dbuser = substr $user, 0, 8;
		} else {
			$dbuser = $user;
		}

		for my $database ( @dbs ) {
			next unless ($database =~ /^$dbuser\_/);

			my $paths = get_wp_path($database, $user);
			next if (!$paths);
			my %wp_path = %{ $paths };
			# Continue on to the next database if there's no file paths returned
			next if (scalar(keys %wp_path) < 1);

			# Loop through the provided doc roots
			foreach my $path (keys %wp_path) {
				$path =~ s/\/\//\//g;
				$path =~ s/\/$//g;

				# Put the path in the list, unless it already exists.
				$path_list{$path} = ({
					'user'          => $user,
					'path'          => $path, 
					'db'            => $database, 
					'options_table' => get_options_table_name($database),
					'domain'        => $wp_path{$path}
				}) unless (exists $path_list{$path});
			}
		}
	}

	# This returns a complex hash that looks like this:
	# '/home/user/public_html' => {
	#    {
	#        'user'          => 'user',
	#        'path'          => '/home/user/public_html',
	#        'db'            => 'user_db',
	#        'options_table' => 'tablename',
	#        'domain'        => 'domainname.tld'
	#    }
	# }
	#
	# All the keys of this hash should be unique.

	return \%path_list;
}

sub get_wp_path {
	my ($database, $user) = @_;

	delete $INC{'Cpanel/DomainLookup.pm'};
	require Cpanel::DomainLookup;
	Cpanel::DomainLookup->import;

	print "Locating WP on $user -- $database\n" if ($debug);

	my $siteurl = get_siteurl($database);

	# Return empty arrayref if there's no site url (not wordpress)
	return unless ($siteurl);

	# Here we grab the domain and URI, since some installs are in sub-folders.
	my $domain = "";
	my $uri = "";

	if ($siteurl =~ /^https?:\/\/$hostname\/\~$user(\/.*)?/) {
		$domain = primary_domain_from_user( $user );
		$uri = $1 || "";
	} elsif ($siteurl =~ /^https?:\/\/(.+)(\/.*)/ ) {
		$domain = $1;
		$uri = $2 || "";
	} elsif ($siteurl =~ /^https?:\/\/(.+)/ ) {
		$domain = $1;
	} else {
		$domain = $siteurl;
	}

	# Do some cleanup of the $domain - remove newline and www
	chomp($domain);
	$domain =~ s/^www\.//g;

	my %roots = Cpanel::DomainLookup::getdocroots($user);
	my $full_docroot = $roots{"$domain"};

	# We really should have obtained a docroot here. If not, return empty arrayref
	return unless ($full_docroot);

	$full_docroot = $full_docroot . $uri if (length($uri) > 1);

	# Do some cleanup
	chomp($full_docroot);

	# There is an attack one could do - set up a blog using a domain from someone else's
	# account, and it could mess stuff up. Ensure that the path contains the user we are
	# looking at.
	my %docroots;
	if ($full_docroot =~ /\/home\d?\/$user\//) {
		$docroots{$full_docroot} = $domain;

		# Now lets try and find docroots that are in sub-dirs
		# TODO: This is fundamentally flawed and returns extra docroots
		# for paths that have legitimate installations.
		#my @additional_paths = <$full_docroot/*>;

		#foreach my $addtlpath (@additional_paths) {
		#	next unless (-d "$addtlpath");
		#	print "\tSearching additional filepath $addtlpath\n" if ($debug);

		#	next unless (-f "$addtlpath/wp-config.php");
		#	print "\t\tFound additional docroot $addtlpath\n" if ($debug);
		#	$docroots{$addtlpath} = $domain unless (exists $docroots{$addtlpath});
		#}
	}

	return \%docroots;
}


sub get_siteurl {
	my $db_name = shift;

	my $wp_options_table = get_options_table_name($db_name);

	# Return nothing unless there's an options table.
	return unless ($wp_options_table);

	my @data = do_sql_query($db_name, "SELECT option_value FROM $wp_options_table WHERE option_name = 'siteurl'");
	return if (!@data);

	while (@data) {
		chomp( $data[0] );
		$data[0] =~ s/^\s+//;
		return $data[0];
	}
}

sub get_options_table_name {
	my $db_name = shift;

	my @tables = do_sql_query($db_name, "SHOW TABLES LIKE '\%_options'");
	return if (!@tables);

	foreach my $table ( @tables ) {
		if ( $table =~ /^[a-zA-Z0-9_-]*_options$/ ) {
			my @tabledef = do_sql_query($db_name, "SHOW CREATE TABLE " . $table);
			if (join(',', @tabledef) =~ /option_value/) {
				return $tabledef[0];
			}
		}
	}
	return 0;
}

sub do_sql_query {
	my ($db_name, $query) = @_;

	# MySQL hex naming conversion
	$db_name =~ s/\@002d/\-/g;
	$db_name =~ s/\@0020/ /g;
	$db_name =~ s/\@002e/\./g;
	$db_name =~ s/\@0026/\&/g;
	$db_name =~ s/\@002a/\*/g;
	$db_name =~ s/\@0023/#/g;
	$db_name =~ s/\@0024/\$/g;
	$db_name =~ s/\@0028/(/g;
	$db_name =~ s/\@0029/)/g;
	$db_name =~ s/\@0021/!/g;
	$db_name =~ s/\@0040/\@/g;

	my $dsn = "DBI:mysql:$db_name;";
	my $dbh = DBI->connect( $dsn, "root", "$mysqlpass", { RaiseError => 1, PrintError => 0 } ) or return;
	my $sth = $dbh->prepare($query);
	eval { $sth->execute(); };
	return 0 if ($@);

	return $sth->fetchrow_array();
}

sub get_all_dbs {
	my $directory = "/var/lib/mysql/";
	my @dirs      = ();
	opendir( DIR, $directory ) or die $!;
	while ( my $dirent = readdir(DIR) ) {
		if ( $dirent =~ /^(\S+_\S+)/ ) {
			push(@dirs, $1);
		}
	}
	close(DIR);
	return \@dirs;
}

sub get_all_users {
	my @users = ();
	open( my $fh, '/etc/trueuserdomains' );
	while ( my $line = <$fh> ) {
		if ( $line =~ /^\S+?: (\S*)$/ ) {
			next unless (is_user_active($1));
			push( @users, $1 );
		}
	}
	close($fh);
	return sort @users;
}

sub primary_domain_from_user {
	my $user = shift;
	my $domain;

	open(FILE, "<", "/etc/trueuserdomains");
	while(<FILE>) {
		chomp;
		if (/^(\S+): $user$/) {
			$domain = $1;
		}
	}
	close(FILE);

	return if (!$domain);

	return $domain;
}

sub get_all_users_domains {
	my @userdomains;
	open(FILE, "/etc/userdomains");
	while(<FILE>) {
		chomp;
		if ( /^(\S+): (\S+)$/ ) {
			push @userdomains, $_;
		}
	}
	close(FILE);

	return \@userdomains;
}

sub is_user_active {
	my ($user) = @_;
	my $suspended_file = "/var/cpanel/suspended/$user";
	my ( $dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks ) = stat($suspended_file);
	if ( $ctime && $ctime <= time - 3888000 ) {
		return 0;
	}
	return 1;
}

sub get_wp_version {
	my $version_file = shift . "/wp-includes/version.php";
	my $version = 0;

	open my $FH, '<', $version_file or warn ("Could not open file $version_file\n");
	while (<$FH>) {
		chomp;
		$version = $1 if (/^\$wp_version\s+?=\s+?\'(\d\.[\d\.]+)\';$/);

		#return (split( "'", $_ ))[1] if (/^\$wp_version/);
	}
	close $FH;

	if ($version =~ /^\d\./) {
		return $version;
	} else {
		return;
	}
}
