#!/usr/bin/perl
$|=1;
####################################################
# editor.cgi
# File/Directory Management Program utility
#
# Author: Steve Horsburgh  (fm@horsburgh.com)
# Version: 0.9
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
####################################################
$|=1;
require 5.002;
require "./preferences.pl";
require "$Cgilib";
#------------------------------------------------------------------#
#-- Main Program --------------------------------------------------#
#------------------------------------------------------------------#

    $isMac = ($ENV{'HTTP_USER_AGENT'} =~ /Mac/) ? 1 : 0;
    $isIE  = ($ENV{'HTTP_USER_AGENT'} =~ /MSIE/) ? 1 : 0;
    if (!$isMac && $isIE) {
      ($IEversion = $ENV{'HTTP_USER_AGENT'}) =~ s/^.*MSIE (\d+).*$/$1/;
    }
    $isIE = ($IEversion >= 4) ? 1 : 0;


	print &PrintHeader();
	&ReadParse();
    &ReadOptions();

    $Basedir    = "/" unless $Basedir;
    $in{'path'} = "/" unless $in{'path'};
    $dpath      = $in{'path'};
    $fpath      = $Basedir . ((($Basedir =~ /\/$/) or ($dpath =~ /^\//)) ? "" : "/") . $dpath;
    $fpath      =~ s/\/+$//;
    $filename   = $fpath . ($fpath =~ /\/$/ ? "" : "/") . $in{'filename'};
    $rfilename  = $dpath . ($dpath =~ /\/$/ ? "" : "/") . $in{'filename'};
    $rfilename  = "/" . $rfilename unless $rfilename =~ /^\//;

    &Error("Editing is not currently allowed, see your system administrator.") unless $AllowEdits;
	&Error("Invalid path specification: $dpath") unless -d $fpath;
	

    print &Header();

	if ($in{'submit'} =~ /save/i) {
	  open(F, ">$filename") || &Error("Unable to save $rfilename");
	  $in{'text'} =~ s/\r//g;
	  print F $in{'text'};
	  close(F);
	  print "<h3>".$rfilename." saved.</h3>\n<a href=".$Fmurl."?path=".$dpath.&GenOptions().">Continue</a>\n";
	  print &Footer();
	  exit;
	}

	$out = "";
	$newfile = $writeable = 0;
	if (-f $filename) {
	  $writeable = 1 if -w $filename;
	} else {
	  $writeable = $newfile = 1;
	}
	
	unless ($newfile) {
	  open(F, "<$filename") || &Error("Unable to open $rfilename for reading.");
      $nrows = 0;
      while (<F>) {
        $nrows++;
        $out .= $_;
	  }
	  close(F);
	  $out =~ s/\&/\&amp;/g; $out =~ s/</\&lt;/g; $out =~ s/>/\&gt;/g;
	}

	if ($writeable) {
	  &Error("$rfilename is not editable.") unless (-T $filename or $newfile);
	  $out = "Editing: <strong>".$rfilename."</strong>".
             "<form method=post action=".$Edurl.">".
             "<input type=hidden name=path value=\"".$dpath."\">".
             "<input type=hidden name=filename value=\"".$in{'filename'}."\">".
             "<textarea class=tt rows=".$Rows." cols=".$Cols." name=text>".
		     $out . "</textarea>" .
		    "<br>\n<input type=submit name=submit value=\"Save\">\n".
            "<input type=button value=\"Cancel\" onClick=\"javascript:location='".$Fmurl."?path=".$dpath.&GenOptions()."'\">".
            &GenOptions("f")."</form>";
	} else {
	  &Error("$rfilename is not viewable.") unless -T $filename;
	  $out = "<strong>".$rfilename." is READONLY.</strong>".
             "<form>".
		     "<textarea class=tt rows=".$Rows." cols=".$Cols." nowrap>".
		     $out . "</textarea></form>" . 
		     "\n<p>\n<a href=".$Fmurl."?path=".$dpath.&GenOptions().">Continue</a>\n";
	}

	print "<h2>FileManager Editor</h2>\n",$out;
    print "<br><em><small>Large files may not be editable in Netscape.</small></em><br>" if (!$isIE and ($nrows > 500));
    print &Footer();
	exit;

#------------------------------------------------------------------#
#-- ReadOptions ---------------------------------------------------#
#------------------------------------------------------------------#

sub ReadOptions {

  $IconMode      = exists $in{'im'}   ? ($in{'im'}  ? 1 : 0) : $IconMode;
  $DirsFirst     = exists $in{'df'}   ? ($in{'df'}  ? 1 : 0) : $DirsFirst;
  $AllowDotFiles = exists $in{'adf'}  ? ($in{'adf'} ? 1 : 0) : $AllowDotFiles;
  $AllowMode     = exists $in{'am'}   ? ($in{'am'}  ? 1 : 0) : $AllowMode;
  $AllowOwnGrp   = exists $in{'aog'}  ? ($in{'aog'} ? 1 : 0) : $AllowOwnGrp;

  $SortBy  = exists $in{'sort'} ? $in{'sort'} : "name";
  $Reverse = exists $in{'rev'}  ? $in{'rev'}  : 0;

  $Rows      = exists $in{'rows'} ? (int($in{'rows'}) < 3  ? 3  : int($in{'rows'})) : $Rows;
  $Cols      = exists $in{'cols'} ? (int($in{'cols'}) < 3  ? 3  : int($in{'cols'})) : $Cols;
  $Divheight = exists $in{'dh'} ? (int($in{'dh'}) < 20 ? 20 : int($in{'dh'})) : $Divheight;
  $MaxCols   = exists $in{'mc'}   ? (int($in{'mc'})   < 1  ? 1  : int($in{'mc'}))   : $MaxCols;
  $FontSize  = exists $in{'bf'}   ? (int($in{'bf'})   < 4  ? 4  : int($in{'bf'}))   : $FontSize;

  $Fontsize_normal  = int($FontSize) > 8 ? int($FontSize) : 10;
  $Fontsize_xsmall  = int($Fontsize_normal * 0.7 + 0.5);
  $Fontsize_small   = int($Fontsize_normal * 0.8 + 0.5);
  $Fontsize_large   = int($Fontsize_normal * 1.2 + 0.5);
  $Fontsize_huge    = int($Fontsize_normal * 1.6 + 0.5);
  $Fxs              = "font-size:".$Fontsize_xsmall .'pt';
  $Fss              = "font-size:".$Fontsize_small  .'pt';
  $Fsn              = "font-size:".$Fontsize_normal .'pt';
  $Fsl              = "font-size:".$Fontsize_large  .'pt';
  $Fsh              = "font-size:".$Fontsize_huge   .'pt';
}

#------------------------------------------------------------------#
#-- GenOptions ----------------------------------------------------#
#------------------------------------------------------------------#

sub GenOptions {
    my $type = shift;
    my $omit = shift || "";
    my $out  = "";

    if ($type eq "f") {
      $out .= "<input type=hidden name=im   value=\"".$IconMode."\">"      unless $omit eq "im";
      $out .= "<input type=hidden name=sort value=\"".$SortBy."\">"        unless $omit eq "sort";
      $out .= "<input type=hidden name=rev  value=\"".$Reverse."\">"       unless $omit eq "rev";
      $out .= "<input type=hidden name=df   value=\"".$DirsFirst."\">"     unless $omit eq "df";
      $out .= "<input type=hidden name=adf  value=\"".$AllowDotFiles."\">" unless $omit eq "adf";
      $out .= "<input type=hidden name=am   value=\"".$AllowMode."\">"     unless $omit eq "am";
      $out .= "<input type=hidden name=aog  value=\"".$AllowOwnGrp."\">"   unless $omit eq "aog";
      $out .= "<input type=hidden name=rows value=\"".$Rows."\">"          unless $omit eq "rows";
      $out .= "<input type=hidden name=cols value=\"".$Cols."\">"          unless $omit eq "cols";
      $out .= "<input type=hidden name=dh   value=\"".$Divheight."\">"     unless $omit eq "dh";
      $out .= "<input type=hidden name=mc   value=\"".$MaxCols."\">"       unless $omit eq "mc";
      $out .= "<input type=hidden name=bf   value=\"".$FontSize."\">"      unless $omit eq "bf";
    } else {
      $out .= "\&im=".  $IconMode      unless $omit eq "im";
      $out .= "\&df=".  $DirsFirst     unless $omit eq "df";
      $out .= "\&adf=". $AllowDotFiles unless $omit eq "adf";
      $out .= "\&am=".  $AllowMode     unless $omit eq "am";
      $out .= "\&aog=". $AllowOwnGrp   unless $omit eq "aog";
      $out .= "\&rows=".$Rows          unless $omit eq "rows";
      $out .= "\&cols=".$Cols          unless $omit eq "cols";
      $out .= "\&dh=".  $Divheight     unless $omit eq "dh";
      $out .= "\&mc=".  $MaxCols       unless $omit eq "mc";
      $out .= "\&bf=".  $FontSize      unless $omit eq "bf";
      $out .= "\&sort=".$SortBy        unless $omit eq "sort";
      $out .= "\&rev=". $Reverse       unless $omit eq "rev";
    }

    return $out;
}

#------------------------------------------------------------------#
#-- Error ---------------------------------------------------------#
#------------------------------------------------------------------#

sub Error {
	my($msg) = shift;
    my $loc = "javascript:location='".$Fmurl."?path=".$dpath.&GenOptions()."'";
    print &Header() unless $DoneHeader;
	print <<EOE;
  <center>
  <h2>ERROR</h2>
  $msg
  <p><a href="$loc">Back</a></p>
  </center>
EOE
	print &Footer();
	exit;
}

#------------------------------------------------------------------#
#-- Header --------------------------------------------------------#
#------------------------------------------------------------------#

sub Header {
  my $uname = (getpwuid($<)||$<);
  my $out = "";
  my $options = &GenOptions();
  $DoneHeader = 1;
  $out .= <<EOH1;
<html>
 <head>
  <title>FileManager Editor</title>
  <meta http-equiv="Expires" content="-1">  
  <style type="text/css">
    TT {$Fss;color:black}
    PRE {$Fss;color:black}
    TEXTAREA {$Fss;color:black}
    P {$Fsn;color:black}
    TD {$Fsn;color:black}
	.rb {font-family:arial,helvetica,sans-serif;$Fxs;text-decoration:none;color:white;}
	.gb {font-family:arial,helvetica,sans-serif;$Fxs;text-decoration:none;color:#cccccc;}
	.bb {font-family:arial,helvetica,sans-serif;$Fxs;text-decoration:none;color:white;}
	.ti {font-family:arial,helvetica,sans-serif;$Fsh;text-decoration:none;color:white;}
    .tt {$Fss;color:black;}
EOH1
  $out .= $isIE ? "A {text-decoration:none;color:#0000ff}\nA:hover {text-decoration:underline;color:red}\n"
                : "A {color:#0000ff}\n";
  $out .= "</style>\n";
  $out .= <<EOH2;
 </head>
 <body bgcolor="#ffffff" background="$Imgprefix/bg.gif" leftmargin=0 topmargin=0 marginheight=0 marginwidth=0 text="#000000" link="#000084" vlink="#333399" alink="#ff0000">
 <center>
 <table border=0 cellspacing=0 cellpadding=0>
  <tr>
   <td width=741 colspan=2 bgcolor="#000042" align="right"><a 
    href="$Fmurl?path=/$options"><img src="$Logo" width=38 height=45 alt="home" border="0" align="left"></a><img
    src="$Imgprefix/dot.gif" width=610 height=7 alt="" border=0><br><font class="ti">FileManager Editor</font>&nbsp;</td>
   <td width=7><img src="$Imgprefix/shadow1.gif" width=7 height=45 alt=""></td>
  </tr>
  <tr>
   <td width=340 bgcolor="#666684" valign="bottom" class=rb><span class=gb>User: </span>$uname</td>
   <td width=401 bgcolor="#666684" valign="bottom" class=rb align="right">$RealOS&nbsp;$RealOSVer&nbsp;</td>
   <td width=7><img src="$Imgprefix/shadow2.gif" width=7 height=20 alt=""></td>
  </tr>
  <tr>
   <td colspan=3 height=7><img src="$Imgprefix/shadow3.gif" width=748 height=7 alt=""></td>
  </tr>
 </table>
 <table border=0 cellspacing=0 cellpadding=0 width=740>
 <tr valign="top">
  <td bgcolor="#ffffff">
EOH2
    return $out;
}

#------------------------------------------------------------------#
#-- Footer --------------------------------------------------------#
#------------------------------------------------------------------#

sub Footer {
  my $gendate = scalar(localtime(time));
  return <<EOF;
    </td>
   </tr>
  </table>
  <table border=0 cellpadding=0 cellspacing=0>
   <tr>
    <td colspan=2 height=3><img src="$Imgprefix/dot.gif" width=748 height=3 alt=""></td>
   </tr>
   <tr>
    <td  width=741 bgcolor="#666684" nowrap align="center"><font class="bb">This information was generated on $gendate.</font></td>
    <td><img src="$Imgprefix/shadow1.gif" width=7 height=20 alt=""></td>
   </tr>
   <tr>
    <td  width=741 bgcolor="#000042" align="center">
     <a href="http://www.horsburgh.com/" class="rb">Designed by Horsburgh.com.</a>
    </td> 
    <td><img src="$Imgprefix/shadow2.gif" width=7 height=20 alt=""></td>
   </tr>
   <tr>
    <td colspan=2 height=7><img src="$Imgprefix/shadow3.gif" width=748 height=7 alt=""></td>
   </tr>
  </table>
  </center>
 </body>
</html>
EOF
}
