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

$msg = param('msg');

if (param('logout'))
{ %credentials=('name', '', 'pass', '');
  $the_cookie = cookie(-name=>'splitreffile',
		     -path=>"/",
		     -value=>\%credentials,
		     -expires=>'+4h',
                     -secure=>"secure");
  $msg =~ s/ /%20/g;
  print header(-cookie=>$the_cookie),
    "<META HTTP-EQUIV='REFRESH' CONTENT='0; URL=/cgi-bin/upload.pl?msg=$msg'>";
  exit
}
else{if (param('name'))
{
  %credentials=("name", param('name'), "pass", param('pass'));

  $the_cookie = cookie(-name=>"splitreffile",
		     -path=>"/",
		     -value=>\%credentials,
		     -expires=>"+4h",
                     -secure=>"secure");

  # Print the header, incorporating the cookie and the expiration date...
  print header(-cookie=>$the_cookie),
    "\n\n<META HTTP-EQUIV='REFRESH' CONTENT='0; URL=/cgi-bin/upload.pl?currentdir=".param('currentdir')."'>";
  exit;
}
else
{
  %credentials = cookie('splitreffile');
  $the_cookie = cookie(-name=>"splitreffile",
		     -path=>"/",
		     -value=>\%credentials,
		     -expires=>"+4h",
                     -secure=>"secure");

#  print header();
}}

#%credentials = cookie('splitreffile');
  print header(-cookie=>$the_cookie);

open PASSWD, '/usr/local/apache/passwd.txt';
@password = <PASSWD>;
close PASSWD;

$uname = $pword = '%%%%%%%%%%%%%';

until ($uname eq $credentials{'name'} && $pword eq $credentials{'pass'}) { 
  my $line;
  if(!($line = pop @password) || $credentials{'name'}.$credentials{'pass'} eq "") {
    print "<html><head>\n<title>Splitreflection File System Login",
    "</title>\n<body>\n",
    "<font color=#0000FF><b>".$msg."</b></font>\n",
    h1("Enter your username/password."),"\n",
    "<form method='post' action='/cgi-bin/upload.pl?currentdir=$currentdir'>",
    "Username ",textfield('name'),"<br>\n",
    "Password ","<input type='password' name='pass'><input type='hidden' name='currentdir' value='$currentdir'><br>",
    submit,
    end_form,
    hr;

    print end_html;
    exit;
  }
  $line =~ s/[\r\n]//g;
  ($uname, $pword, $services) = split ":", $line;
}
  $credentials{'services'} = $services;
  my @list = split ";", $services;
  grep {
    my $key = my $value = $_;
    $key =~ s/=.*$//g;
    $value =~ s/^.*=//g;
    $credentials{$key} = $value;
  } @list;

  if(!$credentials{'file'}) {
    print "You are not authorized to use this service\n";
    exit;
  }

  $basedir = $credentials{'file'};
    

#$cred = $credentials{"name"}.':'.$credentials{"pass"};

#$pass = join "\n", @password;
$currentdir = param('currentdir');

#$cred =~ s/[^a-zA-Z0-9:]//g;

$dirsep = "/";
$webbasedir=$basedir;
$webbasedir =~ s/\/usr\/local\/apache\/htdocs//g;
$currentdir =~ s/[\\\/]/$dirsep/g;
if($currentdir !~ /^$dirsep/g){$currentdir =~ s/^/$dirsep/g;}
if($currentdir eq "/") {$currentdir = ""; }

if (my $file = param('filename')) {
  $fixedfile = $file; $fixedfile =~ s/^.*[\\\/]//g;
  $tmpfile=tmpFileName($file);
  open INFILE, ">".$basedir.$currentdir."$dirsep".$fixedfile;
  print INFILE <$file>;
  close INFILE;
  $msg = $fixedfile." uploaded.";
}

if($folder = param('newfolder')) {
  $fixedfolder = $folder; $fixedfolder =~ s/^.*[\\\/]//g;
  mkdir $basedir.$currentdir.$dirsep.$fixedfolder;
  $msg = "$fixedfolder created.";
}

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

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

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

if (param('checklinks')) { &checklinks; }

$parent = $currentdir;
$parent =~ s/$dirsep[^$dirsep]*$//g;
if($parent !~ /^$dirsep/g){$parent =~ s/^/$dirsep/g;}

while((!opendir(CDIR, $basedir.$currentdir) || $currentdir =~ /[.][.]/g) && $currentdir)
{ $msg = 'Invalid Directory';
  $currentdir = $parent;
  $parent = $currentdir;
  $parent =~ s/$dirsep[^$dirsep]*$//g;
}
@list = readdir CDIR;
closedir(CDIR);

opendir(CDIR, $basedir.$currentdir);
@files = readdir CDIR;
closedir(CDIR);

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

@list = grep {@fstats = stat($basedir.$currentdir."$dirsep".$_);
             @fstats[2] & 16384} @list;

@files = grep {@fstats = stat($basedir.$currentdir."$dirsep".$_);
             $fsize{$_} = @fstats[7];
             @filetime = localtime(@fstats[9]);
             $ftime{$_} = @filetime[2].":".@filetime[1].":".@filetime[0]." ".(@filetime[4]+1)."/".@filetime[3]."/".(@filetime[5]+1900);
             !(@fstats[2] & 16384)} @files;

#grep {@fstats = stat($basedir.$currentdir."$dirsep".$_);
#      $fsize{$_} = @fstats[7];
#      $ftime{$_} = @fstats[9];} @files;

if(param('deletemode')) {
  @list = grep($_ !~ /^[.]*$/g && $_ !~ /^_.*/g &&
    $_ =~ s/^.*$/<tr><td><a href="upload.pl?currentdir=$currentdir$dirsep$_"><img src='\/icons\/dir_dir.gif' border=0>$_<\/a> <\/td><td align='right'><a href="upload.pl?currentdir=$currentdir&deletedir=$_"><img src=\/icons\/dir_del.gif border=0>Delete<\/a><\/td><\/tr>/g &&
    ($_ =~ s/$dirsep$dirsep/$dirsep/g || 1), @list);
}
else {
  @list = grep($_ !~ /^[.]*$/g && $_ !~ /^_.*/g &&
    $_ =~ s/^.*$/<tr><td><a href="upload.pl?currentdir=$currentdir$dirsep$_"><img src='\/icons\/dir_dir.gif' border=0>$_<\/a><\/td><\/tr>/g 
    && ($_ =~ s/$dirsep$dirsep/$dirsep/g || 1), @list);
}
if(param('deletemode')) {
  @files = grep($_ !~ /^[.]*$/g && $_ !~ /^_.*/g, @files);
  @files = grep{
    $_ = "<tr><td><a href=\"$webbasedir$currentdir/".&text2href($_)."\"><img src='/icons/dir_misc.gif' border=0>$_</a> </td><td align='right'><a href=\"upload.pl?currentdir=$currentdir&deletefile=".&text2href($_)."\"><img src=/icons/dir_del.gif border=0>Delete</a></td></tr>";
  } @files;
    
}
else {
  @files = grep($_ !~ /^[.]*$/g && $_ !~ /^_.*/g &&
    (($_ =~ /\.zip/g && $_ =~ s/^.*$/<tr><td><a href="$webbasedir$currentdir\/$_"><img src='\/icons\/dir_misc.gif' border=0>$_<\/a><\/td> <td align='right'>$fsize{$_}<\/td><td align='right'>$ftime{$_}<\/td><td><a href='upload.pl?currentdir=$currentdir&unzip=$_'>unzip<\/a><\/td><\/tr>/g) ||
    ($_ =~ s/^.*$/<tr><td><a href="$webbasedir$currentdir\/$_"><img src='\/icons\/dir_misc.gif' border=0>$_<\/a><\/td> <td align='right'>$fsize{$_}<\/td><td align='right'>$ftime{$_}<\/td><\/tr>/g)) &&
    (($_ =~ s/\\/\//g && $_ =~ s/\/\//\//g) || 1), @files);
}

@files = grep(
    (($_ =~ /\.gif</g || $_ =~ /\.jpg</g) && $_ =~ s/_misc\.gif'/_img.gif'/g) ||
    ($_ =~ /\.html*</g && $_ =~ s/_misc\.gif'/_htm.gif'/g) ||
    ($_ =~ /\.zip</g && $_ =~ s/_misc\.gif'/_zip.gif'/g) ||
    (1), @files);


$dirlist = join "\n", @list;
$filelist = join "\n", @files;

print start_html("Splitreflection File Manager");

print "<H1>Splitreflection File Manager</h1><br>Check out the <a href='statscalendar.pl'>Stats</a> page.<br>",
    "<a href='upload.pl?currentdir=".$currentdir."&checklinks=yes'>Scan for bad links</a><br>",
    strong("<font color=#0000ff>".$msg."</font><br>\n"),
    strong("Logged in as <font color=#0000ff>".$credentials{"name"}.
        "</font> &nbsp; &nbsp; <a href='upload.pl?logout=yes&msg=Logged%20Out'>Log Out</a><br>\n"),
    strong("Current directory - ", $currentdir), br;

if($dirlist =~ />gallery</ && $filelist =~ />gallery.xml</) {
  print
     "<a href='/cgi-bin/gallery.pl?action=load&filename=$currentdir/gallery.xml'>Edit</a>".
     "/<a href='$currentdir/gallery'>View</a> Gallery<br>\n";
}
else {
  if($filelist =~ /.gif</ || $filelist =~ /.jpe*g</ ) {
    print
     "<a href='/cgi-bin/gallery.pl?action=new&srcdir=$currentdir/'>Create Gallery Here</a><br>\n";
  }
}

print
    "\n<table border=1 cellspacing=0 height=0><tr><td valign='top'>\n<table>\n";
if(length($currentdir) > 1){
    print "<tr><td><a href='upload.pl?currentdir=".$parent."'><img src='/icons/dir_parent.gif' border=0>Parent Directory</a></td></tr>\n";}
print $dirlist,
    "\n</table></td><td valign='top'>\n<table>\n",
    $filelist,
    "</table>\n</td></tr valign='top'>\n</table>\n";
if(param('deletemode')) {
  print "<a href='upload.pl?currentdir=$currentdir'>Switch to normal mode</a>";
}
else {
  print "<a href='upload.pl?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;

if($basedir eq "/usr/local/apache/htdocs") {
print stdout
"<br><b>Add a What's New entry!</b><br>\n".
"<form method='get' action='/cgi-bin/addwhatsnew.pl'>\n".
"<input type='hidden' name='user' value='".$credentials{'name'}."'>\n".
"<input type='hidden' name='referrer' value='/new.html'>\n".
"<textarea name='comment' rows=5 cols=40></textarea>\n".
"<input type='submit' value='Submit'>\n".
"</form>\n";
}

print hr(),
    end_html;


sub checklinks {
  print stdout "<table>\n";
  open LIST, "cd $basedir; find | grep -e [.][Hh][Tt][Mm] |";
  while (my $filename = <LIST>) {
    chomp $filename;
    $filename =~ s/^[.]//g;
    my $currentdir = $filename;
    $currentdir =~ s/[^\/]*$//g;
    open MYFILE, "<$basedir$filename";
    my @file = <MYFILE>;
    close MYFILE;
    my $fullfile = join "\n", @file;
    $fullfile =~ s/</>/g;
    $fullfile =~ s/%20/ /g;
    $fullfile =~ s/[\r\n]/ /g;
    @file = split ">", $fullfile;
    @file = grep(($_ =~ /^a /g && $_ =~ /href=['"]/g) || $_ =~ /^img /g && $_ =~ /src=['"]/g, @file);
    grep {
      $_ =~ s/^.*href=['"]//g;
      $_ =~ s/^.*src=['"]//g;
      $_ =~ s/['"].*//g;
      $_ =~ s/http:\/\/[w.]*splitreflection.com//g;
    } @file;
    @file = grep($_ !~ /^[a-zA-Z]*:/g, @file);
    grep {
      if ($_ !~ /^\//) { $_ = $currentdir.$_; }
      if (! stat $basedir.$_) {
        print stdout "<tr><td><a href='$filename'>$filename</a></td><td><a href='$_'>$_</a> was not found.</td></tr>\n";
      }
    } @file;
  }
  print stdout "</table>\n";
  $msg = "Links scanned.";
}


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;
}

