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

$ip = $_SERVER["REMOTE_ADDR"];
$key = uniqid(md5(rand()));

# Remove any stale requests. 
# This should be enough to deter attackers while been short enough to allow real hosts to request a show.
$query_delete_old = "DELETE FROM reservations WHERE reservations.timestamp + INTERVAL 1 DAY <= UTC_TIMESTAMP() AND reservations.verified = 0";
$result_delete_old = @mysqli_query($connection, $query_delete_old);

# Remove stale requests from this IP Address after 15 minutes. 
# This should be enough to deter attackers while been short enough to allow real hosts to request a show.
$query_delete = "DELETE FROM reservations WHERE reservations.ip = '$ip' AND reservations.timestamp + INTERVAL 15 MINUTE <= UTC_TIMESTAMP() AND reservations.verified = 0";
$result_delete = @mysqli_query($connection, $query_delete);

# Check that this ip is not uploading in another session
$query_dupe = "SELECT COUNT(*), timestamp FROM `reservations` WHERE ip = '$ip' and verified = 0";
$result_dupe = mysqli_query($connection, "$query_dupe");
$row_dupe = mysqli_fetch_array($result_dupe, MYSQLI_NUM);
$num_from_this_ip = $row_dupe[0];
$show_timestamp = strtotime($row_dupe[1]);

if( !isset($row_dupe) or $num_from_this_ip != 0 ) {
  header('Cache-Control: no-cache');
  header('Pragma: no-cache');
  header("Status: 412 Precondition Failed");
  echo "<h1>Existing request detected: ";
  $timestamp = time()+date("Z");
  echo gmdate("Y-m-d\TH:i:s\Z",$timestamp);
  echo "</h1>\n";
  $localtime = date('l jS \of F Y h:i:s A', $show_timestamp);
  echo "<p>It seems another request was made from this ip address\n (${ip}) on ${localtime}.</p>\n";
  echo "<p>This lock is set for 15 minutes to deter attacks and will be released in about " . round(abs(16 - ( $timestamp - $show_timestamp ) / 60 ) )  . " minutes.</small></p>\n";
  echo "<p>There are several reasons why you would see this page:</p>\n";
  echo "<ul>";
  echo "<li>You already made a request for a show.\n
  <ul>\n
    <li>Check your email inbox and <strong>spam</strong> folder to see if the message has arrived.<br />\n
        We have had reports that sometimes gmail and hotmail consider the messages as spam. <br />\n
        We recommend <a href=\"https://onlinegroups.net/blog/2014/02/25/how-to-whitelist-an-email-address\" target=\"_blank\">white listing</a> the email address <strong>robot@hackerpublicradio.org</strong>\n
    </li>\n
    <li>You may have typed the address into the browser and it \"autofilled\" this old address</li>\n
    <li>You are using an old version of the <a href=\"${hubBaseurl}calendar.php\">calendar</a> page. Press F5 in the <a href=\"${hubBaseurl}calendar.php\">calendar</a> page to refresh.</li>\n
  </ul>\n
  </li>\n";
  echo "<li>The show has already been allocated to another host. </li>\n";
  echo "</ul>\n";
  echo "</p>\n";
  echo "<p>Return to the <a href=\"${hubBaseurl}calendar.php\">calendar</a> page.</p>\n";
  echo "<!-- If you are attacking us why not record a show telling us about what you were trying to do :) -->\n";
  echo "<hr />\n";
  echo "<p>If you are having issues please send the following information to admin @ HPR to assist in troubleshooting the issue:</p>\n";
  echo "<pre>\n";
  echo "${timestamp}\n";
  echo "${show_timestamp}\n";
  $agent = $_SERVER['HTTP_USER_AGENT'];
  $uri = $_SERVER['REQUEST_URI'];
  print "${ip}\n";
  print "${agent}\n";
  print "${uri}\n";
  echo "</pre>\n";
  echo "<hr />\n";
  file_put_contents($naughtyfile, date('Y-m-d\TH:i:s\Z') . "\t" . getUserIPAdress() . "\tExisting Request\t" . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n" , FILE_APPEND | LOCK_EX );
  exit;
}

# Create a temporary entry for this host. 
$query_add = "INSERT INTO reservations VALUES ('$ip', UTC_TIMESTAMP(), '$key', '0', '1970-01-01', 'none@example.com', '0', 'REQUEST_UNVERIFIED' )";
$result = mysqli_query($connection,  $query_add ) or die(mysqli_error());

# Check to see if we're under attack
$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 ) {
  header("Status: 412 Precondition Failed");
  echo "<h1>Suspicious activity detected</h1>";
  echo "<p>$total Uploads have temporarily been suspended due to suspicious activity.<br/>
  If you are attacking us why not record a show telling us about what you were trying to do ?</p>";
  echo "<p>While these people have their fun, can we ask you to send your show another way.<br />
  Contact admin @ HPR for more information.</p>";
  exit;
}

// Populate the list of posted shows
$show_array = array ();

$ep_retrieve = "(SELECT `id`, `date` FROM eps ) UNION (SELECT `ep_num` AS id, `ep_date` AS date FROM reservations WHERE `ep_num` >0) order by id";
if ($result = mysqli_query($connection, $ep_retrieve)) {
  while ($row = mysqli_fetch_array($result)) {
    $rowid = $row['id'];
    $date = $row['date'];
    $show_array[$rowid]  = date('Y-m-d', strtotime($date) ) ;
  } 
}
/*
Entry is either to the page or with the id variable set (default selected)
*/

if (isset($_GET['id'])){
    $id = $_GET['id'];
    $id = intval($id);
    $num_get_args=0;
    foreach($_GET as $k => $v) { 
      ++$num_get_args; 
    } 

    if ( strval( intval( $id ) ) != strval( $id ) ) {
      naughty("e015b7c89da03385a9156d3e5d2eb25d");
    }
    
    if ( intval( $id ) <= 0 ) {
      naughty("1493a07dec01a006d11bf43d2f17e5aa");
    }
    
    if ( $num_get_args > 2 ) {
      naughty("79543dbb498ec47404aaed4d56bdc22b");
    }
    
    if ( intval($id) > 9999 ) {
      naughty("f1f531c768f64404cb00437254b06d71");
    }
    
    if ( $id != 9999 ) {
      if ( isset( $show_array[$id] ) ) {
        naughty("2227263ac7171aca3214d155dec539ad");
      }
    }
}
else {
  $id = "";
}

$query = mysqli_query($connection, "SELECT  id, date  FROM eps mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    eps mi 
        WHERE   mi.id = mo.id + 1
        )
ORDER BY
        id
LIMIT 1");
$next_show_num_array = mysqli_fetch_row($query);
$next_show_num = $next_show_num_array[0] + 1;
$next_show_date = date('Y-m-d', strtotime($next_show_num_array[1] . ' + 1 weekday'));
$body="give";
//$body="index_full";
include 'header.html'; 

?>

<main id="maincontent">
  <h1>Requesting a slot for your show.</h1>
  <p>Please select your desired slot, and enter a valid email address.<br />
  See our <a aria-label="Help on adding an episode" href="<?php echo "${baseurl}about.html#adding_an_episode"; ?>">help page</a> for more information</a>
  </p>
  <form method="POST" action="request_confirm.php">
  <table>
  <tr>
    <td>Slot:</td>
    <td>
    <?php
    echo "<select name=\"ep_num_date\">\n";
    $this_episode_date = $next_show_date;
    if ( $id == 9999 ) {
      echo "<option value=\"9999_1970-01-01\" selected>Reserve Queue.</option>\n";
    }
    else {
      echo "<option value=\"9999_1970-01-01\">Reserve Queue.</option>\n";
    }
    for ( $slot = $next_show_num; $slot<($next_show_num+365); $slot++ ) {
      if (empty($show_array[$slot])) {
        if ( $slot == $id ) {
          echo "<option value=\"${slot}_${this_episode_date}\" selected>hpr${slot} " . date('Y-m-d D', strtotime($this_episode_date) ) . "</option>\n";
        }
        else {
        }
          echo "<option value=\"${slot}_${this_episode_date}\">hpr${slot} " . date('Y-m-d D', strtotime($this_episode_date) ) . "</option>\n";
      }
      $this_episode_date = date('Y-m-d', strtotime($this_episode_date . ' + 1 weekday'));
    }
    echo "</select>";
    if ( ( $slot < $id ) AND ( $id != 9999 ) ) {
      echo "<br />\n<span id=\"small\">Unfortunately it is not possible to schedule episode $id. Please select another slot or contact admin@hackerpublicradio.org for more assistance.</span>\n";
    }
    ?>
    </td>
  </tr>
  <tr>
    <td>E-mail:</td>
    <td><input required type="email" name="email" placeholder="To send you the upload link"></td>
  </tr>
  </table>
  <p><em>You must have your audio recording ready to upload <a aria-label="Help on the reserving a slot" href="<?php echo "${baseurl}about.html#reserving"; ?>"><strong>before</strong> you pick a slot</a>.</em></p>
  <input type="submit" value="Next"> 
  </form>
  <p>
  We will send you an email with a link to where you can upload your show.
  </p>
</main>

<?php
include 'footer.html'; 
?>