<?php
// CONFIGURATION 
$db_host = "localhost";
$db_user = "stlouisc_wx";
$db_pwd = "f1n4n";
$db_name = "stlouisc_wx";
$partner_id = "1066051000";
$key = "4278b0bf2ac72ec1";
$unit = "s";	// s=standard, m=metric
$url = "http://xoap.weather.com/weather/local/USMO0787?cc=*&dayf=5&link=xoap&prod=xoap&par=1066051000&key=4278b0bf2ac72ec1";
$timestamp = time(); // current timestamp
$xml_url = md5($url);
$interval = 1;	// Hours to keep data in db before being considered old
$expires = $interval*60*60;
$expired_timestamp = $timestamp - $expires;
$connection = mysql_connect($db_host, $db_user, $db_pwd) or die("Could not connect");
mysql_select_db($db_name) or die("Could not select database");

// Delete expired records
$query = "DELETE FROM weather_xml WHERE last_updated <= '$expired_timestamp'";
$result = mysql_query($query) or die('Invalid query: ' . mysql_error());

$query = "SELECT * FROM weather_xml WHERE xml_url = '$xml_url'"; 
$result = mysql_query($query) or die('Invalid query: ' . mysql_error());
$row = mysql_fetch_array($result);

if (mysql_num_rows($result) < 1) // Data not in table - Add from weather.com.
{
	// Get XML Query Results from Weather.com
	$fp = @fopen($url,"r");
	if(is_resource($fp))
	{
		while (!feof ($fp)) $xml .= fgets($fp, 4096);
		fclose ($fp);
	}
	else
	{
		// error - unable to fopen url
		exit("Unable to connect to weather.com");
	}

	$query = "INSERT INTO weather_xml VALUES ('$xml_url', '$xml', '$timestamp')";
	$result = mysql_query($query) or die('Invalid query: ' . mysql_error());
}
else // Data in table, and it is within expiration period - do not load from weather.com, use cached copy instead.
{
	$xml = $row['xml_data'];
}

$parser = xml_parser_create(); 
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser,$xml,$values,$index); 
xml_parser_free($parser);

//echo $xml; // outputs the xml from weather.com
//print_r($values);
//print_r($index);

function getWeatherData($index,$values)
{
	global $length;
	// possible values are 'weather' and 'error'
	switch ($values[0]['tag'])
	{
		case "weather":		
			$return_array['type'] = "weather";

			$return_array['unit']['temp'] = $values[$index['ut'][0]]['value'];
			$return_array['unit']['dist'] = $values[$index['ud'][0]]['value'];
			$return_array['unit']['speed'] = $values[$index['us'][0]]['value'];
			$return_array['unit']['precip'] = $values[$index['up'][0]]['value'];
			$return_array['unit']['pressure'] = $values[$index['ur'][0]]['value'];

			$return_array['loc_info']['name'] = $values[$index['dnam'][0]]['value'];
			$return_array['loc_info']['time'] = $values[$index['tm'][0]]['value'];
			$return_array['loc_info']['lat'] = $values[$index['lat'][0]]['value'];
			$return_array['loc_info']['long'] = $values[$index['lon'][0]]['value'];
			$return_array['loc_info']['time_zone'] = $values[$index['zone'][0]]['value'];
		
			$return_array['cc']['feels_like'] = $values[$index['flik'][0]]['value'];
			$return_array['cc']['last_update'] = $values[$index['lsup'][0]]['value'];
			$return_array['cc']['temp'] = $values[$index['tmp'][0]]['value'];
			$return_array['cc']['text'] = $values[$index['t'][4]]['value']; 
			$return_array['cc']['observation_station'] = $values[$index['obst'][0]]['value'];
			$return_array['cc']['icon'] = $values[$index['icon'][0]]['value'];
			$return_array['cc']['humidity'] = $values[$index['hmid'][0]]['value'];
			$return_array['cc']['visibility'] = $values[$index['vis'][0]]['value'];
			$return_array['cc']['dew_point'] = $values[$index['dewp'][0]]['value'];
			$return_array['cc']['uv_index'] = $values[$index['i'][0]]['value'];
			$return_array['cc']['uv_text'] = $values[$index['t'][6]]['value'];
			$return_array['cc']['moon_icon'] = $values[$index['icon'][1]]['value'];
			$return_array['cc']['moon_text'] = $values[$index['t'][7]]['value'];
			$return_array['cc']['uv_index'] = $values[$index['i'][0]]['value'];
			$return_array['cc']['wind_speed'] = $values[$index['s'][0]]['value'];
			$return_array['cc']['wind_gust'] = $values[$index['gust'][0]]['value'];
			$return_array['cc']['wind_direction'] = $values[$index['d'][1]]['value'];
			$return_array['cc']['wind_text'] = $values[$index['t'][5]]['value'];
			$return_array['cc']['barometer'] = $values[$index['r'][0]]['value'];
			$return_array['cc']['barometer_dir'] = $values[$index['d'][0]]['value'];

			$return_array['shittylinktext'][0] = $values[$index['t'][0]]['value'];
			$return_array['shittylinktext'][1] = $values[$index['t'][1]]['value'];
			$return_array['shittylinktext'][2] = $values[$index['t'][2]]['value'];
			$return_array['shittylinktext'][3] = $values[$index['t'][3]]['value'];
			$return_array['shittylinks'][0] = $values[$index['l'][0]]['value'];
			$return_array['shittylinks'][1] = $values[$index['l'][1]]['value'];
			$return_array['shittylinks'][2] = $values[$index['l'][2]]['value'];
			$return_array['shittylinks'][3] = $values[$index['l'][3]]['value'];

			$counter = 0;
			if (array_key_exists("day",$index))
			{
				foreach ($index['day'] as $day)
				{
					if (isset($values[$day]['attributes']['t']) && $values[$day]['attributes']['t'] != "")
					{
						$day_text = (($counter + 1) * 3) + $counter + 5;  // 4,8,12,...
						$day_wind = ((($counter + 1) * 3) + $counter) + 2; // 5,9,13,...
						$day_windspeed = (($counter + 1) * 2) - 1; // 1,3,5,...
						$day_windgust = (($counter + 1) * 2) - 1; // 1,3,5,...
						$day_winddir = ($counter + 1) * 2; // 2,4,6,...
						$day_humidity = (($counter + 1) * 2) - 1; // 1,3,5,...
						$day_precip = $counter * 2; // 0,2,4,...
						$day_icon = ($counter + 1) * 2; // 2,4,6,...

						$night_text = ((($counter + 1) * 3) + $counter) + 7; // 6,10,14,...
						$night_wind = ((($counter + 1) * 3) + $counter) + 4; // 7,11,15,...
						$night_windspeed = ($counter + 1) * 2; // 2,4,6,...
						$night_windgust = ($counter + 1) * 2; // 2,4,6,...
						$night_winddir = (($counter + 1) * 2) + 1; // 3,5,7,...
						$night_humidity = ($counter + 1) * 2; // 2,4,6,...
						$night_precip = ($counter * 2) + 1; // 1,3,5,...
						$night_icon = (($counter + 1) * 2) + 1; // 3,5,7,...

						isset($values[$day]['attributes']['dt']) ? $return_array['day'][$counter]['date'] = $values[$day]['attributes']['dt'] : $return_array['day'][$counter]['date'] = '';
						isset($values[$day]['attributes']['t']) ? $return_array['day'][$counter]['day'] = $values[$day]['attributes']['t'] : $return_array['day'][$counter]['day'] = '';
						$return_array['day'][$counter]['hi'] = $values[$index['hi'][$counter]]['value'];
						$return_array['day'][$counter]['low'] = $values[$index['low'][$counter]]['value'];
						$return_array['day'][$counter]['sunrise'] = $values[$index['sunr'][$counter+1]]['value'];
						$return_array['day'][$counter]['sunset'] = $values[$index['suns'][$counter+1]]['value'];
						$return_array['day'][$counter]['day_text'] = $values[$index['t'][$day_text]]['value'];
						$return_array['day'][$counter]['day_wind'] = $values[$index['t'][$day_wind]]['value'];
						$return_array['day'][$counter]['day_windspeed'] = $values[$index['s'][$day_windspeed]]['value'];
						$return_array['day'][$counter]['day_windgust'] = $values[$index['gust'][$day_windgust]]['value'];
						$return_array['day'][$counter]['day_winddir'] = $values[$index['d'][$day_winddir]]['value'];
						$return_array['day'][$counter]['day_humid'] = $values[$index['hmid'][$day_humidity]]['value'];
						$return_array['day'][$counter]['day_pct_precip'] = $values[$index['ppcp'][$day_precip]]['value'];
						$return_array['day'][$counter]['day_icon'] = $values[$index['icon'][$day_icon]]['value'];
						$return_array['day'][$counter]['night_text'] = $values[$index['t'][$night_text]]['value'];
						$return_array['day'][$counter]['night_wind'] = $values[$index['t'][$night_wind]]['value'];
						$return_array['day'][$counter]['night_windspeed'] = $values[$index['s'][$night_windspeed]]['value'];
						$return_array['day'][$counter]['night_windgust'] = $values[$index['gust'][$night_windgust]]['value'];
						$return_array['day'][$counter]['night_winddir'] = $values[$index['d'][$night_winddir]]['value'];
						$return_array['day'][$counter]['night_humid'] = $values[$index['hmid'][$night_humidity]]['value'];
						$return_array['day'][$counter]['night_pct_precip'] = $values[$index['ppcp'][$night_precip]]['value'];
						$return_array['day'][$counter]['night_icon'] = $values[$index['icon'][$night_icon]]['value'];
						$counter++;
					}
				}
			}
			break;
		case "error":
			$return_array['type'] = "error";
			$return_array[]['error'] = $values[1]['value'];;
			break;
	}
	//print_r($return_array);
	return $return_array;
}

$weather_array = getWeatherData($index,$values);

if($weather_array['type'] == "error")
{
	echo $weather_array[0]['error'];
}

if($weather_array['type'] == "weather")
{
	$system = $weather_array['unit']['temp'];
	$barometer = $weather_array['unit']['pressure'];
	$response = '';
	$response = "<div id=\"weather\">";
    $response .= "<h2>St. Louis Weather | <a href=\"http://www.weather.com/weather/local/63101\">Extended Forecast</a></h2>";
    $response .= "<ul>";

	if(array_key_exists("day",$weather_array))
	{
		$day_counter = 1;
		foreach($weather_array['day'] as $forecast_day)
		{
//			print_r($forecast_day);

			if($day_counter == 1)
			{
				$forecast_date = ($forecast_day['hi'] == "N/A") ? "Tonight":"Today";
				$forecast_icon = ($forecast_day['hi'] == "N/A") ? $forecast_day['night_icon']:$forecast_day['day_icon'];
				$forecast_tag = ($forecast_day['hi'] == "N/A") ? "$forecast_day[night_text]":"$forecast_day[day_text]";
				if($forecast_day['hi'] != "N/A") {
					$forecast_high = "<p class=\"weather_high\">".$forecast_day['hi']."&deg;</p>";
				}
				else {
					$forecast_high = "<p class=\"weather_na\">Low</p>";
				}
				$forecast_low = $forecast_day['low']."&deg;";			
			}
			else
			{
				$forecast_date = "$forecast_day[day]";
				$forecast_icon = $forecast_day['day_icon'];
				$forecast_tag = $forecast_day['day_text'];
				$forecast_high = "<p class=\"weather_high\">".$forecast_day['hi']."&deg;</p>";
				$forecast_low = $forecast_day['low']."&deg;";
			}			
	    	
	    	$response .= "<li><h3>$forecast_date</h3>";
    	    $response .= "<ul class=\"weather_layout\">";
    		$response .= "<li class=\"weather_image\"><img src=\"/images/weather/45x45/$forecast_icon.png\" /></li>";
    		$response .= "<li class=\"weather_temp\">$forecast_high<p class=\"weather_low\">$forecast_low</p></li>";
    		$response .= "<li class=\"weather_tag\">$forecast_tag</li>";
    	    $response .= "</ul>";
    	    $response .= "</li>";
			$day_counter++;
		}
	}
	$response .= "<li class=\"current\"><h3>Current</h3>";
    $response .= "<ul class=\"current_layout\">";
    $response .= "<li class=\"current_temp\">".$weather_array['cc']['temp'] . "&deg;</li>";
    $response .= "<li class=\"current_tag\">".$weather_array['cc']['text']."</li>";
    $response .= "</ul>";
    $response .= "</li>";
    $response .= "<li class=\"current-image\"><img src=\"/images/weather/110x110/".$weather_array['cc']['icon'].".png\" /></li>";		
	$response .= "</ul>";
	$response .= "<p class=\"weather_meta\">Last update: " . $weather_array['cc']['last_update'] . ". Weather data from St. Louis Univ, MO provided by <a href=\"http://www.weather.com/?prod=xoap&par=1066051000\">Weather.com</a></p></div>";
	echo $response;
}
?>

