<?php
# request.php > request_confirm.php > upload.php > upload_confirm.php 
require "/home/hpr/php/include.php";

$query = "SELECT COUNT(*) as total FROM `reservations` WHERE ep_num = 0";
$result = mysqli_query($connection, "$query");
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$total = $row[0];

if(!isset($total) or $total > 150 ) {
  # This seems to indicate that we are under an attack as we never get 5 shows in the one day from different hosts.
  # A host doing bulk upload will need to do them one by one
  naughty("5971624889258aefb44e5f7bf8dffbd4 Too many requests - shutting down");
}

# This is to prevent anything except hits from the web form. 
if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
  naughty("19e9019c9615f755aec834000892ee9e Request method is not POST"); 
}

if ( empty($_SERVER["REMOTE_ADDR"]) ) {
  naughty("9bb147a251e8db132dafa93d98f8487f The REMOTE_ADDR is missing");
}
else {
  $ip = $_SERVER["REMOTE_ADDR"];
}

if (count($_POST) !== 2) {
  naughty("02de1aef3b9490a417c39170d8f06028 The post contains the incorrect number of entries");
}

# This will check to see if there are any existing requests from this ip address
$query = "SELECT * FROM reservations WHERE ip = '$ip' and `status` =  'REQUEST_UNVERIFIED' and `verified` = 0";
$result = @mysqli_query($connection, $query);
$db = mysqli_fetch_array($result, MYSQLI_ASSOC);

if ( empty($db["ip"]) ) {
  # the request did not come via the web form
  naughty("2162941738512bfdb1d21f288ee7cdb4 There is no reservation available for this ip");
}

if ( strtotime($db['timestamp']) >=  $_SERVER["REQUEST_TIME"] ) {
  # they are playing with the database or time settings
  naughty("f0ad965f523b5c2ade071eb20d3618b5 The timestamp is not correct");
}

if ( strtotime($db['timestamp']) >=  ( $_SERVER["REQUEST_TIME"] ) + 1800 ) {
  # There is too long a time entering the form
  naughty("6570026fd11fc31ac0cada3e1dae4d0b Timeout. You waited too long to react. ");
}

// Basic POST Checks
if ( empty($_POST["ep_num_date"]) or strlen($_POST["ep_num_date"]) !== 15  ) {
  naughty("a32fbe5f0494eb7f34034b164739314d The date is not correct");
}


if ( empty($_POST["email"]) ) {
  naughty("76eaa1a1556faeadfc14631c35b8590a The email is missing");
}

// Getting to the keep section

if ( filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false ) {
  naughty("8c307efe37146015a35e2d928c2c0f69 Invalid email");
}
else {
  $email = htmlspecialchars(filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)); 
}

if ( strpos($_POST["ep_num_date"], '_') !== 4 or strpos($_POST["ep_num_date"], '-') !== 9  or strpos($_POST["ep_num_date"], '-', 10 ) !== 12  ) {
  naughty("705f8e26e42a90b31075a110674b19ee The date format is not correct");
}

if ( !preg_match("/^\d{4}_\d{4}-\d{2}-\d{2}$/", $_POST["ep_num_date"]) ) {
  naughty("ad7f805c2f42be77122ec52f114fe318 The date fails a regex");
}
else {
  list($ep_num, $ep_date) = explode('_', $_POST["ep_num_date"]);
}

if ( intval($ep_num) === 0 ) {
  naughty("9424f7407b2fb83407760ad763286b53 The episode number is not an integer");
}
else {
  $ep_num = intval($ep_num);
}

if ( strtotime($ep_date) === false ) {
  naughty("59c7bff340d023773d987d71df545110 The date is not a valid time");
}
else {
  $ep_date_epoch = strtotime($ep_date);
}


$show_array = array ();
$query = "SELECT (

SELECT max( id )
FROM eps
WHERE eps.date <= UTC_DATE( )
) AS current_ep_num, (

SELECT max( date )
FROM eps
WHERE eps.date <= UTC_DATE( )
) AS current_ep_date, (

SELECT id
FROM eps
WHERE id = ${ep_num}
) AS valid
";

$result = mysqli_query($connection, "$query");
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$current_ep_num = $row[0];
$next_year_ep_num = $current_ep_num+365;
$current_ep_date = $row[1];
$current_ep_date_epoch = strtotime($current_ep_date);
$next_year_ep_date = strtotime(date("Y-m-d", time()) . " + 365 day" );

if ( $ep_num == $row[2] or !empty($row[2]) ) {
  naughty("$ep_num == $row[2] or !empty($row[2]) 47d186ad8d5b21ec7d455477ea08b023 Could not make the reservation in the db");
}

if ( $ep_num != 9999 ) {
  if ( ( $ep_num <= $current_ep_num ) OR ( $ep_num > $next_year_ep_num ) ) {
    naughty("7304801e8ce3b9096d28dbe1a0faa642 Episode in wrong range $ep_num <= $current_ep_num or $ep_num > $next_year_ep_num");
  }

  if ( $ep_date_epoch < $current_ep_date_epoch or $ep_date_epoch > $next_year_ep_date ) {
    naughty("34c4259b45927da50ba5c49970f880a4 Date in wrong range");
  }

  for ($slot=$current_ep_num; $slot < $next_year_ep_num; $slot++) {
    $shows_slot_date[ "${slot}"] = $current_ep_date;
    $shows_date_slot[ "$current_ep_date" ] = $slot;
    $current_ep_date = date('Y-m-d', strtotime($current_ep_date . ' + 1 weekday'));
  }

  if ( empty($shows_slot_date["$ep_num"]) or empty($shows_date_slot["$ep_date"]) ) {
    naughty("d0e113355b35f96945124d8e507759a0 This slot date is not empty");
  }

  if ( $ep_date !== $shows_slot_date["$ep_num"] or $ep_num !== $shows_date_slot["$ep_date"] ) {
    naughty("434cb53552ce1e2708e74a42f438028c This slot is invalid");
  }
} // End of bypass checks

// OK You convinced me. 
$db_ip = $db['ip'];
$db_timestamp = $db['timestamp'];
$db_key = $db['key'];
# UPDATE reservations SET `ep_num` = '3203',  `ep_date` = '2020-11-11', `email` = 'admin@hackerpublicradio.org', `verified` = '0' WHERE `ip` = '62.251.25.147' AND `timestamp` = '2020-08-20 10:55:44' AND `key` = '20ca69e4d9097d1623399c7b85fc8f475f3e56b01a289' AND `status` = 'REQUEST_EMAIL_SENT'

$email_padded = formatemail($email);

$query = "UPDATE reservations SET `ep_num` = '$ep_num',  `ep_date` = '$ep_date', `email` = '$email_padded', `verified` = '0', `status` = 'REQUEST_EMAIL_SENT' WHERE `ip` = '$db_ip' AND `timestamp` = '$db_timestamp' AND `key` = '$db_key'";

$result = mysqli_query($connection,  $query );

if(!isset($result)) {
  naughty("c7405e79b54f582e8db46c69ec4b0f24 Could not write reservation to the db");
}

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("$email");
if ( $ep_num == 9999 ) {
  $mailer->Subject = "Confirmation of request to submit to the reserve pool";
  $mailer->MsgHTML("<p>This email is an automatic reply to a request to submit to the reserve pool on the longest running Community Podcast.<br />
  <em>If you have not made this request then please ignore this email.</em>
  </p>
  <p>
  To confirm your request please confirm by copying and pasting the following link into your browser<br />
  <a href=\"${hubBaseurl}/upload.php?key=${db_key}\">${hubBaseurl}/upload.php?key=${db_key}</a>
  </p>
  <p>
  You have 15 minutes to open this link or your show will automatically be deleted so that the slot can become available to another host. Once you open the link, you have a maximum of 4 Hours to fill in the information.
  </p>
  <p>
  The upload form works on the assumption you will be posting one show at a time, from the same IP address.
  </p>
  <p>
  Please keep this key private.
  </p>
  <p>
  Thanks,<br />
  HPR Bot
  </p>
  <pre>" . date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $db_key . "\t" . $_SERVER["HTTP_USER_AGENT"] . "</pre>"
  );
  $mailer->AltBody = "This email is an automatic reply to a request to  submit to the reserve pool on the longest running Community Podcast.
  If you have not made this request then please ignore this email.

  To confirm your request please confirm by copying and pasting the following link into your browser
  ${hubBaseurl}/upload.php?key=${db_key}

  You have 15 minutes to open this link or your show will automatically be deleted so that the slot can become available to another host. Once you open the link, you have a maximum of 4 Hours to fill in the information.

  The upload form works on the assumption you will be posting one show at a time, from the same IP address.

  Please keep this key private.

  Thanks,

  HPR Bot

  " . date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $db_key . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n";
}
else {
  $mailer->Subject = "Confirmation of request to reserve hpr${ep_num} on ${ep_date}";
  $mailer->MsgHTML("<p>This email is an automatic reply to a request to reserve a podcast slot hpr${ep_num} on ${ep_date} on the longest running Community Podcast.<br />
  <em>If you have not made this request then please ignore this email.</em>
  </p>
  <p>
  To confirm your request please confirm by copying and pasting the following link into your browser<br />
  <a href=\"${hubBaseurl}/upload.php?key=${db_key}\">${hubBaseurl}/upload.php?key=${db_key}</a>
  </p>
  <p>
  You have 15 minutes to open this link or your show will automatically be deleted so that the slot can become available to another host. Once you open the link, you have a maximum of 4 Hours to fill in the information.
  </p>
  <p>
  The upload form works on the assumption you will be posting one show at a time, from the same IP address.
  </p>
  <p>
  Please keep this key private.
  </p>
  <p>
  Thanks,<br />
  HPR Bot
  </p>
  <pre>" . date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $db_key . "\t" . $_SERVER["HTTP_USER_AGENT"] . "</pre>"
  );
  $mailer->AltBody = "This email is an automatic reply to a request to reserve a podcast slot hpr${ep_num} on ${ep_date} on the longest running Community Podcast.
  If you have not made this request then please ignore this email.

  To confirm your request please confirm by copying and pasting the following link into your browser
  ${hubBaseurl}/upload.php?key=${db_key}

  You have 15 minutes to open this link or your show will automatically be deleted so that the slot can become available to another host. Once you open the link, you have a maximum of 4 Hours to fill in the information.

  The upload form works on the assumption you will be posting one show at a time, from the same IP address.

  Please keep this key private.

  Thanks,

  HPR Bot

  " . date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $db_key . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n";
}
$mailer->isHTML(false);


// Set up our connection information.
//$mailer->IsSMTP();


// All done!
//print "We are experiencing issues with the upload process. Please try again tomorrow. <br />\n";


//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 submission. A confirmation email has been sent to <em><?php echo $email; ?></em>. Please copy and paste the link into your browser to confirm your email address, and upload your show media.
    </p>
    <p>You need to <em>open</em> the link within <strong>15 minutes</strong> or the temporary lock will be released. 
    Once you open the link, you have a maximum of 4 Hours to fill in the information.</p>
    <p>The email is sent from the address <strong>robot@hobbypublicradio.com</strong>, and should be in your inbox by the time you read this.</p>
    <p>If it is not there by now, then please <strong>spam</strong> folder. 
    We have had reports that sometimes gmail and hotmail consider the messages as spam. 
    Please consider <a href="https://onlinegroups.net/blog/2014/02/25/how-to-whitelist-an-email-address/" target="_blank">whitelisting</a> the email address <em>robot@hobbypublicradio.com</em>.</p>
    <p>
    <img src="images/gmail-spam.png" alt="gmail is blocking us" />
    </p>
    <p>Return to the <strong><a href="/calendar.php">calendar</a></strong> page.</p>
    <p>
    Thanks,<br />
    <br />
    HPR Bot
    </p>
    <pre>
    <pre>
    <?php print date('Y-m-d\TH:i:s') . "\n" . getUserIP() . "\n" . $db_key . "\t" . $_SERVER["HTTP_USER_AGENT"]; ?>
    </pre>
  </article>
<?php
include 'footer.php'; 
?>
