#!/usr/bin/perl

########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####

use strict;
use File::Basename;

my ($base, $shift, $PERL, $file, $uid, $perms, $oct_perms, $dir, $secpart);

$PERL = '/usr/bin/perl';

$base = '/var/www';
$shift = '';

## parsing arguments

unless($ARGV[0] ne "") {
  &error("mlf||pdb_argv0");
}
unless($ARGV[1] ne "") {
  &error("mlf||pdb_argv1");
}
if($ARGV[1] =~ /\.\./) {
  &error("mlf||pdb_path_invalid||/$ARGV[1]");
}

$file = "$base/$ARGV[0]/$ARGV[1]";
$uid   = getpwnam($ARGV[0]);

unless(-e "$file"){
  &error("mlf||pdb_file_exist||/$ARGV[1]");
}
if($uid != (stat($file))[4]){
  &error("mlf||pdb_file_exist||/$ARGV[1]");
}

&checkSymLink($base, $file);

if($file =~ /[\|&;><`\?\*\$\(\)\[\]\{\}"'#~\\]/){
  &error("mlf||pdb_file_exist||/$ARGV[1]");
}
if(-d "$file"){
  &error("mlf||pdb_isdir||/$ARGV[1]");
}
unless(-T "$file"){
  &error("mlf||pdb_file_text||/$ARGV[1]");
}

$perms = (stat($file))[2] & 07777;
$oct_perms = sprintf "%lo", $perms;

if($oct_perms ne "755"){
  &warning("mlf||pdb_file_chmod||/$ARGV[1]||755");
}

$dir = dirname($file);
$perms = (stat($dir))[2] & 07777;
$oct_perms = sprintf "%lo", $perms;

while(($ARGV[1] !~ /\/$/) && ($ARGV[1] ne "")){
  chop($ARGV[1]);
}
chop($ARGV[1]);
if($oct_perms ne "755") {
  &warning("mlf||pdb_dir_chmod||/$ARGV[1]||755");
}

$secpart = "$base/$ARGV[0]";

if (open(PERLOUT, "$PERL -cw $file 2>&1 |") ) {
  print "$shift";
  while(<PERLOUT>) {
    my $out = $_;
    $out =~ s/\E$secpart\Q//g;
    print $out;
  }
  close(PERLOUT);
} else {
  &error("Can't exec 'perl -cw' command");
  exit 2;
}

exit 0;

## subroutines

sub error {
  my ($msg) = @_;
  print $msg . "\n";
  exit 1;
}

sub warning {
  my ($msg) = @_;
  print $msg . "\n";
  $shift = "\n\n";
}

sub checkSymLink {
  my ($tbase, $tfile) = @_;
  while("$tfile" ne "$tbase") {
    if(-l "$tfile") {
      &error("mlf||pdb_file_exist||/$ARGV[1]");
    }
    $tfile = dirname($tfile);
  }
  return 1;
}

## /subroutines
