<?php
# request.php > request_confirm.php > upload.php > upload_confirm.php

## Recent Changes
# TODO disabled the max notes check. We need to re-enable after we get a feel for the max length
# Removed support for the txt file
# Removde the POST duplication from the json file
# No longer logs the post to log file

require "/home/hpr/php/include.php";

function goback() {
  header( "Location: " . $_SERVER["HTTP_REFERER"] ) ;
  exit;
}
logextra( "Starting upload_confirm.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];

logextra( "Got reservations" );
if ($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("88fe2bc11a90f9f9ab9bdcc8a82d7401 Too many shows waiting - uploads have been suspended.");
}
logextra( "No bulk upload" );
// // // print '<pre>';
// // // var_dump( $_SERVER['REQUEST_METHOD'] );
// // // print '</pre>';



if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
  naughty("29e9019c9615f755aec834000892ee9e, Wrong request method");
}
logextra( "It is a POST" );

if ( empty($_SERVER["REMOTE_ADDR"]) ) {
  naughty("abb147a251e8db132dafa93d98f8487f Missing remote IP address");
}
else {
  $ip = $_SERVER["REMOTE_ADDR"];
}
logextra( "We have a IP of $ip" );

if (count($_POST) !== 15) {
  logextra( "" );
if (count($_POST) !== 17) {
    # 19 is for mosaic
    # if this reports 0 is could be that the max upload is not set correctly in php.ini.
    naughty("7a994999b40e3dc2e3eecfdc36a78d23 Incorrect number of POST entries ".count($_POST) );
  }
}
logextra( "Correct number of POST entries" );

if ( isset( $_POST['key'] ) and strlen( $_POST['key'] ) ===  45  and strlen( htmlspecialchars( stripslashes( strip_tags( $_POST['key'] ) ) ) ) ===  45 and ctype_xdigit( $_POST['key'] ) ) {
  $db_key = htmlspecialchars( stripslashes( strip_tags( $_POST['key'] ) ) );
}
else {
  naughty("2fb4c4e05f0e8f37a5b47565cfb863f5 Field lengths are not correct");
}
logextra( "Field lengths are correct" );

$query = "SELECT * FROM reservations WHERE reservations.ip = '$ip' AND reservations.key = '$db_key' ";
$result = mysqli_query($connection, $query);
$db = mysqli_fetch_array($result, MYSQLI_ASSOC);
logextra( "Getting this reservation from the db" );

if ( empty($db["ip"]) or $db["key"] != $db_key ) {
  naughty("3162941738512bfdb1d21f288ee7cdb4 Could not find this reservation from the db for \"$ip\" and \"$db_key\". Are you using the correct link, or did your ip address change ?");
}
else {
  $db_ip = $db['ip'];
  $db_email = unformatemail($db['email']);
  $db_timestamp = $db['timestamp'];
  $ep_num = $db['ep_num'];
  $ep_date = $db['ep_date'];
}
logextra( "Found this reservation from the db" );

if ( empty($db_email) ) {
  naughty("457bf84c726d1cbbd381933e3a08b2ac did not find a email \"$db_email\" in the db.");
}
logextra( "Got an email $db_email" );

if ( strtotime($db['timestamp']) >=  $_SERVER["REQUEST_TIME"] ) {
  naughty("00ad965f523b5c2ade071eb20d3618b5 The Timestamp is too old");
}
logextra( "Timestamp is not too old" );

if ( strtotime($db['timestamp']) >=  ( $_SERVER["REQUEST_TIME"] ) + 1800 ) {
  naughty("7570026fd11fc31ac0cada3e1dae4d0b The Timestamp is too young");
}
logextra( "Timestamp is not to young" );

if ( empty($_POST["title"]) or strlen($_POST["title"]) > 100 ) {
  naughty("32831f22fb96d02ce819127d558d28a2 The Title length is not less than 100");
}
logextra( "Title length is OK" );

if ( empty($_POST["summary"]) or strlen( $_POST["summary"]) > 200 or strlen(str_replace('\\', '', $_POST["summary"])) > 100 ) {
  naughty("ecfcc4c12bf4319d412d66fd2e239249 The summary length is not between 100 and 200");
}
logextra( "Summary length is OK" );

if ( empty($_POST["shownotes_format"]) ) {
  naughty("a8345484b7a4ebad5af54937a3b2e26b The Shownotes are missing");
}
logextra( "Shownotes are not missing" );

if ( !(
    strcmp($_POST["shownotes_format"], "plain_text") === 0 or
    strcmp($_POST["shownotes_format"], "html5") === 0 or
    strcmp($_POST["shownotes_format"], "Markdown_GitHub") === 0 or
    strcmp($_POST["shownotes_format"], "Markdown_Pandoc") === 0 or
    strcmp($_POST["shownotes_format"], "restructured_text") === 0 or
    strcmp($_POST["shownotes_format"], "txt2tags") === 0 )
    ) {
  naughty("b5609bad7edd70d76d75652fb0592ec4 " . $_POST["shownotes_format"] . " " . strcmp($_POST["shownotes_format"], ". The shownotes_format is not OK"));
}
logextra( "shownotes_format is set OK" );

if ( empty($_POST["explicit"]) ) {
  naughty("39cc8812b02607d613c6a7ba7e789f2c The explicit flag is missing");
}
logextra( "explicit exists" );

if ( strcmp($_POST["explicit"], "Yes") !== 0 ) {
  logextra( "" );
if ( strcmp($_POST["explicit"], "Clean") !== 0 ) {
    naughty("198ab3b8af59ffba12c335239bde2876 The explicit flsg is not Yes or Clean");
  }
}
logextra( "explicit is either Yes or Clean" );

if ( empty($_POST["license"]) or strlen($_POST["license"]) < 4 or strlen($_POST["license"]) > 11 ) {
  naughty("194c24ff7396901c0ccc42fb21344683 The license length is not correct");
}
logextra( "license length is fine" );

if ( !(
    strcmp($_POST["license"], "CC-BY-SA") === 0 or
    strcmp($_POST["license"], "CC-BY-NC-SA") === 0 or
    strcmp($_POST["license"], "CC-BY-NC-ND") === 0 or
    strcmp($_POST["license"], "CC-0") === 0 or
    strcmp($_POST["license"], "CC-BY-NC") === 0 or
    strcmp($_POST["license"], "CC-BY") === 0 or
    strcmp($_POST["license"], "Other") === 0 )
    ) {
  naughty("f5609bad7edd70d76d75652fb0592ec4 The license is has an invalid value");
}
logextra( "license is a valid value" );

// TODO re-enable after we get a feel for the max length
// if ( empty($_POST["notes"]) or strlen($_POST["notes"]) > 100000 ) {
//   naughty("5860799406a323209b902d5104fe7bae The shownotes are too long");
// }
// logextra( "Notes are less than max" );

if ( empty($_POST["notes"]) or strlen($_POST["notes"]) < 30 ) {
  naughty("5860799406a323209b902d5104fe7bae The shownotes are too short");
}
logextra( "Notes are not too short" );

$notes_length = strlen($_POST["notes"]);
logextra( "Notes are $notes_length long." );

if ( ( empty($_POST["series"]) and ($_POST["series"] != 0 ) ) or (strlen($_POST["series"]) > 3 ) ) {
  naughty("f1c83b57821d562f66246d975ef28994 The Series is either missing, zero or greater than 3 in length");
}
logextra( "The Series exists and is less than 3 but not zero" );
$series = $_POST["series"];
$result_series = mysqli_query($connection, "SELECT name FROM miniseries WHERE id='$series'");
logextra( "Series id is in the correct range" );
if (!isset($result_series)) {
  naughty("27457bada69cbc352af762bdf649e905 The Series id is not in the correct range");
}
$data=mysqli_fetch_assoc($result_series);
$series_name = $data['name'];
logextra( "Series has been found" );

if ( !empty($_POST["tags"]) and strlen($_POST["tags"]) > 100 ) {
  naughty("49a69b565acecf9d2a96aacc73aec5aa The tags are missing or greate than 100 long");
}
logextra( "Tags are the correct length" );

if ( empty($_POST["host_name"]) or strlen($_POST["host_name"]) > 40 ) {
  naughty("626eae845e0a448be0544775ab5e4dc4 The hostname is missing or greater than 40 long");
}
logextra( "host_name is set and correct length" );

if ( strlen($_POST["host_profile"]) > 2000 ) {
  naughty("f69ec5999e0a02def5a110489401347f The Host profile exceeds 2000");
}
logextra( "host_profile is correct length" );

if ( empty($_POST["host_license"]) or strlen($_POST["host_license"]) < 4 or strlen($_POST["host_license"]) > 11 ) {
  naughty("f2816b32e97be090a96ceabdc9230c9c The host license length is not correct");
}
logextra( "host_license is in the correct range " );

if ( !(
    strcmp($_POST["host_license"], "CC-BY-SA") === 0 or
    strcmp($_POST["host_license"], "CC-BY-NC-SA") === 0 or
    strcmp($_POST["host_license"], "CC-BY-NC-ND") === 0 or
    strcmp($_POST["host_license"], "CC-0") === 0 or
    strcmp($_POST["host_license"], "CC-BY-NC") === 0 or
    strcmp($_POST["host_license"], "CC-BY") === 0 or
    strcmp($_POST["host_license"], "Other") === 0 )
    ) {
  naughty("978a18fa8558f3180897429e63d6ae55 The show license is has an invalid value");
}
logextra( "host_license is a predfined value" );

if ( empty($_POST["hostid"]) and $_POST["hostid"] != 0 ) {
  naughty("277dc98d43e7840d9f296cce1bc3ec2c The hostid is missing or is 0");
}
logextra( "hostid exists and is not 0" );

$result = mysqli_query($connection, 'SELECT MAX(hostid) as max FROM hosts;');

if (!isset($result)) {
  naughty("93fcc22d0c5ee3fac35e6d658db76059 Failed to retrieve the max host from db");
}
$data=mysqli_fetch_assoc($result);
$maxhost = $data['max'];

logextra( "retrieved the max host from db" );

$hostid = $_POST["hostid"];
logextra( "" );
if ( (strval(intval($hostid)) != strval($hostid)) or ( intval($hostid) < 0 ) or ( intval($hostid) > $maxhost ) ){
  naughty("a0f6cae871b85cb66f85d7ed5e91d1bb The host id is not an int, or the range is not correct");
}
logextra( "host id is int, and in the correct range" );

if ( !empty($_POST["url"]) and strlen($_POST["url"]) > 1024 ) {
  naughty("6d4f180c49ff9b9154bd80070ec2c1f3 The url is not set or is not the correct length");
}
logextra( "The url is set and the correct length" );

if ( !empty($_POST["url"]) ) {
  if ( filter_var($_POST["url"], FILTER_VALIDATE_URL) === false ) {
      naughty("9c307efe37146015a35e2d928c2c0f69 The url has been altered");
    }
    else {
      $url = htmlspecialchars(filter_var($_POST["url"], FILTER_VALIDATE_URL));
    }
}
logextra( "The url has not been altered" );

$dir_structure = "/home/hpr/upload/" . strtotime($db_timestamp) . "_${ep_num}_${ep_date}_${db_key}/";

if ( file_exists( $dir_structure ) ) {
  naughty("d4250c369bd81b27cdc53d0d53321ecd There is an error with the upload dir");
}
logextra( "The upload dir seems fine $dir_structure" );

if (!mkdir($dir_structure, 0777, true)) {
  naughty("804c4be123ca0327840b76bf4f8eb19e The upload directory could not be created");
}

$shownote_file_json = "${dir_structure}/shownotes.json";
if ( file_exists( $shownote_file_json ) ) {
  naughty("85c8df74d172794c49233c1a94c299fd The shownotes json file is missing");
}
logextra( "The shownotes json file exists $shownote_file_json" );

$this_post = print_r($_POST, true);
$this_file = print_r($_FILES, true);

logextra( "Received $this_post, $this_file" );

$show_data_json = array(
  "host" => array(
    "Host_ID" => $_POST['hostid'],
    "Host_Name" => $_POST['host_name'],
    "Host_Email" => $db_email,
    "Host_License" => $_POST['host_license'],
    "Host_Profile" => $_POST['host_profile']
  ),
  "episode" => array(
    "Title" => $_POST['title'],
    "Summary" => $_POST['summary'],
    "Explicit" => $_POST['explicit'],
    "Show_License" => $_POST['license'],
    "Series" => $series,
    "Series_Name" => $series_name,
    "Tags" => $_POST['tags'],
    "Show_Notes" => $_POST['notes']
  ),
  "metadata" => array(
    "Episode_Number" => $ep_num,
    "Episode_Date" => $ep_date,
    "Timestamp" => $db_timestamp,
    "Key" => $_POST['key'],
    "Host_IP" => $db_ip,
    "FILES" => $_FILES,
    "url" => $_POST['url'],
    "Shownotes_Format" => $_POST['shownotes_format'],
  )
);

file_put_contents($shownote_file_json, json_encode( $show_data_json ) );
$shownote_file_json_length = strlen( json_encode( $show_data_json ) );

logextra( "Wrote the shownotes which are $shownote_file_json_length long" );

if ( !file_exists( $dir_structure ) ) {
  naughty("a1534e6d525352dce7183a2e22862049 The dir_structure is missing");
}
logextra( "The dir_structure still exists" );

if ( !file_exists( "$dir_structure/shownotes.json" ) ) {
  naughty("3eb02d6b9ea801d4c5909b4fac0ccd96 The shownotes.json is missing");
}
logextra( "shownotes.json still exists" );

$message="";

if ( !empty($_FILES["host_photo"]["tmp_name"]) and !empty($_FILES["host_photo"]["type"]) and $_FILES["host_photo"]["error"] == 0 ) {
  list($type_main, $type_sub)= explode("/", $_FILES["host_photo"]["type"]);
  if ( empty($type_sub) or strlen($type_sub) > 4 ) {
    naughty("c1381f1d2492f81074d8cb70c85f5fc8 There was an issue with the upload");
  }
  else {
    $temp_photo = $_FILES["host_photo"]["tmp_name"];
    $host_photo = "${dir_structure}/photo";
    move_uploaded_file($temp_photo, $host_photo);
    $message = $message . "A photo was delivered. ";
  }
  logextra( "A photo was delivered" );
}
else {
  $message = $message . "No photo delivered. ";
}
logextra( "No photo delivered" );

// Deal with uploaded files.
$files = count($_FILES["media_files"]["error"]);
if ( $files > 1 ) {
  $message = $message . $files . " files were delivered.";
  logextra( $files . " files were delivered." );
}
else
if ( $files == 1 and $_FILES["media_files"]["error"][ "0"] == 0 ) {
  $message = $message . "One file was delivered.";
  logextra( "One file was delivered." );
}
else {
  if ( empty($_POST["url"]) ) {
    $message = $message . "

You have chosen to upload the files separately from these show notes.

If you wish to send a show using another method then please discuss
it with the HPR Volunteer at admin@hackerpublicradio.org

";
  logextra( "uploading the files separately" );
  }
}

foreach($_FILES["media_files"]["tmp_name"] as $key => $val) {
  if ( $_FILES["media_files"]["error"][ "$key"] == 0 ) {
    $from = $_FILES["media_files"]["tmp_name"][ "$key"];
    $to = $_FILES["media_files"]["name"][ "$key"];
    $to = rawurlencode( "${to}" );
    $to = str_replace("%20","_",$to);
    $to = str_replace("%","~",$to);
    $to = "${dir_structure}/${db_key}_${to}";
    $moveResult = move_uploaded_file($from, $to);
    if ($moveResult != true) {
      echo "ERROR: File not moved correctly >$from< >$to<";
      logextra( "ERROR: File not moved correctly >$from< >$to<" );
    }
    else {
      logextra( "File moved correctly >$from< >$to<" );
    }
  }
}
logextra( "All Files moved" );

########################################################
// OK You convinced me.

if ( $ep_num  == 9999 ) {
  $show_submitted = "RESERVE_SHOW_SUBMITTED";
}
else {
  $show_submitted = "SHOW_SUBMITTED";
}

$query = "UPDATE reservations SET `verified` = '1', `status` = '$show_submitted' WHERE `ip` = '$db_ip' AND `timestamp` = '$db_timestamp' AND `key` = '$db_key'";
$result = mysqli_query($connection,  $query );
if (mysqli_errno($connection)) {
  $error = "MySQL error ".mysqli_errno($connection).": ".mysqli_error($connection)."\n";
  problem("Could not update the show reservation to $status in the db");
  mysqli_free_result($result);
  mysqli_close($connection);
  logextra( "$query");
  die;
}
logextra( "Updating the db to $show_submitted" );
if (!isset($result)) {
  naughty("76ec33229ca023336a2b1c649b0491f5 There was a problem updating the db");
}

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

?>
  <article>
    <header>
        <h1>Thank you</h1>
    </header>
    <p>
    Thank you for your submission.
    </p>
    <pre>
    <?php echo $message; ?>
    </pre>
    <p>
      Your show will now be processed by a HPR Volunteer.
    </p>
    <p>
    Thanks,<br />
    <br />
    HPR Bot
    </p>
  </article>
<?php
logextra( "Sending email" );

# TODO check for both url and file upload

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("$db_email");
$mailer->isHTML(false);
if ( $ep_num  == "9999" ) {
  $mailer->Subject = "Thank you for uploading to the reserve pool";
  $mailer->MsgHTML("<p><em>This email is an automatic reply. If you have not made this request then please ignore this email.</em></p>
  <p>Thank You for recording an episode for the reserve pool.</p>
  <pre>
  $message
  </pre>
  <p>
  Your show will now be processed by a HPR Volunteer.<br />
  Thanks,<br />
  HPR Bot
  </p>");
}
else {
  $mailer->Subject = "Thank you for uploading hpr${ep_num}::${ep_date}";
  $mailer->MsgHTML("<p><em>This email is an automatic reply. If you have not made this request then please ignore this email.</em></p>
  <p>Thank you for recording hpr${ep_num} for release on ${ep_date}.</p>
  <pre>
  $message
  </pre>
  <p>
  Your show will now be processed by a HPR Volunteer.<br />
  Thanks,<br />
  HPR Bot.
  </p>");
}

$mailer->AltBody = "This email is an automatic reply. If you have not made this request then please ignore this email.

Thank you for recording hpr${ep_num}, for release on ${ep_date}.

$message

Your show will now be processed by a HPR Volunteer.

Thanks,

HPR Bot";

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


include 'footer.php';

logextra( "Finished upload_confirm.php");

?>
