#!/usr/bin/perl
#
#Copyright (c) 2001-2004 cPanel, Inc.
#
#This auto install script, "upgrade" is hereinafter referred to as the "Software."  No other parts of this package
#will be considered, infered or implied to be part of the the "Software."
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
#documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
#rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
#permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
#Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
#WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
                                                                                                                             
BEGIN {
	push(@INC,"/usr/local/cpanel");
}

use IPC::Open3;
use SafeFile;

#VARIBLES
my $domain = '%domain%';
my $installpath = '%installpath%';
my $modulename = '%modulename%';
my $modulepath = '%modulepath%';
my $homedir = '%homedir%';
my $user = '%user%';
my $installdir = '%installdir%';
my $publichtml = '%public_html%';
my $sqldb = '%sqldb%';
my $sqluser = '%sqluser%';
my $sqlpass = '%sqlpass%';
my $sqlserver = '%sqlhost%';
my $username = '%username%';
my $password = '%password%';

print "We are upgrading in $installdir...\n";

if(!-e "$installdir/cpanel-upgrade/pkg") {
	# shouldn't have to do this, but doesn't hurt.
	mkdir("$installdir/cpanel-upgrade");
	mkdir("$installdir/cpanel-upgrade/pkg");
	system("tar -C $installdir/cpanel-upgrade/ -xzf $modulepath/pkg.tar.gz");
	print "<br><br>\nCan not find pkg upgrade directory \"$installdir/cpanel-upgrade/pkg\"<br><br>";
	exit(0);
	}

system("cp -af $installdir/cpanel-upgrade/pkg/upload/admin.php $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/css.php $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/index.php $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/show.php $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/install_templates.txt $installdir/");
system("cp -af \"$installdir/cpanel-upgrade/pkg/Tools and Scripts/Other Scripts/upgrade5.php\" $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/cache $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/fonts $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/html $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/lang $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/Skin $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/sources $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/modules $installdir/");
system("cp -af $installdir/cpanel-upgrade/pkg/upload/style_images $installdir/");

# for manually going through all upgrade steps
# print "Try the upgrade script <a href=\"http://$domain$installpath/upgrade5.php\">here</a><br><br>\n";

foreach $env (sort keys %ENV) {
   if ($env ne "PATH") {
      delete $ENV{$env};
   }
}

chdir($installdir);

$ENV{'CONTENT_TYPE'} = 'application/x-www-form-urlencoded';
$ENV{'DOCUMENT_ROOT'} = $publichtml;
$ENV{'SERVER_PROTOCOL'} = 'HTTP/1.0';
$ENV{'GATEWAY_INTERFACE'} = 'CGI/1.1';
$ENV{'REQUEST_URI'} = $installpath . "/" . "upgrade5.php";
$ENV{'SCRIPT_URI'} = $installpath . "/" . "upgrade5.php";
$ENV{'SCRIPT_FILENAME'} = "${installdir}/upgrade5.php";
$ENV{'REDIRECT_STATUS'} = 1;
$ENV{'REQUEST_METHOD'} = "GET";
$ENV{'HTTP_STATUS'} = 200;	      

print "<br><br>";

@QS=("a=tables",
	"a=alter",
	"a=index",
	"a=insert",
	"a=templates",
	"a=cleanup");
# we'll leave out optimze b/c it could take a looooong time on some large boards

foreach my $qs (@QS) {

	$ENV{'QUERY_STRING'} = $qs;
	$ENV{'QUERY_STRING'} = URLEncode($ENV{'QUERY_STRING'});

        if (-e "/var/cpanel/usecpphp") {
              open3(\*PHPW,\*PHPR,"","/usr/local/cpanel/3rdparty/bin/php","upgrade5.php");
        } else {
              open3(\*PHPW,\*PHPR,"","/usr/bin/php","upgrade5.php");
        }
	close(PHPW);
	while(<PHPR>) {
		#	print;
	}
	close(PHPR);

}


unlink("$installdir/upgrade5.php");
chmod(0777,"$installdir/uploads");
chmod(0777,"$installdir/conf_global.php");

print "<b>Complete!</b>\n";

print "<br><br>You can now access your upgraded board: <a 
href=\"http://$domain/$installpath/\">http://${domain}${installpath}/</a><br>\n";
print "<br><br>\n";

sub regsrep {
   my($file,$old,$new) = @_;
   $filelock = SafeFile::safeopen(\*FH,"$file");
   $fileeditlock = SafeFile::safeopen(\*FHT,">$file.tmpeditlib");
   while(<FH>) {
      if ($_ =~ /^$/ || $_ eq "\n" || $_ eq "\r\n") {
         print FHT "$_";
      } elsif($_ =~ /$old/) {
        $result = $1;
         my $mnew = $new;
        $mnew =~ s/\$1/$result/g;
         print FHT "$mnew\n";
      } else {
         print FHT $_;
      }
   }
   SafeFile::safeclose(\*FH,$filelock);
   SafeFile::safeclose(\*FHT,$fileeditlock);
   $fileeditlock = SafeFile::safeopen(\*FHT,"$file.tmpeditlib");
   $filelock = SafeFile::safeopen(\*FH,">$file");
   while(<FHT>) { print FH $_ };
   SafeFile::safeclose(\*FH,$filelock);
   SafeFile::safeclose(\*FHT,$fileeditlock);
}



           
sub URLEncode
{
   my($url)=@_;
   my(@characters)=split(/(\%[0-9a-fA-F]{2})/,$url);

   foreach(@characters)
   {
       if ( /\%[0-9a-fA-F]{2}/ ) # Escaped character set ...
       {
           # IF it is in the range of 0x00-0x20 or 0x7f-0xff
           #    or it is one of  "<", ">", """, "#", "%",
           #                     ";", "/", "?", ":", "@", "=" or "&"
           # THEN preserve its encoding
           #"
           unless ( /(20|7f|[0189a-fA-F][0-9a-fA-F])/i
                   || /2[2356fF]|3[a-fA-F]|40/i )
           {
               s/\%([2-7][0-9a-fA-F])/sprintf "%c",hex($1)/e;
           }
       }
       else # Other stuff
       {
           # 0x00-0x20, 0x7f-0xff, <, >, and " ... "
           s/([\000-\040\177-\377\074\076\042])
               /sprintf "%%%02x",unpack("C",$1)/egx;
       }
   }
   return join("",@characters);
}

