no warnings 'redefine';
use vars qw($r);
sub EditFile
{
    my $name = defined param('name') ? param('name') : $m_sAction;
    my @n = $m_oDatabase->fetch_array("select file from `actions` where action=?", $name);
    FileOpen("$m_hrSettings->{cgi}{bin}/Content/$n[0]");
}

use POSIX 'floor';

sub round
{
    my $x = shift;
    floor($x + 0.5);
}

sub showDir
{
    my $sSubfolder = param('subfolder') ? param('subfolder') : shift;
    $sSubfolder = defined $sSubfolder ? $sSubfolder : $m_hrSettings->{cgi}{bin};
    $sSubfolder =~ s?/$??g;
    my $links = $sSubfolder =~ m?^(.*/)[^/]+$? ? $1 : $sSubfolder;
    my $fname =
      $sSubfolder =~ m?^.*/([^/]+)$?
      ? qq(<span style="color:white">$1</span>)
      : $sSubfolder;
    $links =~ s?//?/?g;
    my $elinks     = uri_escape($links);
    my $esubfolder = uri_escape($sSubfolder);
    $r = 0;
    my $orderby  = defined param('orderBy')  ? param('orderBy')  : 'NULL';
    my $byColumn = defined param('byColumn') ? param('byColumn') : 'a';
    my $state = defined param('desc') ? param('desc') == 1 ? 1 : 0 : 0;
    my $newstate = $state ? 0 : 1;
    my @t = readFiles($sSubfolder, 0);
    my $fileview = new HTML::Menu::TreeView();
    SWITCH:{
      if (defined param('sort')) {
	$fileview->sortTree(1);
	$fileview->desc( $state ? 1 : 0);
	last SWITCH;
      }
      if($byColumn eq 0 or $byColumn eq 1 or $byColumn eq 2){
	$fileview->orderByColumn($byColumn);
	$fileview->desc( $state ? 1 : 0);
	last SWITCH;
      }
      if( $orderby eq 'mTime'){
	@t = sort {lc($a->{mtime}) cmp lc($b->{mtime})} @t;
	@t = reverse @t if $state;
	last SWITCH;
      }
      if( $orderby eq 'Size'){
	@t = sort { $a->{size} <=> $b->{size} } @t;
	@t = reverse @t if $state eq  1;
	last SWITCH;
      }
      $fileview->folderFirst(1);
    }
    $fileview->TrOver(1);

    $fileview->columns(
            a(
               {
                href  => "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$esubfolder&sort=1&desc=$newstate','$m_sAction','$m_sTitle');",
                class => "treeviewLink$m_hrSettings->{size}",
                align => "left",
               },
               'Name'
              )
              . (
                 param('sort')
                 ? (
                    $state
                    ? qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/up.png" border="0" alt="" title="up" width="16" height="16" />|
                    : qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/down.png" border="0" alt="" title="down"/>|
                   )
                 : ''
              )
              . ' ',
            a(
               {
                href  => "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$esubfolder&orderBy=Size&desc=$newstate','$m_sAction','$m_sTitle')",
                class => "treeviewLink$m_hrSettings->{size}",
                align => "left"
               },
               'Size'
              )
              . (
                 $orderby eq 'Size'
                 ? (
                    $state
                    ? qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/up.png" border="0" alt="" title="up" width="16" height="16" />|
                    : qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/down.png" border="0" alt="" title="down"/>|
                   )
                 : ''
              )
              . ' ',
            a(
               {
                href  => "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$esubfolder&byColumn=0&desc=$newstate','$m_sAction','$m_sTitle')",
                class => "treeviewLink$m_hrSettings->{size}",
                align => "left"
               },
               'Permission'
              )
              . (
                 $byColumn == 0 && !param('sort')
                 ? (
                    $state
                    ? qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/up.png" border="0" alt="" title="up" width="16" height="16" />|
                    : qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/down.png" border="0" alt="" title="down" />|
                   )
                 : ''
              )
              . ' ',
            a(
               {
                href  => "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$esubfolder&byColumn=2&desc=$newstate','$m_sAction','$m_sTitle')",
                class => "treeviewLink$m_hrSettings->{size}",
                align => "left"
               },
               'UID'
              )
              . (
                 $byColumn == 2
                 ? (
                    $state
                    ? qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/up.png" border="0" alt="" title="up" width="16" height="16" />|
                    : qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/down.png" border="0" alt="" title="down"/>|
                   )
                 : ''
              )
              . ' ',
            a(
               {
                href  => "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$esubfolder&byColumn=3&desc=$newstate','$m_sAction','$m_sTitle')",
                class => "treeviewLink$m_hrSettings->{size}",
                align => "left"
               },
               'GID'
              )
              . (
                 $byColumn == 3
                 ? (
                    $state
                    ? qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/up.png" border="0" alt="" title="up" width="16" height="16"/>|
                    : qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/down.png" border="0" alt="" title="down" />|
                   )
                 : ''
              )
              . ' ',
            a(
               {
                href  => "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$esubfolder&orderBy=mTime&desc=$newstate','$m_sAction','$m_sTitle')",
                class => "treeviewLink$m_hrSettings->{size}",
                align => "left"
               },
               'Last Modified'
              )
              . (
                 $orderby eq 'mTime'
                 ? (
                    $state
                    ? qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/up.png" border="0" alt="" title="up" width="16" height="16"/>|
                    : qq| <img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/down.png" border="0" alt="" title="down"/>|
                   )
                 : ''
              )
              . ' ',
            "",
    ) if $#t >= 0;
    my $hf = "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$elinks','$m_sAction','$m_sTitle')";


      my $toolbar = div(
        {align => 'left'},
	    a(
              {
               onclick  => "var a = prompt('Enter File Name');if(a != null )requestURI('$ENV{SCRIPT_NAME}?action=newFile&file='+encodeURIComponent(a)+'&dir=$esubfolder','$m_sAction','$m_sTitle')",
               class => "toolbarButton"
              },
              "New File"
          )
          . ' '
          . a(
              {
               onclick  => "var a = prompt('Neues Verzeichnis');if(a != null )requestURI('$ENV{SCRIPT_NAME}?action=makeDir&file=$esubfolder&d='+encodeURIComponent(a),'$m_sAction','$m_sTitle')",
               class => "toolbarButton"
              },
              "New Directory"
          )
          . ' '
          . a(
              {
               onclick  => "var a = prompt('Enter Chmod: 0755');if(a != null ) requestURI('$ENV{SCRIPT_NAME}?action=chmodFile&file=$esubfolder&chmod='+encodeURIComponent(a),'$m_sAction','$m_sTitle')",
               class => "toolbarButton"
              },
              "Chmod",
          )
          . ' '
          . a(
            {
             onclick => "var a = prompt('Enter User:'),b = prompt('Enter Group:');if(a != null  && b != null)requestURI('$ENV{SCRIPT_NAME}?action=chownFile&file=$esubfolder&user='+encodeURIComponent(a)+'&gid='+encodeURIComponent(b),'$m_sAction','$m_sTitle')",
             class => "toolbarButton"
            },
            "Chown",
          )
    );
	

	print qq(<table class="ShowTables" style="margin-top:1.65em">
	<tr class="captionRadius"><td class="captionRadius" colspan="7"><a href="$hf" class="treeviewLink$m_hrSettings->{size}">$links $fname</a></td></tr>
	<tr><td colspan="7" class="toolbar"><div id="toolbarcontent" class="toolbarcontent">$toolbar</div></td></tr>
	<tr><td colspan="7" style="padding:0px;padding-bottom:1em;vertical-align:top;">). ($#t >= 0 ? $fileview->Tree(\@t, $m_sStyle) : '') . q(</td></tr></table>);

}

sub readFiles
{
    my @TREEVIEW;
    my $dir  = shift;
    my $edir = uri_escape($dir);
    my $rk   = shift;
    $r++ if ($rk);
    if (-d "$dir" && -r "$dir") {
        opendir DIR, $dir or warn "files.pl sub readFiles: $dir $!";
        foreach my $d (readdir(DIR)) {
            my $fl = "$dir/$d";
            use File::stat;
            my $sb = stat($fl);
            TYPE: {
                last TYPE if ($d =~ /^\.+$/);
                my $efl  = uri_escape($fl);
                my $href = "javascript:requestURI('$ENV{SCRIPT_NAME}?action=FileOpen&file=$efl','$m_sAction','$m_sTitle')";
                my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($sb->mtime);
                $year += 1900;
                $mon  = sprintf("%02d", $mon);
                $mday = sprintf("%02d", $mday);
                $min  = sprintf("%02d", $min);
                $hour = sprintf("%02d", $hour);
                $sec  = sprintf("%02d", $sec);

                if (-d $fl) {
                    push @TREEVIEW, {
                        text    => $d,
                        href    => "$href",
                        empty   => 1,
                        subtree => [{},{}],
                        mtime   => $sb->mtime,
                        size    => $sb->size,
                        columns => [
                            sprintf("%s",   $sb->size),
                            sprintf("%04o", $sb->mode & 07777),
                            getpwuid($sb->uid)->name,
                            $sb->gid,
                            "$year-$mon-$mday $hour:$min:$sec",
                            qq|<table border="0" cellpadding="0" cellspacing="0" align="right" summary="layout"><tr><td>
<a class="treeviewLink$m_hrSettings->{size}" href="javascript:var a = prompt('Enter Filename:');if(a != null )requestURI('$ENV{SCRIPT_NAME}?action=renameFile&file=$efl&newName='+encodeURIComponent(a),'$m_sAction','$m_sTitle')">rename</a></td>
 <td> <a class="treeviewLink$m_hrSettings->{size}" href="javascript:var a = prompt('Enter User:'),b = prompt('Enter Group:');if(a != null  && b != null)requestURI('$ENV{SCRIPT_NAME}?action=chownFile&file=$efl&user='+encodeURIComponent(a)+'&gid='+encodeURIComponent(b),'$m_sAction','$m_sTitle')">Chown</a></td><td> <a class="treeviewLink$m_hrSettings->{size}" href="javascript:var a = prompt('Enter Chmod: 0755');if(a != null )location.href = '$ENV{SCRIPT_NAME}?action=chmodFile&file=$efl&chmod='+encodeURIComponent(a);">chmod</a></td><td><a class="treeviewLink$m_hrSettings->{size}" href="javascript:var a = prompt('Enter File Name');location.href = '$ENV{SCRIPT_NAME}?action=newFile&file='+encodeURIComponent(a)+'&dir=$edir';"><img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/filenew.png" border="0" alt="new"/></a></td><td><a class="treeviewLink$m_hrSettings->{size}" href="$ENV{SCRIPT_NAME}?action=deleteFile&file=$efl" onclick="return confirm('Realy delete ?')"><img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/editdelete.png" border="0" alt="delete"/></a></td></td></tr></table>|
                        ],
                    };
                    last TYPE;
                }

                if (-f $fl) {
                    my $suffix = $d =~ /\.([^\.]+)$/ ? $1 : '';
                    push @TREEVIEW,
                      {
                        text    => "$d",
                        href    => "$href",
                        mtime   => $sb->mtime,
                        size    => $sb->size,
                        columns => [
                                   sprintf("%s",   $sb->size),
                                   sprintf("%04o", $sb->mode & 07777),
                                   (getpwuid($sb->uid)->name),
                                   $sb->gid,
                                   "$year-$mon-$mday $hour:$min:$sec",
qq|<table border="0" cellpadding="0" cellspacing="0" align="right" summary="layout" style="whitespace:nowrap;"><tr><td><a class="treeviewLink$m_hrSettings->{size}" href="javascript:var a = prompt('Enter Filename:');if(a != null )location.href = '$ENV{SCRIPT_NAME}?action=renameFile&file=$efl&newName='+encodeURIComponent(a);">rename</a></td><td> <a class="treeviewLink$m_hrSettings->{size}" href="javascript:var a = prompt('Enter User:'),b = prompt('Enter Group:');if(a != null  && b != null)location.href = '$ENV{SCRIPT_NAME}?action=chownFile&file=$efl&user='+encodeURIComponent(a)+'&gid='+encodeURIComponent(b);">Chown</a></td><td> <a class="treeviewLink$m_hrSettings->{size}" href="javascript:var a = prompt('Enter Chmod: 0755');if(a != null )location.href = '$ENV{SCRIPT_NAME}?action=chmodFile&file=$efl&chmod='+encodeURIComponent(a);">chmod</a></td><td><a class="treeviewLink$m_hrSettings->{size}" href="$href"><img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/edit.png" border="0" alt="edit"/></a></td><td><a class="treeviewLink$m_hrSettings->{size}" href="$ENV{SCRIPT_NAME}?action=deleteFile&file=$efl" onclick="return confirm('Realy delete ?')"><img src="/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/editdelete.png" border="0" alt="delete"/></a></td></tr></table>|,
                        ],
                        image => (-e "$m_hrSettings->{cgi}{DocumentRoot}/style/$m_sStyle/$m_hrSettings->{size}/mimetypes/$suffix.png")
                        ? "$suffix.png"
                        : 'link_overlay.png',
                      };
                }
            }
        }
        $r = 0;
        return @TREEVIEW;
    }
}

sub FileOpen
{
    my $f = defined param('file') ? param('file') : shift;
    return unless defined $f;
    SWITCH: {
        if (-d $f) {
            &showDir($f);
            last SWITCH;
        }
        if (-T $f) {
            print qq(<div align="center">) . a({-href => "javascript:history.back()"}, translate('back')) . "</div>";
            my $content = openFile($f);
            $content =~ s/<\/textarea>/[\%TEXTAREA\%]/gi;
            &showEditor("Edit File: $f<br/>", $content, 'saveFile', $f);
            last SWITCH;
        }else{
	  print "???";
        }
        if ($f =~ /png|jpg|jpeg|gif$/ && $f =~ m~/var/www/htdocs/(.*)$~) {
            print br() . qq(<div align="center"><img alt="" src="/$1" align="center"/>) . br() . a({-href => "javascript:history.back()"}, translate('back')) . "</div>";
            last SWITCH;
        }
        print br() . translate("UnsopportedFileType") . br() . a({-href => "javascript:history.back()"}, translate('back'));
    }
}

sub saveFile
{
    my $txt = param('txt');
    $txt =~ s/\[%TEXTAREA%\]/<\/textarea>/g;
    my $sFile = param('file');
    use Fcntl qw(:flock);
    use Symbol;
    my $fh = gensym();
    unless (-d $sFile) {
        open $fh, ">$sFile.bak" or warn "files.pl::saveFile $/ $! $/ $sFile $/";
        flock $fh, 2;
        seek $fh, 0, 0;
        truncate $fh, 0;
        print $fh $txt;
        close $fh;
        rename "$sFile.bak", $sFile or warn "files.pl::saveFile $/ $! $/" if (-e "$sFile.bak");
        chmod(0755, $sFile) if ($sFile =~ m?\.pl?);
        showDir();
    } elsif (defined param('title') && defined param('file')) {
        my $sf = param('file') . '/' . param('title');
        open $fh, ">$sf.bak" or warn "files.pl::saveFile $/ $! $/ $sf $/";
        flock $fh, 2;
        seek $fh, 0, 0;
        truncate $fh, 0;
        print $fh $txt;
        close $fh;
        rename "$sf.bak", $sf or warn "files.pl::saveFile $/ $! $/" if (-e "$sf.bak");
        showDir();
    }
}

sub showEditor
{
    my $h  = shift;
    my $t  = shift;
    my $a  = shift;
    my $fi = shift;

    print '<div class="showTables" style="margin-top:1.65em">';

    my $buttons = HTML::Editor::buttons($m_sStyle);
     
    print qq|
<form action ="$ENV{SCRIPT_NAME}" onsubmit="submitForm(this,'$m_sAction','$m_sTitle');return false;" method="post">
 <table cellspacing="5" cellpadding="0" border="0" align="center" summary="files.pl" width="95%">
  <tbody>
   <tr>
      <td>$h</td>
    </tr>
    <tr><td>$buttons</td></tr>
    <tr>
      <td>
       <textarea name="txt" id="txt" style="width:100%;height:640px;">$t</textarea>
      </td>
    </tr>
    <tr>
      <td align="right"><input type="submit" name="save" value="Save"/>
       <input type="hidden" value="$a" name="action"/>
       <input type="hidden" value="$fi" name="file"/>
      </td>
    </tr>
  </tbody>
</table>
</form>
<script language="JavaScript">
scrollToTxt();
</script>
|;
print '</div>';
}

sub newFile
{
    my $d = defined param('dir') ? param('dir') : '';
    my $sFile = param('file');
    unless (-e $sFile) {
        open(IN, ">$d/$sFile") or die $!;
        close IN;
        print translate('newfileadded') if -e $sFile;
    } else {
        print translate('fileExists ') if -e $sFile;
    }
    &showDir($d);
}

sub makeDir
{
    my $d     = param('d');
    my $sFile = param('file');
    unless (-d "$sFile/$d") {
        mkdir "$sFile/$d";
        print translate('newfileadded') if -d $sFile;
    } else {
        print translate('fileExists');
    }
    &showDir($sFile);
}

sub renameFile
{
    my $file    = param('file');
    my $newName = param('newName');
    my $dir     = $file =~ /(.*\/)[^\/]+$/ ? $1 : '/';
    rename $file, "$dir$newName";
    &showDir($dir);
}

sub chownFile
{
    my $user  = param('user');
    my $uid   = getpwnam($user);
    my $gid   = param('gid');
    my $g     = getgrnam($gid);
    my $sFile = param('file');
    use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
    $can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED);
    print "Not allowed" unless $can_chown_giveaway;
    my $cnt = chown $uid, $g, $sFile;
    print "Ok" if $cnt > 0;
    my $d = $sFile =~ m?^(.*)/[^/]+$? ? $1 : $m_hrSettings->{cgi}{bin};
    &showDir($d);
}

sub chmodFile
{
    my $chmod = param('chmod');
    my $sFile = param('file');
    chmod oct($chmod), $sFile if $chmod =~ /\d\d\d\d/ && -e $sFile;
    my $d = $sFile =~ m?^(.*)/[^/]+$? ? $1 : $m_hrSettings->{cgi}{bin};
    &showDir($d);
}

sub deleteFile
{
    my $sFile = param('file');
    unlink $sFile if -e $sFile;
    rmdir $sFile  if -d $sFile;
    my $d = $sFile =~ m?^(.*)/[^/]+$? ? $1 : $m_hrSettings->{cgi}{bin};
    &showDir($d);
}

