<?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 No arguments provided $num_get_args");
}

if ( empty($_POST["anti_spam_question"]) ) {
    naughty("0601a23e358374c293b086bb75606cca You failed the anti spam question");
}

if ( strlen($_POST["anti_spam_question"]) !== 6 ) {
    naughty("6f51e6e7e6820b3fdda5d4ca0df14db1 You have the wrong spam answer");
}

if (strcasecmp('public', $_POST["anti_spam_question"]) !== 0) {
    naughty("6aef421ce05e3ac34f4cd91ae3248a45 You don't know what P is in HPR");
}

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

$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 Too many unprocessed comments - shutting myself down");
}

# 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 Must be a POST"); 
}

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

if (count($_POST) !== 8) {
    naughty("086fe155b0588de68fc5d9e4580254a8 Not correct number of fields");
}

// 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 Your name wrong");
}
$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 The title is too long");
}
$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"]) ) {
    naughty("cd57ab4d7b77a131ed3deb441bd93dcd The comment text is missing.");
}
if ( strlen($_POST["comment_text"]) > 2000 or strpos(strtolower($_POST["comment_text"]), "outlook.con") !== false ) {
    naughty("cd57ab4d7b77a131ed3deb441bd93dcd The comment text is too verbose. Record a show instead.");
}

$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 You selected that you were a spammer");
}

# 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 No response from the db");
    }
    mysqli_free_result($result);

    $result = mysqli_query($connection, 'SELECT MAX(id) as max FROM eps;');
    if (!isset($result)) {
        naughty("f00fb1f47affc3286aadc15038cfd5d7 Could not find the max id");
    }
    while ($row = mysqli_fetch_array($result)) {
        $max_eps = $row['max'];
    }
    mysqli_free_result($result);
}
else {
    naughty("02c560adf1ff39b140fe8b7abe02fd31 Commenting on a non existant show is odd");
}

if ( intval($eps_id) <= 0 ){
    naughty("2903eeac51bb479edb428ae3c896671c Commenting on a non show with ID less than zero is odd");
}

if ( intval($eps_id) > $max_eps ){
    naughty("54aa65c12ba71f3dfc451ff5bc82c798 Commenting on a show that is more than our posted episodes is odd");
}

if ( intval($eps_id) === 0 ) {
    naughty("11fe1f9b76bf9f30e6a3a784832cb738 Commenting on a show zero is odd");
}
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 Could not get the hosts from the db");
}
mysqli_free_result($result);

if ( empty($_POST["hostid"]) or intval($_POST["hostid"]) !=  $host_id ) {
    naughty("b4d71481b7055272728094292fd2a562 Cant find that host id. You picked the wrong host from the list");
}

if ( empty($_POST["justification"]) or strlen($_POST["justification"]) > 200 or strlen($_POST["justification"]) < 20) {
    naughty("156d2d2d5780bd7f4a750f7c162b3394 You need to have a sufficiently long answer to 'What does HPR mean to you?'.");
}
  
# 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 You're saying No justification on a show that requires justification");
    }
    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 A current comment should not require Justification");
    }
    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 Missing REMOTE_ADDR");
}
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 File already exists");
}

$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 Filesize is too big");
}

$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><a href=\"https://hackerpublicradio.org/eps/hpr${eps_id}\">hpr${eps_id}</a> 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>

https://hackerpublicradio.org/eps/hpr${eps_id}

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.php'; 

?>
	<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>
<?php

include 'footer.php';

logextra( "Finished comment_confirm.php");

?>

