#!/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;
use Pos::Webtop::Toolbox;

sub considerAuxAuth
{
	my ($tb) = @{{@_}}{qw/tb/};
	my $db = $tb->getWebtopDbWriter();
	my $client = $tb->getClient();
	my $userId = $client->getUserId();
	my $clientSessionId = $client->getSessionId();
	
	my @expired;

	my @outstanding = $db->query(sql=>"
		select 
			uaa.aux_auth_id as ID
		from
			client_session_aux_auths csaa
			inner join user_aux_auths uaa
				on (csaa.aux_auth_id = uaa.aux_auth_id and user_id = $userId)
		where
			csaa.client_session_id = $clientSessionId
			and (passed = false or expired = true)
	");

	my $cgi = $tb->getCgi();
	
	if (@outstanding)
	{
		# Note that this redirect code only works with simple
		# vars that don't need encoding -- like those used between
		# login.pl and main.  Basically, getRefreshFormHtml doesn't 
		# support un-uri-encoding so we cannot hand it a url with 
		# encoded params or those encoded params will get put in
		# the form inputs for the refresh with those uri encodings.

		my $qs = "";
		my $sep = "?";

		foreach ($cgi->param())
		{
			$qs .= $sep;
			$qs .= $_;
			$qs .= "=";
			$qs .= $cgi->param($_);
			$sep = "&";
		}

		print $tb->getRefreshFormHtml(
			refreshUrl=> "auxauth.pl",
			extraVars=> {loginQueryString=> $qs});

		exit;
	}
}

my $tb = Pos::Webtop::Toolbox->new();
my $oemId = $tb->getOemId();
my $client = $tb->getClient();
my $cgi = $tb->getCgi();
my $displayMain = 1;

$client->checkSession(ignoreAuxAuth=> 1);
$client->setRestrictionSetId(tb=>$tb);

# This *should* get the initial frame draw before anything else.
considerAuxAuth(tb=>$tb);

my $userId = $client->getUserId();
my $action = $cgi->param('action');

my $p = $tb->getPage();
my $oemSet = $tb->getOem;

my $oemName = $oemSet->getSetting(setting=> 'rebrandName');
my $webtopDescription = $oemSet->getSetting(setting=> 'webtopProductName');

$p->addNavBarElement( description=> $webtopDescription );

my $moduleName = $cgi->param('module');
my $confPassed = $cgi->param('confPassed');

my $displayFrameset   = $cgi->param('displayFrameset');
my $bottomFrame       = $cgi->param('bottomFrame');
my $bottomFrameStatus = $cgi->param('bottomFrameStatus');
my $bottomFrameSupport= $cgi->param('bottomFrameSupport');
my $registered  = $cgi->param('r');

warn "DEBUG: r is $registered\n";

$registered = 0 unless defined($registered); 

warn "DEBUG: r is now $registered\n";
	
my $isMobile = $client->isMobileWebtop();

# If they passed the confidence online test, allow them in
if (defined($confPassed) and $confPassed eq "1") {

#	my $db = $tb->getWebtopDbWriter();
#
#	$db->do(sql => "
#		update
#			w_web_sessions
#		set
#			confidence_scan_passed = 1
#		where
#			web_session_id = '" . $db->escape(dirty => $client->getSessionId) . "'
#		");
#
#	$db->commit;

}

# Check to see if they've passed the confidence online checks
my $cdb = $tb->getWebtopDbReader();

#my ($passed) = $cdb->query(sql => "
#	select
#		confidence_scan_passed
#	from
#		w_web_sessions
#	where
#		web_session_id = '" . $cdb->escape(dirty => $client->getSessionId) . "'
#	");
#
## If they haven't passed the confidence online checks, redirect them to it.
#if (not defined($passed) or $passed ne "1") {
#
#	print "Content-type: text/html\n\n
#
#		<html><head>
#		<META HTTP-EQUIV=REFRESH CONTENT='0; URL=confidence.pl?" . $client->getSessionParams() . "'>
#		</head></html>
#
#		";
#
#	exit;
#
#}

# If this session is flagged as a launcher session, do not let them in.
if ($client->isLauncherSession())
{

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

		<html><head>
		You do not have access to this feature.
		</head></html>

		";

	exit;

}


if ( not defined $moduleName )
{
	# try to get from persisted values
	$moduleName = $client->getPersistedValue( name=> "module" );
}

if ( not defined($displayFrameset) and defined $moduleName )
{
	# call requested modules main if we have it in our layout
	my $userId = $client->getUserId();
	my $db = $tb->getWebtopDbReader();
	my $oem = $tb->getOem;

	# if they are set to allow webtop but set to not allow webtop
	# if not using activex on a restrict set it gets very very lame.
	# have to make this check after the ocx failed...couldn't think 
	# of any other way to do this...this is a really ghetto restrict set
	# setting but whatever
	if (!$client->isWebtopAccessEnabled( db=>$db, userId=>$userId ))
	{
		$client->logger( severity=>'NORMAL', logMessage=>"WEBTOP Main: no webtop access - probably caused by a restrict set setup that sux " );
		
		my $temp = "login.pl?logout=1&err=Your account is currently not enabled for " . $oem->getSetting(setting=>'webtopProductName') . " access. Please contact " . $oem->getSetting(setting => 'rebrandName') . " technical support for more information.";

		print $tb->getRefreshFormHtml(refreshUrl=> $temp, top=> 1);

		exit;
	}

	if ( !$client->isWebtopVpnConnectionEstablished(db=>$db) && (!$client->isActivexDisabled(db=>$db) || not defined($client->isActivexDisabled(db=>$db))) )
	{
		$client->notUsingOcx(tb => $tb);
	}

	if(! $registered )
	{
		my $sneakyUser = $client->isUserTryingToBeSneaky(tb=> $tb, db=> $db);
	
		if ($sneakyUser)
		{
			print "Content-type: text/html\n\n";
			print "
			<html><head>
			<script>
			setTimeout(\"top.location.href = 'login.pl?logout=1'\", 0000);
			</script>
			</head></html>
			";
			#print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');

			exit;
		}
	}

	my ($portalized, $activexDisabled, $vpnConnection) = @{$client->isOcxRequiredCaptivePortalCheck(db=> $db, tb=> $tb)};

	if (!$vpnConnection)
	{
		print "Content-type: text/html\n\n";
		print "
		<html><head>
		<script>
		setTimeout(\"top.location.href = 'login.pl?logout=1'\", 0000);
		</script>
		</head></html>
		";
		#print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');
		exit;
	}
	
	if ( $portalized || $activexDisabled )
	{
		my $sessParams = $client->getSessionParams();
		$activexDisabled and $sessParams .= "&ocxFailed=1&displayFrameset=1";
	
		my $url = "main.pl?" . $sessParams . "";
		
		print $tb->getRefreshFormHtml(refreshUrl => $url);

		exit;
	}

	my $cmi = $client->getUserContentModules();

	$moduleName =~ /(\w+)/;
	$moduleName = $1;
	
	if ( exists $cmi->{$moduleName} && $cmi->{$moduleName}->{'shown'} )
	{
		my $class = $moduleName;
		# persist the module name
		$client->setPersistedValue( name=> "module", value=> $class );

		$displayMain = 0;
		# we display the module's main not the webtop main
		my $cm = Pos::Webtop::Web::ContentModuleFactory::createModuleFromClass( toolBox=> $tb, class=> $class );
		
		$cm->main();
	}
}

if ( defined($displayFrameset) ) 
{

	my @params = $cgi->param();
	my $parms = '';
	my $db = $tb->getWebtopDbReader();

	my $sneakyUser = 0;
	if(! $registered )
	{ 
		$sneakyUser = $client->isUserTryingToBeSneaky(tb=> $tb, db=> $db);
	}

	my $oem = $tb->getOem;
	
	# if they are set to allow webtop but set to not allow webtop
	# if not using activex on a restrict set it gets very very lame.
	# have to make this check after the ocx failed...couldn't think 
	# of any other way to do this...this is a really ghetto restrict set
	# setting but whatever
	if (!$client->isWebtopAccessEnabled( db=>$db, userId=>$userId ))
	{
		$client->logger( severity=>'NORMAL', logMessage=>"WEBTOP Main: no webtop access - probably caused by a restrict set setup that sux " );
		
		my $temp = "login.pl?logout=1&err=Your account is currently not enabled for " . $oem->getSetting(setting=>'webtopProductName') . " access. Please contact " . $oem->getSetting(setting => 'rebrandName') . " technical support for more information.";

		print $tb->getRefreshFormHtml(refreshUrl=> $temp, top=> 1);

		exit;
	}

	if ($sneakyUser)
	{
		print "Content-type: text/html\n\n";
		print "
		<html><head>
		<script>
		setTimeout(\"top.location.href = 'login.pl?logout=1'\", 0000);
		</script>
		</head></html>
		";
		#print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');

		exit;
	}

	foreach my $v (@params) 
	{
		if ($v eq 'displayFrameset' || $v eq 'pVprefModule') 
		{
			next;
		}

		if (length($parms)) { $parms .= "&"; }

		$v =~ /(.*)/;
		$v = $1;

		my $p = $cgi->param($v);
		
		$p =~ /(.*)/;
		$p = $1;

		$parms .= URI::Escape::uri_escape($v, "\\W") . "=" . URI::Escape::uri_escape($p, "\\W");
	}

	# If display frameset is enabled, we display the frame set
	print "Content-type: text/html\n\n

	<html>
		<title>$oemName - $webtopDescription</title>
		<frameset border='0' frameborder='0' rows='*,19'>
			<frame name='bodyFrame' marginheight='0' marginwidth='0' frameborder='no' src=\"" . ($isMobile ? "main.pl?" : "portal.pl?") . "" . $client->getSessionParams() . "&$parms\">
			<frame name='statusFrame' marginheight='0' marginwidth='0' frameborder='no' scrolling='no' noresize src=\"main.pl?bottomFrame=1&" . $client->getSessionParams() . "\">
		</frameset>
	</html>
	";
} 
elsif ( defined($bottomFrame) ) 
{

	# If we should display the main page and the bottom frame flag is set, display bottom frame HTML
	print "Content-Type: text/html\n\n";
	print Pos::Webtop::OcxLauncher::getFrameHtml(tb => $tb);

} 
elsif ( defined($bottomFrameStatus) ) 
{

	# If we should display the main page and the bottom frame flag is set, display bottom frame HTML
	print "Content-Type: text/html\n\n";
	print Pos::Webtop::OcxLauncher::getFrameStatusHtml(tb => $tb);

} 
elsif ( defined($bottomFrameSupport) ) 
{
	
	print "Content-Type: text/html\n\n";
	print Pos::Webtop::OcxLauncher::getFrameSupportHtml(tb => $tb);

} 
elsif ( $displayMain ) 
{

	my $db = $tb->getWebtopDbReader();
	my $activeXConnected = $client->isWebtopVpnConnectionEstablished(db=> $db);
	my $oem = $tb->getOem;

	# this is to fix the problem where you sign on and the status frame doesn't load so 
	# the function that updates activex_disabled isn't called, which breaks shit...so this
	# updates that correctly
	if ( !$client->isWebtopVpnConnectionEstablished(db=>$db) && (!$client->isActivexDisabled(db=>$db) || not defined($client->isActivexDisabled(db=>$db))) )
	{
		$client->notUsingOcx(tb => $tb);
	}

	# preview page (webtop main)

	# If the client is captive portalized, redirect them to the portal wizard.
	
	# if they are set to allow webtop but set to not allow webtop
	# if not using activex on a restrict set it gets very very lame.
	# have to make this check after the ocx failed...couldn't think 
	# of any other way to do this...this is a really ghetto restrict set
	# setting but whatever
	if (!$client->isWebtopAccessEnabled( db=>$db, userId=>$userId ))
	{
		$client->logger( severity=>'NORMAL', logMessage=>"WEBTOP Main: no webtop access - probably caused by a restrict set setup that sux " );
		
		my $temp = "login.pl?logout=1&err=Your account is currently not enabled for " . $oem->getSetting(setting=>'webtopProductName') . " access. Please contact " . $oem->getSetting(setting => 'rebrandName') . " technical support for more information.";

		print $tb->getRefreshFormHtml(refreshUrl=> $temp, top=> 1);

		exit;
	}

	my $sneakyUser = 0;
	if(! $registered )
	{	
		$sneakyUser = $client->isUserTryingToBeSneaky(tb=> $tb, db=> $db);
	}

	if ($sneakyUser)
	{
		print "Content-type: text/html\n\n";
		print "
		<html><head>
		<script>
		setTimeout(\"top.location.href = 'login.pl?logout=1'\", 0000);
		</script>
		</head></html>
		";
		#print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');

		exit;
	}

	my ($portalized, $activexDisabled, $vpnConnection) = @{$client->isOcxRequiredCaptivePortalCheck(db=> $db, tb=> $tb)};
	
	if (!$vpnConnection)
	{
		print "Content-type: text/html\n\n";
		print "
		<html><head>
		<script>
		setTimeout(\"top.location.href = 'login.pl?logout=1'\", 0000);
		</script>
		</head></html>
		";
		#print $tb->getRefreshFormHtml(refreshUrl => 'login.pl?logout=1');
		exit;
	}

	if ( $portalized || $activexDisabled )
	{
		my $sessParams = $client->getSessionParams();
		$activexDisabled and $sessParams .= "&ocxFailed=1&displayFrameset=1";
	
		my $url = "main.pl?" . $sessParams . "";
		
		print $tb->getRefreshFormHtml(refreshUrl => $url);

		exit;
	}


	print $p->getHeaderHtml( title=> "Webtop" );
	#print Pos::Webtop::OcxLauncher::getLauncherHtml(tb => $tb);

	# we need to get a 2dim array with class names of the content modules.. the outter array is the columns  (since we are doing
	# columns of data)

	my $cmi = $client->getUserContentModules();
	
	my @cols = ();

	# each key is a perl class name
	foreach ( keys %{ $cmi } )
	{
		my $class = $_;
		my $name = $cmi->{$_}->{'moduleName'};
		next unless $cmi->{$_}->{'shown'};
		my $col = $cmi->{$_}->{'col'};
		my $row = $cmi->{$_}->{'row'};
		my $icon = $cmi->{$_}->{'icon'};
		my $shownMobile = $cmi->{$_}->{'shownMobile'};
		my $requiresActiveX = $cmi->{$_}->{'requiresActiveX'};
		my $noPreview = $cmi->{$_}->{'noPreview'};

		((!$shownMobile && $isMobile) || (!$activeXConnected && $requiresActiveX) || $noPreview) and next;

		$cols[$col]->[$row] = {
			name=> $name,
			class=> $class,
			icon=> $icon
		};
	}

	print "
		<br/>
		<table border=0 cellspacing='2' cellpadding='4' align='center'>
		<tr>
	";

	foreach my $col ( @cols )
	{
		print "
			<td valign='top'>
		";

		foreach my $mod ( @{ $col } )
		{	
			# we need to support oem specific icons, so we have to see if each mod has an oem specific icon 
			# for this module...
			
			my $iconSrc = "LocalWebLib/" . $mod->{'icon'};
			my $codeOemId = Pos::Webtop::Web::OEMLoader::getSkinOemId(oemId=> $oemId);
			my $oemIconSrc = "LocalWebLib/OEM/$codeOemId/" . $mod->{'icon'};
			my $imgLink;
			my $titleLink;
		
			$iconSrc = $oemIconSrc if stat($oemIconSrc);

			if ($mod->{'name'} eq 'Remote Desktop' && !$activeXConnected)
			{
				$imgLink = $client->getFormGetCode(
					text=> "<img border='0' src='$iconSrc'>",
					tagAttributes=> 
					[ 
						{ 
							name=> "CLASS", 
							value=> "BOXLINK" 
						} 
					],
					values=> 
					[ 
						{ 
							name=> "module", 
							value=> $mod->{'class'} 
						}, 
						{ 
							name=> "action", 
							value=> "newDesktop" 
						} 
					]
				);

				$titleLink = $client->getFormGetCode(
					text=> $mod->{'name'},
					tagAttributes=> 
					[ 
						{ 
							name=> "CLASS", 
							value=> "CLMPREVIEWTITLELINK"
						} 
					],
					values=> 
					[ 
						{ 
							name=> "module", 
							value=> $mod->{'class'} 
						}, 
						{ 
							name=> "action", 
							value=> "newDesktop" 
						} 
					]
				);
			}
			else
			{
				$imgLink = $client->getFormGetCode(
					text=> "<img border='0' src='$iconSrc'>",
					tagAttributes=> 
					[ 
						{ 
							name=> "CLASS", 
							value=> "BOXLINK" 
						} 
					],
					values=> 
					[ 
						{ 
							name=> "module", 
							value=> $mod->{'class'} 
						} 
					]
				);

				$titleLink = $client->getFormGetCode(
					text=> $mod->{'name'},
					tagAttributes=> 
					[ 
						{ 
							name=> "CLASS", 
							value=> "CLMPREVIEWTITLELINK"
						} 
					],
					values=> 
					[ 
						{ 
							name=> "module", 
							value=> $mod->{'class'} 
						} 
					]
				);
			}

			my $title = "
				<table border='0' cellspacing='0' cellpadding='0'>
				<tr>
					<td class='CLMPREVIEWTITLE' align='left' valign='middle' width='1%'>
						$imgLink
					</td>
					<td class='CLMPREVIEWTITLE' align='left' valign='middle'>
						\&nbsp;$titleLink
					</td>
				</tr>
				</table>
			";

			my $cm = Pos::Webtop::Web::ContentModuleFactory::createModuleFromClass( toolBox=>$tb, class=> $mod->{'class'} );
			my $box = $tb->createBox( type=> "contentModulePreview", title=> $title, width=> $cm->getPreviewWidth() );
		
			my $modHtml = "";
			my $preview = "";
			$modHtml .= $box->getHeaderHtml();
			$preview  = $cm->getPreviewHtml();

			if (not defined($preview)) {
				next;
			} else {
				$modHtml .= $preview;
			}

			$modHtml .= $box->getFooterHtml();
			$modHtml .= "<span style='font-size: 8px'><br/></span>\n";

			print $modHtml;
		}

		print "
			</td>
		";

		$isMobile and print "</tr><tr>";
	}
	
	print "
		</tr>
		</table>
		<br/>
		<br/>
		<br/>
	";

	print $p->getFooterHtml();

}
