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

## Recent Change
# Support for WYSIWYG https://github.com/slab/quill  BSD-3-Clause license 

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

if ( $_SERVER['REQUEST_METHOD'] !== 'GET' and empty($_SERVER["REMOTE_ADDR"]) and count($_GET) !== 1 ) {
  call412("9a77e4ab24410cbf68a3a05ba97221e4 Not a GET request");
}

logextra( "Is a GET Request" );

if ( isset( $_GET['key'] ) and strlen( $_GET['key'] ) ===  45  and strlen( htmlspecialchars( stripslashes( strip_tags( $_GET['key'] ) ) ) ) ===  45 and ctype_xdigit( $_GET['key'] ) ) {
  $key = htmlspecialchars( stripslashes( strip_tags( $_GET['key'] ) ) );
}
else {
  if ( isset( $_GET['delete'] ) and strlen( $_GET['delete'] ) ===  45  and strlen( htmlspecialchars( stripslashes( strip_tags( $_GET['delete'] ) ) ) ) ===  45 and ctype_xdigit( $_GET['delete'] ) ) {
    $key = htmlspecialchars( stripslashes( strip_tags( $_GET['delete'] ) ) );
    logextra( "Is delete request" );
  }
  else {
    call412("e8ac90fc2a8996e5fb7a83e73e636e80 Invalid key");
  }
}

logextra( "Key is valid" );

$ip = $_SERVER["REMOTE_ADDR"];

$query = "select * FROM reservations WHERE reservations.ip = '$ip' AND reservations.key = '$key' ";
$result = mysqli_query($connection, $query);
if($result === FALSE) {
  call412("91432866e3c9c36a9c4884345d578761 Could not find ip=\"$ip\" AND key=\"$key\" in the database. Did your IP address change ? Was the removed after 15 Munites ?");
}
logextra( "Found ip=\"$ip\" AND key=\"$key\" in the database" );

$db = mysqli_fetch_array($result, MYSQLI_ASSOC);
if ( empty($db) or empty( $db['timestamp'] ) or empty( $db['key'] ) or empty( $db['ep_num'] ) or empty( $db['ep_date'] ) or empty( $db['email'] ) ) {
  call412("b019bd29c1fe5b756e4b620a5428f730 The information for this reservation is not correct in the database.");
}
else {
  $db_timestamp = $db['timestamp'];
  $db_key = $db['key'];
  $email_padded = formatemail($db['email']);
  $email = unformatemail($db['email']);
  $ep_num = $db['ep_num'];
  $ep_date = $db['ep_date'];
  $db_ip = $db['ip'];
  $status = $db['status'];
}

logextra( "The information for this reservation is correct in the database." );

// User selects delete
if ( isset( $_GET['delete'] ) ) {
  $query = "DELETE FROM reservations WHERE reservations.ip = '$ip' AND reservations.key = '$key' ";
  $result = mysqli_query($connection, $query);
  if($result === FALSE) {
    call412("35a7f4e80ecba8284049e9d6261ae523 Could not remove the reservation.");
  }
  else {
    header( "Location: ${hubBaseurl}calendar.php" ) ;
    $dir_structure = "/home/hpr/upload/" . strtotime($db_timestamp) . "_${ep_num}_${ep_date}_${db_key}/";
    rrmdir("$dir_structure");
    logextra( "Removed the reservation" );
    exit;
  }
}

logextra( "Not a delete" );

if ( empty($status) ) {
  naughty("317be55a55a82110b2836499580be486 did not find a status \"$status\" in the db.");
}

logextra( "Found the status $status" );

if ($status !== 'REQUEST_EMAIL_SENT' && $status !== 'EMAIL_LINK_CLICKED') {
  naughty("65743c3fb8a2e171f56ec514ec45c1bc The status \"$status\" is not expected, should be REQUEST_EMAIL_SENT or EMAIL_LINK_CLICKED in the db.");
}
logextra( "The status \"$status\" is expected, should be either REQUEST_EMAIL_SENT or EMAIL_LINK_CLICKED." );
  
// Set the show to verified so that we can remove the temporary lock
$status = strtotime("now") . ".EMAIL_LINK_CLICKED." . date('Y-m-d\TH:i:s\Z');
$query = "UPDATE reservations SET `verified` = '1', `status` = 'EMAIL_LINK_CLICKED' WHERE `ip` = '$db_ip' AND `timestamp` = '$db_timestamp' AND `key` = '$db_key'";
$result = mysqli_query($connection, $query );
if(!isset($result)) {
  naughty("066c518314f0d3b1ad3e4af60fcf36ce Could not change status to EMAIL_LINK_CLICKED");
}

logextra( "Updated status to EMAIL_LINK_CLICKED" );

// Display host information
/*
*/

$ip = $_SERVER["REMOTE_ADDR"];
# TODO need to add the email for new hosts
$query = "SELECT * FROM hosts WHERE hosts.email = '$email' OR hosts.email = '$email_padded'";
$result = mysqli_query($connection, $query);
if($result === FALSE) {
  call412("5cb513b590ab5859bf7603b79402a5cb Could not find a host with email=\"$email\"");
}
$db = mysqli_fetch_array($result, MYSQLI_ASSOC);
if ( empty($db) or empty( $db['hostid'] ) or empty( $db['host'] ) or empty( $db['email'] ) ) {
  $hostid = "0";
  $host = "";
  $profile = "";
  $license = "CC-BY-SA";
  $local_image = 0;
  $status = "Please fill in some information about yourself.";
}
else {
  $hostid = $db['hostid'];
  $host = $db['host'];
  $profile = $db['profile'];
  $license = $db['license'];
  $local_image = $db['local_image'];
  $email_padded = formatemail($db['email']);
  $email = unformatemail($db['email']);
  $status = "Please confirm or change the following information about yourself.";
}

$image_url = "./images/hosts/${hostid}.png";
if ( !file_exists( $image_url )) {
  $image_url = 'https://secure.gravatar.com/avatar/' . md5($email) . '.png&d=404';
}

// Main

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

?>

<body>
<link href="quill.snow.2.0.3.css" rel="stylesheet"> 
<script src="quill.2.0.3.js"></script>
  <?php 
  if ( $ep_num == 9999 ) {
    echo "<h2>Uploading to the reserve pool.</h2>\n";
  }
  else {
    echo "<h2>Uploading hpr${ep_num} for release on ${ep_date}</h2>\n";
  }
  ?>
  <p>
  You can fill in information about yourself and your show below.
  Please see the "<em><a href="<?php echo "${referrerurl}contribute.html#uploading_an_episode"; ?>" target="_blank">Uploading an Episode help page</a></em>" for more information.
  </p>
  <h2><?php echo $status ?></h2>
  <form method="POST" action="upload_confirm.php" enctype="multipart/form-data">
  <table class="upload">
    <tr>
      <td>Host Email (<a href="<?php echo "${referrerurl}contribute.html#profile_email"; ?>" target="_blank">?</a>):</td>
      <td><?php echo $email;?></td>
    </tr>
    <tr>
      <td>Image: (<a href="<?php echo "${referrerurl}contribute.html#profile_image"; ?>" target="_blank">?</a>)</td>
      <td>
      <?php 
      echo "<img src=\"$image_url\" alt=\"host image\" /><br /><small><em>";
      if ( $local_image === 1 ) {
        echo "Image previously uploaded";
      }
      else {
        echo "Image sourced from <a href=\"https://secure.gravatar.com\">gravatar</a>";
      }
      ?>
      </em></small><br />
      Upload your photo/avatar here: <input type="file" name="host_photo" id="photo">      
      </td>
    </tr>
    <tr>
      <td><strong>Name/Handle: (<a href="<?php echo "${baseurl}contribute.html#profile_name_handle"; ?>" target="_blank">?</a>)</strong></td>
      <td><input required type="text" name="host_name" size="40" maxlength="40" placeholder="Enter the name you wish to be know as on HPR" value="<?php echo $host?>"></td>
    </tr>
    <tr>
      <td><strong>Your Default license: (<a href="<?php echo "${baseurl}contribute.html#profile_default_license"; ?>" target="_blank">?</a>)</strong></td>
      <td>
      <select name="host_license">
        <option value="CC-0" <?php if($license == "CC-0") echo "selected"; ?>>CC-Zero/Public Domain (CC-0)
        <option value="CC-BY" <?php if($license == "CC-BY") echo "selected"; ?>>Attribution (CC-BY)
        <option value="CC-BY-SA" <?php if($license == "CC-BY-SA") echo "selected"; ?>>Attribution-ShareAlike (CC-BY-SA)
      </select>
      </td>
    </tr>
    <tr>
      <td>Profile: (<a href="<?php echo "${baseurl}contribute.html#profile"; ?>" target="_blank">?</a>)</td>
      <td>
        <noscript>
          <textarea name="host_profile" maxlength="2000" rows="10" cols="50" placeholder="Enter some text about yourself with links to your blog or other online presence."><?php echo htmlspecialchars($profile) ?></textarea>
        </noscript>
        <div id="editor_profile" name="host_profile"></div>
      </td>
    </tr>
  </table>
  
  
  <h2>Please fill in some information about this episode</h2>
  <table class="upload">
    <tr>
      <td><strong>Title(*) (<a href="<?php echo "${referrerurl}contribute.html#episode_title"; ?>" target="_blank">?</a>):</strong></td>
      <td><input required type="text" name="title" size="50" maxlength="100" placeholder="Enter a short descriptive title for your show."></td>
    </tr>
    <tr>
      <td><strong>Summary(*) (<a href="<?php echo "${referrerurl}contribute.html#episode_short_summary"; ?>" target="_blank">?</a>):</strong></td>
      <td><input required type="text" name="summary" size="70" maxlength="100" placeholder="This is a short 100 character summary of what your show is about."></td>
    </tr>
    <tr>
      <td><strong>Explicit: (<a href="<?php echo "${referrerurl}contribute.html#episode_explicit"; ?>" target="_blank">?</a>)</strong></td>
      <td>
        Is the show <em>Explicit</em> ?:
        <input required type="radio" name="explicit" value="Yes">Yes 
        <input type="radio" name="explicit" value="Clean">No. 
        <small>If in doubt please select <strong>Yes</strong>. See <a href="https://www.apple.com/uk/itunes/podcasts/specs.html#submitting">iTunes</a> for more information.</small>
      </td>
    </tr>
    <tr>
      <td><strong>License: (<a href="<?php echo "${referrerurl}contribute.html#episode_license"; ?>" target="_blank">?</a>)</strong></td>
      <td>
        <select name="license">
            <option value="CC-BY-SA" selected>CC-BY-SA</option>
            <option value="CC-0" >CC-0</option>
            <option value="CC-BY" >CC-BY</option>
            <option value="Other" >Other</option>
        </select>
        <small>See <a href="https://creativecommons.org/licenses/">https://creativecommons.org/licenses/</a> for more information.</small>
      </td>
    </tr>
    <tr>
      <td><strong>Notes(*) (<a href="<?php echo "${referrerurl}contribute.html#episode_show_notes"; ?>" target="_blank">?</a>):</strong></td>
      <td>
        <noscript>
          <textarea required name="notes" maxlength="40000" rows="20" cols="70" placeholder="Please add your show notes here." ></textarea>
        </noscript>
        <div id="editor_notes" name="notes"></div>
      </td>
    </tr>
    <noscript>
      <tr>
        <td>Format: (<a href="<?php echo "${referrerurl}contribute.html#shownotes_format"; ?>" target="_blank">?</a>)</td>
        <td>
          <small>What format if any did you just use in the show notes above ?</small><br />
          <select name="shownotes_format">
              <option value="plain_text" selected>Plain text</option>
              <option value="html5">HTML5 (Preferred)</option>
              <option value="Markdown_GitHub">Markdown (GitHub flavoured)</option>
              <option value="Markdown_Pandoc">Markdown (Pandoc flavoured)</option>
              <option value="restructured_text">RestructuredText</option>
              <option value="txt2tags">txt2tags</option>
          </select>
        </td>
      </tr>
    </noscript>
    <tr>
      <td>Series: (<a href="<?php echo "${referrerurl}contribute.html#episode_series"; ?>" target="_blank">?</a>)</td>
      <td>
        <?php
        $result = mysqli_query($connection, "SELECT id, name FROM miniseries WHERE private=0 ORDER BY name ASC");
        echo "<select name=\"series\"><option value=\"0\" selected>none</option>";
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            printf("<option value=\"{$row['id']}\">{$row['name']}</option>");
        }
        mysqli_free_result($result);
        ?>
        </select>
      </td>
    </tr>
    <tr>
      <td>Tags: (<a href="<?php echo "${referrerurl}contribute.html#episode_tags"; ?>" target="_blank">?</a>)</td>
      <td><input required type="text" name="tags" size="70" maxlength="100" placeholder="Add a list of comma separated tags." /><br />
      Add a list of <strong>comma separated</strong> tags.<br />
      If you can provide tags for your show that would be appreciated; you are certainly the best judge of what makes good tags, but if not then a volunteer will add them later.
      </td>
    </tr>
    <tr>
      <td><strong>Upload Method: (<a href="<?php echo "${referrerurl}contribute.html#episode_upload_method"; ?>" target="_blank">?</a>)</strong></td>
      <td>
        <em>You have the choice of the following upload options:</em> <br />
        <p>
        <strong>1. Upload now</strong> via this browser: (<a href="<?php echo "${referrerurl}contribute.html#episode_upload_method_browser"; ?>" target="_blank">?</a>)<br />
        <input type="file" multiple="multiple" name="media_files[]" title="select if using the http upload option" />
        </p>
        <p>
        <strong>2. Provide a url</strong> we we can directly download it from: (<a href="<?php echo "${referrerurl}contribute.html#episode_upload_method_url"; ?>" target="_blank">?</a>)<br />
        This must be accessable using a curl or wget command.<br />
        Please avoid services that require login or downloading via a browser.<br />
        <input type="url" size="30"  name="url" placeholder="https://example.com/hpr9999.flac">
        </p>
      </td>
    </tr>
  </table>
  <?php echo "<input type=\"hidden\" name=\"hostid\" value=\"$hostid\">"; ?>
  <?php echo "<input type=\"hidden\" name=\"key\" value=\"$key\">"; ?>
  <script>
    document.write(`<?php echo "<input type=\"hidden\" name=\"shownotes_format\" value=\"html5\">"; ?>`);
  </script>
  <br />
  <input type="submit" name="submit_edit" value="Submit"> This will take a <strong>long time</strong>, leave the browser running. You will get an email once the upload is complete.
  <?php 
  if ( $ep_num == 9999 ) {
    echo "<p>\n<em><a href=\"https://" . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . "?delete=$key\">Delete this reservation for the reserve pool</a>.</em>\n</p>\n"; 
  }
  else {
    echo "<p>\n<em><a href=\"https://" . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . "?delete=$key\">Delete this reservation for hpr${ep_num} on ${ep_date}</a>.</em>\n</p>\n"; 
  }
  
  ?>
  <div id="progressbar">
    <div></div>
  </div>

  <script>
  const toolbarOptions = [
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],
    ['link', 'image'],
    ['clean']                                         // remove formatting button
  ];
  
  const quill_profile = new Quill('#editor_profile', {
    modules: {
      toolbar: toolbarOptions
    },
    placeholder: 'Enter your personal profile here...',
    theme: 'snow'
  });
  const form_profile = document.querySelector("form");
    
  quill_profile.root.innerHTML = `<?php echo $profile ?>` .replace(/(<ul>|<ol>|<\/li>)(?:[\s]+)(<li>|<\/ul>|<\/ol>)/g, '$1$2');
  
  form_profile.addEventListener("formdata", (event) => {
    event.formData.append("host_profile", quill_profile.root.innerHTML);
  });

  // const quill = new Quill('#editor_notes', {
  //   modules: {
  //     toolbar: toolbarOptions
  //   },
  //   placeholder: 'Enter your show notes here...',
  //   theme: 'snow'
  // });
  // const form = document.querySelector("form");
  // form.addEventListener("formdata", (event) => {
  //   event.formData.append("notes", quill.root.innerHTML);
  // });
  
  const quill = new Quill('#editor_notes', {
    modules: {
      toolbar: toolbarOptions
    },
    placeholder: 'Enter your show notes here...',
    theme: 'snow'
  });

  function prettyPrintHTML(html) {
    const doc = new DOMParser().parseFromString(html, 'text/html');
    return doc.body.innerHTML
      .replace(/&nbsp;/g, ' ')
      .replace(/></g, '>\n<');
  }

  const form = document.querySelector('form');
  
  form.addEventListener('submit', function (event) {
    const text = quill.getText().trim();

    if (text.length < 30) {
      event.preventDefault();
      alert('You must provide shownotes');
    }
  });
  
  form.addEventListener('formdata', event => {
    const rawHTML = quill.getSemanticHTML();
    const prettyHTML = prettyPrintHTML(rawHTML);
    event.formData.append('notes', prettyHTML);
  });
  
  </script>
  </form>
<?php
logextra( "Form displayed" );
include 'footer.php'; 
?>
