<?php 

// upload_audio.php
// RJM Programming
// March, 2017 

$types = array("audio/wav","audio/x-wav","audio/x-pn-realaudio","audio/x-mpegurl","audio/x-aiff","audio/mpeg","audio/mid",
      "audio/basic","audio/ogg","video/x-sgi-movie","video/x-msvideo","video/quicktime","audio/mp3","video/mp4","video/mpeg",
      "video/x-la-asf","video/ogg","video/webm","audio/mp4");  
$exts = array(".wav",".wav",".ram",".m3u",".aiff",".mp3",".rmi",
      ".snd",".ogg",".movie",".avi",".mov",".mp3",".m4v",".mpeg",
      ".lsx",".ogv",".webm",".m4a"); 

$ourmime="audio/wav";
$htmlis="";
$dvideoaudiosdisplay="block";
if (!isset($_POST['dvideoaudios'])) $dvideoaudiosdisplay="none";
$dlinksdisplay="block";
if (!isset($_POST['dlinks'])) $dlinksdisplay="none";

if (isset($_GET['mediafile'])) {
 if (strpos(urldecode($_GET['mediafile']),".") !== false) {  
  $parts=explode(".",urldecode($_GET['mediafile']));
  $uparts=explode("/",urldecode($_GET['mediafile']));
  for ($it=0; $it<sizeof($exts); $it++) {
    if ("." . $parts[-1 + sizeof($parts)] == $exts[$it]) $ourmime=$exts[$it];
  } 
  header('Content-Type: ' . $ourmime);
  if (isset($_GET['download'])) {
    header('Content-Disposition: attachment; filename="' . $uparts[-1 + sizeof($uparts)] . '"');
  } else {
    header('Content-Disposition: inline');
  }
  echo file_get_contents(urldecode($_GET['mediafile']));
  exit;
 }
} else {
 $htmlis.="<!doctype html>
<html>
<head>
<title>Upload Audio/Video File - RJM Programming - http:/" . "/www.rjmprogramming.com.au</title>
<script type='text/javascript'>

  var tois='',bt='?',at=':',sofar='';

  function fix_jmymobile(plugthisin,beforethis,afterthis) {
    var isok=true;
    var oi=document.getElementById('jmymobile');
    var oival=oi.value;
    var oivals=oival.split(beforethis);
    var ojvals=oivals[0].split(afterthis);
    if (beforethis == '?') isok=false;
    if (beforethis == '?' && plugthisin.indexOf('@') > 0) {
      isok=true;
    }
    if (isok) {
      sofar=ojvals[0] + afterthis + plugthisin + oival.replace(oivals[0],'');
      oi.value=sofar;
      document.getElementById('mymobile').value=sofar;
      if (tois != '' && (document.getElementById('mydurl').value == '' || document.getElementById('mydurl').value != null) && sofar.indexOf(':@') == -1 && sofar.indexOf('@?') == -1 && sofar.indexOf(':?') == -1) {
        document.getElementById('emailsubmit').style.display='block';
      } else if (tois != '' && sofar.indexOf(':@') == -1 && sofar.indexOf('@?') == -1 && sofar.indexOf(':?') == -1) { 
        document.getElementById('fclick').click();
      }
    }
    if (beforethis == '?' && plugthisin.indexOf('@') > 0) {
      tois=plugthisin;
    }
  }

  
  function readBlob(opt_startByte, opt_stopByte) {

    var files = document.getElementById('files').files;
    if (!files.length) {
      alert('Please select a file!');
      return;
    }

    file = files[0];
    filen = file.name;
    var start = parseInt(opt_startByte) || 0;
    var stop = parseInt(opt_stopByte) || file.size - 1;

    var reader = new FileReader();

    /" . "/ If we use onloadend, we need to check the readyState.
    reader.onloadend = function(evt) {
      if (evt.target.readyState == FileReader.DONE) { /" . "/ DONE == 2
        document.getElementById('byte_content').textContent = evt.target.result;
        document.getElementById('byte_range').textContent = 
            ['Read bytes: ', start + 1, ' - ', stop + 1,
             ' of ', file.size, ' byte file'].join('');
        document.getElementById('mydurl').value=evt.target.result;
        fix_jmymobile(tois,bt,at); 
      } 
    };

    var blob = file.slice(start, stop + 1);
    /" . "/reader.readAsBinaryString(blob);
    reader.readAsDataURL(blob);
  }
"; 
}

$ext=".mp3";
$mimetype="application/octet-stream";
$mediatype="audio/wav";
$whichmedia="audio";
      
//Check to determine if the home button has been pressed  
    if(isset($_POST['home'])){  
      header('Location: index.html');
    }
    else
    {

  //Define some variables  
      $dir = dirname(__FILE__)."/uploads/"; 
      //$types = array("image/jpg","image/jpeg");  

//Check to determine if the submit button has been pressed  
    if (isset($_POST['submit']) || isset($_POST['emailsubmit'])) {  


    if (in_array($_FILES['upload']['type'], $types)) {  
        for ($it=0; $it<sizeof($types); $it++) {
          if ($_FILES['upload']['type'] == $types[$it]) $ext=$exts[$it];
          if ($_FILES['upload']['type'] == $types[$it]) $mediatype=$types[$it];
          if ($_FILES['upload']['type'] == $types[$it]) $whichmedia=explode("/",$types[$it])[0];
          if ($_FILES['upload']['type'] == $types[$it]) $mimetype="application/" . explode("/",str_replace("mp4","quicktime",str_replace("mov","quicktime",$types[$it]))[1]);
        }   
    }
//Shorten Variables  
     $tmp_name = $_FILES['upload']['tmp_name'];  
     
 $firstnum = 0;
 $lastbit = sprintf("%ld", $firstnum);
 $realbit = $lastbit . "a" . $ext; //jpg";
 $lastbit .= "" . $ext; //jpg";
 
 while (file_exists($dir.$lastbit) || file_exists($dir.$realbit)) {
  $firstnum += 1;
  $lastbit = sprintf("%ld", $firstnum);
  $realbit = $lastbit . "a" . $ext; //jpg";
  $lastbit .= "" . $ext; //jpg";
 }
 
 $sra = $_SERVER["REMOTE_ADDR"];
 //echo "sra=".$sra;
 if ($sra == '' || $sra == '//' || $sra == '::' || str_replace('.','',$sra) == $sra) {
   $sra = $_SERVER['HTTP_CLIENT_IP'];
   //echo "xsra=".$sra;
 }
 
 $firstnum = 0;
 $iprealbit = '0_'.$sra."" . $ext; //jpg";
 
 while (file_exists($dir.$iprealbit)) {
  $firstnum += 1;
  $iprealbit = sprintf("%ld_", $firstnum);
  $iprealbit .= $sra;
  $iprealbit .= "" . $ext; //jpg";
 }

 $upfile = $dir.$lastbit;
 $urldir="http://www.rjmprogramming.com.au/ephemeral/uploads/";
     
     $new_name = $realbit;   
     
     //$new_name = $_FILES['upload']['name'];  

//Check MIME Type  
    if (in_array($_FILES['upload']['type'], $types) && file_exists($dir) && filesize($tmp_name) <= floor($_POST['MAX_FILE_SIZE'])) {  
                     
         //Move file from tmp dir to new location  

        move_uploaded_file($tmp_name,$dir . $iprealbit);  
        copy($dir . $iprealbit,$dir . $new_name);  

if (isset($_POST['ddownloads']) && isset($_POST['diframes'])) {
 $htmlis.="</script>
</head>
<body onload=\" document.getElementById('recall').src=document.URL.split('#')[0].split('?')[0] + '?mediafile=' + encodeURIComponent('uploads/" . basename($dir . $new_name) ."');  document.getElementById('drecall').src=document.URL.split('#')[0].split('?')[0] + '?download=y&mediafile=' + encodeURIComponent('uploads/" . basename($dir . $new_name) ."'); \" style='background-color: lightblue;'><iframe id='recall' name='recall' style='display:block;' src='about:blank'></iframe><iframe id='drecall' name='drecall' style='display:block;width:1px;height:1px;' src='about:blank'></iframe><table id='mytable'><tbody><tr>";
} else if (isset($_POST['diframes'])) {
 $htmlis.="</script>
</head>
<body onload=\" document.getElementById('recall').src=document.URL.split('#')[0].split('?')[0] + '?mediafile=' + encodeURIComponent('uploads/" . basename($dir . $new_name) ."'); \" style='background-color: lightblue;'><iframe id='recall' name='recall' style='display:block;' src='about:blank'></iframe><table id='mytable'><tbody><tr>";
} else if (isset($_POST['ddownloads'])) {
 $htmlis.="</script>
</head>
<body onload=\" document.getElementById('drecall').src=document.URL.split('#')[0].split('?')[0] + '?download=y&mediafile=' + encodeURIComponent('uploads/" . basename($dir . $new_name) ."'); \" style='background-color: lightblue;'><iframe id='drecall' name='drecall' style='display:block;width:1px;height:1px;' src='about:blank'></iframe><table id='mytable'><tbody><tr>";
} else {
 $htmlis.="</script>
</head>
<body style='background-color: lightblue;'><table id='mytable'><tbody><tr>";
} 

        
        $body=@file_get_contents($dir . $new_name);
        $filename=basename($dir . $new_name);
        

if (isset($_POST['emailsubmit'])) {
if (isset($_POST['mode']) && strpos($_SERVER['SERVER_NAME'], "rjmprogramming.com.au") !== false) {
  if ($_POST['mode'] != '') { // && isset($_POST['mydurl'])) {

    if (isset($_POST['mymobile'])) {
     if ($_POST['mymobile'] != "") {
      $mtm = urldecode($_POST['mymobile']);
      $tos = explode("?", $mtm);
      $to = str_replace("mailto:", "", $tos[0]);
      $subjects = explode("&", $tos[1]);
      $subject = str_replace("subject=", "", $subjects[0]);
      //$body = ($_POST['mydurl']);
      $eol = PHP_EOL;
      $headers = 'From: ' . 'rmetcalfe@rjmprogramming.com.au' . $eol;
      $headers .= 'Reply-To: ' . 'rmetcalfe@rjmprogramming.com.au' . $eol;
      
      //$fname = explode(";", $body);
      //$filename=str_replace("quicktime", "mp4", str_replace("/", ".", str_replace("data:", "", $fname[0]))); 
      //$filename="media.html";
    		$content = chunk_split(base64_encode($body));
    		//$uid = md5(uniqid(time()));

    		// a random hash will be necessary to send mixed content
    		$separator = md5(time());

    		$headers .= "MIME-Version: 1.0" . $eol;
    		$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
    		$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    		$headers .= "This is a MIME encoded message." . $eol . $eol;

    		// message
    		$headers .= "--" . $separator . $eol;
    		$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    		$headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;

    		$headers .= "Please see attachment below:" . $eol . $eol;
    		
            //ourpremail($tem, $mysubject, "", $headers . "--" . $separator . "--");

    		// attachment
    		$headers .= "--" . $separator . $eol;
    		$headers .= "Content-Type: " . $mimetype . "; name=\"" . $filename . "\"" . $eol;
    		$headers .= "Content-Transfer-Encoding: base64" . $eol;
    		$headers .= "Content-Disposition: attachment;filename=\"" . $filename . "\"" . $eol;
    		$headers .= $content . $eol . $eol;
    		
    		$headers .= "--" . $separator . "--";
    		
      mail($to, $subject, "", $headers);
     }
    }
   
  }
} 
}
        if (strpos($htmlis,"</script>") === false) $htmlis.="</script></head><body style='background-color: lightblue;'><table id='mytable'><tbody><tr>";
        
            
        echo $htmlis . "<td style='vertical-align:top;'><iframe name='myiframe' id='myiframe' src='about:blank' style='display:none;'></iframe>
              <div style='display:" . $dlinksdisplay . ";'><a id='mya' style='display:" . $dlinksdisplay . ";font-size:26px;' target='myiframe' 
              onclick=\" document.getElementById('myiframe').style.display='block'; location.href='#mytable';   \" title='Upload' 
              href='" . $urldir . explode("/",$new_name)[-1 + sizeof(explode("/",$new_name))] . "'>" . $_FILES['upload']['name'] . "</a>" . 
              " was uploaded successfully!</div><br><" . $whichmedia . " style='display:" . $dvideoaudiosdisplay . ";' controls><source type='" . $mediatype . "' src='" . $urldir . explode("/",$new_name)[-1 + sizeof(explode("/",$new_name))] . "'></" . $whichmedia . "><br></td>";  
        $toaddr = "rmetcalfe@rjmprogramming.com.au";
        $subj = "Ephemeral audio upload via ".$sra." called "."http://www.rjmprogramming.com.au/ephemeral/uploads/".$iprealbit;
        $cont = "http://www.rjmprogramming.com.au/ephemeral/uploads/".$realbit;
        $hdrs = "From: rmetcalfe@rjmprogramming.com.au"."\r\n";
        //unlink($dir . $iprealbit);
        mail($toaddr, $subj, $cont, $hdrs);
            
    } else {  
       if (strpos($htmlis,"</script>") === false) $htmlis.="</script></head><body style='background-color: lightblue;'><table id='mytable'><tbody><tr>";
                     //Print Error Message  
       echo $htmlis . "<td><small>" . sizeof($_FILES) . " File <strong><em>{$_FILES['upload']['name']}</em></strong> Was Not Uploaded!</small><br /></td>";  
           //Debug  
       $name =  $_FILES['upload']['name'];  
       $type =    $_FILES['upload']['type'];  
       $size =    $_FILES['upload']['size'];  
       $tmp =     $_FILES['upload']['name'];  
       echo "<td>Name: $name<br/ >Type: $type<br />Size: $size<br />Tmp: $tmp" . "</td>";  
    }  
        
    } else {   
        if (strpos($htmlis,"</script>") === false) $htmlis.="</script></head><body style='background-color: lightblue;'><table id='mytable'><tbody><tr>";
        echo $htmlis . '<td>Could Not Upload Files</td>';        
}  
}
        ?>  
<td style="vertical-align:top;"><br><br>
<form style="font-size:34px;background-color: #E4E4E4;" 
 action="<?php echo explode('?',explode('#',$_SERVER['PHP_SELF'])[0])[0] . '?random=' . rand(); ?>" 
 method="post" enctype="multipart/form-data">          
      <fieldset>  
           <legend>Upload Audio/Video "RJM Programming" file(s) (<= 3,000,000 bytes) - Everybody Welcome ... but keep it fairly short!</legend>  
           <input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
           <input onclick=" if (tois != '' && sofar.indexOf(':@') == -1 && sofar.indexOf('@?') == -1 && sofar.indexOf(':?') == -1) {  if (1 == 2) { document.getElementById('myspan').style.display='block'; } document.getElementById('emailsubmit').style.display='block'; } document.getElementById('submit').style.display='inline';  document.getElementById('dmodes').style.display='inline';  " 
           style="font-size:26px;height:60px;background-color: yellow;" 
           type="file" id="files" name="upload" accept="video/*,audio/*" capture></input>  
      </fieldset>
<span id='myspan' style='display:none;' class="readBytesButtons">
  <button style='display:none;' data-startbyte="0" data-endbyte="4">1-5</button>
  <button style='display:none;' data-startbyte="5" data-endbyte="14">6-15</button>
  <button style='display:none;' data-startbyte="6" data-endbyte="7">7-8</button>
  <button style='background-color:pink;'>Email this Audio/Video</button>
</span>
<div style='display:none;' id="byte_range"></div>
<div style='display:none;' id="byte_content"></div>
      <p>Fill out all fields below to email your content, before clicking above to create Audio/Video:</p>
      <input name='mode' type='hidden' value='y'></input>
      <input id='jmydurl' name='mydurl' type='hidden' value=''></input>
      To: <input onblur="fix_jmymobile(this.value,'?',':');" name='to' type='email' value='' style='width:300px;'></input></br>
      Subject: <input onblur="fix_jmymobile(encodeURIComponent(this.value),'&body=','?subject=');" name='subject' type='text' value='My Audio/Video Share ... which you may need to download ...' style='width:300px;'></input></br>
      <input name='mymobile' id='jmymobile' type='hidden' value='mailto:@?subject=My%20Audio%2FVideo%20Share%20...%20which%20you%20may%20need%20to%20download%20...&body='></input></br>
      <input id='submit' style="font-size:36px;color: green;display:none;" type="submit" name="submit" 
      value="Upload Audio/Video Files" /> <div style='display:none;' id='dmodes'> Links: <input type='checkbox' name='dlinks' id='dlinks' checked></input> Audio/Video Controls: <input type='checkbox' name='dvideoaudios' id='dvideoaudios' checked></input> Downloads: <input type='checkbox' name='ddownloads' id='ddownloads' checked></input> Iframe: <input type='checkbox' name='diframes' id='diframes' checked></input></div> 
      <input onclick="if (1 == 2) { document.getElementById('fclick').click(); } " name='emailsubmit' id='emailsubmit' style="font-size:36px;color: green;display:none;" type="submit"  
      value="Email Audio/Video Files" />  
      <!--input style="color: red;" type="submit" name="home" value="Reload Home Page..." /-->  
</form></td></tr></tbody></table>
<form style='display:none;' id='myform' method='POST' enctype='application/x-www-urlencoded' action="<?php echo explode('?',explode('#',$_SERVER['PHP_SELF'])[0])[0]; ?>" target='myiframetwo'>
<!--form style='display:none;' id='myform' method='POST' action='http://www.rjmprogramming.com.au/HTMLCSS/camera_api.php' target='myiframetwo'-->
<input id='mydurl' name='mydurl' type='hidden' value=''></input>
<input id='mymobile' name='mymobile' type='hidden' value=''></input>
<input id='mode' name='mode' value='y'></input>
<input id='fclick' type='submit' value='Email'></input>
</form>
<iframe style='display:none;' id='myiframetwo' name='myiframetwo' src='http://www.rjmprogramming.com.au/ephemeral/upload_helper.php'></iframe>

<script type='text/javascript'>
  
  document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
    //alert(0);
    if (evt.target.tagName.toLowerCase() == 'button') {
    //alert(1);
      var startByte = evt.target.getAttribute('data-startbyte');
      var endByte = evt.target.getAttribute('data-endbyte');
      readBlob(startByte, endByte);
    }
  }, false);

</script>
</body>
</html>
