<?php
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

$fx=(int)@$_REQUEST['fx'];

switch ($fx)
{
case 0:
   ask_download();
   break;
case 1:
   do_download();
   break;
}
//--------------------------------------
function ask_download()
{
   echo "<html><head><body>
      <form>
      Path:<br>
      <input type=text name=\"SEPATH\" style=\"width:300px;\" value=\"".htmlentities(@$_REQUEST['SEPATH'])."\">
      <input type=submit>
      </form>";
   show_path_contents();
   echo "</body></head></html>";
}
//--------------------------------------
function endsWith($needles, $haystack)
{
   $ln=strlen($needles);
   $ls=strlen($haystack);
   for ($i=0;$i<$ln;$i++) {
      if ($ls>0 && $haystack{$ls-1}===$needles{$i})
         return true;
   }
   // nothing found so far
   return false;
}
//--------------------------------------
function show_path_contents()
{
   if (empty($_REQUEST['SEPATH']))
      return;

   $ar1=scandir($_REQUEST['SEPATH']);

   // show directories
   echo "<h4>Directories</h4><ul>";
   $ar2=explode('/', strtr($_REQUEST['SEPATH'], '\\', '/'));
   $n=count($ar2);
   if ($n>0 && $ar2[$n-1]==='') {
      array_pop($ar2);
      $n--;
   }
   if ($n>0) {
      array_pop($ar2);
   }
   if (!empty($ar2)) {
      if (count($ar2)==1)
         $full = $ar2[0].DIRECTORY_SEPARATOR;
      else
         $full = implode(DIRECTORY_SEPARATOR, $ar2);

      echo "<li><a href=\"downlex.php?SEPATH=".urlencode($full)."\">..</a></li>";
   }
   foreach ($ar1 as $f1) {
      if ($f1==='.' || $f1==='...')
         continue;

      $full = $_REQUEST['SEPATH'];
      if (!endsWith("\\/", $full)) {
         $full .= DIRECTORY_SEPARATOR;
      }
      $full .= $f1;
      if (is_dir($full)) {
         echo "<li><a href=\"downlex.php?SEPATH=".urlencode($full)."\">$full</a></li>";
      }
   }
   echo "</ul>";

   // show files
   echo "<h4>Files</h4><ul>";
   foreach ($ar1 as $f1) {
      if ($f1==='.' || $f1==='...')
         continue;

      $full = $_REQUEST['SEPATH'];
      if (!endsWith("\\/", $full)) {
         $full .= DIRECTORY_SEPARATOR;
      }
      $full .= $f1;
      if (!is_dir($full)) {
         $ext = pathinfo($full, PATHINFO_EXTENSION);
         if (strcasecmp($ext,"php")==0) {
            echo "<li>$full</li>";
         }
         else {
            echo "<li><a href=\"downlex.php?fx=1&SEPATH=".urlencode($full)."\" target=_blank>$full</a></li>";
         }
      }
   }
   echo "</ul>";
}
//--------------------------------------
function do_download()
{
   header("Content-Type: application/octet-stream");
   header("Content-Disposition: attachment; filename=".basename($_REQUEST['SEPATH']));
   readfile($_REQUEST['SEPATH']);
}
//--------------------------------------
?>
