#!/usr/local/bin/perl
#*********************************************************************
#*  PROGRAM : Locator.cgi
#*  AUTHOR  : Gregory Galiardi
#*  PURPOSE : This cgi script will present the user with a series of  
#*            screens on which they can select criteria for the 
#*            a locator inquiry to the Satellite Situation Center  
#*            database.
#*	DATE 	: 7-Jul-96
#*  MODIFICATION HISTORY
#*  2/26/97  GCG Added the variable $no_output_selected to be used 
#*               between the routines in filter_options.pl,
#*               location_filer.pl and region_filters.pl to determine
#*               if any valid output had been selected.
#*               Also promoted the variable reg_filter_labels to be 
#*               used between filter_options.pl and location_filter.pl
#*               to determine if RNG_FLTR_METHOD should be displayed
#*               by location_filter.pl.
#* 3/10/97   GCG Corrected errors in HTML formating of output for all
#*               subsystems.
#*********************************************************************     

#*********************************************************************
#*  What follows is a list of all the "include" files
#*********************************************************************
if (`pwd` =~ /sscfac_dev/) {
  require "/usr/local/etc/httpd/cgi-bin/sscfac_dev/ssc_lib.pl";
} else {
  require "/usr/local/etc/httpd/cgi-bin/sscweb/ssc_lib.pl";
}
require "./locator_files/b_field_models.pl";
require "./locator_files/command_menu.pl";
require "./locator_files/filter_options.pl";
require "./locator_files/location_filters.pl";
require "./locator_files/output_options.pl";
require "./locator_files/region_filters.pl";
require "./locator_files/sc_selection.pl";
require "./locator_files/tab_out_options.pl";

#*********************************************************************
#*  This program uses the CGI.pm library of Perl cgi routines.  
#*  The lates version of this library can be found at:
#*	http://www-genome.wi.mit.edu/ftp/pub/software/WWW
#*  RCJ-06/2002  Actually, the web site is now: stein.cshl.org/WWW/
#*  RCJ-06/2002  I added the 'unshift' line below. I had to remove the URl from
#*       the DEFAULT_DTD in CGI.pm so that the page would look
#*       ok under Netscape 6.2.1 and 6.2.2
#*     Other changes were made to CGI.pm so that we would have lower case
#*     tags, the 'label' tag for radio_group, checkbox_group and checkbox,
#*       and the 'fieldset' tag for radio_group.
#*********************************************************************
BEGIN {
        unshift(@INC,'/usr/local/etc/httpd/cgi-bin/sscfac_dev/CDAWeb_CGI.pm-2.79');
      }

	use CGI qw(-no_xhtml);
	$query=new CGI;
	$query->autoEscape(undef);
#*********************************************************************
#*  Set up the "global" variables.
#*********************************************************************
	$|=1;
    $current_dir = `pwd`;
    $machine_name = 'sscweb.gsfc.nasa.gov';

	@coord_sys = ("TOD","J2000","GEO","GM","GSE","GSM","SM");
	%coord_sys_labels = ("TOD","GEI/TOD", "J2000","GEI/J2000","GEO","GEO","GM","GM","GSE","GSE","GSM","GSM","SM","SM");
	@values = (1,2);
	%date_labels = (1,"yyyy ddd",2,"yyyy/mm/dd",3,"yyyy-Mmm-dd",4,"yyyy-MMM-dd");
	%time_labels = (1,"hh.hhhh",2,"hh:mm:ss",3,"hh:mm");
	%distance_labels = (1,"R<sub>E</sub> - Earth Radii",2,"km - Kilometers",3,"km - Integers",
					4,"km - Scientific Notation");
	$no_output_selected = 0;
	$used_rng_fltr_method = 0;
	@MNMX_VAL=(1,2);
	%MNMX_LABELS=(1," ",2," ");
	%reg_filter_labels = (1,"Must pass all specified range filters",
								2,"Must pass at least 1 specified range filter");
	#sections is a translation table so I don't have to keep typing the long names
	%sections=("Spacecraft/Time Range Selection","SCS","Output Options","TOS","Filtering Options","SFO",
		   "Spacecraft Location Filters","PFO","Spacecraft Region Filters","SRF","Additional Location Filters","OLF",
		   "B Field Model Selection","BFM","Output Units/Formatting","FO","Input Summary","IS");					


	#command will be defined if we are about to execute query
	$command = $query->param('SUBMIT');
	$dblisting=$query->param('database_listing.x');
	#go_to will be defined if the user is going to another section of the form
	$go_to = $query->param('GO_TO');
	$ssc = $query->param('SSC');
	$prev_section = $query->param('PREV_SECTION');
	#sections is a translation table so I don't have to keep typing the long names
	$section = $sections{$go_to};

	if (!defined($section)) {
		$section = 'SCS';
	}
    if (!defined($ssc)) {
        $ssc = 'LOCATOR_GENERAL';
    }		
	if ($command =~ /Standard/) {
		$section = $prev_section;
		$ssc = "LOCATOR_GENERAL";
	} elsif ($command =~ /Advanced/) {
		$section = $prev_section;
		$ssc = "LOCATOR";		
		foreach $spcr ($query->param('SPCR')) {
			$query->param($spcr . "_res", $query->param('RESOLUTION'));
		}
	}

	if (`pwd` =~ /sscfac/) {
		if ($ssc eq 'LOCATOR') {
			$interface = 'Advanced Facilities';
		} else {
			$interface  = 'Standard Facilites';
		}
	} else {
		if ($ssc eq 'LOCATOR') {
			$interface = 'Advanced';
		} else {
			$interface  = 'Standard';
		}	
	}

	if (($ssc eq 'LOCATOR') && ($section eq 'SFO')) {
				$section = 'PFO';
	} elsif (($ssc eq 'LOCATOR_GENERAL') && (($section eq 'PFO') || ($section eq 'OLF') || ($section eq 'SRF'))) {
				$section = 'SFO';
	} elsif (($ssc eq 'LOCATOR_GENERAL') && ($section eq 'BFM')) {
				$section = 'FO';
	}elsif (defined($dblisting)) {
		$section = 'DBL';
	}


	#*********************************************************************
	#*  Start the html page.
	#*********************************************************************
	print $query->header;
    print $query->start_html("SSC Locator Form");
# Temporary Header

# end Temporary Header
	print "\n<center>\n<h1>SSC Locator Form</h1></center>\n";
 print qq!<p><H5><font color="blue">Special Notice:  A long-term error in the SSCWeb implementation of the Tsyganenko 1987 and 1989<br> external field models has been recently identified while installing the Tsyganenko 1996<br> model and is now corrected for all models.<p>The error could produce noticeable effects in both the computed local field (usually <2% but occasionally<br> larger) and in field line tracings (usually <0.3% in traced latitude and longitude but occasionally larger),<br> particularly from spacecraft like Geotail deeper in the magnetosphere.<p>Users who have relied on highest-fidelity field-line tracings from such spacecraft may want to rerun<br> selected cases to determine if specific changes are significant to their research expectations of SSCWeb<br>.  We greatly apologize that any error of this nature was not previously detected in our testing procedures<br> and corrected.

 </font></H5></center></p>!;

	print "<center><h3>$interface Interface</h3></center>\n";

    if (`pwd` =~ /sscfac/) {
       $process_url = "http://$machine_name/cgi-bin/sscfac/Locator.cgi";
       if(`pwd` =~ /sscfac_dev/) { 
           $process_url = "http://$machine_name/cgi-bin/sscfac_dev/Locator.cgi";
       }
    } else {
       $process_url = "http://$machine_name/cgi-bin/sscweb/Locator.cgi";
    }
	print $query->startform('POST',$process_url);

	#*********************************************************************
	#*Check to see if the database is available.
	#*********************************************************************	
             
    $chk=&chk_db;
    if ($chk ne '') {
    	if ($chk =~ /ERROR/) {
    	      $section = 'SCS';
              undef($command);
        }
        print "<hr size=\"5\"><p><pre> $chk </pre><p><hr size=\"5\">\n";
    } else {
	#***********************************************************************
	#* If this is the password protected version get the users email address
	#* from the email_list.txt file.
	#***********************************************************************
	if ($query->auth_type() eq 'Basic') {
		$user=$query->remote_user();
		if (open(EMAIL,"./locator_files/email_list.txt")) {
			my(@email) = <EMAIL>;
    	    close EMAIL;
    	    foreach $em (@email) {
    	    	@em_rec = split(/:/,$em);
    	       if ($query->remote_user() eq $em_rec[0]) {
    	       		$email=$em_rec[1];
    	       	} 
    	    }
    	    if (!defined($email)) {
    	       $email = "UNKNOWN";
    	    }
    	}
	}

	#if we just left the spacecraft selection page make sure the input is correct otherwise return to that page.
	if (($prev_section eq 'SCS') && ($section ne 'DBL') && (!defined($command))) {
			$itxt = 0;
		    &set_env($itxt);
			$valid = &sat_time(*query,$itxt);
		if ($valid ne '') {
			if ($valid =~ /ERROR/) {
				$section = 'SCS';
				undef($command);
			}
			print "<hr size=\"5\"><p><pre> $valid </pre><p><hr size=\"5\"><p>\n";
		}	
	}

	if (defined($command)) {
		&do_command;
	}
	
	#*********************************************************************
	#*  Display the appropriate section of the form.
	#*********************************************************************
	&display_section;
	}
	#* A bizarre exception.  Since the RNG_FLTR_METHOD potentially needs to be 
	#* dsiplayed on two pages we set a flag ($used_rng_fltr_method == 0) to check
	#* if the variable has been displayed to the user.  If not then we keep the
	#* value in a hidden field here.  It was done this was since the displaying
	#* of the same varialbe in two seperate sections was not supported by the 
	#* design without making a whole seperate set of subroutines for it.
	if 	($used_rng_fltr_method == 0){
		print $query->hidden(-name=>"RNG_FLTR_METHOD",
    	                    -default=>$query->param("RNG_FLTR_METHOD"));
	}
	print "\n";
	#keep track of where we were last
	$query->param('PREV_SECTION',$section);
	print $query->hidden(-name=>'PREV_SECTION',
				-default=>$query->param('PREV_SECTION'));
	print "\n";
	$query->param('SSC',$ssc);
	print $query->hidden(-name=>'SSC',
	  				-default=>$query->param('SSC'));

#*********************************************************************
#*  Print out command menu and end the form.
#*********************************************************************
	&command_menu;
	print $query->end_form;
	&responsible_official;
	print $query->end_html;





#*********************************************************************
#*  SUBROUTINE : do_command
#*  PURPOSE : This routine checks to see if a "command" has been submitted
#             and processes that command.
#*  MODIFICATION HISTORY
# TJK change all /scratch/ssc to /tmp/ssc

#********************************************************************* 
sub do_command {
	#*********************************************************************
	#*  If we are executing the query perform the proper steps
	#*********************************************************************
	if($command eq 'Submit query and wait for output') {	
		$|=1;  
         $mode=0;
         #$logger="/var/tmp/ssctst_$$.log";
         $logger="/tmp/ssc/ssctst_$$.log";
         #$infile="/var/tmp/ssc_in$$.txt";
         $infile="/tmp/ssc/ssc_in$$.txt";
         $outfile="ssc_out$$.txt";
         $filename_out=$query->param('savefile');
         ($rtn_string,@cur_list)=&tab_valid(*query);
		if ($rtn_string =~ /ERROR/) {
				$section = 'SCS'; 	
				print "<hr size=\"5\"><p> $rtn_string <p><hr size=\"5\"><p>\n";
		} else {
			if ($rtn_string ne '') {
				print "<hr size=\"5\"><p> $rtn_string <p><hr size=\"5\"><p>\n";
			}
#			foreach $cl (@cur_list) {
#				print "$cl\n<BR>";
#			}
			print "<center><b>Output is sent as generated; please allow server to complete transfer if full time range is desired.</b></center>\n<br />";
			print "<pre>\n";
         	&loc_tab_svr($mode, @cur_list);
			print "</pre>\n";
            $section = 'OUT';
    	} 
   	  } elsif ($command eq 'Submit query as background job') {
            #$logger="/var/tmp/ssctst_$$.log";
            $logger="/tmp/ssc/ssctst_$$.log";
            #$infile="/var/tmp/ssc_in$$.txt";
            $infile="/tmp/ssc/ssc_in$$.txt";
            $outfile="ssc_out$$.txt";
            $filename_out=$query->param('OUTPUT_FILE');
   			print "<p>A batch job has been submitted to process your Locator query.<br />  You may retrieve the results from";
			print " <a href=http://$machine_name/query_output/$filename_out>http://$machine_name/query_output/$filename_out</a><br />\n";
	        $mode=1;
	        $itxt=1;
	        &set_env($itxt);
	        ($rtn_string,@cur_list)=&tab_valid(*query);
		    if ($rtn_string =~ /ERROR/) {
				$section = 'SCS'; 	
				print "<hr size=\"5\"><p> $rtn_string <p><hr size=\"5\"><p>\n";
		    } else {
			    if ($rtn_string ne '') {
			    	print "<hr size=\"5\"><p> $rtn_string <p><hr size=\"5\"><p>\n";
			     }
         	     &loc_tab_svr($mode, @cur_list);
                 $section = 'OUT';
    	     }
		} elsif ($command eq 'Save query in file on host') {
		#local($path) = "/var/tmp/$user/";
			local($path) = "/usr/local/etc/httpd/cgi-bin/fac_acct/$user/";
		#	print "path = $path\n<BR>";
			print "path = ~/fac_acct/".$user."\n<br />";
			local($filename_out) = $query->param('SAVEFILE');
			print "filename_out = $filename_out\n<br />";
			local($saved) = &save_parameters($path,$filename_out,$query);
			if ($saved >= 0) {
				print "<strong>State has been saved to file $filename_out</strong>\n";
			} else {
				print "<strong>Error:</strong> couldn't write to file $filename_out: $!\n";
			}
		} elsif ($command eq 'Restore query from file saved on host') {
		   local($restorefile) = $query->param('RESTOREFILE');
#     print "$restorefile <P>\n";
		#	$query = &restore_parameters("/var/tmp/$user/",$restorefile,$query);
			$query = &restore_parameters("/usr/local/etc/httpd/cgi-bin/fac_acct/$user/",$restorefile,$query);
			$section = '';
		} elsif ($command eq 'Prepare query to be saved locally') {
		        print "<hr>\nThe information in this form has been updated.<br />";
			print "<em>You may now safely save this page.</em>\n<br />"; 
		        print "Select &quot;Save As&quot; or &quot;Save Page As&quot; from the FILE menu and save the file in ";
		        print "the format &quot;SOURCE&quot; or &quot;HTML&quot; (exact wordings vary among different ";
                        print "browsers).<br /> When you want to edit/use this query later, ";
		        print "open the file with your Web browser.<br />\n";
                        # Save Problem
                        print "<hr><br /><center><strong>URGENT NOTICE:</strong> to <strong>Macintosh</strong> users ";
                        print "using <strong>Netscape Navigator</strong> 4.x</center><br /> ";
                        print "The &quot;Prepare query to be saved locally&quot; function does NOT work with current versions ";
                        print "(4.x) of Netscape Navigator on a Macintosh. Information is not actually saved and ";
                        print "cannot be restored. You must use a browser such as Microsoft Internet Explorer for this function ";
                        print "to work correctly. We apologize for this inconvenience.<p> ";
                        print "<strong>Also Note:</strong><br />";
                        print "We have also seen infrequent cases where the interaction of the SSCWeb environment<br />";
                        print "with a Web browser may become corrupted, such that SSCWeb executes a different command than<br />";
                        print "that requested.  In the event you see suspicious symptoms, we suggest that you SAVE your<br />";
                        print " present SSCWeb environment, then fully quit and restart your Web browser, then restore the<br />";
                        print qq! saved SSCWeb environment. <a href="mailto:ssc\@sscweb.gsfc.nasa.gov"> Please contact</a> us !;
                        print "if you experience continuing or frequent problems. <br />"; 

	                #fool the remaining code into hiding all sections of the form.
                  	#by setting section to an value that will cause all sections 
			#to be printed out as "hidden"
			$section = "SAVE";
		}
}	

#*********************************************************************
#*  SUBROUTINE : save_parameters
#*  PURPOSE : This routine saves the state of the form to a file   
#*            on the host machine. 
#*  MODIFICATION HISTORY
#********************************************************************* 
sub save_parameters {
    local($path,$filename,$query) = @_;
    #make sure the filename is only alphanumeric characters.
    $filename = &clean_file_name($filename);
    if (open(FILE,">". $path . $filename)) {
        $query->save(FILE);
        close FILE;
    } else {
		return -1;
    }
	return 0;
}


#*********************************************************************
#*  SUBROUTINE : restore_parameters
#*  PURPOSE : This routine restores the state of the form from a file   
#*            on the host machine. 
#*  MODIFICATION HISTORY
#********************************************************************* 
sub restore_parameters {
    local($path,$filename,$query) = @_;
    #make sure the filename is only alphanumeric characters.
    $filename = &clean_file_name($filename);
    if ($restorefile ne "No queries saved") {
 	   if (open(FILE,$path . $filename)) {
	        $query = new CGI(FILE);  # Throw out the old query, replace it with a new one
	        close FILE;
	        print "<strong>State has been restored from file $filename</strong>\n";
	    } else {
	        print "<strong>Error:</strong> couldn't restore file $path$filename: $!\n";
	    }
	 } else {
   		print "<strong>Error:</strong>No queries currently saved.\n";
	}  
    return $query;
}

#*********************************************************************
#*  SUBROUTINE : clean_file_name
#*  PURPOSE : checks for metacharacters in the file name. If there are
#*			 complain bitterly and die. 
#*  MODIFICATION HISTORY
#********************************************************************* 

sub clean_file_name {
   local($name) = @_;
   unless ($name=~/^[\w\.-]+$/) {
      print "<strong>$name has naughty characters.  Only ";
      print "alphanumerics are allowed.  You can't use absolute names.</strong>";
      die "Attempt to use naughty characters";
   }
   return $name;
}


sub database_listing {
  print "<hr>\n<center><h2>SSC Satellite Database Listing</h2></center>\n";
  print "<pre>\n";

#  $db_path="/home/wharfrat/sscops/edb/data/vaxcdf";
  $db_path="/home/sscops/edb/data/vaxcdf";
  $ENV{'SSC_MANAGER'} ="$db_path";
  $ENV{'SSC_CDF'} ="$db_path";

#  system("/home/wharfrat/ssc/ssc3.0/bin/scansat");
  system("/home/ssc/ssc3.0/bin/scansat");

# old call  system("/usr/local/etc/http/cgi-bin/sscweb/sat_list");
  print "</pre>\n";

}



#*********************************************************************
#*  SUBROUTINE : display_section
#*  PURPOSE :	Determines which section of the form to display and  
#*            	calls the appropriate subroutines to display that section
#*				and hide the rest.
#*  MODIFICATION HISTORY
#********************************************************************* 
sub display_section{


	if ($section eq 'SCS'){
			&sc_table("shown");
	} elsif ($section eq 'IS') {
			&sc_table("summary");
	} else {
			&sc_table("hidden");
	}


	if ($section eq 'TOS'){
			&tabular_output_options("shown");
	} elsif ($section eq 'IS') {
			&tabular_output_options("summary");
	} else {
		&tabular_output_options("hidden");
	}
	
	if ($ssc eq 'LOCATOR') {
		if ($section eq 'PFO'){
			&filter_options("shown");
		} elsif ($section eq 'IS'){	
			&filter_options("summary");
		} elsif ($ssc eq 'LOCATOR'){
			&filter_options("hidden");
		}

		if ($section eq 'OLF'){
			&location_filters("shown");
		} elsif ($section eq 'IS') {
			&location_filters("summary");
		} else {
			&location_filters("hidden");
		}

		if ($section eq 'SRF'){
			&region_filters("shown");
		} elsif ($section eq 'IS') {
			&region_filters("summary");
		} else {
			&region_filters("hidden");
		}
	}

	if ($ssc eq 'LOCATOR_GENERAL') {
		if ($section eq 'SFO' ){
			&filter_options("shown");
			&location_filters("shown");
			&region_filters("shown");
		} elsif (($section eq 'IS') && ($ssc eq 'LOCATOR_GENERAL')){
			&filter_options("summary");
			&location_filters("summary");
			&region_filters("summary");
		} elsif ($ssc eq 'LOCATOR_GENERAL') {
			&filter_options("hidden");
			&location_filters("hidden");
			&region_filters("hidden");
		}
	}
	
	if (($section eq 'BFM') && ($ssc eq 'LOCATOR')){
		&b_field_models("shown");
	} elsif ($section eq 'IS') {
		&b_field_models("summary");
	} else {
		&b_field_models("hidden");
	}


	if ($section eq 'FO'){
		&output_options("shown");
	} elsif ($section eq 'IS') {
		&output_options("summary");
	} else {
		&output_options("hidden");
	}
	if ($section eq 'DBL') {
		&database_listing;
	 }
}



	
#*  PURPOSE :	Gives credit/blame at the bottom of each page, along 
#* 				with the date and time the page was generated.
#*  MODIFICATION HISTORY
#*          
#********************************************************************* 

sub responsible_official {
print <<EOH;
<hr>
<p>
<img align="bottom" src="/bullet/blu_bullet_half.gif" alt=""><a href="http://$machine_name/bugs.html">Known bugs for SSCWeb</a>

<p>
<h4>Responsible NASA official and Curators:</h4><p>
<address>
<a href="mailto:Robert.E.McGuire.1\@gsfc.nasa.gov">Robert McGuire</a>, (301) 286-7794<br />
Head Space Physics Data Facility<br />
Code 632<br />
NASA Goddard Space Flight Center<br />
Greenbelt, MD 20771<br />
</address>
<p>
SSCWeb <a href="mailto:ssc\@sscweb.gsfc.nasa.gov">Curators</a>

<p>
EOH
@time = localtime(time());
%month= (0,"Jan",1,"Feb",2,"Mar",3,"Apr",4,"May",5,"Jun",6,"Jul",7,"Aug",8,"Sep"
,9,"Oct",10,"Nov",11,"Dec");
$time[5]=$time[5]+1900.0;
print "Page generated on: $time[3] $month{$time[4]} $time[5]  at $time[2]:$time[1] \n";
}