#!/usr/bin/perl -Tw -I. -I/usr/local/positive/Perl

#
# This software is copyright (c) 2001-2002 Positive Networks, Inc.  All rights reserved.
#
# This software is the proprietary and confidential property of Positive Networks, Inc.
# Possession, transmission, publication, or use of this software is prohibited except by prior written consent.
#

use strict;
use Config::General;

use Pos::Webtop::Web::ModuleLoader;
use Pos::Webtop::Web::OEMLoader;
use Pos::MessageQueue::Put::MQI;

#
# 2019.05.22: LMoody
#		Added to support ANXSC-178
#
my $conf = new Config::General("/usr/local/positive/conf/VpnDownload.conf");
my %config = $conf->getall;

my $mqi = MQI->new();
my $mqiHostName  = $mqi->getHostName();
my $mqiQueueName = $mqi->getQueueNameByType( type=> "queueRunSql" );

my $tb = Pos::Webtop::Toolbox->new();

if(not defined $tb)
{
	die "unable to build a toolbox";
}

my $client = $tb->getClient();
my $cgi = $tb->getCgi();

if(not defined $client or not defined $cgi)
{
	die "unable to get an object from the toolbox";
}

# verify the user
$client->checkSession(ignoreAuxAuth=> 1);


my $userId = $client->getUserId();
my $userName = $client->getUserName();
my $db = $tb->getWebtopDbReader();
my $si = $client->getSessionId();
my $mode = $cgi->param('mode');

my $usertype;

if ($mode eq 'vpn')
{
	my ($vpnAccess,$vpnDownload) = @{$client->isVpnAccessEnabled(db=> $db, userId=> $userId)};

	if (!$vpnAccess || !$vpnDownload || !$client->isUserRegistered(tb=> $tb, db=> $db))
	{
		print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');
		exit;
	}
}
elsif($mode eq 'netcon')
{
	$usertype = $client->getUserType(db=>$db, userId=> $userId);

	if ($usertype ne 'NAT AGENT')
	{
		print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');
		exit;
	}
}
else
{
		print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');
		exit;
}


my $referrer = $ENV{'HTTP_REFERER'};
my $browserInfo = substr($ENV{'HTTP_USER_AGENT'}, 0, 255);
my $ip = $ENV{'REMOTE_ADDR'};

my $is95 = $cgi->param('is95');
my $is98 = $cgi->param('is98');
my $isME = $cgi->param('isME');
my $productName;
my $productInstallPath;

my $iosDownload = 0;
my $vpnDownload = 0;
my $osxDownload = 0;

($vpnDownload) = $db->query( sql => "
	select
		can_download_vpn
	from
		user_vpn_access
	where
		user_id = '$userId'
		limit 1
	");


($iosDownload) = $db->query( sql => "
	select
		can_download_l2tp_ios
	from
		user_vpn_access
	where
		user_id = '$userId'
		limit 1
	");

($osxDownload) = $db->query( sql => "
	select
		can_download_l2tp_macosx
	from
		user_vpn_access
	where
		user_id = '$userId'
		limit 1
	");

my $oem = $tb->getOem;

if ( defined $mode and $mode eq 'vpn' )
{
	
	$productName = $oem->getSetting(setting => 'vpnProductName');
	$productInstallPath = $oem->getSetting(setting => 'installerPath');

	if ($is95 or $is98 or $isME)
	{
		my $osVersion;
		if ($is95)
		{
			$osVersion = "95";
		}	
		if ($is98)
		{
			$osVersion = "98";
		}	
		if ($isME)
		{
			$osVersion = "ME";
		}	
		my @version = $db->query(sql => "
											select
												required_major,
												required_minor
											from software_product_forced_rel a,
											os b
											where a.os_id = b.os_id
											and b.os_major_ver_name = '$osVersion'
		");
		my ($majorVersion, $minorVersion) = @ { $version[0] };
		
		my $currentMajorVersion = "0";
		my $currentMinorVersion = "0";

		if ($productInstallPath =~ /vpn\-(\d+)\.(\d+)/)
		{
			$currentMajorVersion = $1;
			$currentMinorVersion = $2;
		}

		if ($currentMajorVersion == 0)
		{
			#Must be on stable, latest, or testing.
			my $softwareBranch;
			if ($productInstallPath =~ /vpn\-(.+)\//)
			{
				$softwareBranch = $1;
			}
			@version = $db->query(sql => "
				select
					c.major_release_number,
					c.minor_release_number
				from user_software_versions a,
				software_product_branches b,
				software_releases c
				where b.software_product_id = a.software_product_id and b.software_branch_type_id = a.software_branch_type_id
				and c.software_release_id = b.software_release_id
				and a.software_product_id = 1
				and a.user_id = $userId
			");
			($currentMajorVersion, $currentMinorVersion) = @ { $version[0] };
			if (int($currentMajorVersion) > int($majorVersion) or (int($currentMajorVersion) == int($majorVersion) and int($currentMinorVersion) > int($minorVersion)))
			{
				$productInstallPath =~ s/$softwareBranch/$majorVersion.$minorVersion/;
			}
		}
		else
		{
			if (int($currentMajorVersion) > int($majorVersion) or (int($currentMajorVersion) == int($majorVersion) and int($currentMinorVersion) > int($minorVersion)))
			{
				$productInstallPath =~ s/$currentMajorVersion/$majorVersion/;
				$productInstallPath =~ s/$currentMinorVersion/$minorVersion/;
			}
		}
	}

        #	
        # VPN-4153  
        #    2012-04-19 - LM
        #	

	my $dbw = $tb->getWebtopDbWriter();

	#$dbw->do( sql=> " update user_enrollment_metrics set client_download_date=" . $dbw->getCurrentDateString() . " where user_id = " . $client->getUserId() . " and client_download_date is null" );
	#$dbw->commit();

	my $sql = "update user_enrollment_metrics set client_download_date=" . $dbw->getCurrentDateString() . " where user_id = " . $client->getUserId() . " and client_download_date is null";

        $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );
}
if ( defined $mode and $mode eq 'netcon' )
{
	$productName = $oem->getSetting(setting => 'networkConnectorName');
	$productInstallPath = $oem->getSetting(setting => 'netconInstallerPath');
}

$oem->printHtmlHeader;
my $companyLogoSettings = $tb->getCompanyLogoSettings();
$oem->printBodyHeader(companyText=> $companyLogoSettings->{'companyText'}, companyImage=> $companyLogoSettings->{'companyImage'}, removeSupportImages => $companyLogoSettings->{'removeSupportImages'});
printBodyText( oem=> $oem );
$oem->printBodyFooter;
$oem->printHtmlFooter;


$db->do( sql=> "delete from client_sessions where client_session_id = $si" );
$db->commit();


exit;

sub printBodyText
{
	my ($oem) = @{{@_}}{qw/oem/};

	print "
		<!-- START BODY TEXT -->
		<div class=\"BOXTD1\"><span style='font-size: 18px;'><b>Ready to download</b></span></div>
		
		<center>
			<table border=\"0\">
			  <tr>
				 <td colspan=\"3\">
						<center>
						<table border='0'>
						<tr>
							<td class='BOXTD1'>
							  <br>
								  <b>Please click the link to download the $productName " . ($productName eq 'VPN Client' ? "" : "client" ) . "<br><br>
							</td>
						</tr>
						</table>
						</center>
				 </td>
			  </tr>
			  <tr>
			  	<td>
			  		<table cellspacing='10' cellpadding='1' border='0' width='100%'>
			  			<tr>
							<td align=\"center\" valign=\"top\" class=BOXDEF>

";

if ($vpnDownload || $usertype eq "NAT AGENT")
{
	#
	# 20200707 - LM moodyl@opentext.com
	#	ANXSC-292 : Added support to show Windows 10 support for Netcons, too
	#
	#
	my( @info ) = $db->query( sql=> "
				SELECT 
					major_release_number,
	         			minor_release_number
					FROM user_software_versions AS usv
					JOIN software_products AS sp ON sp.software_product_id = usv.software_product_id
					JOIN software_releases AS sr ON sr.software_release_id = usv.software_release_id
						 WHERE user_id = $userId AND sp.distribution_identifier = '$mode'" );

	my($currentMajorVersion, $currentMinorVersion ) = @{ $info[0] };

	print "
						<div id=\"downloadWin\"> 	";

	if( ( $currentMajorVersion ==  $config{showWin10MajorVersion} && $currentMinorVersion >= $config{showWin10MinorVersion} )  ||
	    		( $currentMajorVersion ==  $config{showWin10NetconMajorVersion} && $currentMinorVersion >= $config{showWin10NetconMinorVersion} ) ) 
	{

	print "
			  						<table cellspacing='10' cellpadding='1' border='0' width='100%'>
										<tr>
											<td align=\"center\" valign=\"top\" class=BOXDEF colspan=\"2\">
												<b><u>Works with:</u></b>
											</td>
										</tr>
										<tr>
											<td align=\"left\" valign=\"top\" class=BOXDEF>
												Windows&reg; 10
											</td>
										</tr>
			";

	}
	else
	{
	print "
			  						<table cellspacing='10' cellpadding='1' border='0' width='100%'>
										<tr>
											<td align=\"center\" valign=\"top\" class=BOXDEF colspan=\"2\">
												<b><u>Works with:</u></b>
											</td>
										</tr>
										<tr>
											<td align=\"left\" valign=\"top\" class=BOXDEF>
												Windows&reg; 7
											</td>
											<td align=\"center\" valign=\"top\" class=BOXDEF>
												Windows&reg; 8
											</td>
										</tr>
			";
	}

	print "
										<tr>
											<td align=\"center\" valign=\"top\" class=BOXDEF colspan=\"2\">
                               		<i>Windows&reg; is a registered trademark of Microsoft Corporation</i>
                                 </td>
                           	</tr>
									</table>
									<a href='$productInstallPath'>
									Download Now</a>
					</div>
	";
}

print "
							</td>
							<td align=\"center\" valign=\"top\" class=BOXDEF>
";

if ($iosDownload && $usertype ne "NAT AGENT")
{
	my $agent = $ENV{'HTTP_USER_AGENT'};
	
print "
								<div id=\"downloadIpadIphone\">
									<table cellspacing='10' cellpadding='1' border='0' width='100%'>
										<tr>
										<td align=\"center\" valign=\"top\" class=BOXDEF colspan=\"2\">
											<b><u>Works with:</u></b>
											</td>
										</tr>
										<tr>
											<td align=\"left\" valign=\"top\" class=BOXDEF>
												iPhone&reg;
											</td>
											<td align=\"center\" valign=\"top\" class=BOXDEF>
												iPad&reg;
											</td>
										</tr>
										<tr>
											<td align=\"center\" valign=\"top\" class=BOXDEF colspan=\"2\">
												<i>iPhone&reg; and iPad&reg; are registered trademarks of Apple Inc.</i>
											</td>
										</tr>
										</table>	
										<a href=\"" . ($agent =~ /iPad/ || $agent =~ /iPhone/ ? "https://services.anx.com/MDM/welcome" : "javascript:alert('Please go to https://services.anx.com/MDM/welcome with you iPhone/iPad to configure your device for vpn access.');" )  . "\">

										Download Now</a><br>
								</div>
	";
}

print "
							</td>
							<td align=\"center\" valign=\"top\" class=BOXDEF>
";

if ($osxDownload && $usertype ne "NAT AGENT")
{
#
# 20180619 - LM moodyl@opentext.com
#	ANXSC-24 : Added support to download the dmg from any WebTop VM
#		   Added support to use WebTop specific dmg filename
#
#
	my $conf = new Config::General('/usr/local/positive/conf/VpnDownload.conf');
        my %config = $conf->getall;
        my $macClientDmg = $config{macClientDmg};
        my $thisUrl = $config{thisUrl};

	$macClientDmg = "PositiveProMacClientLite.dmg" unless ( defined( $macClientDmg ) && length( $macClientDmg ) > 0 );
	$thisUrl = "https://webtop.positivenetworks.net/" unless ( defined( $thisUrl ) && length( $thisUrl ) > 0 );

print "
								<div id=\"downloadIpadIphone\">
									<table cellspacing='10' cellpadding='1' border='0' width='100%'>
										<tr>
											<td align=\"center\" valign=\"top\" class=BOXDEF colspan=\"2\">
												<b><u>Works with:</u></b>
											</td>
										</tr>
										<tr>
											<td align=\"left\" valign=\"top\" class=BOXDEF colspan=\"2\">
												OS X&reg;
											</td>
										</tr>
										<tr>
											<td align=\"center\" valign=\"top\" class=BOXDEF colspan=\"2\">
												<i>OS X&reg; is a registered trademark of Apple Inc.</i>
											</td>
										</tr>
									</table>
									<a href=\"https://${thisUrl}/mcl/${macClientDmg}\">

									Download Now</a><br>
								</div>
	";
}
print "
							</td>
						</tr>
					</table>
				</td>	
				<td align=\"center\" valign=\"middle\">

	<script LANGUAGE=\"JavaScript1.3\" TYPE=\"text/javascript\">
	function isBrowserIE8()
	{
		var rv = -1; // Return value assumes failure
		if (navigator.appName == 'Microsoft Internet Explorer')
		{
			var ua = navigator.userAgent;
			var re  = new RegExp(\"MSIE ([0-9]{1,}[\.0-9]{0,})\");
			if (re.exec(ua) != null)
			rv = parseFloat( RegExp.\$1 );
		}

		if (rv == 8.0)
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}

	function isBrowserIE7()
	{
		var rv = -1; // Return value assumes failure
		if (navigator.appName == 'Microsoft Internet Explorer')
		{
			var ua = navigator.userAgent;
			var re  = new RegExp(\"MSIE ([0-9]{1,}[\.0-9]{0,})\");
			if (re.exec(ua) != null)
			rv = parseFloat( RegExp.\$1 );
		}

		if (rv == 7.0)
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}

	if ((is_winme) || (is_win2k) || (is_winxp) || (is_win98) || (window.navigator.userAgent.indexOf('NT 5.2') != -1) || (window.navigator.userAgent.indexOf('NT 6.0') != -1) || (window.navigator.userAgent.indexOf('NT 6.1') != -1)) 
	{
		e4 = document.getElementById('downloadWin')

		if (isBrowserIE7() || isBrowserIE8() )
		{
			if (window.navigator.userAgent.indexOf('NT 6.1') != -1)
			{
				e1 = document.getElementById('iewin7')
				e2 = document.getElementById('iewin7text')
			}
			else if (window.navigator.userAgent.indexOf('NT 6.0') != -1)
			{
				e1 = document.getElementById('ievista')
				e2 = document.getElementById('ievistatext')
			}
			else if (window.navigator.userAgent.indexOf('SV1') != -1)
			{
				e1 = document.getElementById('iexpsp2')
				e2 = document.getElementById('ie60sp2text')
			}
			else if (is_winxp || (window.navigator.userAgent.indexOf('NT 5.2') != -1)) 
			{
				e1 = document.getElementById('iexp')
				e2 = document.getElementById('ie60text')
			} 
			else 
			{
				e1 = document.getElementById('ie60')
				e2 = document.getElementById('ie60text')
			}

		}
		else if (is_ie6up) 
		{
			if (window.navigator.userAgent.indexOf('SV1') != -1)
			{
				e1 = document.getElementById('iexpsp2')
				e2 = document.getElementById('ie60sp2text')
			}
			else if (is_winxp || (window.navigator.userAgent.indexOf('NT 5.2') != -1)) 
			{
				e1 = document.getElementById('iexp')
				e2 = document.getElementById('ie60text')
			} 
			else 
			{
				e1 = document.getElementById('ie60')
				e2 = document.getElementById('ie60text')
			}
		} 
		else 
		{
			if (is_ie5up) 
			{
				e1 = document.getElementById('ie50')
				e2 = document.getElementById('ie50text')
			} 
			else 
			{
				e1 = document.getElementById('mozilla')
				e2 = document.getElementById('mozillatext')
			}
		}
	}
	else 
	{
		e1 = document.getElementById('nowin');
		e2 = document.getElementById('nowintext');
		e4 = document.getElementById('downloadWin')
	}	
		
	if ((is_winme) || (is_win98))
	{
		e3 = document.getElementById('support98');
	}
	else
	{
		e3 = document.getElementById('nosupport98');
	}
	
	e1.style.display = 'block';
	e2.style.display = 'block';
	e3.style.display = 'block';
	e4.style.display = 'block';

	</script>
						 </td>
					  </tr>
					</table>
				 </td>
			  </tr>
			  <tr>
				 <td width=\"100%\" align=\"center\" colspan=\"3\">&nbsp;</td>
			  </tr>
			  <!--
			  <tr>
				 <td width=\"100%\" align=\"center\" colspan=\"3\"><img border=\"0\" src=\"LocalWebLib/Self-i1.gif\" width=\"805\" height=\"6\"></td>
			  </tr>
			  -->
			</table>
			</center>
			<!-- END BODY TEXT -->
	";
}	

