<?
/* About the only variables you need to set */
    $path = "/home/virtual/site3/fst/var/www/html/aurora_temp/"; //Path to server-writable directory
    $user = 1;			//Set to 0 if you want to disallow users from entering different ZIP codes
    $embed = 0;			//Set to 1 to display only the table (no style elements, etc)	
    $default_zip = "99515";	//ZIP to display index for by default
    $db_name = "alaskastudio_com_aurora";		//Database name
    $db_host = "localhost";	//Database host
    $db_user = "xxxxx";		//Database username
    $db_pass = "xxxxxxx";	//Database password
    $db_table = "zip_codes";	//ZIP code table

    if($user == 1 && (isset($_GET["zip"]) && (is_numeric($_GET["zip"]) || strlen($_GET["zip"]) == 6))) {
	$zip = $_GET["zip"];

	if(strlen($zip) == 6) {
		$zip = str_split($zip,3);
		$zip = $zip[0]."+".$zip[1];
	}

    }elseif(!isset($_GET["zip"]) || $user == 0) {
	$zip = $default_zip;
    }elseif(!is_numeric($_GET["zip"])) {
	die("<html><body>Invalid ZIP!\n</body>\n</html>");
    }

/* Establish MySQL connection, select DB, get coords */
   $link = mysql_connect($db_host,$db_user,$db_pass);
   mysql_select_db($db_name);

   $sql = "SELECT state,latitude FROM ".$db_table." WHERE zip='".$zip."' LIMIT 0,1";
   $res = mysql_query($sql);

   if((!$res || mysql_num_rows($res) == 0) && strlen($zip) != 7) {
	die("<html><body>ZIP not found. Try another close ZIP, perhaps?</body></html>");
   } elseif(strlen($zip) == 7) {
	$coords[0] = "";
	$coords[1] = 63;
   } else {
	$coords = mysql_fetch_row($res);
	$coords[0] = ", ".$coords[0];
   }
    
/* Source URLs - if you change them, you may also need to change the preg_match expressions */
    $url_aurora = "http://www.gi.alaska.edu/cgi-bin/predict.cgi";
    $url_weather = "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=".$zip;    

/* File naming variable */
    $fprefix = strftime("%d%b%g")."_".$zip."_";
    
/* Scores assigned to different weather/aurora conditions */
    $aurora_score_array = array(
    				"at its maximum peak" => 10,
    				"high" => 9,
    				"active" => 7,
    				"moderate" => 5,
    				"quiet" => 1
    				);
    				
    $weather_score_array2 = array(
    				"Clear" => 0,
    				"Mostly clear" => -2,
    				"Partly cloudy" => -3,
				"A chance" => -7,
    				"Mostly cloudy" => -7,
    				"showers" => -2,
    				"rain" => 0,
    				"snow" => -2,
    				"fog" => -2,
    				"Cloudy" => -10,
    				"Rain" => -10,
    				"Showers" => -10,
    				"Snow" => -10,
    				);  

/* Parsing source URLs and calculating scores, index, and rating */
    preg_match_all("|Auroral activity will be (.+) today|Uis",get_put($url_aurora),$aurora);
    preg_match("/<div id=\"b\">Tonight<\/div>\s*?<div>(\w+)[\s]?(cloudy|clear|sunny|chance|).*?(rain|snow|showers|fog|\.)/s",get_put($url_weather),$weather2);
    preg_match("|<title>(.*),([\sa-zA-Z]*?).*Forecast : Weather Underground</title>|Uis",get_put($url_weather),$title);
    preg_match("|, ([0-9]*)% of the Moon is Illuminated</h4>|Uis",get_put($url_weather),$moon);

    ($weather2[2] == "") ? $weather_score1=intval($weather_score_array2[$weather2[1]]) : $weather_score1=intval($weather_score_array2[$weather2[1]." ".$weather2[2]]);
    ($weather2[3] != ".") ? $weather_score2=intval($weather_score_array2[$weather2[3]]) : $weather_score2=0;

    $moon_score = intval($moon[1])*.05;	
    if((10+intval($weather_score1+$weather_score2)) < 0) {
	$weather_score = 0;
    } else {
	$weather_score = (10+intval($weather_score1+$weather_score2));
    }

    $aurora_score = intval($aurora_score_array[$aurora[1][0]]);

    if($coords[1] > 63 && $coords[1] < 73) {
	$geo_correct = 1;
    } elseif($coords[1] < 64 && $coords[1] > 61) {
	$geo_correct = .95;
    } elseif($coords[1] < 62 && $coords[1] > 60) {
	$geo_correct = .9;
    } elseif($coords[1] < 61 && $coords[1] > 56) {
	$geo_correct = .85;
    } elseif($coords[1] < 57 && $coords[1] > 47) {
	$geo_correct = .7;
    } elseif($coords[1] < 48 && $coords[1] > 35) {
	$geo_correct = .1;
    } elseif($coords[1] < 36) {
	$geo_correct = .05;
    }

    if($aurora_score == 10) { $geo_correct = $geo_correct+((1-$geo_correct)/3); }

    if(($weather_score*$aurora_score)-$moon_score < 0) {
	    $aurora_raw = 0;
    } else {
	    $aurora_raw = (($weather_score*$aurora_score)-$moon_score)*(5*$geo_correct);
    }

    if($weather_score != 0 && $aurora_score && $weather_score) {
    	$aurora_index = (round($aurora_raw,1)/500)*(100);
    } else {
    	$aurora_index = 0;
    }

    if($aurora_score == 0) {
	$aurora_rating = "No Aurora Prediction";
    } elseif($aurora_raw >= 0 && $aurora_raw <= 2) {
    	$aurora_rating = "Not Visible";
    } elseif($aurora_raw > 2 && $aurora_raw < 176) {
    	$aurora_rating = "Poor";
    } elseif($aurora_raw > 175 && $aurora_raw < 250) {
    	$aurora_rating = "Moderate";
    } elseif($aurora_raw > 249 && $aurora_raw < 360) {
    	$aurora_rating = "Good";
    } elseif($aurora_raw > 359 && $aurora_raw < 500) {
    	$aurora_rating = "Excellent";
    } elseif($aurora_raw >= 500) {
    	$aurora_rating = "Get Out There!";
    }
    
/* Printing the output */
$content = "";

if(!isset($_GET["wap"]) || $_GET["wap"] == 0) {

if($embed == 0) {
	$content .= "<html>\n<head>\n<title>Aurora Viewing Index :: "
	.$title[1].", ".$title[2]
	."</title>\n"
	."<style type=\"text/css\">\n<!--\n"
	."body {font-family: arial, helvetica;}\n"
	."li {font-size: 90%;}\n"
	.".tiny {font-size: 75%;}\n"
	."a:link {text-decoration: none; color: #0000FF;}\n"
	."a:hover {text-decoration: underline; color: #007D00;}\n"
	."a {text-decoration: none; color: #0000FF;}\n"
	."td.rating {border: 1px solid #000; color: #FFFFFF; width: 144px;}\n"
	."td.main {border: 0; text-align: left; color: #000000;}\n"
	."td.right {border: 0px solid #000; text-align: center; width: 100%;}\n"
	."td.stats {border: 0; text-align: left; width: 100%; font-size: 65%; color: #000000}\n"
	."table.rating {border: 0; color: #FFFFFF;}\n"
	."table.main {border: 0; width: 100%; color: #FFFFFF;}\n"
	.".submit {background-color: #FFFFFF; border-color: #000000; border-style: double; border-width: 1; color: #000000;}\n" 	
	."-->\n</style>\n"
	."</head>\n"
	."<body>\n";
}

$content .= "<table class=\"main\"><tr><td class=\"right\" valign=\"top\">";

$content .= "<table class=\"rating\">\n<tr>\n<td align=\"center\">\n"
	."<font color=\"#000000\" class=\"tiny\"><u>Aurora Prediction For:</u><br><b>"
	.$title[1].$coords[0]
	."</b></font>\n"
	."</td>\n</tr>\n"
	."<tr>\n<td align=\"center\">\n"
	."<a href=\"http://www.gi.alaska.edu/cgi-bin/predict.cgi\">\n"
    	.$aurora_rating."</a></td>\n</tr>\n"
	."<tr>\n<td align=\"center\">\n"
        ."<table width=\"75%\">\n"
    	."<tr><td class=\"rating\" align=\"center\" width=\"100%\" bgcolor=\"#00".aurora_color(round($aurora_raw/2,0))."00\">".round($aurora_index,0)."%</td></tr>"
    	."</table>\n"
	."</td>\n</tr>\n";


   if($user == 1) {
	$content .= "<tr><td align=\"center\" class=\"tiny\"><font color=\"#000000\"><form action="
	.$_SERVER[SCRIPT_NAME]
	." method=\"GET\">&nbsp;<br>ZIP:&nbsp;</font><input type=\"text\" name=\"zip\" size=\"6\" maxlength=\"6\"><p>" 	
	."<input type=\"submit\" class=\"submit\" value=\"Submit\"></form>" 	
	."</td>\n</tr>\n"
	."<tr>\n<td class=\"stats\"><br><center><b><u>Data used in this prediction</b></u></center></td>\n</tr>"
		."<tr>\n<td class=\"stats\">Latitude: <b>".round($coords[1],1)."&deg; N</b></td>\n</tr>"
	."<tr>\n<td class=\"stats\">Lat Correction: <b>".((-1+$geo_correct)*100)."%</b></td>\n</tr>"
	."<tr>\n<td class=\"stats\">Aurora Score: <br><b>".$aurora_score." out of 10</b></td>\n</tr>"
	."<tr>\n<td class=\"stats\">Weather Score: <br><b>".$weather_score." out of 10</b></td>\n</tr>"
	."<tr>\n<td class=\"stats\">Moon Phase: <br><b>".$moon[1]."% illuminated</b></td>\n</tr>"
	."<tr>\n<td class=\"stats\">Moon Score: <b>-".$moon_score."</b>
	<br><br><a href=\"http://salmon.nict.go.jp/awc/live/auluvewin1_mx_eng.php\" target=\"_blank\"><img src=\"http://salmon.nict.go.jp/live/aurora_cam/ql/latest_l.jpg\" width=120 height=90 
     style=\"border-width:0px;vertical-align:top;\" alt=\"Latest Aurora Image\"><br>Latest Autrora Image!</a></td>\n</tr>"
	;
   }

$content .= "</td>\n</tr>\n"
	."</table>\n"
	
	."</td></tr></table>";

if($embed == 0) {
	$content .= "</body>\n</html>";
}

} elseif(isset($_GET["wap"]) && $_GET["wap"] == 1) {

$content = "<?xml version=\"1.0\"?>\n"
	."<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">\n"
	."<wml>\n"
	."<head>\n<meta http-equiv=\"Cache-Control\" content=\"max-age=0\" forua=\"true\" />\n"
	."<meta http-equiv=\"Cache-Control\" content=\"must-revalidate\" />\n</head>\n"
	."<card id=\"enter\" title=\"Aurora Viewing Index\">\n"
	."<p align=\"center\">\nAurora Viewing Index for:<br/><br/>\n"
	."<b>".$title[1].$coords[0]."</b><br/>\n"
	.$aurora_rating." (".round($aurora_index,0)."%)<br/><br/>\n"
  	."Enter your ZIP/postal code:<br/>\n"
	."<input name=\"zp\" size=\"6\" maxlength=\"6\" /><br/>\n"
  	."Example: 99801 or V6C3C9<br/>\n"
	."<a href=\"index.php?wap=1&zip=$(zp)\">View Local Aurora Viewing Index</a><br/>\n"
	."</p>\n</card>\n</wml>";
}

if(isset($_GET["wap"]) && $_GET["wap"] == 1) {
	header("Content-type: text/vnd.wap.wml");
	header('Content-Disposition: inline; filename="index.wml"');
}

echo $content;

/* Functions */
function aurora_color($int){
   return sprintf("%02X", $int);
}
    
function get_put($url) {
	global $path, $fprefix;
	
	$rdf = parse_url($url);
	
/* With this new code, set $days to be the number of days old a file should 
be before it's deleted. If you want to modify this so it's hours, minutes, 
or seconds, take out the /24, /60/24, or /60/60/24 in $diff respectively: */

$i = 0; 
$days = 1; 

if($handle = opendir($path)) { 

$files = array(); 

while(false !==($file = readdir($handle))) { 
        if($file != "." && $file != ".." && $file != "index.html") { 
                $diff = (time() - filectime($path.$file))/60/60; 

             if ($diff > $days) { 
                unlink($path.$file); 
                } else { 
                $files[] = $file; 
                $i++; 
                } 
        } 
} 

rsort($files); 
reset($files); 
closedir($handle); 
}
if(!in_array($fprefix.$rdf['host'], $files)) {
    
    		$fp = fsockopen($rdf['host'], 80, $errno, $errstr, 15);
        
		if (!$fp) {
			$read_contents = "<font class=\"content\">Problem!</font>";
		        return;
		}
		
		if ($fp) {
        		fputs($fp, "GET " . $rdf['path'] . "?" . $rdf['query'] . " HTTP/1.0\r\n");
        		fputs($fp, "HOST: " . $rdf['host'] . "\r\n\r\n");
        		$contents = "";
        		
        		while(!feof($fp)) {
	    			$pagetext = fgets($fp,300);
	    			$contents .= chop($pagetext);
			}
			
			fputs($fp,"Connection: close\r\n\r\n");
			fclose($fp);
	
			$file = $fprefix.$rdf['host'];
			$dest = fopen($path.$file,"w");
	
			fwrite($dest,$contents);
			fclose($dest);

			$handle = fopen($path.$file,"r");
		
			while (!feof($handle)) {
				$read_contents .= fread($handle, 8192);
			}

			fclose($handle);
		}

	} elseif(in_array($fprefix.$rdf['host'], $files)) {

			$file = $fprefix.$rdf['host'];
			$handle = fopen($path.$file,"r");
		
			while (!feof($handle)) {
				$read_contents .= fread($handle, 8192);
			}
	
			fclose($handle);
	}	

	return $read_contents;
}
?>