<?php
// fileinfotable.php 
// Create table of information about filespec
// RJM Programming
// October, 2014

$iscalled = "";


function url_exists($url) {  // Thanks to http://stackoverflow.com/questions/2280394/how-can-i-check-if-a-url-exists-via-php
    $exists = false;
    if (strpos($url, "https:") !== false || strpos($url, "HTTPS:") !== false) {
     if (!$fp = curl_init($url)) return false;
     return true;
    } else if (strpos($url, "http:") !== false || strpos($url, "HTTP:") !== false) {
     $file = $url;
     $file_headers = @get_headers($file);
     if (strpos($file_headers[0], " 404 ") !== false) { // == 'HTTP/1.1 404 Not Found') {
      $exists = false;
     } else {
      $exists = true;
     }
   } else {
     $exists = file_exists($url);
   }
   return $exists;
}

   if (isset($_GET['fsp'])) {
     $iscalled = "y";
     $fsp = $_GET['fsp'];
   } else if (isset($_POST['fsp'])) {
     $iscalled = "y";
     $fsp = $_POST['fsp'];
   } else {
     $fsp = "*";
     $ext = ".xml";
   }
   
   if (isset($_GET['ext'])) {
     if ($iscalled == "") $fsp = "";
     $iscalled = "y";
     $ext = $_GET['ext'];
   } else if (isset($_POST['ext'])) {
     if ($iscalled == "") $fsp = "";
     $iscalled = "y";
     $ext = $_POST['ext'];
   } else if ($iscalled != "") {
     $ext = "";
   } 
         
   if (isset($_GET['dir'])) {
     $iscalled = "y";
     $dir = $_GET['dir'];
   } else if (isset($_POST['dir'])) {
     $iscalled = "y";
     $dir = $_POST['dir'];
   } else {
     $dir = '/Library/pgAgent/Downloads/CRL/';
   }
   
   if ($iscalled == "") {
    $outhtml = "<!DOCTYPE html>\n<html><head><title>File Information Table</title>\n";
    
    $outhtml .= '
<script type="text/javascript">
  var fcont="";
  var bigi=0;
  var wl="";
  var doneonce="";
  var presm="sm";
  
  function check(thisfordelim) {
    var outval = thisfordelim.value;
    if (outval.length > 0) {
      if ((outval + "@!@").indexOf(String.fromCharCode(47) + "@!@") == -1 && (outval + "@!@").indexOf(String.fromCharCode(92) + "@!@") == -1) {
        if (outval.indexOf(String.fromCharCode(92)) != -1) {
          outval = outval + String.fromCharCode(92);
          thisfordelim.value = outval;
        } else if (outval.indexOf(String.fromCharCode(47)) != -1) {
          outval = outval + String.fromCharCode(47);
          thisfordelim.value = outval;
        } else {
          outval = outval + String.fromCharCode(47);
          thisfordelim.value = outval;
        }
      }
    }
    return outval;
  }

  function readBlob(opt_startByte, opt_stopByte) {

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

    var file = files[0];
    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("");
        process(evt.target.result);
      }
    };

    var blob = file.slice(start, stop + 1);
    reader.readAsBinaryString(blob);
  }
  
  function doonload() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
  var iii=0;
} else {
  document.getElementById("files").style.display = "none";
  document.getElementById("file").style.display = "none";
  if (1 == 2) { alert("The File APIs are not fully supported in this browser."); }
}
  var ourf=location.search.split("myf=")[1] ? location.search.split("myf=")[1].split("&")[0] : ""; 
  document.body.innerHTML = document.body.innerHTML + decodeURIComponent(ourf);

  document.querySelector(' . "'.readBytesButtons'" . ').addEventListener(' . "'click'" . ', function(evt) {
    if (evt.target.tagName.toLowerCase() == "button") {
      var startByte = evt.target.getAttribute("data-startbyte");
      var endByte = evt.target.getAttribute("data-endbyte");
      readBlob(startByte, endByte);
    }
  }, false);
  
  document.getElementById("files").addEventListener("change", handleFileSelect, false);
  
  }
  
function process(infilecontents) {
         if (1 == 7) { alert(infilecontents); }
         var ourlines = infilecontents.split(String.fromCharCode(10)); 
         var ourwords = infilecontents.split(String.fromCharCode(32)); 
         var myfis = "<br><br><p id=myf align=center>Filename is <strong>" + escape(document.getElementById("file").files[0].mozFullPath + document.getElementById("file").value) + "</strong> ... Type is (" + (document.getElementById("file").files[0].type || "n/a") + ") ... Date is " + (document.getElementById("file").files[0].lastModifiedDate ? document.getElementById("file").files[0].lastModifiedDate.toLocaleDateString() : "n/a") + " ... Size is " + infilecontents.length + " bytes ... Line Count is " + ourlines.length + " ... Word Count is " + ourwords.length + "</p>";
         document.body.innerHTML = document.body.innerHTML + myfis;
         var huh = document.URL.split("?");
         if (huh.length > 1) {
           location.href = huh[0] + "?myf=" + decodeURIComponent(myfis);
         } else {
           location.href = document.URL + "?myf=" + decodeURIComponent(myfis);
         }
         fcont = infilecontents;
}


  function handleFileSelect(evt) {
    var ourcont="";
    var readers = new Array();
    var f;
    var thelines;
    var thewords;
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    var file; // = files[0];
    var start; // = parseInt(opt_startByte) || 0;
    var stop; // = parseInt(opt_stopByte) || file.size - 1;
    var blob; // = file.slice(start, stop + 1);
    

    document.getElementById("list").innerHTML = "";
    try {
     document.getElementById("xlist").innerHTML = "";
    } catch (exx) {
    }
   
    if (document.body.innerHTML.indexOf("my" + "res") == -1) {
      document.body.innerHTML = document.body.innerHTML + "<span id=my" + "res style=display:none;>~" + "~</span>";
    } else {
      document.getElementById("my" + "res").innerHTML = "~" + "~";
    }

    for (var i = 0, f; f = files[i]; i++) {
      bigi = eval(1 + i);
      file = f;
      start = 0;
      fcont = "";
      stop = file.size - 1;

      readers[readers.length] = new FileReader();
  
    // If we use onloadend, we need to check the readyState.
    readers[readers.length - 1].onloadend = function(evt) {
      if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        var xfcont=evt.target.result;
        var thoselines = xfcont.split(String.fromCharCode(10)); 
        var thosewords = xfcont.split(String.fromCharCode(32)); 
        if (document.body.innerHTML.indexOf("~" + "~") == -1) {
          document.body.innerHTML = document.body.innerHTML + "<span id=my" + "res style=display:none;>;" + bigi + "~" + thoselines.length + "~" + thosewords.length + "~" + "~</span>";
        } else {
          document.body.innerHTML = document.body.innerHTML.replace("~" + "~", ";" + bigi + "~" + thoselines.length + "~" + thosewords.length + "~" + "~");
        }
        var sofar = document.getElementById("my" + "res").innerHTML;
        var sofars = sofar.split(";");
        var sofarlw;
        for (var j=1; j<sofars.length; j++) {
          if (sofars[j] != "") {
            sofarlw = sofars[j].split("~");
            document.getElementById("l" + j).innerHTML = sofarlw[1];
            document.getElementById("w" + j).innerHTML = sofarlw[2];
          }
          document.getElementById("prelist").value = encodeURIComponent(document.getElementById("list").innerHTML);
        }
      }
    };
        

      output.push("<li>Filename is <strong>", escape(f.mozFullPath + f.name), "</strong> ... Type is (", f.type || "n/a", ") ... Date is ",
                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : "n/a", " ... Size is ", 
                  f.size, " bytes ... Line Count is <span id=l" + bigi + ">", "", "</span> ... Word Count is <span id=w" + bigi + ">", "", "</span>", 
                  "</li>");

      blob = file.slice(start, stop + 1);
      readers[readers.length - 1].readAsText(blob, "UTF-8");

    }
    document.getElementById("list").innerHTML = "<ul>" + output.join("") + "</ul>";
    document.getElementById("prelist").value = encodeURIComponent(document.getElementById("list").innerHTML);
    doneonce="y";
  }


</script>
';    
    
    $outhtml .= "</head>\n";
    $outhtml .= "<body style='background-color:yellow;' onload='doonload();'><h1 align='center'>File Information Table</h1><div align='center'><form style='background-color:lightgreen;' align='center' border=5 method='POST' action='" . $_SERVER['PHP_SELF'] . "'>";
    $outhtml .= "<input type='hidden' name='fsp' id='fsp' value=''></input><br>";
    $outhtml .= "Filepath (or  URL): <input size=120 type='text' name='dir' id='dir' value='" . $dir . "' onblur=' if (this.value.length > 0) {  check(this); }'></input><br><br>";
    $outhtml .= "Filespec (or Name): <input size=120 type='text' name='ext' id='ext' value='" . $fsp . $ext . "'></input><br><br>";
    $outhtml .= "<input type='submit' name='xsubmit' id='xsubmit' value='Submit'></input>";
    $outhtml .= "</form></div><div align='center' style='background-color:orange;'><br><br><h2>... or ...</h2>";
    $moi = $_SERVER['PHP_SELF'];
    if (1 == 1) {  // Thanks to http://www.html5rocks.com/en/tutorials/file/dndfiles/
    $outhtml .= '<input onmouseover=" if (doneonce.length > 0) { document.getElementById(presm).click();  } " type="file" id="files" name="files[]" multiple />';
    if (isset($_POST['prelist'])) { $outhtml .= '<div id="xlist" name="xlist">' . urldecode($_POST['prelist']) . '</div><br>' . '<output id="list" name="list"></output>'; } else { $outhtml .= '<output id="list" name="list"></output>';  } 
    $outhtml .= '
    <form id="myfx" name="myfx" style="display:none;" method="POST" action="./fileinfotable.php"><input type="hidden" name="prelist" id="prelist" value=""></input><input type="submit" name ="sm" id="sm" value="Presubmit"></input></form></div><div align="center" style="background-color:lightgray;"><br><br><h2>... or ...</h2><input type="file" id="file" name="file" />     Read bytes: 
<span class="readBytesButtons">
  <button data-startbyte="0" data-endbyte="4" style="display:none;">1-5</button>
  <button data-startbyte="5" data-endbyte="14" style="display:none;">6-15</button>
  <button data-startbyte="6" data-endbyte="7" style="display:none;">7-8</button>
  <button onclick="readBlob(0,0);">Process</button>
</span>
<div id="byte_range" style="display:none;"></div>
<div id="byte_content" style="display:none;"></div>
';
    } else {
    $outhtml .= '    
      <form style="background-color: #E4E4E4;" action="' . $moi . '" method="post" enctype="multipart/form-data">  
        
      <fieldset align="center">  
           <legend align="center">Browse for local file</legend>  
           <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
           <input style="background-color: yellow;" size="100" type="file" id="browsefile" name="browsefile" onchange="analyze();" />  
      </fieldset>  
      <input style="color: green;display:none;" type="submit" name="submit" value="Browse for File" />  
</form>
';
	}
    $outhtml .= "</div>";    
    $outhtml .= "</body></html>";
   } else {
    $outhtml = "<html><head><title>File Information Table for " . $dir . $fsp . $ext . "</title></head>\n";
    $outhtml .= "<body style='background-color:yellow;'><h1 align='center'>File Information Table for " . $dir . $fsp . $ext . "</h1><table style='background-color:lightgreen;' align='center' border=5 cellpadding=12 cellspacing=8><tr style='background-color:lightblue;'>";
    if ($dir == "") {
     $outhtml .= "<th><a href='./fileinfotable.php' title='Another go?'>Filename</a></th><th>Date</th><th>Size (bytes)</th><th>Lines</th><th>Words</th></tr>";
    } else {
     $outhtml .= "<th>Filename in <a href='./fileinfotable.php' title='Another go?'>" . $dir . "</a></th><th>Date</th><th>Size (bytes)</th><th>Lines</th><th>Words</th></tr>";
    }
    
    if (strpos($dir . $fsp . $ext, "https:") !== false || strpos($dir . $fsp . $ext, "http:") !== false || strpos($dir . $fsp . $ext, "HTTPS:") !== false || strpos($dir . $fsp . $ext, "HTTP:") !== false) {
      if (url_exists($dir . $fsp . $ext)) {
         $cdt = "";
         $cont = file_get_contents($dir . $fsp . $ext);
         $recs = explode("\n", $cont);
         $words = explode(" ", $cont);
		 $h = get_headers($dir . $fsp . $ext, 1); // Thanks to http://stackoverflow.com/questions/845220/get-the-last-modified-date-of-a-remote-file
         $cdt = "";
         try {
		   $cdt = $h['Last-Modified'];
		 } catch (Exception $exxx) {
		   $cdt = "";
		 }
		 $outhtml .= "<tr><td>" . str_replace($dir, "", $dir . $fsp . $ext) . "</td><td>" . $cdt . "</td><td>" . strlen($cont) . "</td><td>" . count($recs) . "</td><td>" . count($words) . "</td></tr>";
      }
    } else {
   
     foreach (glob($dir . $fsp . $ext) as $filename) {
      if (url_exists($filename)) {
        
         $lines = file($filename); 
         $cwords = 0;
         foreach ($lines as $line) {
          $cwords += str_word_count($line);
         }
         $outhtml .= "<tr><td>" . str_replace($dir, "", $filename) . "</td><td>" . date("F d Y H:i:s", filemtime($filename)) . "</td><td>" . filesize($filename) . "</td><td>" . count($lines) . "</td><td>" . $cwords . "</td></tr>";
        
      }
     }
    }
    $outhtml .= "</table></body></html>";
   }
   
   echo $outhtml;
?>
