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

use strict;
use CGI qw/:standard/;
use XML::Simple;
use XML::Parser;
use Pos::Webtop::Toolbox;
use Digest::MD5();
use Pos::Webtop::FileShare::Smb;
use MIME::Base64;
use HTML::Entities;
use URI::Escape;
use File::Basename;

my $cgi = CGI->new;
my $tb = Pos::Webtop::Toolbox->new();
my $client = $tb->getClient();

my $conf   = new Config::General("/usr/local/positive/conf/PosPerl.conf");
my %config = $conf->getall;

my $restrictionSetId = $cgi->param('r');
my $key = $cgi->param('k');

my $closeImg = "<img src='LocalWebLib/action_close16.svg' style='height: 19px; width: 19px' onclick=javascript:dc(this); title='Close connection'>";
my $docImg = "<img src='LocalWebLib/mime_document32-1.svg' style='height: 19px; width: 19px'>";
my $folderImg = "<img src='LocalWebLib/mime_folder32.svg' style='height: 19px; width: 19px'>";
my $profileImg = "<img src='LocalWebLib/mime_tcpip_profile32.svg' style='height: 19px; width: 19px'>";
my $rootFolderImg = "<img src='LocalWebLib/mime_content_server_objects32.svg' style='height: 19px; width: 19px'>";

my $raddr = $ENV{'REMOTE_ADDR'};
my $smbShare;

my $m = $cgi->param('m');
my $userId  = $cgi->param('U');
$userId = getUserId() unless( defined( $userId ) && length( $userId ) );

my $ERR100 = "Please close the browser window, fileshare access cannot be granted.";
my $ERR101 = "Sorry, file FILETAG could not be deleted."; 
my $ERR102 = "Sorry, folder FOLDERTAG could not be created.";
my $ERR103 = "Sorry, file FILETAG could not be renamed.";
my $ERR104 = "Cannot rename FILETAG to FILETAG in the same folder.";
my $ERR105 = "This folder is empty.";
my $ERR106 = "Sorry, file FILETAG could not be moved.";
my $ERR107 = "Cannot move FILETAG to the same folder.";

#
# Make certain origin is valid
#
my $valid = 0;
my $referrer = $ENV{'HTTP_REFERER'};
my( @referrerArr ) = split( "/", $referrer );

#for( my $i=0; $i<scalar( @referrerArr ); $i++ ) {
#	if( $referrerArr[$i] =~ m/^def/ )  {
#		my( @fileArr ) = split( "\\?", $referrerArr[$i] );
#	
#		my $md5 = Digest::MD5->new();
#        	$md5->add( $fileArr[$0] . "\n" );
#       		my $digest = $md5->hexdigest();
#
#		if( $digest eq $config{'webtopReferrer'} ) {
#			$valid = 1;
#			last;
#		}
#	}
#}

#warn "$config{'webtopRelease'}:$raddr:webtopBackend.pl:Bad referrer\n" && exitNow() unless( $valid );
#
#
#

sub showErrorModal
{
	my( $error, $showImage, $showOk ) = @{{@_}}{qw/error showImage showOk/};
	$showOk = 1 unless( defined( $showOk ) && length( $showOk ) );
	$showImage = 0 unless( defined( $showImage ) && length( $showImage ) ) ;

my $html = "
	<div class='ot-modal ot-modal--is-active' id='errdiv' style='z-index: 1501;'>
  		<div class='ot-modal__background'>
  		</div>
  		<div class='ot-modal__content'>
    			<div class='ot-modal__header'>
      				<p class='title'>
					<input type='text' disabled class='ot-input' value='WARNING'>
				</p>
    			</div>
    			<div class='ot-modal__body'>
      				<div class='ot-m-1' style='background: #white; width: 525px; height: 150px;'>
";

if( $showImage ) {
	$html .= "
					<img src='LocalWebLib/ill_workspace_xecm220.svg' style='height: 152px; width: 152px'>
		";
}

$html .= "
					<div class='ot-form-control'>
						<div class='text'>
						$error
						</div>
					</div>
      				</div>
   			</div>
			<div class='ot-modal__footer'>
";

	if( $showOk )  {
	$html .= "
                        	<button class='ot-btn ot-btn--is-primary' onclick=javascript:document.getElementById('errdiv').setAttribute('class','ot-modal');>
                       		OK

                                </button>
";
	}

$html .= "
                       	</div>
  		</div>
	</div>
";

	return( $html );
}

sub buildTreeHtml
{
	my( $isCorporate, $modal, @thisDirList ) = @_;
	my $html;
	my $row = 0;
	my $q = $cgi->param('q');
	my $modalTag = "";
	$modalTag = "M" unless( $modal == 0 );	
	my $heightDiff = "150px";
	$heightDiff = "300px" unless( $modal == 0 );

	$html = "
		<div class='ot-list-tile ot-list-tile--is-simple' style='height: calc( 100vh - $heightDiff );'>

                	<div class='ot-list-tile__body'>
                        	<div class='ot-panel__body'>
					<div id='fstree${modalTag}' class='ot-tree'>
";

	foreach my $item (@thisDirList) {
		my $dir = $item->{'itemName'};
		$dir = strim( str=> $dir );	
	
		my $img = $folderImg;
		$img = $rootFolderImg unless( $row > 0 );	

		$html .= "
			<div role='button' class='ot-tree-node ot-tree-node--level-0 ot-tree-node--is-expanded' id='fstreer${modalTag}${row}' onclick=javascript:rlt(${modal},${row});>
				<a class='ot-tree-node__icon'>
					<i id='fstree${modalTag}${row}' class='ot-tree-node--is-expanded'>
					</i>
				</a>
				<button class='ot-tree-node__value' title='Click to view files'>$img $dir</button>
				<p hidden>
					<input size='0' type='password' name='rlta${modalTag}${row}' id='rlta${modalTag}${row}' value='$q'>
					<input size='0' type='password' name='rltb${modalTag}${row}' id='rltb${modalTag}${row}' value='$dir'>
					<input size='0' type='password' name='rltc${modalTag}${row}' id='rltc${modalTag}${row}' value='$userId'>
					<input size='0' type='password' name='rltd${modalTag}${row}' id='rltd${modalTag}${row}' value='$isCorporate'>
				</p>
			</div>";		
		
		$row++;
	}

	$html .= "
					</div>
				</div>
			</div>
			<p hidden>
				<input size='0' type='password' name='rltt${modalTag}' id='rltt${modalTag}' value='${row}'>
			</p>
		</div>
	";
					
	if( $modal ) {
	$html .= "
		<p hidden>
			<input size='0' type='password' name='treeDst' id='treeDst' value='dIs0^0'>
		</p>
	";
	}
	
	return( $html );
}

sub buildEmptyPanelHtml
{
	my $html;

	$html = "
	<div class='ot-list-tile ot-list-tile--is-simple' style='height: calc( 100vh - 150px );'>
        	<div class='ot-list-tile__body'>
                	<div class='ot-panel__body'>
				<div style='display: block; text-align: center' class='ot-form-control'>
					<div style='width: 100%; height: 100px; opacity: 1;'></div>

					<img src='LocalWebLib/ill_workspace_xecm220.svg' style='height: 152px; width: 152px'>
					<div class='text'>
						<p style='color: black;'>
							<span>The folder is empty</span>
						</p>
					</div>
				</div>
			</div>
		</div>
	
		<p hidden>
			<input size='0' type='password' name='rlpt' id='rlpt' value='0'>
		</p>
	</div>
	";

	return( $html );
}

sub buildPanelHtml
{
	my( $isCorporate, @thisDirList ) = @_;
	my $row = 0;
	my $html;
	my $imageDir = "LocalWebLib";
	my $img;

	my $q = $cgi->param('q');

	#<meta name='viewport' content='width=device-width, initial-scale=1'>
	$html = "
	<div class='ot-list-tile ot-list-tile--is-simple' style='height: calc( 100vh - 150px );'>
        	<div class='ot-list-tile__body'>
                	<div class='ot-panel__body'>
				<ul class='ot-list ot-list--is-very-high-density'>
	";

	foreach my $item (@thisDirList) {
		my $file = $item->{'itemName'};
		$file = strim( str=> $file );	

		if( $item->{'itemType'} eq "directory" ) {
			$img = $folderImg;	
		}
		elsif( $item->{'itemType'} eq "file" ) {
			my($file, $path, $ext) = fileparse( $file, '\.[^\.]*' );

			if( $ext eq ".dat" || $ext eq ".txt" || $ext eq ".doc" || $ext eq ".docx" ) {
				$img = $docImg;
			}
			elsif( $ext eq ".pps" || $ext eq ".ppt" || $ext eq ".pptx" ) {
				#$img = $imageDir . "/mime_photo32.svg";
				$img = "<img src='LocalWebLib/mime_photo32.svg' style='height: 19px; width: 19px'>";
			}
			elsif( $ext eq ".xls" || $ext eq ".xlsx" ) {
				#$img = $imageDir . "/mime_excel32.svg";
				$img = "<img src='LocalWebLib/mime_excel32.svg' style='height: 19px; width: 19px'>";
			}
			elsif( $ext eq ".gif" || $ext eq ".jpg" ||  $ext eq ".jpeg" || $ext eq ".ico" || $ext eq ".pdf" || $ext eq ".png" || $ext eq ".svg" || $ext eq ".png" ) {
				#$img = $imageDir . "/mime_image32.svg";
				$img = "<img src='LocalWebLib/mime_image32.svg' style='height: 19px; width: 19px'>";
			}
			elsif( $ext eq ".bat" || $ext eq ".exe" || $ext eq ".jar" || $ext eq ".java" || $ext eq ".sh" || $ext eq ".war" ) {
				#$img = $imageDir . "/mime_java32.svg";
				$img = "<img src='LocalWebLib/mime_java32.svg' style='height: 19px; width: 19px'>";
			}
			else {
				$img = $docImg;
			}
		}
							
		my $i = 0;
		my @units = ("B", "KB", "MB", "GB");
		
		for( @units ) {
			last if $item->{'itemBytes'} < 1024;

			$item->{'itemBytes'} /= 1024;
			$i++;
		}

		my $fileSizeUnit = sprintf("%.2f %s", $item->{'itemBytes'}, $units[$i]);

	$html .= "
				<li tabindex='-1' class='ot-list__item' id='fsr${row}' title='$fileSizeUnit'>
					<input id='fsrcbx${row}' type='checkbox'>
			        	<div style='width: 1px; height: 1px; opacity: 1;'></div>
					$img $file
					<p hidden>
						<input size='0' type='password' name='pra${row}' id='pra${row}' value='$q'>
						<input size='0' type='password' name='prb${row}' id='prb${row}' value='$file'>
						<input size='0' type='password' name='prc${row}' id='prc${row}' value='$userId'>
						<input size='0' type='password' name='prd${row}' id='prd${row}' value='$isCorporate'>
					</p>
				</li>
		";

		$row++;
	}

	$html .= "
				</ul>
			</div>
		</div>
	
		<p hidden>
			<input size='0' type='password' name='rlpt' id='rlpt' value='${row}'>
		</p>
	</div>
	";

	return( $html );
}

sub showCorporateFileShare
{
	my( $remoteAddr, $drive, $itemType, $isTree, $modal ) = @{{@_}}{qw/remoteAddr drive itemType isTree modal/};
	$modal = 0 unless( defined( $modal ) && length( $modal ) );
	$remoteAddr =~ s/\//\/\//g;

	my @thisDirList;
	my $html;
	my $rc = 0;

	my $db = $tb->getWebtopDbWriter();
        my( @clientDriveShares ) = $db->query( sql=> "
                                        SELECT
                                                net_user,
                                                net_pass
                                        FROM
                                                client_drive_shares
                                        WHERE
                                                user_id = $userId
						AND remote_addr = '" . $db->escape( dirty => $remoteAddr ). "'
						LIMIT 1
                                        " );

	my($shareUserName, $sharePassword) = @{ $clientDriveShares[0] };

	if( scalar( @clientDriveShares ) ) {
		my( undef, $serverName, $shareName, $initialFolder) = split(/\\{1,2}/,$remoteAddr,4);

		( @thisDirList ) = connectSmb( shareUserName=> $shareUserName, sharePassword=> $sharePassword, 
						serverName=> $serverName, shareName=> $shareName, webSessionId=> getClientSessionId(), 
						itemType=> $itemType, drive=>$drive );
	}

	if( scalar( @thisDirList ) ) {
		if( $isTree ) {
			$html = buildTreeHtml( 1, $modal, @thisDirList );	
		}
		else {
			$html = buildPanelHtml( 1, @thisDirList );	
		}
	}

	if( ! scalar( @clientDriveShares ) ) { 
		$html = showErrorModal( error=>"$ERR100", showOk=>0 );
	}
	elsif( ! scalar( @thisDirList ) ) {
		$html = buildEmptyPanelHtml();
	}

	$rc = 1 unless( ! length( $html ) );

	return( $rc, $html );
}

sub showPersonalFileShare
{
	my( $remoteAddr, $drive, $itemType, $isTree, $modal ) = @{{@_}}{qw/remoteAddr drive itemType isTree modal/};
	$modal = 0 unless( defined( $modal ) && length( $modal ) );

	my @serverFileshareArr = split( ",", $remoteAddr );
	my $serverName= $serverFileshareArr[0];
	my $shareName = $serverFileshareArr[1];
 	my $shareUserName;
	my $sharePassword;	
	my $db = $tb->getWebtopDbWriter();
	my @thisDirList;
	my $html;
	my $rc = 0;

	my $networkPath =  "\\\\${serverName}\\${shareName}";

	my( $fileShareId ) = $db->query( sql=> "
					SELECT fsu.fileshare_id
					FROM
						w_smb_fileservers fsv, 
						w_smb_fileshares fsh, 
						w_smb_fileshare_users fsu
					WHERE
						fsh.fileshare_id = fsu.fileshare_id
						AND fsh.fileserver_id = fsv.fileserver_id
						AND user_id = $userId
						AND fsh.fileshare_name = '$shareName'
						AND fsv.fileserver_hostname = '$serverName'
						LIMIT 1
				" );

	if( length( $fileShareId ) ) {
		my( @netresourceAuthCache ) = $db->query( sql=> "
						SELECT 
							net_user, 
							net_pass
						FROM 
							netresource_auth_cache
						WHERE 	
							user_id = $userId
							AND network_path = '" . $db->escape( dirty=> "$networkPath" ) . "'
						" );
	
		if( scalar( @netresourceAuthCache ) ) {
			( @thisDirList ) = connectSmb( shareUserName=>$netresourceAuthCache[0][0], sharePassword=>$netresourceAuthCache[0][1], 
						serverName=>$serverName, shareName=>$shareName, webSessionId=>getClientSessionId(),
						itemType=>$itemType, drive=>$drive );
		}

		if( $isTree ) {
			$html = buildTreeHtml( 0, $modal, @thisDirList );	
		}
		else {
			$html = buildPanelHtml( 0, @thisDirList );	
		}
	}

	if( ! length( $fileShareId ) ) {
		$html = showErrorModal( error=>"$ERR100", showOk=>0 );
	}
	elsif( ! scalar( @thisDirList ) ) {
		$html = buildEmptyPanelHtml();
	}

	$rc = 1 unless( ! length( $html ) );

	return( $rc, $html );
}

sub executeSmb
{
	my( $remoteAddr,$drive,$driveNew,$folderName,$file,$command,$isCorporate,$fileNew) = @{{@_}}{qw/remoteAddr drive driveNew folderName file command isCorporate fileNew/};
	$drive = "" unless ( defined( $drive ) && length( $drive ) );
	$file  = "" unless ( defined( $file ) && length( $file ) );

 	my $shareUserName;
	my $sharePassword;	
	my $serverName;
	my $shareName;
	my $initialFolder;
	my $error;
	my $html;
	my $rc = 0;

	my $db = $tb->getWebtopDbWriter();
	$remoteAddr =~ s/\//\/\//g;

	if( $isCorporate == 0 ) {
		my @buff = split( ",", $remoteAddr );

		$serverName = $buff[0];
		$shareName  = $buff[1];

		my $networkPath =  "\\\\${serverName}\\${shareName}";
		my( $fileShareId ) = $db->query( sql=> "
					SELECT fsu.fileshare_id
					FROM
						w_smb_fileservers fsv, 
						w_smb_fileshares fsh, 
						w_smb_fileshare_users fsu
					WHERE
						fsh.fileshare_id = fsu.fileshare_id
						AND fsh.fileserver_id = fsv.fileserver_id
						AND user_id = $userId
						AND fsh.fileshare_name = '$shareName'
						AND fsv.fileserver_hostname = '$serverName'
						LIMIT 1
				" );
	
		if( length( $fileShareId ) ) {
			my( @netresourceAuthCache ) = $db->query( sql=> "
						SELECT 
							net_user, 
							net_pass
						FROM 
							netresource_auth_cache
						WHERE 	
							user_id = $userId
							AND network_path = '" . $db->escape( dirty=> "$networkPath" ) . "'
						" );
		
			$shareUserName = $netresourceAuthCache[0][0];
			$sharePassword = $netresourceAuthCache[0][1]; 
		}
	}
	else {
		( undef, $serverName, $shareName, $initialFolder) = split(/\\{1,2}/,$remoteAddr,4);

        	my( @clientDriveShares ) = $db->query( sql=> "
                                        SELECT
                                                net_user,
                                                net_pass
                                        FROM
                                                client_drive_shares
                                        WHERE
                                                user_id = $userId
						AND remote_addr = '" . $db->escape( dirty=> $remoteAddr ) . "'
                                                AND restrict_set_id = 1
						LIMIT 1
					" );

		($shareUserName, $sharePassword) = @{ $clientDriveShares[0] };
	}

        my( $domain ) = $db->query( sql=> "
						SELECT
							corp_network_domain
						FROM
                        				users
                				WHERE
                        				user_id = $userId
        				" );

	if( length( $domain ) ) {
		$smbShare = Pos::Webtop::FileShare::Smb->new(
                        shareUserName => $shareUserName,
                        sharePassword => $sharePassword,
                        serverName    => $serverName,
                        shareName     => $shareName,
                        domain        => $domain,
			webSessionId  => getClientSessionId()
                );
	}
	else {
		$smbShare = Pos::Webtop::FileShare::Smb->new(
                        shareUserName => $shareUserName,
                        sharePassword => $sharePassword,
                        serverName    => $serverName,
                        shareName     => $shareName,
			webSessionId  => getClientSessionId()
                );
	}	

	if( $command eq "createFolder" ) {
		$rc = $smbShare->createFolder( dirPath=>$drive, folderName=>$folderName );
		if( ! $rc ) {
			$error = $ERR102;
			$error =~ s/FOLDERTAG/$folderName/;
		}
	}
	elsif( $command eq "deleteFile" ) {
		$rc = $smbShare->deleteFile( dirPath=>$drive, filename=>$file );
		if( ! $rc  ) {
			$error = $ERR101;
			$error =~ s/FILETAG/$file/;
		}
	}
	elsif( $command eq "getFile" ) {
		$html = $smbShare->getFile( dirPath=>$drive, filename=>$file );
		$rc = 1 unless( ! length( $html ) );
	}
	elsif( $command eq "moveFile" ) {
		if( $drive ne $driveNew ) {
			$rc = $smbShare->moveItem( dirPath=>$drive, itemName=>$file, newDirPath=>$driveNew, newItemName=>$file );

			if( ! $rc ) {
				$error = $ERR106;
				$error =~ s/FILETAG/$file/;
			}
		}
		else {
			$error = $ERR107;
			$error =~ s/FILETAG/$file/;
		}
	}
	elsif( $command eq "renameFile" ) {
		if( $file ne $fileNew ) {
			$rc = $smbShare->renameItem( dirPath=>$drive, itemName=>$file, newDirPath=>$drive, newItemName=>$fileNew, isDir=>0);

			if( ! $rc ) {
				$error = $ERR103;
				$error =~ s/FILETAG/$file/;
			}	
		}
		else {
			$error = $ERR104;
			$error =~ s/FILETAG/$file/g;
		}
	}
	elsif( $command eq "putFile" ) {
		my $uploadFileHandle = 0;
		$smbShare->putFile( dirPath=>$drive, filename=>$file, uploadFileHandle=>$uploadFileHandle, overwriteFile=>"1" );
	}

	$html = showErrorModal( error=>$error ) unless( $rc );

	return( $rc, $html );
}

sub connectSmb
{
	my( $shareUserName,$sharePassword,$serverName,$shareName,$webSessionId,$drive,$itemType )
				= @{{@_}}{qw/shareUserName sharePassword serverName shareName webSessionId drive itemType/};

	$drive = "" unless ( defined( $drive ) && length( $drive ) );
	$itemType = "all" unless( defined( $itemType ) && length( $itemType ) );

	my @thisDirList;
	my $db = $tb->getWebtopDbWriter();

        my( $domain ) = $db->query( sql=> "
						SELECT
							corp_network_domain
						FROM
                        				users
                				WHERE
                        				user_id = $userId
        				" );

	$drive = "\\" . $drive unless( ! length( $drive ) );
	
	if( length( $domain ) ) {
		$smbShare = Pos::Webtop::FileShare::Smb->new(
                        shareUserName => $shareUserName,
                        sharePassword => $sharePassword,
                        serverName    => $serverName,
                        shareName     => $shareName,
                        domain        => $domain,
                        webSessionId  => $webSessionId
                );
	}
	else {
		$smbShare = Pos::Webtop::FileShare::Smb->new(
                        shareUserName => $shareUserName,
                        sharePassword => $sharePassword,
                        serverName    => $serverName,
                        shareName     => $shareName,
                        webSessionId  => $webSessionId
                );
	}	

	my $dirList = $smbShare->getDirListing( dirPath=>$drive, getExtendedInfo=>0 );
	if( length( $dirList ) ) {
		#	
		# Add fake root
		#	
		if( ! length( $drive ) && $itemType eq "directory" ) {
			my %rootItem = (
                        	"itemName"  => "This fileshare",
                        	"itemType"  => "directory",
                        	"itemBytes" => "0",
                        	"itemMtime" => "0"
                	);

			push( @thisDirList, { %rootItem } );
		}

		my @sortedDirList = sort { $a->{'itemType'} cmp $b->{'itemType'} } (sort { uc($a->{'itemName'}) cmp uc($b->{'itemName'}) } @{$dirList});

		foreach my $item (@sortedDirList) {
			if( $itemType eq "all" || $itemType eq $item->{'itemType'} ) {
				push( @thisDirList, $item );
			}
		}
	}

	return( @thisDirList );
}

sub exitNow
{
	my $q = $config{'webtopTimedout'};
	my $s = $config{'webtopLanding'};

	my $msg = "$config{'webtopRelease'}:$raddr:exitNow():No session\n";
	my $url = "loginwt.pl?q=$q&s=$s";

	print "Content-Type: text/html\nCache-Control: no-cache\n\n
 
		<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
               	<head>
               	<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
		<meta http-equiv=refresh content=\'0; url=${url}\' />
               	</head>
               	</html>
        ";
	
	exit(1);
}

sub touchSession
{
	my $db = $tb->getWebtopDbWriter();
	$db->do( sql=> "
			UPDATE client_sessions SET touch_time = NOW()
				WHERE user_id = $userId
			" );
	$db->commit();
}
	
sub strim
{
        my($str) = @{{@_}}{qw/str/};

        !defined $str and return undef;
        $str =~ s/^\s+//;
        $str =~ s/\s+$//;

        return $str;
}

sub getUserId
{
	my $db = $tb->getWebtopDbWriter();
	my $sql;

	my $thisUserId = $client->getUserId();

	if( ! length( $thisUserId ) ) {		
		my $clientSessionId = $client->getSessionId();

		if( length( $clientSessionId ) ) {
			$sql = "SELECT user_id FROM client_sessions WHERE client_session_id = "	. $clientSessionId . " 
					AND client_session_type_id IN (1,4)";
		}
		else {
			$sql = "SELECT user_id FROM client_sessions WHERE rawip32_to_dotted_quad(public_ip_address) = '$raddr' 
					AND client_session_type_id IN (1,4)";
		}
	
		($thisUserId) = $db->query( sql=> $sql );
	}

	exitNow() unless( length( $thisUserId ) );

	return( $thisUserId );
}
		
sub getClientSessionId
{
	my $db = $tb->getWebtopDbWriter();
	my $clientSessionId = $client->getSessionId();

	if( ! length( $clientSessionId ) ) {
		my $sql = "SELECT client_session_id FROM client_sessions WHERE user_id = $userId
				AND client_session_type_id IN (1,4)";
		($clientSessionId) = $db->query( sql=> $sql );
	
		if( ! length( $clientSessionId ) ) {
			$sql = "SELECT client_session_id FROM client_sessions WHERE rawip32_to_dotted_quad(public_ip_address) = '$raddr' 
				AND client_session_type_id IN (1,4)";

			($clientSessionId) = $db->query( sql=> $sql );
		}
	}

	#exitNow() unless( length( $clientSessionId ) );

	return( $clientSessionId );
}

#
# Main:
#

touchSession() unless ( $cgi->param('m') eq $config{'webtopCheckIdleTimeout'} );

if($cgi->param('m') eq $config{'webtopGetCorporateBookmark'} )
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( @bookmarks ) = $db->query( sql=> "
					SELECT
						0,
						bookmark_id,
						'Corporate' AS category_name,
						bookmark_display_name AS display_name,
						bookmark_url AS url
					FROM
						user_bookmarks
					WHERE
						user_id = $userId
						AND
						restrict_set_id = " . ((! defined($restrictionSetId)) ? "NULL" : "'$restrictionSetId'" ) . "
					ORDER BY category_name, display_name
                        	" );

	if( scalar( @bookmarks ) ) {
		$html .= "<ul class='ot-list ot-list--is-very-high-density'>";

		my $row = 0;
		foreach my $bookmark ( @bookmarks ) {
			my( $categoryId, $bookmarkId, $categoryName, $displayName, $url ) = @$bookmark;

			$html .= "
				<li tabindex='-1' class='ot-list__item' id='cbmImg${row}' onclick='javascript:vb(${row},1);' title='Click to view $url'>
					$profileImg $displayName
					
					<p hidden>
						<input size='0' type='password' name='cba${row}' id='cba${row}' value='$bookmarkId'>
						<input size='0' type='password' name='cbb${row}' id='cbb${row}' value='$categoryId'>
						<input size='0' type='password' name='cbc${row}' id='cbc${row}' value='$displayName'>
						<input size='0' type='password' name='cbd${row}' id='cbd${row}' value='$url'>
					</p>
				</li>
				";

			$row++;
		}

		$html .= "</ul>";
	}
	else { 
		$html .= "
			        <div style='width: 100%; height: 50px; opacity: 1;'></div>
				<div id='cbm0' style='display: block; text-align: center' class='ot-form-control'>
					<img src='LocalWebLib/mime_tcpip_profile32.svg' style='height: 98px; width: 98px'> 
                			<div class='text'>
                        			<p style='color: black;'>
                                			<span>No corporate bookmarks were provisioned</span>
                        			</p>
					</div>
				</div>
			";
	}

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopGetPersonalBookmark'} )
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( @bookmarks ) = $db->query( sql=> "
                        		SELECT
						wub.category_id,
						user_bookmark_id,
						category_name,
						display_name,
						url
					FROM
						w_user_bookmarks AS wub
						JOIN w_user_bookmark_categories AS wubc ON wub.category_id = wubc.category_id
					WHERE
						user_id = $userId
					ORDER BY category_name, display_name
				" );

	my $row = 0;
	my $lastCategoryName = "";

	$html = "<div id='' onclick='javascript:rf(0);gbm();sf(1,0,1);'>
			<img src='LocalWebLib/action_add32.svg' style='height: 19px; width: 19px' title='Create bookmark'>

			<div id='bm0' style='display: block; text-align: center' class='ot-form-control'>
				<div style='width: 100%; height: 32px; opacity: 1;'></div>
				<img src='LocalWebLib/mime_tcpip_profile32.svg' style='height: 98px; width: 98px'> 
				<div class='text'>
					<p style='color: black;'>
						<span>Click the plus symbol above to create a bookmark</span>
					</p>
				</div>
			</div>
        	</div>";

	if( scalar( @bookmarks ) ) {
		$html .= "<div id='bmtr' class='ot-tree'>";

		foreach my $bookmark ( @bookmarks ) {
			my( $categoryId, $userBookmarkId, $categoryName, $displayName, $url ) = @$bookmark;

			if( length( $lastCategoryName ) && ( $categoryName ne $lastCategoryName ) ) {
				$html .= "</div>";
			}

			if( $categoryName ne $lastCategoryName ) {
				$html .= "
					<div role='button' class='ot-tree-node ot-tree-node--level-0 ot-tree-node--is-expanded' id='bmgr${row}' onclick=javascript:tt(${row});>
						<a class='ot-tree-node__icon'>
							<i id='bmgri${row}' class='ot-tree-node--is-expanded'>
							</i>
						</a>
						<button class='ot-tree-node__value'>$folderImg $categoryName</button>

						<div id='bgImg${row}' onclick='javascript:ubg(${row});'>
							<img src='LocalWebLib/action_edit32.svg' style='height: 19px; width: 19px' title='Manage bookmark group'>
							<p hidden>
								<input size='0' type='password' name='bga${row}' id='bga${row}' value='$categoryId'>
								<input size='0' type='password' name='bgb${row}' id='bgb${row}' value='$categoryName'>
							</p>
						</div>
					</div>
					<div id='bmgc${row}' style='display: block;'>
					";
			}

			$html .= "
					<div class='ot-tree-node ot-tree-node--level-1'>
						<button class='ot-tree-node__value' id='bmImg${row}' onclick='javascript:vb(${row},0);' title='Click to view $url'> 
							$profileImg $displayName
						</button>

						<div id='bmImg${row}' onclick='javascript:ub(${row});'>
							<img src='LocalWebLib/action_edit32.svg' style='height: 19px; width: 19px' title='Manage bookmark'>

							<p hidden>
								<input size='0' type='password' name='ba${row}' id='ba${row}' value='$userBookmarkId'>
								<input size='0' type='password' name='bb${row}' id='bb${row}' value='$categoryId'>
								<input size='0' type='password' name='bc${row}' id='bc${row}' value='$displayName'>
								<input size='0' type='password' name='bd${row}' id='bd${row}' value='$url'>
							</p>
						</div>
					</div>
				";
			
			$lastCategoryName = $categoryName;	
			$row++;
		}

		$html .= "</div>";
	}

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif( $cgi->param('m') eq $config{'webtopGetPersonalFileshare'} )
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( @fileShares ) = $db->query( sql=> "
					SELECT
						fsv.fileserver_id, 
						fsh.fileshare_id,
						fsv.fileserver_hostname, 
						fsh.fileshare_name, 
						fsu.display_drive_letter
					FROM
						w_smb_fileservers fsv, 
						w_smb_fileshares fsh, 
						w_smb_fileshare_users fsu
					WHERE
						fsh.fileshare_id = fsu.fileshare_id
						AND fsh.fileserver_id = fsv.fileserver_id
						AND user_id = $userId
					ORDER BY fsv.fileserver_hostname, fsh.fileshare_name
				" );

	my $id = 0;
        my $row = 0;

	$html = "<div id='' onclick='javascript:sf(1,0,2);'>
                	<img src='LocalWebLib/action_add32.svg' style='height: 19px; width: 19px' title='Create fileshare'>
			<div id='fs0' style='display: block; text-align: center' class='ot-form-control'>
			        <div style='width: 100%; height: 32px; opacity: 1;'></div>
					
				<img src='LocalWebLib/mime_document32-1.svg' style='height: 98px; width: 98px'> 
                		<div class='text'>
                        		<p style='color: black;'>
                                		<span>Click the plus symbol above to create a fileshare</span>
                        		</p>
				</div>
			</div>
                </div>";

	if( scalar( @fileShares ) ) {
		$html .= "<ul class='ot-list ot-list--is-very-high-density'>";

		foreach my $fileShare ( @fileShares ) {
			my( $fileServerId, $fileShareId, $fileServerHostname, $fileShareName, $displayDriveLetter ) = @$fileShare;

			$displayDriveLetter = $displayDriveLetter . ":" unless( length( $displayDriveLetter ) == 0 );
			my $thisFileShare = "\\\\" . $fileServerHostname . "\\" . $fileShareName;
			$thisFileShare = strim( str=> $thisFileShare );

			#
			# Don't display unless user has credentials
			#
			my( $cnt ) = $db->query( sql=> "
						SELECT 
							COUNT(1) 
						FROM 
							netresource_auth_cache
						WHERE 	
							user_id = $userId
							AND network_path = '" . $db->escape( dirty=> "$thisFileShare" ) . "'
						" );
			next unless( $cnt );

			my $pad = (315 - length( $thisFileShare ));

			$html .= "	
				<li tabindex='-1' class='ot-list__item' id='fsImg${row}'>
					<div id='fsiImg${row}' onclick='javascript:vfs(${row},0);' title='Click to browse $thisFileShare'>
						$docImg $thisFileShare
						<div style='height: .75rem; width:${pad}px; opacity: 1;'></div>
					</div>
					
					<div id='fsmImg${row}' onclick=javascript:uf(${row});>
						<img src='LocalWebLib/action_edit32.svg' style='height: 19px; width: 19px' title='Manage fileshare'>

						<p hidden>
							<input size='0' type='password' name='fa${row}' id='fa${row}' value='$fileServerId'>
							<input size='0' type='password' name='fb${row}' id='fb${row}' value='$fileShareId'>
							<input size='0' type='password' name='fc${row}' id='fc${row}' value='$fileServerHostname'>
							<input size='0' type='password' name='fd${row}' id='fd${row}' value='$fileShareName'>
							<input size='0' type='password' name='fe${row}' id='fe${row}' value=''>
							<input size='0' type='password' name='ff${row}' id='ff${row}' value=''>
							<input size='0' type='password' name='fz${row}' id='fz${row}' value='$thisFileShare'>
						</p>
					</div>
				</li>
			";

			$row++;
		}

		$html .= "
			</ul>
		";
	}

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopGetCorporateFileshare'} ) 
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( @clientDriveShares ) = $db->query( sql=> "
                			SELECT
                        			net_user, 
						net_pass, 
						drive_letter, 
						remote_addr, 
						TO_CHAR(last_access_date, 'yyyy/mm/dd hh24:mi:ss')
                			FROM
                        			client_drive_shares
               				WHERE
						user_id = $userId
                        			AND restrict_set_id = $restrictionSetId
					ORDER BY drive_letter, remote_addr
        				" );

	if( scalar( @clientDriveShares ) ) { 
		my $id = $userId;
        	my $row = 0;

		$html .= "<ul class='ot-list ot-list--is-very-high-density'>";

		foreach my $clientDriveShare( @clientDriveShares ) {
			my( $netUser, $netPass, $driveLetter, $remoteAddr, $lastAccessDate ) = @$clientDriveShare;
			my( undef, $hostName, $fileshareName, $fileshareInitialFolder ) = split( /\\{1,2}/, $remoteAddr, 4);

			$remoteAddr = strim( str=> $remoteAddr );
			$netUser = strim( str=> $netUser );

			my $cleanRemoteAddr = $remoteAddr;
			$cleanRemoteAddr =~ s/\\/\-/g;

			$html .= "
				<li tabindex='-1' class='ot-list__item' id='cfsImg${row}' onclick='javascript:vfs(${row},1);' title='Click to browse ${driveLetter}:${remoteAddr}'>
					<div id='cfsiImg${row}' onclick='javascript:(${row});' title='Click to browse ${driveLetter}:${remoteAddr}'>
					$docImg ${driveLetter}:${remoteAddr}
					</div>
					<p hidden>
						<input size='0' type='password' name='cfa${row}' id='cfa${row}' value='$id'>
						<input size='0' type='password' name='cfb${row}' id='cfb${row}' value='${cleanRemoteAddr}'>
						<input size='0' type='password' name='cfc${row}' id='cfc${row}' value=''>
						<input size='0' type='password' name='cfd${row}' id='cfd${row}' value=''>
						<input size='0' type='password' name='cfz${row}' id='cfz${row}' value='${driveLetter}:${remoteAddr}'>
					</p>
				</li>
				";
			
			$row++;		
		}
		
		$html .= "
			</ul>
		";
	}
	else {
		$html .= "
			        <div style='width: 100%; height: 50px; opacity: 1;'></div>
				<div id='cfs0' style='display: block; text-align: center' class='ot-form-control'>
					<img src='LocalWebLib/mime_document32-1.svg' style='height: 98px; width: 98px'> 
                			<div class='text'>
                        			<p style='color: black;'>
                                			<span>No corporate fileshares were provisioned</span>
                        			</p>
					</div>
				</div>
			";
	}

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopGetBookmarkGroup'} ) 
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( @categories ) = $db->query( sql=> "
                                        SELECT
                                                category_id, category_name
                                        FROM
                                                w_user_bookmark_categories
                                        WHERE
                                                user_id = $userId
                                        ORDER BY category_name
                                " );

	$html = "<select class='ot-select' name='bmGroup' id='bmGroup' style='width: 15em'>
                	<option value='0' selected></option>
		";
									
	foreach my $category ( @categories ) {
		my( $categoryId, $categoryName ) = @$category;
		$html .= "  <option value='$categoryId'>$categoryName</option>";
	}

	$html .= "</select>";

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopGetSummary'} ) 
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my $clientSessionId = $client->getSessionId();

	my( @row ) = $db->query( sql=> "
					SELECT rawip32_to_dotted_quad(private_ip_address),
						ROUND( EXTRACT(epoch FROM connect_date) / 60 ),
						ROUND( EXTRACT(epoch FROM touch_time) / 60 )
						FROM client_sessions
						WHERE user_id = " . $userId . " AND client_session_type_id IN (1,4)
					" );
	
	my( $privateIpAddress, $connectDate, $touchTime ) = @{ $row[0] };
	my $duration = ( $touchTime - $connectDate );
	$duration = "$duration minute" . ( $duration == 1 ? "" : "s" );

	my $disconnect = "Maximum 24 hours";

	my( $timeoutMinutes ) = $db->query( sql=> "
					SELECT  
						timeout_minutes
						FROM user_idle_timeout
							WHERE user_id = $userId
						" );
	if( length( $timeoutMinutes ) ) {
		my( $now ) = $db->query( sql=> "		
						SELECT ROUND( EXTRACT(epoch FROM NOW()) / 60 )
						" );

		$disconnect = ( $now - $touchTime );
		$disconnect = "$disconnect minute" . ( $disconnect == 1 ? "" : "s" );
	}

$html .= "	
<div style='height: calc( 100vh - 100px ); width: calc( 100vw - 100px ); position: relative;'> 
	<div class='ot-table'>
		<div class='ot-table-wrapper'>
			<div class='ot-table-container'>
				<div class='ot-table-content'>
					<div role='table body' class='ot-table__body'>
						<div class='ot-container'>
							<div class='ot-table-header-group'>
								<div class='ot-table__subheader'>
									<div class='ot-table__column' style='width: 33%; text-align: left;'>
										<p>VPN</p>
									</div>
									<div class='ot-table__column' style='width: 33%; text-align: left;'>
										<p>Duration</p>
									</div>	
									<div class='ot-table__column' style='width: 34%; text-align: left;'>
										<p>Disconnect In</p>
									</div>	
								</div>
							</div>
							<div class='ot-table-row-group' id='tdTab'>
								<div class='ot-table__row'>
									<div class='ot-table__column' style='width: 33%; text-align: left;'>
										<p>$privateIpAddress</p>
									</div>
									<div class='ot-table__column' style='width: 33%; text-align: left;'>
										<p>$duration</p>
									</div>
									<div class='ot-table__column' style='width: 34%; text-align: left;'>
										<p>$disconnect</p>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
	";

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopLoadPersonalBookmarkTitle'} ) 
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( $displayName ) = $db->query( sql=> "
                        		SELECT
						display_name
					FROM
						w_user_bookmarks AS wub
						JOIN w_user_bookmark_categories AS wubc ON wub.category_id = wubc.category_id
					WHERE 
						user_bookmark_id = $key AND user_id = $userId
				" );

	$html .= "
	  	<li id='tm${key}' class='ot-tabs__item'>
			<a onclick=javascript:tbtab(${key});>$profileImg $displayName</a>
               	</li>
	";

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopLoadCorporateBookmarkTitle'} ) 
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( $displayName ) = $db->query( sql=> "
					SELECT
						bookmark_display_name AS display_name
					FROM
						user_bookmarks
					WHERE
						bookmark_id = $key  
						AND 
						user_id = $userId 
				" );

	$html .= "
	  	<li id='tm${key}' class='ot-tabs__item'>
			<a onclick=javascript:tbtab(${key});>$profileImg $displayName</a>
               	</li>
	";

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopLoadCorporateFileshareTitle'} ) 
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my $dirtyRemoteAddr = $key;
	$dirtyRemoteAddr =~ s/-/\\/g;

	my( $remoteAddr ) = $db->query( sql=> "
                			SELECT
						remote_addr
                			FROM
                        			client_drive_shares
               				WHERE
						remote_addr = '$dirtyRemoteAddr'
						AND 
						user_id = $userId 
					" );

	$html .= "
	  	<li id='tm${key}' class='ot-tabs__item'>
			<a onclick=javascript:tbtab('${key}');>$docImg $dirtyRemoteAddr</a>
               	</li>
		";

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopLoadPersonalFileshareTitle'} )  
{
	my $db = $tb->getWebtopDbWriter();
	my $html;

	my( $fileshareName ) = $db->query( sql=> "
					SELECT
						fsh.fileshare_name
					FROM
						w_smb_fileservers fsv, 
						w_smb_fileshares fsh, 
						w_smb_fileshare_users fsu
					WHERE
						fsh.fileshare_id = fsu.fileshare_id
						AND fsh.fileserver_id = fsv.fileserver_id
						AND user_id = $userId
				" );

	$html .= "
	  	<li id='tm${key}' class='ot-tabs__item'>
			<a onclick=javascript:tbtab('${key}');>$docImg $fileshareName</a>
               	</li>
		";

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopCheckIdleTimeout'} )  
{
	my $db = $tb->getWebtopDbWriter();

	my $timeoutMinutes = 0;
	my $warnMinutes = 0;
	my $forceSignOut= 0;
	my $showModal = 0;
	my $timeDiff = 0;
	my $timeRemaining = 0;
	my $html;
	my $msg;
	my $called = $cgi->param('c');

	my $clientSessionId = getClientSessionId();

	if( ! length( $clientSessionId ) ) {
		$html = "1^2^$called^$html";
		print "Content-Type: text/html\n\n";
		print "$html";	

		exit(1);
	}
	
	if( $called == 0  ) {
		$called++;

		$html = "0^0^$called^0";
		print "Content-Type: text/html\n\n";
		print "$html";	

		exit(1);
	}

	my( @row ) = $db->query( sql=> "
					SELECT  
						timeout_minutes,
            					warn_minutes
						FROM user_idle_timeout
							WHERE user_id = $userId
						" );

	if( scalar( @row ) ) {
		( $timeoutMinutes, $warnMinutes ) = @{ $row[0] };
		$warnMinutes = 0 unless( defined( $warnMinutes ) && length( $warnMinutes ) );
	}

	if( $timeoutMinutes > 0 ) {
		my( $touchTime ) = $db->query( sql=> "		
							SELECT 
								ROUND( EXTRACT(epoch FROM touch_time) / 60 )
									FROM client_sessions
									WHERE user_id = $userId AND  client_session_type_id IN (1,4)
							" );

		my( $now ) = $db->query( sql=> "		
						SELECT ROUND( EXTRACT(epoch FROM NOW()) / 60 )
						" );
		$timeDiff = ( $now - $touchTime );

		if( $timeDiff >= $timeoutMinutes ) {
			$showModal = 1;	
			$forceSignOut = 1;
		}
		else {
			if( $warnMinutes > 0 ) {	
				$timeDiff = ( $now - $touchTime );
				if( $timeDiff > $warnMinutes ) {
					$showModal = 1;	
				}
			}
		}
	}

	if( $showModal == 1 ) {
		if( $forceSignOut ) {
			$msg = "Your session has expired due to inactivity.";
		}
		else {
			$msg = "Your session will expire in $warnMinutes minute" . ( $warnMinutes == 1 ? "." : "s." );
		}

		$html = "<div class='ot-modal ot-modal--is-active' id='itodiv' style='z-index: 4999;'>
				<div class='ot-modal__background'>
				</div>
				<div class='ot-modal__content'>
					<div class='ot-modal__header'>
						<p class='title'>
							<input type='text' disabled class='ot-input' name='mt8' id='mt8' value='INFORMATION'>
						</p>
					</div>
					<div class='ot-modal__body'>
						<div class='ot-m-1' style='background: #white; width: 450px; height: 150px;'>
							<div class='ot-form-control'>
								<div id='itoMsgDiv' class='ot-form-control'>
									$msg	
								</div>
							</div>
						</div>
					</div>
					<div class='ot-modal__footer'>
						<div class='ot-btn-group'>
		";

		if( $forceSignOut ) {
		$html .= "			<button class='ot-btn ot-btn--is-primary' onclick='javascript:q();'>
			  				Sign out
		      				</button>
		";
		}
		else {
		$html .= "			<button class='ot-btn ot-btn--is-primary' onclick='javascript:sto();'>
							OK
						</button>
		";
		}

		$html .= "			</div>
    					</div>
  				</div>
			</div>
		";
	}

	$called++;

	#
	# Had to include the session decontruction here...
	#
	if( $forceSignOut ) {
		#
		# Shutdown tunnel
		#
		my( $tunnelName ) = $db->query( sql=> "
						SELECT tunnel_name 
							FROM client_sessions	
							WHERE client_session_id = $clientSessionId AND client_session_type_id IN (1,4)
						" );

		if( length( $tunnelName ) ) {
			my $url = $config{'l2tpWebserviceUrl'} . "?c=0&u=&t=$tunnelName";
			my $request = HTTP::Request->new(GET=>$url );
			my $ua = LWP::UserAgent->new;
			my $response = $ua->request( $request );
		}

		$db->do( sql=> "DELETE FROM anx_portal_sessions WHERE client_session_id = $clientSessionId" );
		$db->commit();
	}

	if( length( $html ) ) {
		$html = "1^$forceSignOut^$called^$html";
	}
	else {
		$html = "0^0^$called^0";
	}

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopUserAclWebsite'} )  
{
	my $db  = $tb->getWebtopDbWriter();
	my $url = $cgi->param('u');
	my $html = "";

	my( @rows ) = $db->query( sql=> "
					SELECT protocol_name,
						location
						FROM w_user_acls AS wua 
						JOIN w_acl_protocols AS wap ON wap.protocol_id = wua.protocol_id
						JOIN w_acl_targets AS wat ON wat.target_id = wua.target_id
						WHERE user_id = $userId 
							AND wat.target_name = 'DENY' 
							AND wap.protocol_name in ('HTTP', 'HTTPS')
			" );

	my( @workArr ) = split( "/", $url );
	foreach my $row ( @rows ) {
		my( $protocolName, $location ) = @$row;
	
		$protocolName = uc( $protocolName ) . ":";
		next unless( $protocolName eq uc( $workArr[0] ) );

		my( @aclLocationArr ) = split( "/", $location );
		push( @aclLocationArr, $location ) unless( scalar( @aclLocationArr ) );

		my( @cmpArr );
		foreach my $work ( @workArr ) {
			next unless ( length( $work ) );
			next unless ( uc( $work ) ne "HTTP:" && uc( $work ) ne "HTTPS:" );

			push( @cmpArr, $work );
		}

		if( $aclLocationArr[0] eq $cmpArr[0] ) {
			my $i=0;

			shift( @aclLocationArr );
			shift( @cmpArr );
			foreach my $aclLocation ( @aclLocationArr )  {

				if( $aclLocation eq "*" || $aclLocation eq $cmpArr[$i] ) {
					
					$html = "<div class='ot-modal ot-modal--is-active' id='acldiv' style='z-index: 3501;'>
							<div class='ot-modal__background'>
							</div>
							<div class='ot-modal__content'>
								<div class='ot-modal__header'>
									<p class='title'>
										<input type='text' disabled class='ot-input' value='WARNING'>
									</p>
								</div>
								<div class='ot-modal__body'>
									<div class='ot-m-1' style='background: #white; width: 450px; height: 150px;'>
										<div class='ot-form-control'>
											Your access to $url is restricted.	
										</div>
									</div>
								</div>
								<div class='ot-modal__footer'>
									<button class='ot-btn ot-btn--is-primary' onclick=javascript:doq('aclDiv');>
									OK
									</button>
								</div>
							</div>
						</div>
					";

					last;
				}

				$i++;
			}	
		}
	}

	$html = "OK" unless( length( $html ) ) ;
	
	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopDiagnostic'} ) {
	my $db = $tb->getWebtopDbWriter();
	my $html;
	my $xml;
	my $msg = "Diagnostics is not available, please try again later.";
	my $badImg = "<img src='LocalWebLib/action_small_delete14.svg' style='height: 19px; width: 19px'>";
	my $okImg = "<img src='LocalWebLib/form_checkbox14_on_readonly.svg' style='height: 19px; width: 19px'>";
	my @objs = ();
	
	$ENV{'PATH'} = '/usr/local/positive/WebInterface:/usr/bin:/bin';
	my( $userName ) = $db->query( sql=> "SELECT user_name FROM users WHERE user_id=$userId" );
	my $response = `diagnosL2tpUserTunnel.pl $userName`; 

	$html = "<div class='ot-modal ot-modal--is-active' id='dgdiv' style='z-index: 3501;'>
			<div class='ot-modal__background'>
			</div>
			<div class='ot-modal__content'>
				<div class='ot-modal__header'>
					<p class='title'>
						<input type='text' disabled class='ot-input' value='INFORMATION'>
					</p>
				</div>
				<div class='ot-modal__body'>
					<div class='ot-m-1' style='background: #white; width: 400px; height: 300px;'>
							<div class='ot-form-control'>
	";

	if( length( $response ) ) {
		my $simple = XML::Simple->new();

		local $ENV{XML_SIMPLE_PREFERRED_PARSER} = "XML::Parser";
		eval { $xml = $simple->XMLin( "$response" )};
			
		if( ref( @{$xml->{'steps'}->{'step'}} ) eq "ARRAY" ) {
			@objs = @{$xml->{'steps'}->{'step'}};
		}
		else {
			push( @objs, @{$xml->{'steps'}->{'step'}} );
		}


		$html .= "<ul class='ot-list ot-list--is-very-high-density'>";

		my $row = 1;
		foreach my $obj ( @objs ) {
			my $seq = $obj->{'seq'};
			my $hidden = $obj->{'hidden'};
			my $method = $obj->{'method'};
			my $status = $obj->{'status'};
			my $task = $obj->{'task'};
			my $reason = $obj->{'reason'};

			my $img = $okImg;
			$img = $badImg unless( $status == 1 );
			
			if( ! $hidden ) { 	
				$html .= "<li tabindex='-1' class='ot-list__item'>";
				$html .= $img . " Step ${row}  $task";
				$html .= "</li>";
		
				$row++;
			}

		}

		$html .= "	
			</ul>
	";
	}
	else {
		$html .= $msg;
	}

	$html .= "
						</div>
					</div>
				</div>
				<div class='ot-modal__footer'>
					<button class='ot-btn ot-btn--is-primary' onclick=javascript:doq('diagDiv');>
					OK
					</button>
				</div>
			</div>
		</div>
	";					

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopShowFileShareTree'} ) {
	my $q = $cgi->param('q');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $modal = $cgi->param('M');
	$modal = 0 unless( defined( $modal ) && length( $modal ) );
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );

	if( $cgi->param('i') eq "root" ) {
		$itemType = "directory";
	}

	if( $isCorporate == 0 ) {
		( $rc, $html ) = showPersonalFileShare( remoteAddr=>$q, itemType=>$itemType, isTree=>1, modal=>$modal );
	}
	elsif( $isCorporate == 1 ) {
		( $rc, $html ) = showCorporateFileShare( remoteAddr=>$q, itemType=>$itemType, isTree=>1, modal=>$modal );
	}

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopLoadFileSharePanel'} ) {
	my $q = $cgi->param('q');
	my $drive = $cgi->param('d');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );

	if( $isCorporate == 0 ) {
		( $rc, $html ) = showPersonalFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
	}
	elsif( $isCorporate == 1 ) {
		( $rc, $html ) = showCorporateFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
	}

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopDeleteFileShareDocument'} ) {
	my $q = $cgi->param('q');
	my $drive = $cgi->param('d');
	my $file = $cgi->param('f');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );

	$drive = "" unless( $drive ne "This fileshare" );
	$drive = "\\". $drive unless( ! length( $drive ) );

	( $rc, $html ) = executeSmb( remoteAddr=>$q, drive=>$drive, file=>$file, command=>"deleteFile", isCorporate=>$isCorporate );

	if( $rc ) {
		if( $isCorporate == 0 ) {
			( $rc, $html ) = showPersonalFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
		}
		elsif( $isCorporate == 1 ) {
			 ( $rc, $html ) =  showCorporateFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
		}
	}

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopDownloadFileShareDocument'} ) {
	my $q = $cgi->param('q');
	my $drive = $cgi->param('d');
	my $file = $cgi->param('f');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );

	$drive = "" unless( $drive ne "This fileshare" );
	$drive = "\\". $drive unless( ! length( $drive ) );

	( $rc, $html ) = executeSmb( remoteAddr=>$q, drive=>$drive, file=>$file, command=>"getFile", isCorporate=>$isCorporate );

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopMoveFileShareDocument'} ) {
	my $q = $cgi->param('q');
	my $drive = $cgi->param('d');
	my $driveNew = $cgi->param('D');
	my $file = $cgi->param('f');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );

	$drive = "" unless( $drive ne "This fileshare" );
	$driveNew = "" unless( $driveNew ne "This fileshare" );

	$drive = "\\". $drive unless( ! length( $drive ) );
	$driveNew = "\\". $driveNew unless( ! length( $driveNew ) );

	( $rc, $html ) = executeSmb( remoteAddr=>$q, drive=>$drive, driveNew=>$driveNew, file=>$file, command=>"moveFile", isCorporate=>$isCorporate );

	if( $rc == 1 ) {
		if( $isCorporate == 0 ) {
			( $rc, $html ) = showPersonalFileShare( remoteAddr=>$q, drive=>$driveNew, itemType=>$itemType, isTree=>0 );
		}
		elsif( $isCorporate == 1 ) {
			( $rc, $html ) = showCorporateFileShare( remoteAddr=>$q, drive=>$driveNew, itemType=>$itemType, isTree=>0 );
		}
	}

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopRenameFileShareDocument'} ) {
	my $q = $cgi->param('q');
	my $drive = $cgi->param('d');
	my $file = $cgi->param('f');
	my $fileNew = $cgi->param('F');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );
	
	$drive = "" unless( $drive ne "This fileshare" );
	$drive = "\\". $drive unless( ! length( $drive ) );

	( $rc, $html ) = executeSmb( remoteAddr=>$q, drive=>$drive, file=>$file, fileNew=>$fileNew, command=>"renameFile", isCorporate=>$isCorporate );
	if( $rc == 1 ) {
		if( $isCorporate == 0 ) {
			( $rc, $html ) = showPersonalFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
		}
		elsif( $isCorporate == 1 ) {
			( $rc, $html ) = showCorporateFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
		}
	}

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopUploadFileShareDocument'} ) {
	my $q = $cgi->param('q');
	my $drive = $cgi->param('d');
	my $file = $cgi->param('f');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );

	( $rc, $html ) = executeSmb( remoteAddr=>$q, drive=>$drive, file=>$file, command=>"putFile", isCorporate=>$isCorporate );

	if( $rc ) {
		if( $isCorporate == 0 ) {
			( $rc, $html ) = showPersonalFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
		}
		elsif( $isCorporate == 1 ) {
			( $rc, $html ) = showCorporateFileShare( remoteAddr=>$q, drive=>$drive, itemType=>$itemType, isTree=>0 );
		}
	}

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}
elsif($cgi->param('m') eq $config{'webtopCreateFileShareFolder'} ) {
	my $q = $cgi->param('q');
	my $drive = $cgi->param('d');
	my $folderName = $cgi->param('F');
	my $file = $cgi->param('f');
	my $isCorporate = $cgi->param('c');
	my $itemType = $cgi->param('i');
	my $ajax = $cgi->param('ajax');
	my $html;
	my $rc = 0;

	$q = uri_unescape( $q );
	$q = decode_base64( $q );
	$q = HTML::Entities::decode( $q );

	( $rc, $html )=executeSmb( remoteAddr=>$q, drive=>$drive, folderName=>$folderName, file=>$file, command=>"createFolder", isCorporate=>$isCorporate );

	if( $rc ) {
		if( $isCorporate == 0 ) {
			( $rc, $html ) = showPersonalFileShare( remoteAddr=>$q, itemType=>"directory", isTree=>1 );
		}
		elsif( $isCorporate == 1 ) {
		 	( $rc, $html ) = showCorporateFileShare( remoteAddr=>$q, itemType=>"directory", isTree=>1 );
		}
	}

	$html = "$rc^$html" unless( ! $ajax );

	print "Content-Type: text/html\n\n";
	print "$html";	
}

1;
