#!/usr/bin/perl
use strict 'refs';
use lib '..';
use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser/;

my $cgi = CGI->new;
$msg = $cgi->param('msg');

if($credentials{'srfile'}) {
  die "$credentials{'username'} is not authorized to use this service\n";
  exit;
}

  open my $fh, "</usr/local/web/filemanager.conf";
  @basedirs = <$fh>;
  close $fh;

  open my $fh, "<$credentials{'home'}/.web/filemanager.conf";
  my @userdirs = <$fh>;
  close $fh;
  if($userdirs[0] =~ /!/)
  {
    shift @userdirs;
    @basedirs = @userdirs;
  }
  else
  {
    push @basedirs, @userdirs;
  }

  @basedirs = grep($_ !~ /^$/, @basedirs);
  my %dirs;
  grep
  {
    chomp $_;
    my ($key, $value) = split " ", $_, 2;
    $key =~ s/^\~/$credentials{'home'}/;
    $key =~ s/\/$//;
    $key =~ s/(.*)/$1/;
    $dirs{$key} = ($value || $dirs{$key} || $key);
    $_ = $key;
  } @basedirs;
    
$currentdir = $cgi->param('currentdir');

if(! grep
     {
       my $bd = $_;
       my $ret = 0;
       if($currentdir =~ /^($bd(\/.*)?)$/)
       {
         $currentdir = $1;
	 $ret = 1;
       }
       $ret;
     } @basedirs )
{ $currentdir = $basedirs[0]; }

#if(grep($currentdir =~ /^$_/, @basedirs))
#{
#  #ok
#}
#else
#{
#  $currentdir = $basedirs[0];
#}

if (my $file = $cgi->param('filename')) {
  if($currentdir =~ /(.*)/){$currentdir = $1;}
  $fixedfile = $file; $fixedfile =~ s/^.*[\\\/]//g;
  if("$currentdir/$fixedfile" =~ /(.*)/){$fixedfile = $1;}
  if(open my $fh, ">$fixedfile")
  {
    my $line;
    while(read($file, $line, 1024 * 10))
    {
      print $fh $line;
    }
    close $fh;
    $msg = $fixedfile." uploaded.";
  }
  else
  {
    $msg = "Could not create file $fixedfile: $!.";
  }
}

if($folder = $cgi->param('newfolder')) {
  $fixedfolder = $folder; $fixedfolder =~ s/^.*[\\\/]//g;
  if("$currentdir/$fixedfolder" =~ /(.*)/){$fixedfolder = $1;}
  if(mkdir "$fixedfolder")
  {
    $msg = "$fixedfolder created.";
  }
  else
  {
    $msg = "Error creating folder $fixedfolder.";
  }
}

if($folder = $cgi->param('deletedir')) {
  $fixedfolder = $folder; $fixedfolder =~ s/^.*[\\\/]//g;
  if(!(rmdir "$currentdir/$fixedfolder")){
    $msg="Error deleting $fixedfolder.  Might not be empty.";
  }
  else {$msg="$fixedfolder deleted.";}
}

if($file = $cgi->param('deletefile'))
{
  $fixedfile = $file; $fixedfile =~ s/^.*[\\\/]//g;
  if("$currentdir/$fixedfile" =~ /(.*)/){$fixedfile = $1;}
  if(!(unlink "$fixedfile")){
    $msg="Error deleting $fixedfile.";
  }
  else {$msg = "$fixedfile deleted.";}
}

if($file = $cgi->param('unzip')) {
  if($currentdir =~ /(.*)/){$currentdir = $1;}
  $fixedfile = $file; $fixedfile =~ s/^.*[\\\/]//g;
  if($fixedfile =~ /(.*)/){$fixedfile = $1;}
  chdir $currentdir;
  open my $fh, "/usr/bin/unzip -o $fixedfile|";
  @filedata = <$fh>;
  close $fh;
  @filedata = grep($_ =~ /^    /g, @filedata);
  $msg = join "<br>\n", @filedata;
}  

if((! -d $currentdir) || $currentdir =~ /\.\./g)
{ $msg = "Invalid Directory $currentdir";
  $currentdir = $basedirs[0];
}

if($cgi->param('action') eq "download")
{
  my $file = $currentdir."/".$cgi->param('file');
  if($file =~ /(.*)/){$file = $1;}
  
  my $ct = `/usr/bin/file -bi \"$file\"`;
  chomp $ct;
  my @stat = stat $file;
  print "Content-type: $ct\n".
  "Cache-Control: no-cache\n".
  "Content-disposition: inline; filename=".$cgi->param('file')."\n".
  "Content-length: $stat[7]\n\n";
  open my $fh, "<$file" or die "$file: $!";
  while(my $line = <$fh>)
  { print $line; }
  close $fh;
  exit;
}

opendir my $dh, $currentdir;
my @files = readdir $dh;
closedir $dh;

@files = grep(/^[^\.]/, @files);

@files = sort {uc($a) cmp uc($b)} @files;
my @list = @files;

@files = grep(-f "$currentdir/$_", @files);
@list = grep(-d "$currentdir/$_", @list);

my $output =
"Content-type: text/html\n\n".
"<html>\n".
" <head>\n".
"  <title>Splitreflection File Manager</title>\n".
" </head>\n".
" <body>\n".
" <b>Available Filesystems</b><br />\n";

my $subdir = $currentdir;
my $dirhead;
while(my ($key, $value) = each %dirs)
{
  $output .=
  "<a href='?currentdir=$key'>$value</a><br/>\n";
  if($subdir eq $currentdir)
  {
    if($subdir =~ s/^$key//)
    { $dirhead = $key; }
  }
}

$output .=
"<b><font color=#0000ff>$msg</font></b><br>\n".
"<b>Current directory - <a href='?currentdir=$dirhead'>$dirhead</a>";

grep
{
  if($_)
  {
    $dirhead .= "/$_";
    $output .= "/<a href='?currentdir=$dirhead'>$_</a>";
  }
} split "/", $subdir;

$output .= "</b>\n".
"<table border=1 cellspacing=0 height=0><tr><td valign='top'>\n<table>\n";
grep
{
  if($cgi->param('deletemode'))
  {
    $output .=
    "<tr><td><a href='?currentdir=$currentdir/$_'><img src='/pub/icons/dir_dir.gif' border=0>$_</a> </td><td align='right'><a href='?currentdir=$currentdir&deletedir=$_'><img src=/pub/icons/dir_del.gif border=0>Delete</a></td></tr>\n";
  }
  else 
  {
    $output .= "<tr><td><a href='?currentdir=$currentdir/$_'><img src='/pub/icons/dir_dir.gif' border=0>$_</a></td></tr>\n";
  }
} @list;

$output .=
"</table></td><td valign='top'>\n<table>\n";

print $output;

grep
{
  my @stat = stat "$currentdir/$_";
  $stat[9] = &time2text($stat[9]);
  my $icon = "misc";
  if($_ =~ /\.gif$|\.jpe?g$/i){ $icon = "img"; }
  if($_ =~ /\.html?$/i){ $icon = "htm"; }
  if($_ =~ /\.zip$/i){ $icon = "zip"; }
  my $url = "?action=download&currentdir=$currentdir&file=".&text2href($_);
  if($currentdir =~ /([^\/]*)\/public_html(.*)/)
  { $url = "http://www.splitreflection.com/~$1$2/$_"; }
  if($currentdir =~ /^\/home\/websites\/([^\/]+)\/htdocs(.*)/)
  { $url = "http://www.$1$2/$_"; }

  my $output = 
  "<tr><td><a href='$url'><img src='/pub/icons/dir_$icon.gif' border=0>$_</a></td>".
  "<td align='right'>";
  if($cgi->param('deletemode'))
  {
    $output .= "<a href='?currentdir=$currentdir&deletefile=".&text2href($_)."'><img src=/pub/icons/dir_del.gif border=0>Delete</a></td></tr>\n";
  }
  else
  {
    if($_ =~ /\.zip$/)
    {
      $output .= "$stat[7]</td><td align='right'>$stat[9]</td><td><a href='?currentdir=$currentdir&unzip=$_'>unzip</a></td></tr>\n";
    }
    else
    {
      $output .= "$stat[7]</td><td align='right'>$stat[9]</td></tr>\n";
    }
  }
  print $output;
} @files;

print 
    "</td></tr>".
    "</table>\n</td></tr valign='top'>\n</table>\n";
if($cgi->param('deletemode'))
{
  print "<a href='?currentdir=$currentdir'>Switch to normal mode</a>";
}
else 
{
  print "<a href='?currentdir=$currentdir&deletemode=yes'>Switch to delete mode</a>";
}

# Start a multipart form.
print
    start_multipart_form().
    filefield('filename','',45).
    "<input type='hidden' name='currentdir' value='$currentdir'>".
    submit('submit','Upload File'). endform.
    start_multipart_form().
    textfield('newfolder', '',45).
    "<input type='hidden' name='currentdir' value='$currentdir'>".
    submit('folder', 'Create Folder').
    endform.
    hr().
    end_html;

exit;

sub href2text {
  my $line = join "", @_;
  while($line =~ /%([0-9A-Fa-f][0-9A-Fa-f])/){
    my $char = chr(hex($1));
    $line =~ s/%$1/$char/g;
  }
return $line;
}

sub text2href {
  my $percent = sprintf "%%%x", ord "%";
  my $line = join "", @_;
  $line =~ s/%/$percent/g;

  while($line =~ /([^a-zA-Z0-9%\\\]])/){
    my $char = sprintf "%%%x", ord $1;
    $line =~ s/[$1]/$char/g;
  }
return $line;
}

sub time2text
{
  my @wday = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
  my @month = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
  my $time = shift;
  my @ltime = localtime($time);
  $ltime[5] += 1900;
  my $m = "AM";
  if($ltime[2] >= 12){ $m = "PM"; }
  $ltime[2] %= 12;
  $ltime[2] ||= 12;
  return "$wday[$ltime[6]] $month[$ltime[4]] $ltime[3] $ltime[5] ".sprintf("%02d:%02d:%02d",$ltime[2],$ltime[1],$ltime[0])." $m";
}

