<?php
# eps.php > comment_confirm.php > eps.php 
require "/home/hpr/php/include.php";

$num_get_args = 0;

foreach($_GET as $k => $v) { 
    ++$num_get_args; 
} 

if ( $num_get_args > 0 ){
    # they didn't supply any arguments
    naughty("9e756ee22b7cdcdb150a5baf167caa25 $num_get_args");
}

if ( empty($_POST["anti_spam_question"]) ) {
    naughty("0601a23e358374c293b086bb75606cca");
}

if ( strlen($_POST["anti_spam_question"]) !== 6 ) {
    naughty("6f51e6e7e6820b3fdda5d4ca0df14db1");
}

if (strcasecmp('public', $_POST["anti_spam_question"]) !== 0) {
    naughty("6aef421ce05e3ac34f4cd91ae3248a45");
}

$comment_directory = "/home/hpr/comments";

if ( ! file_exists( $comment_directory ) ) {
    # Looks like the comments directory has not been created
    naughty("d5342ea497f701656433e81fb5eed064");
}

$unprocessed_comments = iterator_count(new FilesystemIterator("$comment_directory", FilesystemIterator::SKIP_DOTS));

if( $unprocessed_comments >= 10 ) {
    # There has to be at least one comment here as they are calling the script, and too many is suspicious
    naughty("093f42abee30e69e0e4d5125c70a0f7c");
}

# This is to prevent anything except hits from the web form. 
# Anyone wanting to script uploads can do so via ftp
if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
    naughty("87613fc139b251b673e1dd51e378e462"); 
}

if ( empty($_SERVER["REMOTE_ADDR"]) ) {
    naughty("d7d0b6ab9689be244e1b6a8fbe6effba");
}
else {
    $ip = $_SERVER["REMOTE_ADDR"];
}

if (count($_POST) !== 8) {
    naughty("086fe155b0588de68fc5d9e4580254a8");
}

// Basic POST Checks
if ( empty($_POST["comment_author_name"]) or strlen($_POST["comment_author_name"]) > 40 or strtolower($_POST["comment_author_name"]) == "testdog" ) {
    naughty("294356cd36d3f9b75da4d8c0a6108881");
}
$comment_author_name = json_encode( $_POST["comment_author_name"] );

if ( empty($_POST["comment_title"]) or strlen($_POST["comment_title"]) > 100 ) {
    naughty("a89efb428cfe36996a65b371d5f4e303");
}
$comment_title = json_encode( $_POST["comment_title"] );

if ( empty($_POST["comment_text"]) or strlen($_POST["comment_text"]) > 2000 or strpos(strtolower($_POST["comment_text"]), "outlook.con") !== false ) {
    naughty("cd57ab4d7b77a131ed3deb441bd93dcd");
}
$comment_text = json_encode( $_POST["comment_text"] );

if ( empty($_POST["spammer"]) or strcmp($_POST["spammer"], "No") !== 0 ) {
    naughty("b2ec68bd04cee0f64143ce4827a97e7c");
}

# We check to see if the eps_id has been suplied, that it's a integer, and that it's in our range.

if (isset($_POST['eps_id'])){
    $eps_id = intval( $_POST['eps_id'] );

    $query = "SELECT COUNT(*) FROM eps WHERE id='$eps_id'";
    $result = mysqli_query($connection, "$query");
    $row = mysqli_fetch_array($result, MYSQLI_NUM);
    $total = $row[0];
    if ( !isset($result) or ( $total != 1 ) ) {
        naughty("5348e3c2aee3644730c70d3f000bcb01");
    }
    mysqli_free_result($result);

    $result = mysqli_query($connection, 'SELECT MAX(id) as max FROM eps;');
    if (!isset($result)) {
        naughty("f00fb1f47affc3286aadc15038cfd5d7");
    }
    while ($row = mysqli_fetch_array($result)) {
        $max_eps = $row['max'];
    }
    mysqli_free_result($result);
}
else {
    naughty("02c560adf1ff39b140fe8b7abe02fd31");
}

if ( intval($eps_id) <= 0 ){
    naughty("2903eeac51bb479edb428ae3c896671c");
}

if ( intval($eps_id) > $max_eps ){
    naughty("54aa65c12ba71f3dfc451ff5bc82c798");
}

if ( intval($eps_id) === 0 ) {
    naughty("11fe1f9b76bf9f30e6a3a784832cb738");
}
else {
    $eps_id = intval($eps_id);
}

# extra spam checks to see if they supplied the correct host id
$query = "SELECT hosts.host, eps.title, eps.summary, eps.date, eps.hostid, eps.series, miniseries.name, eps.explicit FROM eps, hosts, miniseries WHERE eps.id='$eps_id' AND eps.valid=1 AND eps.hostid = hosts.hostid AND eps.series = miniseries.id";
if ($result = mysqli_query($connection, $query)) {
    while ($row = mysqli_fetch_array($result)) {
        $host = $row['host'];
        $title = $row['title'];
        $summary = $row['summary'];
        $ep_date = $row['date'];
        $host_id = $row['hostid'];
        $series_id = $row['series'];
        $series_name = $row['name'];
        $explicit = $row['explicit'];
    } 
}
else {
    naughty("c34561d684ad97241c95a1287688638b");
}
mysqli_free_result($result);

if ( empty($_POST["hostid"]) or intval($_POST["hostid"]) !=  $host_id ) {
    naughty("b4d71481b7055272728094292fd2a562");
}

if ( empty($_POST["justification"]) or strlen($_POST["justification"]) > 200 or strlen($_POST["justification"]) < 20) {
    naughty("156d2d2d5780bd7f4a750f7c162b3394");
}
  
# Checks to see how old the show is
#$current_episode_number = GetLatestPublishedShow($connection);
list ($current_episode_date, $current_episode_number) = GetLatestPublishedShow($connection);

if ( ( $eps_id <= $current_episode_number ) and ( $eps_id >= ( $current_episode_number - 20 ) ) ) {
    if ( strcmp($_POST["justification"], "No justification is asked for or required.") !== 0 ) {
        naughty("9357d78bf73b03ee2dd902a4c975f91d");
    }
    else {
        $justification = json_encode("Current Comment");
    }
}
else {
    if ( strcmp($_POST["justification"], "No justification is asked for or required.") === 0 ) {
        print ">" . $_POST["justification"] ."< eps_id: $eps_id, current_episode_number: $current_episode_number, ";
        naughty("df4af9bdd0302f672d6311c76bdc461a");
    }
    else {
        $justification = json_encode( $_POST["justification"] );
    }
}



if ( empty($_SERVER["REMOTE_ADDR"]) ) {
  naughty("611144d4c0d575fffbf8f3ef11f8ad68");
}
else {
  $ip = $_SERVER["REMOTE_ADDR"];
}
$comment_ip = json_encode( $ip );

// OK You convinced me. 

$key = uniqid(md5(rand()));
$timestamp = time()+date("Z");
$timestamp = gmdate("Y-m-d\TH:i:s\Z",$timestamp);
$comment_file = "${comment_directory}/${timestamp}_${ip}_${key}.json";
$timestamp = json_encode($timestamp);
$comment_key = json_encode( $key );
if ( file_exists( $comment_file ) ) {
  naughty("ef5d14b33b262bfbf5d40544fdeb9ec3");
}

$comment_data = "{
    \"eps_id\": $eps_id,
    \"ip\": \"$ip\",
    \"comment_timestamp\": $timestamp,
    \"comment_author_name\": $comment_author_name,
    \"comment_title\": $comment_title,
    \"comment_text\": $comment_text,
    \"justification\": $justification,
    \"key\": $comment_key
}";

file_put_contents($comment_file, $comment_data );

if ( filesize( $comment_file ) > 4000 ) {
  naughty("56e00e793a27168511d1cfda11d3bc55");
}

// Mail the comment

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require_once('/home/hpr/php/PHPMailer/Exception.php');
require_once('/home/hpr/php/PHPMailer/PHPMailer.php');
require_once('/home/hpr/php/PHPMailer/SMTP.php');

date_default_timezone_set('Etc/UTC');

$mailer = new PHPMailer(true); 
$mailer->isSMTP();
$mailer->Host = "$mailerHost";
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Port = "465";
$mailer->Username = "$mailerUsername";
$mailer->Password = "$mailerPassword";


// Set up to, from, and the message body.  The body doesn't have to be HTML; check the PHPMailer documentation for details.
$mailer->Sender = 'robot@hobbypublicradio.com';
$mailer->addReplyTo('admin@hackerpublicradio.org', 'HPR Admins');
$mailer->setFrom('robot@hobbypublicradio.com', 'HPR Robot');
$mailer->addBCC('admin@hackerpublicradio.org');
$mailer->addBCC('admin@hobbypublicradio.org');
$mailer->AddAddress('comments@hackerpublicradio.org');
$mailer->isHTML(false);
$mailer->Subject = "New Comment for show hpr${eps_id} on ${ep_date} ${key}";
$mailer->MsgHTML("<p>hpr${eps_id} on ${ep_date} by ${host} with the title <strong>${title}</strong> \"${summary}\"</p>
<p>
See attachment for the json comment file.
</p>
<p>
There are now " . ++$unprocessed_comments . " unprocessed comments.
</p>
<p>
Thanks,<br />
HPR Bot
</p>
<pre>" . date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $key . "\t" . $_SERVER["HTTP_USER_AGENT"] . "</pre>"
);
$mailer->AltBody = "hpr${eps_id} on ${ep_date} by ${host} with the title ${title} \"${summary}\"</p>

See attachment for the json comment file.

There are now ${unprocessed_comments} unprocessed comments.

Thanks,
HPR Bot
" . date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $key . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n";
$mailer->addAttachment($comment_file, "${key}.json", "base64", "application/json");

//send the message, check for errors
if (!$mailer->send()) {
    echo 'Mailer Error: ' . $mailer->ErrorInfo;
}


$body="give";
//$body="index_full";
include 'header.html'; 

?>

<main id="maincontent">
	<hr />
	<article>
		<header>
				<h1>Thank you</h1>
		</header>
		<p>
		Thank you for your comment. A moderator will get to your comment at some point.
		</p>
		<p>
		Thanks,<br />
		<br />
		HPR Bot
		</p>
		<pre>
		<pre>
		<?php print date('Y-m-d\TH:i:s') . "\n" . getUserIP() . "\n" . $_SERVER["HTTP_USER_AGENT"]; ?>
		</pre>
	</article>
</main>

<?php

include 'footer.html';

logextra( "Finished comment_confirm.php");

?>

