#!/usr/bin/perl
###############################################################################
# WebAPP - Web Automated Perl Portal                                          #
# install_subs.pl                                                             #
#                                                                             #
# Version History: v1.0 - August 2007                                         #
#                                                                             #
# Copyrights protected, WebAPP 2007 (http://www.web-app.net  info@web-app.net)#
# License: please see enclosed license file.                                  #
###############################################################################
my $installscriptname = "WebAPP";
my $installversion="1.0";
my $installupdatename = "SE";
my $installbuildnumber = "3";
##############
sub print_head{
##############
my($head_req)=@_;
if($info{'type'}){ $head_req="$info{'type'}";}
print qq~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>$installscriptname $installversion - Automated Perl Portal Installer</title>
<style type="text/css">
.style1 {color: #2F426D; font-weight: bold;font-size: 36px;}.style2 {color: #2F426D; font-weight: bold; font-size: 24px; }.style3 {font-size: 24px; color: #2F426D;}.style4 {color: #0F1C62;font-weight: bold;font-size: 24px;}.style5 {	font-weight: bold;font-size: 18px;color: #0F1C62;}.style7 {	font-weight: bold;	font-size: 18px;color: #008000;}.style8 {	font-weight: bold;font-size: 14px;color: #000070;}
</style>
<script language="javascript" type="text/javascript">
function confirmSubmit()
{
var agree=confirm("The upgrade will attempt to move all your old cgi-bin/ and html/ files to $PATH[1]/install/OLD Please note that the upgrade is irreversible, but it would backup your entire site into the install/OLD folder. Are you sure that you want to continue?");
if (agree)
	return true;
else
	return false;
}
</script>
</head>
<body link="green" vlink="green" alink="green">
<div align="center"><img src="http://www.web-app.net/images/logo_blue_orb.jpg" alt="http://www.web-app.net" width="510" height="100" longdesc="http://www.web-app.net" /></div>
<table width="876" border="0" align="center">~;
if($head_req eq "start"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion $installupdatename<br><font color="green"><b><u>WebAPP Install - Confirm main paths and Unzip the install files</b></u></font></h3>
	</center>
	<hr size=3 color="#5579C7">~;
	}
elsif($head_req eq "one"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion <br></center><p><center></h3>
	<h3><font color="green"><b><u>WebAPP Install - Step 1 out of 3</b></u></font></h3>
	</center></td></tr>
	<hr size=3 color="#5579C7">~;
	}
elsif($head_req eq "default"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion <br></center><p><center></h3>
	<h3><font color="green"><b><u>WebAPP Default Install - Step 2 out of 3</b></u></font></h3>
	</center></td></tr>
	<hr size=3 color="#5579C7">~;
	}
elsif($head_req eq "upgrade"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion <br></center><p><center></h3>
	<h3><font color="green"><b><u>WebAPP Upgrade Install - Step 2 out of 3</b></u></font></h3>
	</center></td></tr>
	<hr size=3 color="#5579C7">~;
	}
elsif($head_req eq "advance"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion <br></center><p><center></h3>
	<h3><font color="green"><b><u>WebAPP Advance Install - Step 2 out of 3</b></u></font></h3>
	</center></td></tr>
	<hr size=3 color="#5579C7">~;
	}
elsif($head_req eq "two"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion <br></center><p><center></h3>
	<h3><font color="green"><b><u>WebAPP Default Install - Step 3 out of 3</b></u></font></h3>
	</center></td></tr>
	<hr size=3 color="#5579C7">~;
	}
elsif($head_req eq "twoadvance"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion <br></center><p><center></h3>
	<h3><font color="green"><b><u>WebAPP Advance Install - Step 3 out of 3</b></u></font></h3>
	</center></td></tr>
	<hr size=3 color="#5579C7">~;
	}
elsif($head_req eq "twoupgrade"){
	print qq~<center><h3><font color="#000070">$installscriptname v$installversion <br></center><p><center></h3>
	<h3><font color="green"><b><u>WebAPP Upgrade Install - Step 3 out of 3</b></u></font></h3>
	</center></td></tr>
	<hr size=3 color="#5579C7">~;
	}
}

#################
sub bad_cookie{
#################
die 
"The install failed to confirm your install cookie, if you are the owner of this server\n you would need to ftp to your server and remove this file: cookie.dat from your install/ folder.
\nPlease note this is a security measure to prevent remote access from other users while installing your WebAPP site.\n\n Should you require more information, kindly do not hesitate to contact us at http://www.web-app.net\n\n";
}

#################
sub make_cookie{
#################
$sidkey = generate_key(17);
use CGI;
$query = new CGI;
$cookieexp="+42d";
$install_cookie = $query->cookie(-name=>installcookie,
			 -value=>$sidkey,
			 -expires=>"$cookieexp",
			 -httponly=>"1",
			 -path=>"/");
print qq~Set-Cookie: $install_cookie\n~;
open CCK, ">./cookie.dat"; print CCK "$sidkey"; close CCK;
return "NEW";
}

#################
sub test_cookie{
#################
if ($ENV{'HTTP_COOKIE'}) {
	use CGI qw/:standard/;
	use CGI::Cookie;
	%cookies = fetch CGI::Cookie;
    foreach (keys %cookies) {
		$client_cookie{'$_'} = $cookies{$_}->value;  
		if($_ eq "installcookie") { $installcookie = $client_cookie{'$_'};}
	}
}

if(open CCK,"./cookie.dat"){
	$stored_cookie=<CCK>; 
	close(CCK);
	if($stored_cookie eq "$installcookie"){ return "OK";}
}
else{ make_cookie(); }

}

################
sub generate_key {
#################
my($key_length) = @_;
my $generatedkey;
my $_rand;
if (!$key_length) { $key_length = 17; }
my @key_chars = split("", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
srand;
for (my $i=0; $i <= $key_length - 1; $i++) {
  $_rand = int(rand 62);
  $generatedkey .= $key_chars[$_rand];
	}
return $generatedkey;
}

############
sub getinput {
############
read(STDIN, $input, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $input);
foreach $pair(@pairs) {
($name, $value) = split(/=/, $pair);
$name =~ tr/+/ /;
$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$input{$name} = $value;
	}
	@vars = split(/&/, $ENV{QUERY_STRING});
	foreach $var(@vars) {
	($v,$i) = split(/=/, $var);
	$v =~ tr/+/ /;
	$v =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$i =~ tr/+/ /;
	$i =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$i =~ s/<!--(.|\n)*-->//g;
	$input{$v} = $i;
	}
}

##############
sub test_scripturl{
##############
print "Location: $PATH[0]/ok.gif\n" or print "<font color=green><b>OK</b></font>";
#use CGI qw(:standard); 
#print "Pragma: no-cache\n";
#print "Content-type: image/jpg\n\n"; 
#open (IMAGE, $basedir/images/ok.gif); 
#binmode(IMAGE); STDOUT;
#my $buffer="";
#while ( read( IMAGE, $buffer, 16_384) ){print $buffer;}
#close IMAGE;	
#exit 0; 
}

#############
sub getinfo {
#############
my ($getinf_req)=@_;
if(open MAIN,"<./paths.txt"){chomp(@PATH=<MAIN>);close (MAIN);}
if(-e "$PATH[1]/cgi-lib_/admin.pl"){unlink("$PATH[1]/cgi-bin.zip");}
if(-d "$PATH[2]/themes_"){unlink("$PATH[2]/html.zip");}

#gzip and tar
@gzipprog = `whereis gzip`; ($gzipprog)=(split/\s+/,($gzipprog[0]))[1];
@tarprog = `whereis tar`; ($tarprog)=(split/\s+/,($tarprog[0]))[1];
#PREPARE PATHS
$subdircnt=(@subdir) = split/\//,$ENV{SCRIPT_NAME};
$magickstick="/";
$installdir_="$subdir[$#$subdir-1]";
if($installdir_ && $installdir_ ne ""){$installdir="$magickstick$installdir_";}else{$installdir=();}
$cgidir_="$subdir[$#$subdir-2]";
if($cgidir_ && $cgidir_ ne ""){$cgidir="$magickstick$cgidir_";}else{$cgidir=();}
#URL PATHS
if($subdircnt>4){($subfolder)=split/$cgidir/,$ENV{SCRIPT_NAME};}
else{$subfolder=();}
if($ENV{SCRIPT_URI} && $ENV{SCRIPT_URI} ne ""){($webappurl)=split/$installdir\/\w+\.cgi/,$ENV{SCRIPT_URI};}
else{
	if($ENV{HTTP_REFERER}=~/$installdir\/\w+\.cgi$/){($webappurl)=split/$installdir\/\w+\.cgi/,$ENV{HTTP_REFERER};}
	else{
		if($ENV{'HTTP_HOST'} && $ENV{'HTTP_HOST'} ne ""){$webappurl="http://$ENV{'HTTP_HOST'}$subfolder$cgidir";}
		else{
			if($ENV{'SERVER_NAME'} && $ENV{'SERVER_NAME'} ne ""){$webappurl="http://$ENV{'SERVER_NAME'}$subfolder$cgidir";}
		}			
	}
}	

$baseurl="$PATH[0]" || "$ENV{DOCUMENT_ROOT}"; # else...split/$cgidir/,$webappurl;
if($baseurl=~m|/$|){$baseurl=~s/\/$//;}

#DIRECTORY PATHS
$myscriptpath="$PATH[1]";
($testscriptpath)=split/$installdir\/\w+\.cgi/,$ENV{SCRIPT_FILENAME};
$scriptpath="$myscriptpath" || "$testscriptpath";
#$myrootpath="$PATH[2]";
($mytestrootpath)=split/$cgidir/,$ENV{SCRIPT_FILENAME};
$testrootpath="$PATH[2]" || "$mytestrootpath";
#most common
if(-e "$testrootpath/ok.gif"){$rootpath=$testrootpath; $dontcheck="1";}
#separated html folder
elsif(!$dontcheck){
	if($ENV{DOCUMENT_ROOT_REAL} ne ""){
		if(-e "$ENV{DOCUMENT_ROOT_REAL}$subfolder/ok.gif"){
			$rootpath="$ENV{DOCUMENT_ROOT_REAL}$subfolder"; $dontcheck="1";
			}
		elsif(-e "$ENV{DOCUMENT_ROOT_REAL}/ok.gif"){
			$rootpath="$ENV{DOCUMENT_ROOT_REAL}"; $dontcheck="1";
			}
	}
	else{
		if($ENV{DOCUMENT_ROOT} ne ""){
			if(-e "$ENV{DOCUMENT_ROOT}$subfolder/ok.gif"){
				$rootpath="$ENV{DOCUMENT_ROOT}$subfolder"; $dontcheck="1";
				}
			elsif(-e "$ENV{DOCUMENT_ROOT}/ok.gif"){
				$rootpath="$ENV{DOCUMENT_ROOT}"; $dontcheck="1";
				}
			}
	}
}
#special cases, fedore, free bsd and other funny servers
else{
	($rootpath)=split/$ENV{SCRIPT_NAME}/,$ENV{SCRIPT_FILENAME};
	if(-e "$rootpath/ok.gif"){$htmldir=();}
	elsif(-e "$rootpath/home/ok.gif"){$htmldir="/home";}
	elsif(-e "$rootpath/doc/ok.gif"){$htmldir="/doc";}
	elsif(-e "$rootpath/docs/ok.gif"){$htmldir="/docs";}
	elsif(-e "$rootpath/www/ok.gif"){$htmldir="/www";}
	elsif(-e "$rootpath/wwws/ok.gif"){$htmldir="/wwws";}
	elsif(-e "$rootpath/http/ok.gif"){$htmldir="/http";}
	elsif(-e "$rootpath/https/ok.gif"){$htmldir="/https";}
	elsif(-e "$rootpath/html/ok.gif"){$htmldir="/html";}
	elsif(-e "$rootpath/htmls/ok.gif"){$htmldir="/htmls";}
	elsif(-e "$rootpath/httpdoc/ok.gif"){$htmldir="/httpdoc";}
	elsif(-e "$rootpath/httpdocs/ok.gif"){$htmldir="/httpdocs";}
	elsif(-e "$rootpath/httpsdocs/ok.gif"){$htmldir="/httpsdocs";}
	elsif(-e "$rootpath/www_doc/ok.gif"){$htmldir="/www_doc";}
	elsif(-e "$rootpath/www_docs/ok.gif"){$htmldir="/www_docs";}
	elsif(-e "$rootpath/wwwdoc/ok.gif"){$htmldir="/www_doc";}
	elsif(-e "$rootpath/wwwdocs/ok.gif"){$htmldir="/www_docs";}
	else{ 
#YOU DID TRY EVERYTHING RAMBO, NOW ITS TIME TO D.I.Y OR CONTACT US SO WE CAN DO IT FOR YOU
	if($ENV{SCRIPT_NAME} =~/advance/g){
	$nopath=qq~????????????????????????~;
	$default_error=qq~<img src="http://www.web-app.net/images/help_me.gif" title="IMPORTANT!"><font color=red>ERROR! The advance install script did not manage to locate your html folder. <br>Please correct the red fields under. If you are not sure what the correct paths are, kindly ftp to your site and check the folder structure and try again or contact your host provider for support. <br><font color=green>If this error persists, please report the issue to the WebAPP support group at <a href=http://www.web-app.net/cgi-bin/index.cgi?action=forum&board=Welcome>http://www.web-app.net</a> Thank you!</font></h3><br>~;
	$redfields=qq~ style="font-size: 14px; color:red; weight:bold;"~;
	$red1=qq~<font color=red>~; $red2=qq~</font>~;
	}
	elsif($ENV{SCRIPT_NAME} =~/default/g){
		$default_error=qq~<img src="http://www.web-app.net/images/help_me.gif" title="IMPORTANT!"><font color=red>ERROR! The $default install script did not manage to locate your html folder.<br>Please go back and try the "Advanced installation".<br>~;
		}
	}
}

# EMAIL PATHS AND COOKIES
($hosturl) = split/$installdir/,$ENV{SERVER_NAME};
$smtpfun = $ENV{SERVER_NAME};
@mailprog = `whereis sendmail`;
($mailprog)=(split/\s+/,($mailprog[0]))[1];
$mailprogram_="$mailprog" || "/usr/sbin/sendmail";
$mailprogram="$mailprogram_ -t";
@g_email=split/\./,$hosturl;
$email_domain="$g_email[$#g_email-1].$g_email[$#g_email]";
$myemail_="info\@$email_domain";
$myemail="$ENV{'SERVER_ADMIN'}" || "$myemail_"; 

$cookiestring = "$hosturl";
$cookiestring =~ s/\W|_//ig;
$cookiestring =~ s/^www//ig;
$cookienameuid = $cookiestring . "uid";
$cookienamepwd = $cookiestring . "pwd";
$cookienamethm = $cookiestring . "thm";
$cookienamelng = $cookiestring . "lng";
$cookieform = $cookiestring . "form";
$cookiemac = $cookiestring . "mac";
$cookiepref = $cookiestring . "pref";
$cookiesid = $cookiestring . "sid";
$webapp = "http://www.web-app.net";
}

#################
sub welcome{
##################
print_head(start);
$MYURLPATH="$PATH[0]" || "$URLPATH";
$myscriptpath="$PATH[1]" || "$scriptpath";
$myrootpath="$PATH[2]" || "$rootpath";

if($ENV{QUERY_STRING} !~ m|IMAGE$| && $PATH[0] eq ""){
	$index_error=qq~<font color=red><b>Please start the install at: <u>http://www.your_webapp_site.com</u><br>
	It is also recommended that you read the README.txt file before you install WebAPP v. 1.0
	<br>Thank you!</b></font>~;
	logevent("ERROR\|Installation did not start at: http://www.your_webapp_site.com");
	}

$ok=qq~<font color=green><b>OK</b></font>~;
$notok=qq~<font color=red><b>ERROR: please try another path.</b></font>~;
$unzip2ok=qq~<INPUT TYPE="submit" VALUE="Unzip &#187" name="moda5" STYLE="color: #FFFFFF; font-family: Verdana; font-weight: bold; font-size: 12px; background-color: #006600;" size="12" onclick="alert('Please click OK now and wait while your cgi-bin data is being processed. This may take a minute or two. Please DO NOT click anything before the unzipped files are listed and the Unzip button disappears.');">~;
$unzip3ok=qq~<INPUT TYPE="submit" VALUE="Unzip &#187" name="moda6" STYLE="color: #FFFFFF; font-family: Verdana; font-weight: bold; font-size: 12px; background-color: #006600;" size="12" onclick="alert('Please click OK now and wait while your html data is being processed. This may take a minute or two. Please DO NOT click anything before the unzipped files are listed and the Unzip button disappears.');">~;
if(-e "$myscriptpath/cgi-bin.bin" || -e "$myscriptpath/cgi-bin.zip" || -e "$myscriptpath/cgi-lib_/admin.pl" || -e "$myscriptpath/cgi-lib/admin.pl"){
	$ok2=$ok; 
		if((-e "$myscriptpath/cgi-bin.bin" || -e "$myscriptpath/cgi-bin.zip") && !$input{'moda5'}){$unzip2=$unzip2ok;}
	}
	else{ $ok2=$notok;}
if(-e "$myrootpath/html.zip" || -e "$myrootpath/ok.gif"){
	$ok3=$ok; 
		if((-e "$myrootpath/html.bin" || -e "$myrootpath/html.zip") && !$input{'moda6'}){$unzip3=$unzip3ok;}
	}
	else{ $ok3=$notok;}
	
if($ok3 eq "$ok" && $ok2 eq "$ok" && (!-e "$myrootpath/html.zip" || $input{'moda6'}) && (!-e "$myscriptpath/cgi-bin.zip" || $input{'moda5'})){$continue=1;}	

print qq~$index_error
<h3><center>Welcome to the $installscriptname v$installversion Installer. Please <u>test</u> and <u>confirm</u> the paths below before proceeding.</center><center><img src="http://www.web-app.net/images/help_me.gif" title="You may also join our support forums for help finding your server paths.">If you do not know your correct path information, please check with your web hosting provider first.~;

$chmod_test=chmod_file("./test.cgi", "0755");
if($chmod_test=~m|^OK|){
	print qq~<BR><font color=GREEN><img src="http://www.web-app.net/images/help_me.gif" title="use this script to inspect for the correct paths on your server."> You may also use this <a href="./test.cgi?&action=advance" target="_blank"><u>tool</u></a> to test for the correct paths.
	</font>~;
	}
	

 print qq~</center></b></h3>	
<form method="post" action="./setup.cgi?"><input type="hidden" name="action" value="update"><h4>

Your site location: <input type="text" class="textinput" name="sitepath" value="$MYURLPATH" size="50">
Test: <img src="$MYURLPATH/ok.gif">~;
if(!$continue){print qq~ <INPUT TYPE="submit" VALUE="Update" name="moda1" STYLE="color: #FFFFFF; font-family: Verdana; font-weight: bold; font-size: 12px; background-color: #006600;" size="12">~;
	} 
	print qq~ <br>
	
	
Your html directory path: <input type="text" class="textinput" name="htmldirpath" value="$myrootpath" size="50">
Test: $ok3~; 
if(!$continue){print qq~ <INPUT TYPE="submit" VALUE="Update" name="moda3" STYLE="color: #FFFFFF; font-family: Verdana; font-weight: bold; font-size: 12px; background-color: #006600;" size="12">~;
	}
	print qq~ $unzip3<br>	
	
Your cgi-bin directory path: <input type="text" class="textinput" name="cgidirpath" value="$myscriptpath" size="50">
Test: $ok2 ~; 
if(!$continue){print qq~ <INPUT TYPE="submit" VALUE="Update" name="moda2" STYLE="color: #FFFFFF; font-family: Verdana; font-weight: bold; font-size: 12px; background-color: #006600;" size="12">~;
	}
	print qq~ $unzip2<br>~;
		
	if($continue){
		print qq~
	<FORM METHOD="LINK" ACTION="./cgi-bin/install/setup.cgi">
	<div align="center"><INPUT TYPE="submit" VALUE="Continue &#187" name="moda4" STYLE="color: #FFFFFF; font-family: Verdana; font-weight: bold; font-size: 12px; background-color: #006600;" size="14"><br><font color="red" size=-1><img src="http://www.web-app.net/images/help_me.gif" title="IMPORTANT!"><b>If <u>all</u> the three tests result with "OK" and <u>all files are unzipped</u> click above button to continue with the install.</b></font></div>~;
	}
	print qq~<hr size=3 color="#5579C7"></form>~;
}
#################
sub start{
##################
print_head(one);

if(-s "../conf/config.cnf" || -s "../conf/config.dat"){$recom2=qq~(recommended)~; $conf_upgrade=qq~onClick="return confirmSubmit();"~;}
else{$recom1=qq~(recommended).~;}
if($recom2){$alert_db=qq~ onclick= "alert('The install detected that you still have not removed your old site files, please remove your old files and try again, otherwise please select upgrade.'); return false;"~;}
else{$alert_db2=qq~ onclick= "alert('The install can not detect your old db/ folder, please select default install.'); return false;"~;}
print qq~
<p class="style5"><h3><center></center></td></tr>
	<tr>
  <td class="style5"><u><strong>Please choose your installation type:</strong></u><strong><br />
     1.)  <a href="./default.cgi" $alert_db>Default installation &#187&#187</a>$recom1<br>
     2.)  <a href="./advance.cgi" $alert_db>Advanced installation &#187&#187</font></a></strong><br>     
     3.)  <a href="./upgrade.cgi" $alert_db2 $conf_upgrade>Upgrade (beta) &#187&#187</a>$recom2<br>
	</td></tr></table><hr size=3 color="#5579C7"></p>
	<h5><b><font color="#0F1C62">*Please note: the upgrade is still in beta phase, we recommend this function only for advanced users</font></b></h5>~;
}

################
sub look_for_file{
################
my($file_2look4)=@_;
if(-e "$file_2look4"){return ("OK\|found file: $file_2look4");}
else{return ("ERROR\|could not find file: $file_2look4");}
}

################
sub movefiles {
################
use File::Copy;
my $magicus="_";
getinfo();
### DO NOT CHANEG THIS LINE! ###
if(!-d $scriptdir){
	die "ERROR Your scriptdir is not defined, please contact http://www.web-app.net support \nor try a different instal option, thank you";
}
#################################################################################################################
if(-B "$rootpath/themes/standard/images/english/logo.jpg"){
	copy_file("$rootpath/themes/standard/images/english/logo.jpg", "$rootpath/themes_/standard/images/english/logo.jpg", "anyway");
	}

opendir(IMGUL, "$rootpath/images/uploads");
	my @UPimages = grep { /[a-zA-Z1-9]/ } readdir(IMGUL);
foreach(@UPimages){
	if(-B "$rootpath/images/uploads/$_"){
		copy_file("$rootpath/images/uploads/$_", "$rootpath/images_/uploads/$_");
		}
	}
closedir(IMGUL);


opendir(IMGUL, "$datadir");
my @DBtxt = grep { /txt$/ } readdir(DBTXT);
foreach(@DBtxt){
	if(-T "$datadir/$_" && $datadir/$_ ne "contributors.txt" && $datadir/$_ ne "ver.txt"){
		copy_file("$datadir/$_", "$scriptdir/db_");
		}
	}
closedir(DBTXT);

opendir(CACH, "$datadir/cache");
my @cache = grep { /tmp$/ } readdir(CACH);
foreach(@cache){
	if(-T "$datadir/cache/$_"){
		copy_file("$datadir/cache/$_", "$scriptdir/db_/cache");
		}
	}
closedir(CACH);

if(-T "$datadir/banned/banned_ip.txt"){
	copy_file("$datadir/banned/banned_ip.txt", "$scriptdir/db_/banned/banned_ip.txt");
	}

opendir(BN, "$datadir/banners");
my @banners = grep { /[a-zA-Z1-9]/ } readdir(BN);
foreach(@banners){
	if(-T "$datadir/banners/$_"){
		copy_file("$datadir/banners/$_", "$scriptdir/db_/banners/$_");
		}
	}
closedir(BN);

opendir(BL, "$datadir/blocks");
my @blocks = grep { /[a-zA-Z1-9]/ } readdir(BL);
foreach(@blocks){
	if(-T "$datadir/blocks/$_"){
		copy_file("$datadir/blocks/$_", "$scriptdir/db_/blocks/$_");
		}
	}
closedir(BL);

opendir(DOWN, "$datadir/downloads");
my @downloads = grep { /[a-zA-Z1-9]/ } readdir(DOWN);
foreach(@downloads){
	if(-T "$datadir/downloads/$_"){
		copy_file("$datadir/downloads/$_", "$scriptdir/db_/downloads/$_");
		}
	}
closedir(DOWN);

opendir(LINK, "$datadir/links");
my @links = grep { /[a-zA-Z1-9]/ } readdir(LINK);
foreach(@links){
	if(-T "$datadir/links/$_"){copy_file("$datadir/links/$_", "$scriptdir/db_/links/$_");
	}
}
closedir(LINK);


opendir(FORUM, "$datadir/forum");
my @forums = grep { /[a-zA-Z1-9]/ } readdir(FORUM);
foreach(@forums){
	if(-T "$datadir/forum/$_"){
		copy_file("$datadir/forum/$_", "$scriptdir/db_/forum/$_");
		}
	}
closedir(FORUM);

opendir(FORUM2, "$datadir/forum/messages");
my @forums2 = grep { /[a-zA-Z1-9]/ } readdir(FORUM2);
foreach(@forums2){
	if(-T "$datadir/forum/messages/$_"){copy_file("$datadir/forum/messages/$_", "$scriptdir/db_/forum/messages/$_");
	}
}
closedir(FORUM2);

opendir(GALLERY, "$datadir/gallery");
my @gallery = grep { /[a-zA-Z1-9]/ } readdir(GALLERY);
closedir(GALLERY);
foreach $gal1(@gallery){
	if(-T "$datadir/gallery/$gal1"){copy_file("$datadir/gallery/$gal1", "$scriptdir/db_/gallery/$gal1");}
	else{ 
		make_dir("$scriptdir/db_/gallery/$gal1", "0777");
		opendir(GALLERY2, "$datadir/gallery/$gal1");
		my @gallery2 = grep { /[a-zA-Z1-9]/ } readdir(GALLERY2);
		foreach $gall2(@gallery2){
			if(-T "$datadir/gallery/$gal1/$gal2"){copy_file("$datadir/gallery/$gal1/$gal2", "$scriptdir/db_/gallery/$gal1/$gal2", "just", "no_log");}
		}
	}
}
closedir(GALLERY);
closedir(GALLERY2);

opendir(HELP, "$datadir/help");
my @help = grep { /[a-zA-Z1-9]/ } readdir(HELP);
foreach(@help){
	if(-T "$datadir/help/$_"){
		copy_file("$datadir/help/$_", "$scriptdir/db_/help/$_");
		}
	}
closedir(HELP);

opendir(MEM, "$datadir/members");
my @members = grep { /[a-zA-Z1-9]/ } readdir(MEM);
foreach(@members){
	if(-T "$datadir/members/$_" && $_  ne "restrictedmemberlist.dat"){copy_file("$datadir/members/$_", "$scriptdir/db_/members/$_", "just", "no_log");
	}
}
closedir(MEM);

opendir(MEN, "$datadir/menuman");
my @menumans = grep { /[a-zA-Z1-9]/ } readdir(MEN);
foreach(@menumans){
	if(-T "$datadir/menuman/$_"){copy_file("$datadir/menuman/$_", "$scriptdir/db_/menuman/$_");
	}
}
closedir(MEN);

opendir(POL, "$datadir/menuman");
my @poll = grep { /[a-zA-Z1-9]/ } readdir(POL);
foreach(@poll){
	if(-T "$datadir/polls/$_"){copy_file("$datadir/polls/$_", "$scriptdir/db_/polls/$_");
	}
}
closedir(POL);

opendir(SHT, "$datadir/showhtml");
my @sht = grep { /[a-zA-Z1-9]/ } readdir(SHT);
foreach(@sht){
	if(-T "$datadir/showhtml/$_"){copy_file("$datadir/polls/$_", "$scriptdir/db_/showhtml/$_");
	}
}
closedir(SHT);

opendir(TP, "$datadir/topics");
my @topics = grep { /[a-zA-Z1-9]/ } readdir(TP);
foreach(@topics){
	if(-T "$datadir/topics/$_"){copy_file("$datadir/topics/$_", "$scriptdir/db_/topics/$_");
	}
}
closedir(TP);

opendir(TP2, "$datadir/topics/articles");
my @topics2 = grep { /[a-zA-Z1-9]/ } readdir(TP2);
foreach(@topics2){
	if(-T "$datadir/topics/articles/$_"){copy_file("$datadir/topics/articles/$_", "$scriptdir/db_/topics/articles/$_", "just", "no_log");
	}
}
closedir(TP2);
		
if(!-d "$scriptdir/install/OLD"){$rename_makedir=make_dir("$scriptdir/install/OLD", "0777"); logevent("$rename_makedir");}
chmod_file("$scriptdir/install/OLD", "0777"); # FORCE IT!
if(!-d "$scriptdir/install/OLD"){ 
	die "Error: Could not create backup folder. \nPlease make sure that your backup folder exist here: $scriptdir/install/OLD";
	} # EXTRA TEST TO BE 100% SURE THAT BACKUP FOLDER IS THERE!
@old_site_dir= qw/admin cgi-lib conf db lang mods Modules upgrade user-lib/;
foreach $dir(@old_site_dir){
	if(-d "$scriptdir/$dir$magicus"){move_dir("$scriptdir/$dir", "$scriptdir/install/OLD/$dir");}
	}
if(-d "$rootpath/images_"){move_dir("$rootpath/images", "$scriptdir/install/OLD/images");}
if(-d "$rootpath/themes_"){move_dir("$rootpath/themes", "$scriptdir/install/OLD/themes");}
renamefiles();
}

################
sub move_dir{
################
my ($mvsource, $mvdestination)=@_;
$oldext="_OLD";
if(-d "$mvdestination"){
	rename("$mvdestination", "$mvdestination$oldext");
	logevent("OK\|ok but had to rename your: $mvdestination to: $mvdestination$oldext");
	}
if(move("$mvsource","$mvdestination")==1){
	chmod_file("$mvdestination", "0644");
	logevent("OK\|moved $mvsource to $mvdestination");
	}
else{logevent("ERROR\|can not move $mvsource to $mvdestination");}
}

################
sub copy_file{
################
my ($cpsource, $cpdestination, $cp_type, $log_type)=@_;  
if(-s "$cpsource" > -s "$cpdestination" || $cp_type eq "anyway"){
	unlink("$cpdestination");
	if(copy("$cpsource", "$cpdestination")==1){ 
		unless($log_type eq "no_log"){logevent("OK\|converted old file: $cpsource to your new db!");}
		}
	else{logevent("ERROR\|could not update $cpsource");}
	}
else{logevent("OK\|updated your db with a new db file: $cpsource");}
}

################
sub make_dir{
################
my ($dir2make, $permissions) = @_;
$makdir=mkdir("$dir2make", $permissions);
if($makdir){return ("OK\|created directory $dir2make");}
else{return "ERROR\|cant create directory $dir2make";}
}

################
sub renamefiles{
#################
use lib "../Modules_";
eval("use Memoize"); if ($@){rename_file("../Modules_/Memoize_.pm", "../Modules_/Memoize.pm"); }
if(-e "$PATH[1]/cgi-lib_/admin.pl"){unlink("$PATH[1]/cgi-bin.zip");}
if(-e "$PATH[2]/themes_"){unlink("$PATH[2]/html.zip");}
@NEWDIRS=qw/db_ admin_ cgi-lib_ conf_ lang_ mods_ Modules_ upgrade_ user-lib_/;
foreach (@NEWDIRS){
	$rename0=();
	if(-d "../$_"){
		$new_name=$_; 
		$new_name=~s/_//; 
		$rename0=rename_file("../$_", "../$new_name");
		logevent("$rename0");
		}
	}
$logindex=chmod_file("../index.cgi", "0755"); logevent("$logindex");
chmod_html();
$rename3=rename_file("$rootpath$htmldir/images_", "$rootpath$htmldir/images"); logevent("$rename3");
$rename4=rename_file("$rootpath$htmldir/themes_", "$rootpath$htmldir/themes"); logevent("$rename4");
}

################
sub chmod_file {
################
$chmodfailed = "0";
my ($destination, $permissions) = @_;
if(chmod(oct($permissions), $destination)){return ("OK\|chmod $permissions $destination");}
else{return "ERROR\|cant chmod $permissions $destination";}
}

################
sub move_file {
################
my ($mvsource, $mvdestination) = @_;
if(system("mv $mvsource -Rf $mvdestination")==0){return("OK\|moved $mvsource to $mvdestination");}
else{return "ERROR\|cant move $mvsource to $mvdestination";}
}

################
sub rename_file {
################
$renamefailed = "0";
my ($source, $destination) = @_;
if(rename("$source", "$destination")){return ("OK\|renamed $source to $destination");}
else{	
		if(!-e "$source"){return "OK\|renamed before $source to $destination";}
		else{return "ERROR\|cant rename $source to $destination";}
	}
}

###############
sub logevent{
###############
my($event_tolog)= shift;
$mytime= time;
$logtime=localtime($mytime);
open LOG, ">>./install.log";
print LOG "$logtime|$event_tolog\n";
close LOG;
}

##############
sub remove_file{
################
my ($file2remove)=@_;
if(unlink($file2remove)){return("OK\|deleted $file2remove");}
	else{
		if(!-e "$file2remove"){return "OK\|deleted before $file2remove";}
		else{return "ERROR\|cant delete $file2remove";}
	}
}

###############
sub empty_cookies{
###############
print qq~Set-Cookie: $cookiesid=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: $cookiemac=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: $cookiepref=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: $cookieform=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: $cookieuserlang=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: $cookieusertheme=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: $cookieusername=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: $cookiepassword=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;
print qq~Set-Cookie: WELCOME=; path=/; expires=Tue, 01-Jan-1980 00:00:00 GMT;\n~;

}
#################
sub unlink_files{
##################
#my $haccess=".htaccess";
#open HTA, ">./$haccess";
#print HTA "Order allow,deny\ndeny from all\n";
#close HTA;
ubbjs();
$unlink1=remove_file("./setup.cgi");logevent($unlink1);unlink("$scriptdir/install/setup.cgi");
$unlink2=remove_file("./config.tmp");logevent($unlink2);unlink("$scriptdir/install/config.tmp");
$unlink3=remove_file("./advance.cgi");logevent($unlink3);unlink("$scriptdir/install/advance.cgi");
$unlink4=remove_file("./upgrade.cgi");logevent($unlink4);unlink("$scriptdir/install/upgrade.cgi");
$unlink5=remove_file("./config.temp");logevent($unlink5);unlink("$scriptdir/install/config.temp");
$unlink6=remove_file("./default.cgi");logevent($unlink6);unlink("$scriptdir/install/default.cgi");
$unlink8=remove_file("./test.cgi");logevent($unlink8);unlink("$scriptdir/install/test.cgi");
$unlink9=remove_file("./paths.txt");logevent($unlink9);unlink("$scriptdir/install/paths.txt");
$unlink10=remove_file("./cookie.dat");logevent($unlink10);unlink("$scriptdir/install/cookie.dat");
chmod_file("./install.log", "0600");
$unlink12=remove_file("./install_subs.pl");logevent($unlink12);unlink("$scriptdir/install/install_subs.pl");


}

#############
sub store_old{
############
use File::Copy;
my ($old_file)=@_;
$oldext=".old";
unless(-d "./OLD"){make_dir("./OLD", "0755");}
chmod_file("./OLD", "0755"); # FORCE IT!
move("../$old_file", "./OLD/$old_file$oldext");
}
##############
sub newsletter {
##############
my ($myemail)=@_;
$mysite="$ENV{'HTTP_HOST'}";
if(!$myemail){
	@g_email=split/\./,$mysite;
	$myemail="info\@$g_email[$#g_email-1].$g_email[$#g_email]";
	}
$toemail="newsletter\@web-app.net";
$subject_nl="Subscribe $mysite $myemail";
$message_nl="Subscribe $mysite $myemail";

if(open MAIL, "| /usr/sbin/sendmail -t"){
	print MAIL "To: $toemail\n";
	print MAIL "From: $myemail\n";
	print MAIL "Subject: $subject_nl\n";
	print MAIL "Message: $message_nl\n";
	}
else{
	open MAIL, "| /usr/lib/sendmail -t";
	print MAIL "To: $toemail\n";
	print MAIL "From: $myemail\n";
	print MAIL "Subject: $subject_nl\n";
	print MAIL "Message: $message_nl\n";
	}
	close MAIL;
}

################
sub ubbjs{
################
$andytri=qq~imagefiles:['$baseurl/images/min.gif', '$baseurl/images/close.gif', '$baseurl/images/restore.gif', '$baseurl/images/resize.gif'],~;
$ubbjsfile="$basedir/ubb.js";
if(open UBJS1,"<$ubbjsfile"){
	@UBB=<UBJS1>;
	close(UBJS1);
	open UBJS2,">$ubbjsfile" or die "cant open to write $ubbjsfile";
	foreach(@UBB){
		if($_ =~ /andytri/){print UBJS2 "$andytri\n";}
		else{print UBJS2 "$_";}
	}
	close(UBJS2);
	}
}

################
sub chmod_html{
################
if(-d "$PATH[2]/images_"){
	chmod_file("$PATH[2]/images_", "0777");
	opendir(IMGDIR, "$PATH[2]/images_");
	for my $imagedirfiles(grep (/[a-zA-Z1-9]/, readdir (IMGDIR))){
		chmod_file("$PATH[2]/images_/$imagedirfiles", "0777");
		if(-d "$PATH[2]/images_/$imagedirfiles"){
			opendir(IMGDIR2, "$PATH[2]/images_/$imagedirfiles");	
			for my $imagedirfiles2(grep (/[a-zA-Z1-9]/, readdir (IMGDIR2))){
				chmod_file("$PATH[2]/images_/$imagedirfiles/$imagedirfiles2", "0777");	
			}			
		}
	closedir(IMGDIR2);
	closedir(IMGDIR);	
	}
	
	opendir(IMGDIRb, "$PATH[2]/images_/forum/buttons");
	for my $imageb(grep (/[a-zA-Z1-9]/, readdir (IMGDIRb))){
		chmod_file("$PATH[2]/images_/forum/buttons/$imageb", "0777");
		}
	closedir(IMGDIRb);
	
	opendir(IMGDIRs, "$PATH[2]/images_/forum/smilies");
	for my $imagess(grep (/[a-zA-Z1-9]/, readdir (IMGDIRs))){
		chmod_file("$PATH[2]/images_/forum/smilies/$imagess", "0777");
	}
	closedir(IMGDIRs);
	
	opendir(IMGDIRsv, "$PATH[2]/images_/stats/visits");
	for my $imagesv(grep (/[a-zA-Z1-9]/, readdir (IMGDIRsv))){
		chmod_file("$PATH[2]/images_/stats/visits/$imagesv", "0777");
	}
	closedir(IMGDIRs);
	
	opendir(IMGDIRf, "$PATH[2]/images_/memberslist/flags");
	for my $imagef(grep (/[a-zA-Z1-9]/, readdir (IMGDIRf))){
		chmod_file("$PATH[2]/images_/memberslist/flags/$imagef", "0777");
	}	
	closedir(IMGDIRf);	
	
	opendir(IMGDIRg, "$PATH[2]/images_/memberslist/gender");
	for my $imageg(grep (/[a-zA-Z1-9]/, readdir (IMGDIRg))){
		chmod_file("$PATH[2]/images_/memberslist/gender/$imageg", "0777");
	}
	closedir(IMGDIRg);

	chmod_file("$PATH[2]/images_/topics/new/1.gif", "0777");			
	chmod_file("$PATH[2]/images_/memberslist/forum/star.gif", "0777");
}

if(-d "$PATH[2]/themes_"){
	chmod_file("$PATH[2]/themes_", "0755");
	opendir(THMDIR, "$PATH[2]/themes_");
		for my $themesdirfiles(grep (/[a-zA-Z1-9]/, readdir (THMDIR))){
			chmod_file("$PATH[2]/themes_/$themesdirfiles", "0777");
			}
	closedir(THMDIR);		
			
	opendir(THMDIR2, "$PATH[2]/themes_/standard");	
		for my $themesdirfiles2(grep (/[a-zA-Z1-9]/, readdir (THMDIR2))){
			chmod_file("$PATH[2]/themes_/standard/$themesdirfiles2", "0755");
			}	
	closedir(THMDIR2);		
				
	opendir(THMDIR3, "$PATH[2]/themes_/standard/images");	
		for my $themesdirfiles3(grep (/[a-zA-Z1-9]/, readdir (THMDIR3))){
			chmod_file("$PATH[2]/themes_/standard/images/$themesdirfiles3", "0777");
			}	
	closedir(THMDIR3);	
	
	opendir(THMDIR4, "$PATH[2]/themes_/styleeditor/images");	
		for my $themesdirfiles4(grep (/[a-zA-Z1-9]/, readdir (THMDIR4))){
			chmod_file("$PATH[2]/themes_/styleeditor/images/$themesdirfiles4", "0777");
			}	
	closedir(THMDIR4);	
			
	chmod_file("$PATH[2]/themes_/standard/images/english/logo.jpg", "0777");
	chmod_file("$PATH[2]/themes_/styleeditor/index.html", "0777");
	chmod_file("$PATH[2]/themes_/styleeditor/plugin.css", "0777");		
	}
}

################
sub upgradekey{
#################
my($updated_key, $updated_value, $updatereq)=@_;
$config_file="../conf/config.cnf"; 
$updatedvalue=quotemeta($updated_value); 
open(UDCONFIG,"<$config_file");
@CONF=<UDCONFIG>;
chomp;
close(UDCONFIG);
open(CONFDB,">$config_file");
if($updatereq eq "createkey"){print CONFDB "\$$updated_key=qq\~$updatedvalue\~\;\n";}
foreach(@CONF){
	($mykey)=split/\=/,$_,2;
	if($mykey eq "\$$updated_key" && $updatereq eq "updatekey"){print CONFDB "\$$updated_key=qq\~$updatedvalue\~\;\n";}
	else{print CONFDB "$_";}
}
close CONFDB;
do $config_file
}
1;
