#!/usr/bin/perl
use lib '/home/erealms/ethereal/mgmt/perl';

#################################################################################
# Created       : Martin Foster
# Modified      : 06-Aug-2006
#################################################################################
#
# Vanity - The outlet for ones vanity showing pictures of users as they have
#          requested.    
# Copyright (C) 2000-2006  Martin Foster
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# Author of this script can be contacted at the following:
#       E-Mail  : martin@ethereal-realms.org
#       Address : 3456 Wolfe Cres
#                 Halifax, Nova Scotia
#                 B3L 3S2
#
#################################################################################

use CGI;							# Common gateway interface
use CGI::Carp qw(fatalsToBrowser);				# CGI Error logs
use strict;							# Strict variable enforcement

use Ethereal::Database;						# Database handler
use Ethereal::Login;						# Login handler
use Ethereal::Param;						# Parameter control
use Ethereal::Template;						# Template handler

#################################################################################
# Gobal override
#################################################################################
$CGI::POST_MAX=1024 * 50;					# Maximum posts
$CGI::DISABLE_UPLOADS = 1;					# Disable uploads


#################################################################################
# Data Members
#################################################################################
my $cgi;							# Common gateway interface handle
my $database;							# Database handle
my $login;							# Login display
my $param;							# Parameter handle
my $tmpl;							# Template handle

my $statement;							# Database statement
my $res;							# Results list

my $url;							# Self referencing link
my $lnk;							# Appended link

my $count;							# Counter
my $vid;							# Setting things up

my $user;							# Login name

my $counts;							# Number of entries for votes
my $results;							# Results of voting
my $score;							# Before mangling
my $success;							# Successful login

my $def;							# Default handle
my $nav;							# Navigation capabilities
my $vanity;							# Vanity display
my $vote;							# Voting capabilities

my %vanity;							# Vanity hash


#################################################################################
# Program Area
#################################################################################

	# Initial handles
	$cgi      = new CGI;
	$database = new Ethereal::Database();

	# Kill switch
	exit if $database->{'COMP_VANITY'} eq 'false';

	# Connect and Fetch
	$database->Connect($cgi);


	# Parameter handling
	$param = new Ethereal::Param($database, $cgi);
	$param->GetParam();

	# Link with hash
	$database->GetHashVanity(\%vanity);

	
	# Initialize handles
	$tmpl     = new Ethereal::Template(\%vanity);
	$login    = new Ethereal::Login($database, $cgi, $param);

	
	# Authenthication
	$success = $login->GetVerificationNormal()
	 if (defined($param->{'USER'}));


	# How can one be vain without 
	if ((defined($param->{'VID'}))
	 && (($success) || (!defined($param->{'USER'}))))
	{
		# Print document header and html header
		print $cgi->header()
		  unless (defined($param->{'USER'}));
		print $database->DocumentGetHeader(), "\n";

		
		# Make sure the user exists
		($user) = $database->DataGet("SELECT PuppeteerLogin
			FROM Vanity
			WHERE VanityID=?", $param->{'VID'}
		 );


		# Things are defined
		if (defined($user))
		{
			# Is there a need to record a vote?
			if ((defined($param->{'VANITY_VOTE'}))
			 && ($param->{'VANITY_VOTE'} =~ /^\d{1,2}$/)
			 && ($param->{'VANITY_VOTE'} > 0)
			 && ($param->{'VANITY_VOTE'} < 11))
			{
				# Quickly insert and get on with it
				$database->Quick("INSERT INTO VanityVotes
					(VanityID,
					 PuppeteerLogin,
					 VoteLevel)
					VALUES (?,?,?)",

				 $param->{'VID'},
				 $param->{'USER'},
				 $param->{'VANITY_VOTE'}
				);
			}

			
			# Start a larger process
			# Prepare
			$database->Pull(\$statement, "SELECT
				  VanityID     AS \"VanityID\",
				  VanityPath   AS \"VanityPath\",
				  VanityHeight AS \"VanityHeight\",
				  VanityWidth  AS \"VanityWidth\",
				  VanityVote   AS \"VanityVote\"
				FROM Vanity
				WHERE PuppeteerLogin=?
				  AND VanityPublic=?
				ORDER BY VanityID",

			 $user,
			 'yes'
			);


			# Verification
			if ($res = $statement->fetchrow_hashref())
			{
				# Self referencing link
				$url  = $cgi->url(-absolute=>1);
					
				# Link
				$lnk = (defined($param->{'USER'}))
				 ? $param->EmbedInline(USER=>$param->{'USER'}, CRYPT=>$param->{'CRYPT'}) . '&'
				 : '?';


				# Initialize
				$count = 0;

				# Set base template
				$nav   = '';
				 
				
				# Keep looping until you find
				do
				{
					# Increment
					$count++;
					
					# Set template
					$vid = 'VID=' . $res->{'VanityID'};
					
					# Display
					$nav .= ($res->{'VanityID'} ne $param->{'VID'})
					 ? $tmpl->Pass('TagNavDis', MLINK=>$url . $lnk . $vid, MCOUNT=>$count)
					 : $tmpl->Pass('TagNavVis', MLINK=>$url . $lnk . $vid, MCOUNT=>$count);

					
					# Need to bypass
					if ($res->{'VanityID'} eq $param->{'VID'})
					{
					
						# Information display
						# Create template
						$vanity = $tmpl->Pass('TmplVanityDisplay',
							LIMAGE  => $res->{'VanityPath'},
							MID     => $res->{'VanityID'}, 
							MHEIGHT => $res->{'VanityHeight'},
							MWIDTH  => $res->{'VanityWidth'}
						 );


	 					# Vanity voting capability
						# Penis size measurements below
						if ((defined($param->{'USER'}))
						 && ($res->{'VanityVote'} eq 'yes'))
						{
							# Has there been a vote
							($results) = $database->DataGet("SELECT VoteLevel
								FROM VanityVotes
								WHERE VanityID=?
								  AND PuppeteerLogin=?",
	
							 $res->{'VanityID'},
							 $param->{'USER'}
							);
		
							# Hanging judge time
							unless (defined($results))
							{
								# Start of form
								my $frmstart  = $cgi->start_form();
								   $frmstart .= $param->EmbedNormal($param->Flat());
	
								# End of form
								my $frmend    = $cgi->end_form();

								# Level widget
								my $frmlevel  = $cgi->radio_group(
									-name      => 'VANITY_VOTE',
									-values    => ['1','2','3','4','5','6','7','8','9','10'],
									-default   => '10',
									-linebreak => 'true'
								 );
							

								# Generate appropriatly
								$vote = $tmpl->Pass('TmplVanityVote',
									WFRMSTART => $frmstart, 
									WFRMEND   => $frmend,
									WLEVEL    => $frmlevel,
									WVOTE     => $cgi->submit($vanity{'TxtVote'})
								 );
							}
						}


						# Catch another circumstance
						# These will use variable template names.  Listed below for non-removal.
						#   TmplVanityRes01
						#   TmplVanityRes02
   						#   TmplVanityRes03
						#   TmplVanityRes04
						#   TmplVanityRes05
						#   TmplVanityRes06
						#   TmplVanityRes07
   						#   TmplVanityRes08
						#   TmplVanityRes09
						#   TmplVanityRes10

						if (($res->{'VanityVote'} eq 'yes')
						 && (!defined($vote)))
					 	{
							# Get the average results
							($results, $counts) = $database->DataGetVanityScores($res->{'VanityID'});      
	
							# Make sure information is proper
							$results = (defined($results)) ? int($results) : 0;

							# Check and see
							if ($results > 0)
							{
								# Additional massaging
								$score   = $results;
								$results = ($results < 10) ? 0 . $results : $results;
	
								# Display simple template
								$vote = $tmpl->Pass('TmplVanityRes' . $results,
									MLEVEL => $score,
									MCOUNT => $counts
								 );
							}

							# No votes so don't show
							else
							{
								# Something has to be there
								$vote = $vanity{'TmplVanityResNil'};
							}
						}

						# All else failed
						# Default template
						elsif (!defined($vote))
						{
							# Something has to be there
							$vote = $vanity{'TmplVanityResNil'};
						}
					}

				} while ($res = $statement->fetchrow_hashref());
			}

			# Finish statement
			$statement->finish();

			# Fetch default handle
			($def) = $database->DataGetDefault($user);


			# Display final template
			$tmpl->Show('TmplVanity',
				LSTNAV   => $nav,
				MDEFAULT => $def,
				MVANITY  => $vanity,
				MVOTES   => $vote
			 );
		}

		# Document footer
		print $database->DocumentGetFooter(), "\n";
	}

#################################################################################
# Sub-Routines
#################################################################################
