<?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 = $_POST["comment_author_name"];
$comment_author_name_json = json_encode( $_POST["comment_author_name"] );

if ( $comment_author_name === preg_replace('/[^a-zA-Z0-9_ ]/', '', $comment_author_name) ) {
  $comment_author_name_ascii = "ASCII";
}
else {
  $comment_author_name_ascii = "EXTENDED";
}

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

if ( $comment_title === preg_replace('/[^a-zA-Z0-9_ ]/', '', $comment_title) ) {
  $comment_title_ascii = "ASCII";
}
else {
  $comment_title_ascii = "EXTENDED";
}

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

if ( $comment_text === preg_replace('/[^a-zA-Z0-9_ ]/', '', $comment_text) ) {
  $comment_text_ascii = "ASCII";
}
else {
  $comment_text_ascii = "EXTENDED";
}

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 = "Current Comment";
        $justification_json = 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 = $_POST["justification"];
        $justification_json = json_encode( $_POST["justification"] );
    }
}

if ( $justification === preg_replace('/[^a-zA-Z0-9_ ]/', '', $justification) ) {
  $justification_ascii = "ASCII";
}
else {
  $justification_ascii = "EXTENDED";
}

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 = $timestamp;
$timestamp_json = json_encode($timestamp);
$comment_key_json = json_encode( $key );
if ( file_exists( $comment_file ) ) {
  naughty("ef5d14b33b262bfbf5d40544fdeb9ec3");
}

$comment_data = "{
    \"eps_id\": $eps_id,
    \"ip\": \"$ip\",
    \"comment_timestamp\": $timestamp_json,
    \"comment_author_name\": $comment_author_name_json,
    \"comment_title\": $comment_title_json,
    \"comment_text\": $comment_text_json,
    \"justification\": $justification_json,
    \"key\": $comment_key_json
}";

file_put_contents($comment_file, $comment_data );

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

$user_agent = preg_replace('/ \(/', "\n", $_SERVER["HTTP_USER_AGENT"] );
$user_agent = preg_replace('/\) /', "\n", $user_agent );

// 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->CharSet = 'UTF-8';
$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>
<a href=\"https://hub.hackerpublicradio.org/cms/comment_process.php?key=$key&action=block\">Block</a>, 
<a href=\"https://hub.hackerpublicradio.org/cms/comment_process.php?key=$key&action=delete\">Delete</a>, or
<a href=\"https://hub.hackerpublicradio.org/cms/comment_process.php?key=$key&action=publish\">Publish</a>.
</p>

<p>
There are now " . ++$unprocessed_comments . " unprocessed comments.
</p>
<p>
Thanks,<br />
HPR Bot
</p>
<pre>
$timestamp
$ip
$key
$user_agent
</pre>
<hr />
<p>
<strong>Comment on eps_id</strong>: $eps_id,<br />
<br />
<strong>comment_author_name</strong> ($comment_author_name_ascii): $comment_author_name,<br />
<strong>comment_title</strong> ($comment_title_ascii): $comment_title,<br />
<strong>comment_text</strong> ($comment_text_ascii): 

$comment_text

<br/>
<strong>justification</strong> ($justification_ascii): 
$justification
</p>
<hr />
<strong>comment_title_json</strong>: $comment_title_json,<br />
<strong>comment_text_json</strong>: $comment_text_json,<br />
<strong>justification_json</strong>: $justification_json,<br />
<hr />"
);
$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
$timestamp
$ip
$key
$user_agent
";
$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>
		<?php echo 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");

?>