#!/usr/bin/perl -w

#******************************************************************************************************
#   ATTENTION: THIS FILE HEADER MUST REMAIN INTACT. DO NOT DELETE OR MODIFY THIS FILE HEADER.
#
#   Name: uu_ini_status.pl
#   Link: http://uber-uploader.sourceforge.net/
#   Revision: 1.2
#   Date: 11/03/2007 2:16PM
#   Initial Developer: Peter Schmandra
#   Description: Initialize the progress bar and exit
#
#   Licence:
#   The contents of this file are subject to the Mozilla Public
#   License Version 1.1 (the "License"); you may not use this file
#   except in compliance with the License. You may obtain a copy of
#   the License at http://www.mozilla.org/MPL/
# 
#   Software distributed under the License is distributed on an "AS
#   IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
#   implied. See the License for the specific language governing
#   rights and limitations under the License.
#
#************************************************************************************************************************************

# Makes %ENV Safer (Programming Perl By Oreilly pg.560)
$ENV{'PATH'} = '/bin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

require "uu_lib.pl";

my $this_version = "1.2";                                         # Version of this driver      

#####################################################################################################################
# The following possible query string formats are assumed
#
# 1. ?tmp_sid=some_sid_number&config_file=some_config_name&rnd_id=some_random_number
# 2. ?tmp_sid=some_sid_number&rnd_id=some_random_number
# 3. ?cmd=about
#####################################################################################################################
my %query_string = &parse_query_string($ENV{'QUERY_STRING'});

# Check query string sent to script
if(exists($query_string{'cmd'}) && $query_string{'cmd'} eq 'about'){ &kak("<u><b>UBER UPLOADER AJAX PROGRESS PAGE</b></u><br> UBER UPLOADER VERSION = <b>" . $uber_version . "<\/b><br>UU_INI_STATUS = <b>" . $this_version . "<b><br>\n", 1, __LINE__); }
elsif(exists($query_string{'cmd'}) && $query_string{'cmd'} ne 'about'){ &kak("<font color='red'>ERROR<\/font>: Invalid command passed<br>\n", 1, __LINE__); }
elsif(exists($query_string{'tmp_sid'}) && $query_string{'tmp_sid'} !~ m/(\w{32})/){ &xml_kak("<ini_status><error_status>1</error_status><error_msg>ERROR: Invalid session-id " . $query_string{'tmp_sid'} . "</error_msg></ini_status>"); }
elsif((!exists($query_string{'cmd'}) || !defined($query_string{'cmd'})) && (!exists($query_string{'tmp_sid'}) || !defined($query_string{'tmp_sid'}))){ &xml_kak("<ini_status><error_status>1</error_status><error_msg>ERROR: Invalid parameters passed</error_msg></ini_status>"); }

#######################################################################
# Attempt to load the config file that was passed to the script. If
# no config file name was passed then load the default config file. 
#######################################################################
if(exists($query_string{'config_file'}) && defined($query_string{'config_file'}) && $query_string{'config_file'} =~ m/(\w{5,32})/ && $MULTI_CONFIGS_ENABLED){ 
	my $config_file = $query_string{'config_file'};
	
	unless(eval "require configs::$config_file"){
		if($@){ &xml_kak("<ini_status><error_status>1</error_status><error_msg>ERROR: Failed to load config file " . $config_file . ".pm</error_msg><stop_upload>1</stop_upload></ini_status>"); }
	}
}
elsif(exists($query_string{'config_file'}) && defined($query_string{'config_file'}) && (!$MULTI_CONFIGS_ENABLED || $query_string{'config_file'} !~ m/(\w{5,32})/)){
	if(!$MULTI_CONFIGS_ENABLED){ &xml_kak("<ini_status><error_status>1</error_status><error_msg>ERROR: Multi config files disabled</error_msg><stop_upload>1</stop_upload></ini_status>"); }
	elsif($query_string{'config_file'} !~ m/(\w{5,32})/){ &xml_kak("<ini_status><error_status>1</error_status><error_msg>ERROR: Invalid config file name</error_msg><stop_upload>1</stop_upload></ini_status>"); }
}
else{
	unless(eval "require configs::uu_default_config"){
		if($@){ &xml_kak("<ini_status><error_status>1</error_status><error_msg>ERROR: Failed to load default config file uu_default_config.pm</error_msg><stop_upload>1</stop_upload></ini_status>"); }
	}
}

my $temp_dir_sid = $config->{temp_dir} . $query_string{'tmp_sid'};    # temp_dir/session-id                      
my $flength_file = $temp_dir_sid . "/flength";                        # temp_dir/session-id/flength     
my $flength_file_exists = 0;                                          # track the flength file
my $total_bytes = 0;                                                  # size of the upload in bytes
      
# Keep trying to find the flength file for 10 secs
for(my $i = 0; $i < 10; $i++){
	if(-e $flength_file && -r $flength_file){
		# We found the flength file
		$flength_file_exists = 1;
		
		open(FLENGTH, $flength_file);
		$total_bytes = <FLENGTH>;
		close(FLENGTH);
		
		last;
	}
	else{ sleep(1); }
}

#####################################################################################
# Ok, we couldn't find the flength file after 10 seconds. This means
#
# a. The upload was so fast the flength file was deleted before it could be read.
# b. The flength file does not exist because the script is not set up properly.
# c. The flength file does not exist due to some kind of server caching.
#
# More info can be found at http://uber-uploader.sourceforge.net/?section=flength 
#
# So, issue "Failed to find flength file" and exit. Upload may succeed anyway.
#####################################################################################
if(!$flength_file_exists){ 
	&xml_kak("<ini_status><error_status>1</error_status><error_msg>ERROR: Failed to find flength file</error_msg></ini_status>"); 
}

######################################################################
# Found the flength file but it contains an error. So, clean up the 
# temp directories and issue error
######################################################################
if($total_bytes =~ m/ERROR/g){
	&deldir($temp_dir_sid);
	&xml_kak("<ini_status><error_status>1</error_status><error_msg>$total_bytes</error_msg><stop_upload>1</stop_upload></ini_status>");
}

# Everything looks good so build the xml output and dump it to screen (initialize progress bar) 
my $xml_msg;
$xml_msg .= "<ini_status>";
$xml_msg .= "<error_status>0</error_status>";
$xml_msg .= "<start_time>".time()."</start_time>";
$xml_msg .= "<temp_dir>".$config->{temp_dir}."</temp_dir>";
$xml_msg .= "<total_bytes>".$total_bytes."</total_bytes>";
$xml_msg .= "<get_data_speed>".$config->{get_data_speed}."</get_data_speed>";
$xml_msg .= "<cedric_progress_bar>".$config->{cedric_progress_bar}."</cedric_progress_bar>";
$xml_msg .= "</ini_status>";              
&xml_kak($xml_msg);

# Dump xml to screen
sub xml_kak{
	my $xml = shift;
	
	print "Content-type: text/xml\n\n"; 
	print "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
	print $xml;
	exit;
}