<?php

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

date_default_timezone_set('UTC');

// executed by postshow.bash
// curl --netrc-file $HOME/.netrc --verbose --request POST https://hub.hackerpublicradio.org/cms/add_show_json.php --data-ascii @post_show.json --header "Content-Type: application/json"

logextra( "Starting add_show_json.php");

//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    throw new Exception('Request method must be POST!');
}

//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
    throw new Exception('Content type must be: application/json');
}

//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));

//Attempt to decode the incoming RAW post data from JSON.
$decoded_json = json_decode($content, true);

//If json_decode failed, the JSON is invalid.
if(!is_array($decoded_json)){
    problem( "Received content contained invalid JSON!" );
}

if ( empty($_SERVER["REMOTE_ADDR"]) ) {
  problem("No REMOTE_ADDR");
}
else {
  $ip = $_SERVER["REMOTE_ADDR"];
}
logextra( "We have a IP of $ip" );

// Check the key

$provided_key = $decoded_json['key'];

if ( isset( $provided_key ) and strlen( $provided_key ) ===  45  and strlen( htmlspecialchars( stripslashes( strip_tags( $provided_key ) ) ) ) ===  45 and ctype_xdigit( $provided_key ) ) {
  $db_key = htmlspecialchars( stripslashes( strip_tags( $provided_key ) ) );
}
else {
  problem("no valid key found");
}
logextra( "Found Valid \$key: $db_key" );

// Check if this is a known reservation

$query = "SELECT * FROM reservations WHERE reservations.key = '$db_key' ";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
$db = mysqli_fetch_array($result, MYSQLI_ASSOC);
logextra( "Getting this reservation from the db" );

if ( $db["key"] != $db_key ) {
  problem("Could not find the reservation in the db");
}
logextra( "Found this reservation from the db" );

// Check title

$provided_title = urldecode( $decoded_json["title"] );

if ( empty($provided_title) or strlen($provided_title) > 100 ) {
  problem("Title length is not OK");
}
logextra( "Title length is OK" );
$title = $provided_title;

// Check summary

$provided_summary = urldecode( $decoded_json["summary"] );

if ( empty($provided_summary) or strlen( $provided_summary) > 200 or strlen(str_replace('\\', '', $provided_summary)) > 100 ) {
  problem("Summary length is not OK");
}
logextra( "Summary length is OK" );
$summary = $provided_summary;

// Check Adult flag

$provided_explicit = urldecode( $decoded_json["explicit"] );

if ( empty($provided_explicit) ) {
  problem("explicit is missing");
}
logextra( "explicit exists" );

if ( strcmp($provided_explicit, "Yes") !== 0 ) {
  logextra( "explicit is not yes" );
  if ( strcmp($provided_explicit, "Clean") !== 0 ) {
    problem("explicit needs to be either Yes or Clean");
  }
}
logextra( "explicit is either Yes or Clean" );

$explicit = $provided_explicit;

if ( $explicit === "Clean" ) {
  $explicit = 0;
}
else {
  $explicit = 1;
}

// Check notes

$provided_notes = urldecode( $decoded_json["notes"] );

if ( empty($provided_notes) or strlen($provided_notes) > 100000 ) {
  problem("Notes are missing not less than max");
}
logextra( "Notes are present and are under the max length" );

$notes = $provided_notes;

// Check episode Lisence

$provided_episode_license = urldecode( $decoded_json["episode_license"] );

if ( empty($provided_episode_license) or strlen($provided_episode_license) < 4 or strlen($provided_episode_license) > 11 ) {
  problem("episode_license length is not fine");
}
logextra( "episode_license length is fine" );

$query = "SELECT short_name FROM licenses WHERE short_name = '$provided_episode_license'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["short_name"]) ) {
    problem( "No result returned for this short_name:\"${provided_episode_license}\"" );
  }
}

$episode_license = $provided_episode_license;

logextra( "episode_license is a valid value \"${episode_license}\"" );

// Check Series ID

$provided_series_id = urldecode( $decoded_json["series_id"] );

if ( ( empty($provided_series_id) and ($provided_series_id != 0 ) ) or (strlen($provided_series_id) > 3 ) ) {
  problem("Series id is not in the correct range");
}
logextra( "series length is fine" );

if ( (strval(intval($provided_series_id)) != strval($provided_series_id)) ){
  problem("series is not an int");
}
logextra( "series is int" );

$query = "SELECT COUNT(id) AS count_id FROM miniseries WHERE id='$provided_series_id'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["count_id"]) ) {
    problem( "No result count returned for this miniseries:\"${provided_series_id}\"" );
  }
  $count_id = $db["count_id"];
  if ( $count_id === 0 ) {
    problem( "No result returned for this query \"$query\"" );
  }
}

$series_id = $provided_series_id;

logextra( "Series ID was found \"$series_id\"" );

// Check Series Name

$provided_series_name = urldecode( $decoded_json["series_name"] );

if ( empty( $provided_series_name ) or strlen( $provided_series_name ) < 3 or strlen( $provided_series_name ) > 50 ) {
  problem("series_name length is not correct");
}

$query = "SELECT name FROM miniseries WHERE id='$series_id'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["name"]) ) {
    problem( "No result name returned for this miniseries:\"${series_id}\"" );
  }
  $db_series_name = $db["name"];
}
logextra( "Series name has been found in db: \"$db_series_name\"" );

if ( $provided_series_name != $db_series_name ) {
  problem("Provided series_name \"$provided_series_name\" and db_series_name \"$db_series_name\" don't match.");
}

$series_name = $provided_series_name;

logextra( "Series Name was found \"$series_name\"" );

// Check Tags

$provided_tags = urldecode( $decoded_json["tags"] );

if ( empty( $provided_tags ) or strlen( $provided_tags ) < 3 or strlen( $provided_tags ) > 100 ) {
  problem("Tags are not the correct length");
}
logextra( "Tags are the correct length" );
$tags = $provided_tags;

// Check Host ID

$provided_hostid = urldecode( $decoded_json["hostid"] );

if ( empty( $provided_hostid ) or ( $provided_hostid === 0 ) or ( $provided_hostid > 999 ) or ( strlen( $provided_hostid ) > 3 ) or ( strval( intval( $provided_hostid ) ) != strval( $provided_hostid ) ) ) {
  problem("Host id is not in the correct range \"${provided_hostid}\"");
}
logextra( "host id length is fine" );

$query = "SELECT COUNT(hostid) AS count_hostid FROM hosts WHERE hostid='$provided_hostid'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["count_hostid"]) ) {
    problem( "No result count returned for this hostid:\"${provided_hostid}\"" );
  }
  $count_hostid = $db["count_hostid"];
  if ( $count_hostid === 0 ) {
    problem( "No result returned for this query \"$query\"" );
  }
}

$host_id = $provided_hostid;

logextra( "Host ID was found \"$host_id\"" );

// Check Host Name

$provided_host_name = urldecode( $decoded_json["host_name"] );

if ( empty( $provided_host_name ) or strlen( $provided_host_name ) < 2 or strlen( $provided_host_name ) > 50 ) {
  problem("host_name length is not correct");
}

$query = "SELECT host FROM hosts WHERE hostid='$host_id'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["host"]) ) {
    problem( "No result host name returned for this host_id:\"${host_id}\"" );
  }
  $db_host_name = $db["host"];
}
logextra( "Host name has been found in db: \"$db_host_name\"" );

if ( $provided_host_name != $db_host_name ) {
  problem("Provided host_name \"$provided_host_name\" and db_host_name \"$db_host_name\" don't match.");
}

$host_name = $provided_host_name;

logextra( "Host ID was found \"$host_name\"" );

// Check Host Lisence

$provided_host_license = urldecode( $decoded_json["host_license"] );

if ( empty($provided_host_license) or strlen($provided_host_license) < 4 or strlen($provided_host_license) > 11 ) {
  problem("host_license length is not fine");
}
logextra( "host_license length is fine" );

$query = "SELECT short_name FROM licenses WHERE short_name = '$provided_host_license'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["short_name"]) ) {
    problem( "No result returned for this short_name:\"${provided_host_license}\"" );
  }
}

$host_license = $provided_host_license;

logextra( "host_license is a valid value \"${host_license}\"" );

// Check Episode Date

$provided_ep_date = urldecode( $decoded_json["ep_date"] );

if ( !preg_match( "/^\d{4}-\d{2}-\d{2}$/", $provided_ep_date ) ) {
  problem("ep_date fails the regex match \"${provided_ep_date}\"");
}

if ( strtotime( $provided_ep_date ) === false ) {
  problem("ep_date didn't convert to date \"${provided_ep_date}\"");
}
$ep_date_epoch = strtotime( $provided_ep_date );

$ep_date = $provided_ep_date;
logextra( "ep_date checkes passed: $ep_date, $ep_date_epoch" );

// Check Host Profile

$provided_host_profile = urldecode( $decoded_json["host_profile"] );

if ( strlen( $provided_host_profile ) > 2000 ) {
  problem("host_profile is not the correct length");
}
logextra( "host_profile is correct length" );

$host_profile = $provided_host_profile;

// Check Host email

$provided_email = urldecode( $decoded_json["email"] );

if ( empty( $provided_email ) or ( strlen( $provided_email ) > 100 ) ) {
  problem("Host email is not in the correct length \"${provided_email}\"");
}
logextra( "host email length is fine" );

if (!filter_var($provided_email, FILTER_VALIDATE_EMAIL)) {
  problem("Host email is not in the correct format. \"${provided_email}\"");
}
logextra( "host email passes validation $provided_email" );

$query = "SELECT COUNT(email) AS count_email FROM hosts WHERE email='$provided_email'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["count_email"]) ) {
    problem( "The email address is not in the database:\"${provided_email}\"" );
  }
  $count_email = $db["count_email"];
  if ( $count_email === 0 ) {
    problem( "No result returned for this query \"$query\"" );
  }
}

$email = $provided_email;
logextra( "Host email was found in the database \"$email\"" );

// Confirm the provided Host ID, hostname and email match in the db.

$query = "SELECT COUNT(hostid) AS count_hostid FROM hosts WHERE hostid='$host_id' AND host = '$host_name' AND email='$provided_email'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty($db["count_hostid"]) ) {
    problem( "The email address is not in the database:\"${provided_email}\"" );
  }
  $count_hostid = $db["count_hostid"];
  if ( $count_hostid === 0 ) {
    problem( "No result returned for this query \"$query\"" );
  }
}

logextra( "Host email and host id were found in the database \"$host_id\", \"$host_name\", \"$email\", " );

// Check Duration

$provided_duration = urldecode( $decoded_json["duration"] );

if ( empty( $provided_duration ) or $provided_duration < 120 or $provided_duration > 43200 ) {
  problem("Duration id is not in the correct range");
}
logextra( "Duration length is fine" );

$duration = $provided_duration;

logextra( "Duration was found \"$duration\"" );

// Check Episode Number

$provided_ep_num = intval( urldecode( $decoded_json["ep_num"] ) );

if ( !isset( $provided_ep_num ) ) {
  problem("ep_num is not set ");
}

if ( empty( $provided_ep_num ) ) {
  problem("ep_num is empty ");
}

// SELECT MAX(ep_num) FROM `reservations` → 3627
// SELECT MIN(ep_num) FROM `reservations` WHERE ep_num > 0 → 3582

$result = mysqli_query($connection, 'SELECT MAX(ep_num) FROM `reservations`;');
if (!isset($result)) {
  problem("Can't get max eps from reservations");
}

$max_eps_array = mysqli_fetch_row( $result );
$max_eps = $max_eps_array[0];
mysqli_free_result($result);

$result = mysqli_query($connection, 'SELECT MIN(ep_num) FROM `reservations` WHERE ep_num > 0;');
if (!isset($result)) {
  problem("Can't get min eps from reservations");
}
$min_eps_array = mysqli_fetch_row( $result );
$min_eps = $min_eps_array[0];
mysqli_free_result($result);

if ( $provided_ep_num < $min_eps ) {
  problem("ep_num is too small");
}

if ( $provided_ep_num > $max_eps ) {
  problem("ep_num is too big");
}

if ( intval($provided_ep_num) === 9999 ) {
  problem("ep_num is a reserved show 9999");
}

if ( intval($provided_ep_num) === 0 ) {
  problem("ep_num is 0");
}

$ep_num = intval($provided_ep_num);

// Workflow Check
// SHOW_SUBMITTED → SHOW_POSTED → MEDIA_TRANSCODED → UPLOADED_TO_IA → UPLOADED_TO_RSYNC_NET

$result = mysqli_query($connection, "SELECT ep_num FROM reservations WHERE ep_num='$ep_num' AND status='SHOW_SUBMITTED';");
if (!isset($result)) {
    problem("Cant get info from reservations db");
}
$db_ep_num_array = mysqli_fetch_row( $result );
$db_ep_num = $db_ep_num_array[0];
mysqli_free_result($result);

if ( $db_ep_num != $ep_num ){
    problem("Cant find $ep_num with status of SHOW_SUBMITTED");
}

$query = "SELECT COUNT(id) AS count_id FROM eps WHERE id = '$ep_num'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  $count_id = $db["count_id"];
  if ( $count_id != 0 ) {
    problem( "$count_id An existing episode has been posted with this episode id:\"${ep_num}\"" );
  }
}

logextra( "The episode ID \"$ep_num\" has not already been assigned" );

/////////////////////////////////////////////////////////////////////////
// Update database - Actual Changes

// Update host_profile

$query = "SELECT profile FROM hosts WHERE hostid = '$host_id' and host = '$host_name'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}

$db = mysqli_fetch_array($result, MYSQLI_ASSOC);

if ( $db["profile"] != "$host_profile" ) {
  logextra("The host_profile is different to that in the db");
  $host_profile = mysqli_real_escape_string( $connection, $host_profile );
  $query = "UPDATE `hosts` SET `profile` = '$host_profile' WHERE `hosts`.`hostid` = '$host_id';";
  $result = mysqli_query($connection, $query );
  if (!isset($result)) {
    problem("could not update the host profile");
  } else {
    logextra( "Updating the host profile" );
  }
}
logextra( "The profile is the same to that in the db" );

// Update license

$query = "SELECT license FROM hosts WHERE hostid = '$host_id' and host = '$host_name'";
$result = @mysqli_query($connection, $query);
if($result === FALSE) {
  problem( "No result returned for this query \"$query\"" );
}
else {
  $db = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if ( empty( $db["license"] ) ) {
    problem( "No result returned for this license:\"${provided_episode_license}\"" );
  }
}

$db_license = $db["license"];
if ( strcmp( $host_license, $db_license ) !== 0 ) {
  logextra("The host_license \"$host_license\" is not the same to that in the db \"$db_license\"");
  $host_license = mysqli_real_escape_string( $connection, $host_license );
  $query = "UPDATE `hosts` SET `license` = '$host_license'  WHERE `hosts`.`hostid` = '$host_id';";
  $result = mysqli_query($connection, $query );
  if (!isset($result)) {
    problem("could not update the host license");
  } else {
    logextra( "Updating the host license" );
  }
}
else {
  logextra( "The host_license is the same to that in the db \"$host_license\"" );
}

$title = mysqli_real_escape_string( $connection, $title );
$summary = mysqli_real_escape_string( $connection, $summary );
$notes = mysqli_real_escape_string( $connection, $notes );
$tags = mysqli_real_escape_string( $connection, $tags );

$query_add = "INSERT INTO eps VALUES ('$ep_num', '{$ep_date}', '{$title}', '{$duration}', '{$summary}', '{$notes}', '{$host_id}', '{$series_id}', '{$explicit}', '{$episode_license}', '{$tags}', '0', '0', '0')";
$result = mysqli_query($connection, $query_add );
if(!$result) {
  problem("DB problem - The show $ep_num was not added to the eps db.");
}
if (mysqli_errno( $connection )) {
  $error = "MySQL error ".mysqli_errno( $connection ).": ".mysqli_error()."\n";
  problem("MySQL error- The show $ep_num was not added to the eps db.\n$error");
}

logextra( "Added the entry: $query_add" );

$result = mysqli_query($connection, "SELECT `id` FROM `eps` WHERE `id` = '$ep_num';");
if (!isset($result)) {
  problem("DB problem - The show $ep_num has not been added to the eps db");
}
$db_ep_num_array = mysqli_fetch_row( $result );
$db_ep_num = $db_ep_num_array[0];
mysqli_free_result($result);
if (mysqli_errno( $connection )) {
  $error = "MySQL error ".mysqli_errno( $connection ).": ".mysqli_error()."\n";
  problem("MySQL error- The show $ep_num was not added to the eps db.\n$error");
}

$result = mysqli_query($connection, "UPDATE reservations SET `status` = 'SHOW_POSTED' WHERE `ep_num` = '$ep_num' AND status='SHOW_SUBMITTED';" );
if (!isset($result)) {
  problem("DB problem - The show $ep_num has not been added to the eps db");
}
if (mysqli_errno( $connection )) {
  $error = "MySQL error ".mysqli_errno( $connection ).": ".mysqli_error()."\n";
  problem("Could not update the show status to SHOW_POSTED in the db");
}

logextra( "Finished $ep_num ." );
?>
