#!/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 Pos::Webtop::Web::ModuleLoader;

my $tb         = Pos::Webtop::Toolbox->new();
my $client     = $tb->getClient();
my $cgi        = $tb->getCgi();
my $db         = $tb->getWebtopDbWriter();
my $oem        = $tb->getOem();

$client->checkSession();

my $userId     = $client->getUserId();
my $customerId = $client->getCustomerId();
my @serverInfo = $db->query(sql => "
	select
		cos.base_url,
		cos.is_secure
	from
		conf_online_servers cos,
		user_conf_online_settings ucos
	where
		ucos.conf_online_server_id = cos.conf_online_server_id
		AND ucos.user_id = '$userId'
	");

print "Content-type: text/html\n\n";

# If they don't have any server information, force a redirect and allow them through.  This use case should never happen...but...
if (scalar(@serverInfo) == 0) {

	$db->do(sql => "
		update
			w_web_sessions
		set
			confidence_scan_passed = 1
		where
			user_id = '$userId'
		");

	print "
		<html><body>
		<meta http-equiv='refresh' content='0; main.pl?pVwsh=" . $client->getSessionHash() . "&pVwsi=" . $client->getSessionId() . "'>
		</body></html>
		";

	exit;

}

my ($baseUrl, $isSecure) = @{ $serverInfo[0] };

#my $rewriterPrefixUrl = "http://confidence.positivenetworks.net/"; # XXX: testing
#my $rewriterPrefixedBaseUrl = "http://confidence.positivenetworks.net/"; # XXX: testing

my $rewriterPrefixUrl = Pos::Webtop::OcxLauncher::getRewriterPrefix();
my $rewriterPrefixedBaseUrl = Pos::Webtop::OcxLauncher::getRewriterPrefix() . $baseUrl;

# Append a slash if one is not already at the end.
if (!($rewriterPrefixedBaseUrl =~ /\/$/)) {
	$rewriterPrefixedBaseUrl .= "/";
}

# Append a slash if one is not already at the end.
if (!($rewriterPrefixUrl =~ /\/$/)) {
	$rewriterPrefixUrl .= "/";
}

# Remove the scheme prefix.
$rewriterPrefixUrl =~ s/^(.*):\/\/(.*)$/$2/;

print STDERR "confidence: Using base URL: $rewriterPrefixedBaseUrl\n";

print "
	<script language='javascript' version='1.3'>

		function setRewriterCookie() {

			document.cookie = \"positive=$customerId+" . $client->getSessionId() . "+" . $client->getSessionHash() . "; domain=." . $oem->getSetting(setting => 'domain') . "; path=/;\";

		}

		setRewriterCookie();

	</script>

	<html>
		<head>
			<link TYPE='text/css' HREF='LocalWebLib/stylesheet.css' REL='stylesheet'>
			<meta http-equiv='expires' content='0'/>
			<meta http-equiv='pragma' content='no-cache'/>
			<title>
				Confidence Online Scan
			</title>

			<!-- Standard scripts, we do not include events.js, though.  We do that ourselves. -->
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/N4resize.js") . "\"></script>
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/preload.js") . "\"></script>
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/conf.js") . "\"></script>
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/utils.js") . "\"></script>

			<!-- utils.js overrides -->

			<script language='javascript' version='1.3'>

				function includeFile(src, type, language) {

					src = '$rewriterPrefixedBaseUrl' + src;

					document.write(\"\\<script src='\" + src + \"' type='\" + type + \"' language='\" + language + \"'\\>\\<\\/script\\>\"); 

				}

				// Default functions that can be overriden by customers.
				var rewriterBaseUrl = '$rewriterPrefixedBaseUrl';
				var animatedImage   = 'LocalWebLib/confanim.gif';
				var stillImage      = 'LocalWebLib/confstill.gif';

				function userCanProceed() {

					return true;

				}

				function onTrojanFound(failedToFix) {

					if (failedToFix) {

						updateStatus('A trojan was found on your computer and could not be fixed.');

					} else {

						var msg = 'A trojan was found on your computer and has been disabled.';

						if (userCanProceed()) {
							msg = msg + '<br/><br/>Please click \\<a href=\"javascript:redirect();\"\\>here\\<\\/a\\> to proceed.';
						}

						updateStatus(msg);

					}

				}

				function writeBanner() {

					document.write('Confidence Online Trojan Scan');

				}

			</script>

			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/detect.js") . "\"></script>
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/elements.js") . "\"></script>
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/clienttag.js") . "\"></script>
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/state.js") . "\"></script>

			<!-- Customer specific overrides -->
			<script type='text/javascript' language='javascript' src=\"" . HTML::Entities::encode($rewriterPrefixedBaseUrl . "include/custom.js") . "\"></script>

			<script language='javascript' version='1.3'>

				// Update variables to make them absolute
				RELCODEBASE = CODEBASE;
				CODEBASE    = '$rewriterPrefixedBaseUrl' + CODEBASE;

				// Their server must be reached through the URL rewriter.  As such, we must prefix things appropriately.
				if (IS_HTTPS == true || IS_HTTPS == 'true') {
					IPADDRESS = '$rewriterPrefixUrl' + 'https://' + IPADDRESS;
				} else {
					IPADDRESS = '$rewriterPrefixUrl' + 'http://' + IPADDRESS;
				}

				// Since we're redirecting through the rewriter, HTTPS should be true, but we doublecheck.
				if (String('$rewriterPrefixedBaseUrl').substring(0,5) == 'https') 
					IS_HTTPS = 'true';
				else
					IS_HTTPS = 'false';

				// Utility methods
				function updateStatus(statusHtml) {

					var status = getObjectById('status');

					if (status != null) {
						status.innerHTML = statusHtml;
					}

				}

				function redirect() {

					// Hmmm, yes, I know.  Talk to WholeSecurity about this one.
					document.location = 'main.pl?pVwsh=" . $client->getSessionHash() . "&pVwsi=" . $client->getSessionId . "&confPassed=1';

				}

				// Event implementors

				function onNotSupported() {

					redirect();

				}

				function onActiveXNoScan() {

					var anim = getObjectById('animatedImage');
					
					if (anim != null) {
						anim.src = stillImage;
					}

					if (RELCODEBASE == (WINME_AX + '#Version=' + IE_VERSION))
						CODEBASE = WINME_AX_INSTALLER;
					else if (RELCODEBASE == (WIN98_AX + '#Version=' + IE_VERSION))
						CODEBASE = WIN98_AX_INSTALLER;
					else if (RELCODEBASE == (WINNT_AX + '#Version=' + IE_VERSION)) 
						CODEBASE = WINNT_AX_INSTALLER;
					else if (RELCODEBASE == (WIN2K_AX + '#Version=' + IE_VERSION))
						CODEBASE = WIN2K_AX_INSTALLER;
					else if (RELCODEBASE == (WINXP_AX + '#Version=' + IE_VERSION))
						CODEBASE = WINXP_AX_INSTALLER;

					// Update codebase to be absolute
					RELCODEBASE = CODEBASE;
					CODEBASE    = '$rewriterPrefixedBaseUrl' + CODEBASE;

					if (IS_ACTIVEX_NONADMIN_UPGRADE)
						updateStatus('\\<table width=\"470\" style=\"font-size: 10pt; color: #0600ba;\"\\>\\<tr\\>\\<td align=\"center\"\\>\\<font color=\"red\"\\>ActiveX failed to start\\<\\/font\\>\\<br\\/\\>\\<br\\/\\>If you are not running Windows with administrator privileges: \\<br\\>\\<br\\>\\<table style=\"font-size: 10pt; color: black;\"\\>\\<tr\\>\\<td\\>\\<ul\\>\\<li\\>Download the latest \\<a href=\"' + CODEBASE + '\"\\>ActiveX control installer\\<\\/a\\>.\\<\\/li\\>\\<li\\>Shutdown the browser session.\\<\\/li\\>\\<li\\>Run the installer.\\<\\/li\\>\\<li\\>Start browser and return to this page to activate the scan.\\<\\/li\\>\\<\\/td\\>\\<\\/tr\\>\\<\\/table\\>\\<\\/td\\>\\<\\/tr\\>\\<\\/table\\>');
					else
						updateStatus('\\<table width=\"470\" style=\"font-size: 10pt; color: #0600ba;\"\\>\\<tr\\>\\<td align=\"center\"\\>\\<font color=\"red\"\\>ActiveX failed to start\\<\\/font\\>\\<br\\/\\>\\<br\\/\\>If you are not running Windows with administrator privileges, download the \\<a href=\"' + CODEBASE + '\"\\>ActiveX control installer\\<\\/a\\>. After downloading and running the installer, refresh this Internet Explorer browser session to activate the scan.\\<\\/td\\>\\<\\/tr\\>\\<tr\\>\\<td align=\"center\"\\>You may also need to change your Internet Explorer security settings to \"Medium\" or to make sure that the custom setting \"Script ActiveX controls marked safe for scripting\" is not disabled.  To check your settings, click on the Security tab from the \"Options...\" menu.\\<\\/td\\>\\<\\/tr\\>\\<tr\\>\\<td align=\"center\"\\>It is recommended that you add this site to the \"Trusted Sites\" list.\\<\\/td\\>\\<\\/tr\\>\\<\\/table\\>');

				}

				function onScanStart() {
					
					var anim = getObjectById('animatedImage');

					if (anim != null) {
						anim.src           = animatedImage;
						anim.style.display = 'block';
					}

					updateStatus('Scanning your system...');
				}

				function onScanCompleted() {
					
					var anim = getObjectById('animatedImage');

					if (anim != null) {
						anim.src = stillImage;
					}

					updateStatus('Scan completed.');
				}

				function onServerFailed() {
					updateStatus('Server failed.  Please refresh to re-try.');
				}

				function onNonEmbedTrojanFound(failed) {
					onTrojanFound(failed);
				}

				function onEmbedTrojanFound(failed) {
					onTrojanFound(failed);
				}

				function onNoTrojanFound() {

					updateStatus('Connecting you to your corporate network.');

					redirect();

				}

				function onScanCancelled() {
					updateStatus('The scan was canceled.  Please click \\<a href=\"javascript:ScanSystem();\"\\>here\\<\\/a\\> to scan again.');
				}

			</script>
		</head>
		" . $tb->getDomJs . "
		<body onLoad='javascript:if (IS_ACTIVEX && IS_SUPPORTED) ScanSystem();'>
			<center>
			<br/>
			<br/>
			<table class='BOXTABLE' cellspacing='1px' cellpadding='1' border='0'>
				<th class='BOXTH' align='center'>
					<br/>
					<script language='javascript' version='1.3'>
						writeBanner();
					</script>
					<br/>
					<br/>
				</th>
				<tr>
					<td class='BOXTD'>
						<table width='550' bgcolor='white' cellpadding='2' cellspacing='2'>
							<tr>
								<td align='center'>
									<br/>
									Please be patient while your computer's security is validated.<br/>
								</td>
							</tr>
							<tr>
								<td align='center' height='30'>
									<br/>
									<img style='display: none' id='animatedImage'/>
									<br/>
								</td>
							</tr>
							<tr>
								<td id='status' align='center' style='color: #0600ba; font-family: \"Terminal\", \"Helevetica\", \"Arial\", \"Verdana\"; font-size: 10pt'>
								</td>
							</tr>
							<tr>
								<td>
									<br/>
								</td>
							</tr>
							<noscript>
							<tr>
								<td style='color: red' align='center'>
									<b>Javascript is disabled.</b>
									<br/>
									<br/>
								</td>
							</tr>
							<tr>
								<td>
									Please enable Javascript on your browser and refresh the page.
								</td>
							</tr>
							</noscript>
							<tr>
								<td>
									<script language='javascript' version='1.3'>
										writeInstallerLink();
									</script>
								</tr>
							</tr>
							<tr>
								<td>
									<script language='javascript' version='1.3'>
										writeClientTag();
									</script>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<th class='BOXTH' align='right' style='font-size: 8pt'>
					<br/>
					<i>&copy; 2003 Positive Networks, Inc.</i><br/>
					<br/>
				</th>
			</table>
			</center>
		</body>
	</html>
	";

# Always commit at the end.
$db->commit;
