/** * Returns the weather-data for the supplied location * * @param string $id * @param string $unitsFormat * @return PEAR_Error|array * @throws PEAR_Error * @access public */ function getWeather($id = "", $unitsFormat = "") { static $clouds; if (!isset($clouds)) { $clouds = array("sky clear", "few", "scattered", "broken", "overcast"); } $status = $this->_checkLocationID($id); if (Services_Weather::isError($status)) { return $status; } // Get other data $units = $this->getUnitsFormat($unitsFormat); $weatherReturn = array(); if ($this->_cacheEnabled && ($weather = $this->_cache->get("GW-" . $id, "weather"))) { // Same procedure... $this->_weather = $weather; $weatherReturn["cache"] = "HIT"; } else { // Check, if the weatherSoap-Object is present. If not, connect to the Server and retrieve the WDSL data if (!$this->_weatherSoap) { $status = $this->_connectServer(); if (Services_Weather::isError($status)) { return $status; } } // ...as last function $weather = $this->_weatherSoap->getWeatherReport($id); if (Services_Weather::isError($weather)) { return $weather; } $this->_weather = $weather; if ($this->_cacheEnabled) { // ...and cache it $expire = constant("SERVICES_WEATHER_EXPIRES_WEATHER"); $this->_cache->extSave("GW-" . $id, $this->_weather, "", $expire, "weather"); } $weatherReturn["cache"] = "MISS"; } $update = trim(str_replace(array("T", "Z"), " ", $this->_weather->timestamp)) . " GMT"; $weatherReturn["update"] = gmdate(trim($this->_dateFormat . " " . $this->_timeFormat), strtotime($update)); $weatherReturn["updateRaw"] = $this->_weather->timestamp; if (strlen($this->_weather->station->region) && strlen($this->_weather->station->country)) { $locname = $this->_weather->station->name . ", " . $this->_weather->station->region . ", " . $this->_weather->station->country; } elseif (strlen($this->_weather->station->country)) { $locname = $this->_weather->station->name . ", " . $this->_weather->station->country; } else { $locname = $this->_weather->station->name; } $weatherReturn["station"] = $locname; $weatherReturn["wind"] = $this->convertSpeed($this->_weather->wind->prevailing_speed, "mps", $units["wind"]); $weatherReturn["windDegrees"] = $this->_weather->wind->prevailing_direction->degrees; $weatherReturn["windDirection"] = $this->_weather->wind->prevailing_direction->compass; if ($this->_weather->wind->prevailing_speed != $this->_weather->wind->gust_speed) { $weatherReturn["windGust"] = $this->convertSpeed($this->_weather->wind->gust_speed, "mps", $units["wind"]); } if ($this->_weather->wind->varying_from_direction != "" && $this->_weather->wind->varying_to_direction != "") { $weatherReturn["windVar"] = array("from" => $this->_weather->wind->varying_from_direction, "to" => $this->_weather->wind->varying_to_direction); } $weatherReturn["visibility"] = $this->convertDistance($this->_weather->visibility->distance / 1000, "km", $units["vis"]); $weatherReturn["visQualifier"] = $this->_weather->visibility->qualifier; $condition = array(); for ($i = 0; $i < sizeof($this->_weather->phenomena); $i++) { $condition[] = $this->_weather->phenomena[$i]->string; } $weatherReturn["condition"] = implode(", ", $condition); if (is_array($this->_weather->sky->layers)) { $layers = array(); for ($i = 0; $i < sizeof($this->_weather->sky->layers); $i++) { if (strtoupper($this->_weather->sky->layers[$i]->type) != "CLEAR") { $layers[$i] = array(); $layers[$i]["amount"] = $clouds[$this->_weather->sky->layers[$i]->extent]; $layers[$i]["height"] = $this->convertDistance($this->_weather->sky->layers[$i]->altitude, "m", $units["height"]); if (strtoupper($this->_weather->sky->layers[$i]->type) != "CLOUD") { $layers[$i]["type"] = ucwords(str_replace("_", "", $this->_weather->sky->layers[$i]->type)); } } } if (sizeof($layers)) { $weatherReturn["clouds"] = $layers; } } $weatherReturn["temperature"] = $this->convertTemperature($this->_weather->temperature->ambient, "c", $units["temp"]); $feltTemperature = $this->calculateWindChill($this->convertTemperature($weatherReturn["temperature"], $units["temp"], "f"), $this->convertSpeed($weatherReturn["wind"], $units["wind"], "mph")); $weatherReturn["feltTemperature"] = $this->convertTemperature($feltTemperature, "f", $units["temp"]); $weatherReturn["dewPoint"] = $this->convertTemperature($this->_weather->temperature->dewpoint, "c", $units["temp"]); $weatherReturn["humidity"] = $this->_weather->temperature->relative_humidity; $weatherReturn["pressure"] = $this->convertPressure($this->_weather->pressure->altimeter, "hpa", $units["pres"]); return $weatherReturn; }
/** * Returns the message for a certain error code * * @param PEAR_Error|int $value * @return string * @access private */ function _errorMessage($value) { static $errorMessages; if (!isset($errorMessages)) { $errorMessages = array(SERVICES_WEATHER_ERROR_SERVICE_NOT_FOUND => "Requested service could not be found.", SERVICES_WEATHER_ERROR_UNKNOWN_LOCATION => "Unknown location provided.", SERVICES_WEATHER_ERROR_WRONG_SERVER_DATA => "Server data wrong or not available.", SERVICES_WEATHER_ERROR_CACHE_INIT_FAILED => "Cache init was not completed.", SERVICES_WEATHER_ERROR_DB_NOT_CONNECTED => "MetarDB is not connected.", SERVICES_WEATHER_ERROR_HTTP_PROXY_INVALID => "The given proxy is not valid, please use the notation http://[user[:pass]@]host[:port].", SERVICES_WEATHER_ERROR_SUNFUNCS_DATE_INVALID => "The date you've provided for calculation of sunrise/sunset is not a timestamp.", SERVICES_WEATHER_ERROR_SUNFUNCS_RETFORM_INVALID => "The return format you've provided for calculation of sunrise/sunset is not valid.", SERVICES_WEATHER_ERROR_METAR_SOURCE_INVALID => "The METAR/TAF source you've provided has an invalid type or path.", SERVICES_WEATHER_ERROR_UNKNOWN_ERROR => "An unknown error has occured.", SERVICES_WEATHER_ERROR_NO_LOCATION => "No location provided.", SERVICES_WEATHER_ERROR_INVALID_LOCATION => "Invalid location provided.", SERVICES_WEATHER_ERROR_INVALID_PARTNER_ID => "Invalid partner id.", SERVICES_WEATHER_ERROR_INVALID_PRODUCT_CODE => "Invalid product code.", SERVICES_WEATHER_ERROR_INVALID_LICENSE_KEY => "Invalid license key."); } if (Services_Weather::isError($value)) { $value = $value->getCode(); } return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[SERVICES_WEATHER_ERROR_UNKNOWN_ERROR]; }
// // $Id: ejse-basic.php,v 1.3 2004/05/07 14:41:36 eru Exp $ require_once "Services/Weather.php"; // Object initialization - error checking is important, because of // handling exceptions such as missing PEAR modules or not being online $ejse =& Services_Weather::service("Ejse", array("debug" => 2)); if (Services_Weather::isError($ejse)) { die("Error: " . $ejse->getMessage() . "\n"); } /* Erase comments to enable caching $status = $ejse->setCache("file", array("cache_dir" => "/tmp/cache/")); if (Services_Weather::isError($status)) { echo "Error: ".$status->getMessage()."\n"; } */ $ejse->setUnitsFormat("metric"); $ejse->setDateTimeFormat("d.m.Y", "H:i"); $location = "81611"; // Aspen, CO //$location = "02115"; // Boston, MA //$location = "96799"; // Pago Pago, AS //$location = "09009"; // Armed Forces Europe -> Error // Now iterate through available functions for retrieving data foreach (array("getLocation", "getWeather", "getForecast") as $function) { $data = $ejse->{$function}($location); if (Services_Weather::isError($data)) { echo "Error: " . $data->getMessage() . "\n"; continue; } var_dump($data); }
/** * Get the forecast for the next days * * @param string $int * @param int $days Values between 1 and 9 * @param string $unitsFormat * @return PEAR_Error|array * @throws PEAR_Error * @access public */ function getForecast($id = "", $days = 2, $unitsFormat = "") { $status = $this->_checkLocationID($id); if (Services_Weather::isError($status)) { return $status; } if (!in_array($days, range(1, 9))) { $days = 2; } // Get other data $units = $this->getUnitsFormat($unitsFormat); $forecastReturn = array(); if ($this->_cacheEnabled && ($forecast = $this->_getCache($id, "forecast"))) { // Same procedure... $this->_forecast = $forecast; $forecastReturn["cache"] = "HIT"; } else { // Check, if the weatherSoap-Object is present. If not, connect to the Server and retrieve the WDSL data if (!$this->_weatherSoap) { $status = $this->_connectServer(); if (Services_Weather::isError($status)) { return $status; } } // ...as last function $forecast = $this->_weatherSoap->GetNineDayForecastInfo2($this->_username, $this->_password, $id); if (Services_Weather::isError($forecast)) { return $forecast; } $this->_forecast = $forecast; if ($this->_cacheEnabled) { // ...and cache it $this->_saveCache($id, $this->_forecast, "", "forecast"); } $forecastReturn["cache"] = "MISS"; } $forecastReturn["days"] = array(); // Initialize some arrays $temperatureHigh = array(); $temperatureLow = array(); for ($i = 1; $i <= $days; $i++) { preg_match("/(-?\\d+)\\D+/", $this->_forecast->{"Day" . $i}->High, $temperatureHigh); preg_match("/(-?\\d+)\\D+/", $this->_forecast->{"Day" . $i}->Low, $temperatureLow); $day = array("tempertureHigh" => $this->convertTemperature($temperatureHigh[1], "f", $units["temp"]), "temperatureLow" => $this->convertTemperature($temperatureLow[1], "f", $units["temp"]), "day" => array("condition" => $this->_forecast->{"Day" . $i}->Forecast, "conditionIcon" => $this->_forecast->{"Day" . $i}->IconIndex, "precipitation" => trim(str_replace("%", "", $this->_forecast->{"Day" . $i}->PrecipChance)))); $forecastReturn["days"][] = $day; } return $forecastReturn; }
/** * METAR provides no forecast per se, we use the TAF reports to generate * a forecast for the announced timeperiod * * @param string $id * @param int $days Ignored, not applicable * @param string $unitsFormat * @return PEAR_Error|array * @throws PEAR_Error * @access public */ function getForecast($id = "", $days = null, $unitsFormat = "") { $id = strtoupper($id); $status = $this->_checkLocationID($id); if (Services_Weather::isError($status)) { return $status; } // Get other data $units = $this->getUnitsFormat($unitsFormat); $location = $this->getLocation($id); if (Services_Weather::isError($location)) { return $location; } if ($this->_cacheEnabled && ($forecast = $this->_cache->get("METAR-" . $id, "forecast"))) { // Wee... it was cached, let's have it... $forecastReturn = $forecast; $this->_forecast = $forecastReturn; $forecastReturn["cache"] = "HIT"; } else { // Download forecast $forecastData = $this->_retrieveServerData($id, "taf"); if (Services_Weather::isError($forecastData)) { return $forecastData; } elseif (!is_array($forecastData) || sizeof($forecastData) < 2) { return Services_Weather::raiseError(SERVICES_WEATHER_ERROR_WRONG_SERVER_DATA, __FILE__, __LINE__); } // Parse forecast $forecastReturn = $this->_parseForecastData($forecastData); if (Services_Weather::isError($forecastReturn)) { return $forecastReturn; } if ($this->_cacheEnabled) { // Cache weather $expire = constant("SERVICES_WEATHER_EXPIRES_FORECAST"); $this->_cache->extSave("METAR-" . $id, $forecastReturn, $unitsFormat, $expire, "forecast"); } $this->_forecast = $forecastReturn; $forecastReturn["cache"] = "MISS"; } $this->_convertReturn($forecastReturn, $units, $location); return $forecastReturn; }
/** * Returns the message for a certain error code * * @param PEAR_Error|int $value * @return string * @access private */ function _errorMessage($value) { static $errorMessages; if (!isset($errorMessages)) { $errorMessages = array(SERVICES_WEATHER_ERROR_SERVICE_NOT_FOUND => "Requested service could not be found.", SERVICES_WEATHER_ERROR_UNKNOWN_LOCATION => "Unknown location provided.", SERVICES_WEATHER_ERROR_WRONG_SERVER_DATA => "Server data wrong or not available.", SERVICES_WEATHER_ERROR_CACHE_INIT_FAILED => "Cache init was not completed.", SERVICES_WEATHER_ERROR_DB_NOT_CONNECTED => "MetarDB is not connected.", SERVICES_WEATHER_ERROR_UNKNOWN_ERROR => "An unknown error has occured.", SERVICES_WEATHER_ERROR_NO_LOCATION => "No location provided.", SERVICES_WEATHER_ERROR_INVALID_LOCATION => "Invalid location provided.", SERVICES_WEATHER_ERROR_INVALID_PARTNER_ID => "Invalid partner id.", SERVICES_WEATHER_ERROR_INVALID_PRODUCT_CODE => "Invalid product code.", SERVICES_WEATHER_ERROR_INVALID_LICENSE_KEY => "Invalid license key."); } if (Services_Weather::isError($value)) { $value = $value->getCode(); } return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[SERVICES_WEATHER_ERROR_UNKNOWN_ERROR]; }
/** * Get the forecast for the next days * * @param string $id * @param int $days Values between 1 and 5 * @param string $unitsFormat * @return PEAR_Error|array * @throws PEAR_Error * @access public */ function getForecast($id = "", $days = 5, $unitsFormat = "") { $status = $this->_checkLocationID($id); if (Services_Weather::isError($status)) { return $status; } if (!is_int($days) || $days < 1 || $days > 5) { $days = 5; } // Get other data $units = $this->getUnitsFormat($unitsFormat); $forecastReturn = array(); if (is_object($this->_forecast)) { $forecastReturn["cache"] = "MEM"; } elseif ($this->_cacheEnabled && ($forecast = $this->_getCache($id, "forecast"))) { // Encore... $this->_forecast = $forecast; $forecastReturn["cache"] = "HIT"; } else { // ... $status = $this->_parseWeatherData($id, "forecast"); if (Services_Weather::isError($status)) { return $status; } $forecastReturn["cache"] = "MISS"; } // Make sure the location object has been loaded if (!is_object($this->_location)) { $this->getLocation($id); } // Some explanation for the next two lines: (same as above) // weather.com isn't always supplying the timezone in the update string, but // uses "Local Time" as reference, which is imho utterly stupid, because it's // inconsistent. Well, what I do here is check for this string and if I can // find it, I calculate the difference between the timezone at the location // and this computers timezone. This amount of seconds is then subtracted from // the time the update-string has delivered. $update = str_replace("Local Time", "", $this->_forecast->lsup); $adjustTZ = $update == $this->_forecast->lsup ? 0 : $this->_location->zone * 3600 - date("Z"); $forecastReturn["update"] = gmdate($this->_dateFormat . " " . $this->_timeFormat, strtotime($update) - $adjustTZ); $forecastReturn["updateRaw"] = $this->_forecast->lsup; $forecastReturn["days"] = array(); for ($i = 0; $i < $days; $i++) { $day = array("temperatureHigh" => round($this->convertTemperature($this->_forecast->day[$i]->hi, "f", $units["temp"]), 2), "temperatureLow" => round($this->convertTemperature($this->_forecast->day[$i]->low, "f", $units["temp"]), 2), "sunrise" => date($this->_timeFormat, strtotime($this->_forecast->day[$i]->sunr)), "sunset" => date($this->_timeFormat, strtotime($this->_forecast->day[$i]->suns)), "day" => array("condition" => $this->_forecast->day[$i]->part[0]->t, "conditionIcon" => $this->_forecast->day[$i]->part[0]->icon, "wind" => round($this->convertSpeed($this->_forecast->day[$i]->part[0]->wind->s, "mph", $units["wind"]), 2), "windGust" => round($this->convertSpeed($this->_forecast->day[$i]->part[0]->wind->gust, "mph", $units["wind"]), 2), "windDegrees" => $this->_forecast->day[$i]->part[0]->wind->d, "windDirection" => $this->_forecast->day[$i]->part[0]->wind->t, "precipitation" => $this->_forecast->day[$i]->part[0]->ppcp, "humidity" => round($this->_forecast->day[$i]->part[0]->hmid, 1)), "night" => array("condition" => $this->_forecast->day[$i]->part[1]->t, "conditionIcon" => $this->_forecast->day[$i]->part[1]->icon, "wind" => round($this->convertSpeed($this->_forecast->day[$i]->part[1]->wind->s, "mph", $units["wind"]), 2), "windGust" => round($this->convertSpeed($this->_forecast->day[$i]->part[1]->wind->gust, "mph", $units["wind"]), 2), "windDegrees" => $this->_forecast->day[$i]->part[1]->wind->d, "windDirection" => $this->_forecast->day[$i]->part[1]->wind->t, "precipitation" => $this->_forecast->day[$i]->part[1]->ppcp, "humidity" => round($this->_forecast->day[$i]->part[1]->hmid, 1))); $forecastReturn["days"][] = $day; } return $forecastReturn; }
/** * Constructor * * @param array $options * @param mixed $error * @throws PEAR_Error * @access private */ function Services_Weather_Common($options, &$error) { // Set some constants for the case when PHP4 is used, as the // date_sunset/sunrise functions are not implemented there if (!defined("SUNFUNCS_RET_TIMESTAMP")) { define("SUNFUNCS_RET_TIMESTAMP", 0); define("SUNFUNCS_RET_STRING", 1); define("SUNFUNCS_RET_DOUBLE", 2); } // Set options accordingly if (isset($options["cacheType"])) { if (isset($options["cacheOptions"])) { $status = $this->setCache($options["cacheType"], $options["cacheOptions"]); } else { $status = $this->setCache($options["cacheType"]); } if (Services_Weather::isError($status)) { $error = $status; return; } } if (isset($options["unitsFormat"])) { if (isset($options["customUnitsFormat"])) { $this->setUnitsFormat($options["unitsFormat"], $options["customUnitsFormat"]); } else { $this->setUnitsFormat($options["unitsFormat"]); } } if (isset($options["httpTimeout"])) { $this->setHttpTimeout($options["httpTimeout"]); } else { $this->setHttpTimeout(60); } if (isset($options["httpProxy"])) { $status = $this->setHttpProxy($options["httpProxy"]); if (Services_Weather::isError($status)) { $error = $status; return; } } if (isset($options["dateFormat"])) { $this->setDateTimeFormat($options["dateFormat"], ""); } if (isset($options["timeFormat"])) { $this->setDateTimeFormat("", $options["timeFormat"]); } }
/** * Get the forecast for the next days * * @param string $int * @param int $days Values between 1 and 9 * @param string $unitsFormat * @return PEAR_Error|array * @throws PEAR_Error * @access public */ function getForecast($id = "", $days = 2, $unitsFormat = "") { $status = $this->_checkLocationID($id); if (Services_Weather::isError($status)) { return $status; } if (!in_array($days, range(1, 9))) { $days = 2; } // Get other data $units = $this->getUnitsFormat($unitsFormat); $forecastReturn = array(); if ($this->_cacheEnabled && ($forecast = $this->_cache->get($id, "forecast"))) { // Same procedure... $this->_forecast = $forecast; $forecastReturn["cache"] = "HIT"; } else { // ...as last function $forecast = $this->_weatherSoap->GetNineDayForecastInfo($id); if (Services_Weather::isError($forecast)) { return $forecast; } $this->_forecast = $forecast; if ($this->_cacheEnabled) { // ...and cache it $expire = constant("SERVICES_WEATHER_EXPIRES_FORECAST"); $this->_cache->extSave($id, $this->_forecast, "", $expire, "forecast"); } $forecastReturn["cache"] = "MISS"; } $forecastReturn["days"] = array(); for ($i = 1; $i <= $days; $i++) { preg_match("/(-?\\d+)\\D+/", $this->_forecast->{"Day" . $i}->High, $temperatureHigh); preg_match("/(-?\\d+)\\D+/", $this->_forecast->{"Day" . $i}->Low, $temperatureLow); $day = array("tempertureHigh" => $this->convertTemperature($temperatureHigh[1], "f", $units["temp"]), "temperatureLow" => $this->convertTemperature($temperatureLow[1], "f", $units["temp"]), "day" => array("condition" => $this->_forecast->{"Day" . $i}->Forecast, "conditionIcon" => $this->_forecast->{"Day" . $i}->IconIndex, "precipitation" => trim(str_replace("%", "", $this->_forecast->{"Day" . $i}->PrecipChance)))); $forecastReturn["days"][] = $day; } return $forecastReturn; }
/** * Constructor * * @param array $options * @param mixed $error * @throws PEAR_Error * @see Science_Weather::Science_Weather * @access private */ function Services_Weather_Common($options, &$error) { // Set options accordingly if (isset($options["cacheType"])) { if (isset($options["cacheOptions"])) { $status = $this->setCache($options["cacheType"], $options["cacheOptions"]); } else { $status = $this->setCache($options["cacheType"]); } if (Services_Weather::isError($status)) { $error = $status; return; } } if (isset($options["unitsFormat"])) { if (isset($options["customUnitsFormat"])) { $this->setUnitsFormat($options["unitsFormat"], $options["customUnitsFormat"]); } else { $this->setUnitsFormat($options["unitsFormat"]); } } if (isset($options["httpTimeout"])) { $this->setHttpTimeout($options["httpTimeout"]); } if (isset($options["dateFormat"])) { $this->setDateTimeFormat($options["dateFormat"], ""); } if (isset($options["timeFormat"])) { $this->setDateTimeFormat("", $options["timeFormat"]); } }
/** * METAR provides no forecast per se, we use the TAF reports to generate * a forecast for the announced timeperiod * * @param string $id * @param int $days Ignored, not applicable * @param string $unitsFormat * @return PEAR_Error|array * @throws PEAR_Error * @access public */ function getForecast($id = "", $days = null, $unitsFormat = "") { $id = strtoupper($id); $status = $this->_checkLocationID($id); if (Services_Weather::isError($status)) { return $status; } // Get other data $units = $this->getUnitsFormat($unitsFormat); $location = $this->getLocation($id); if ($this->_cacheEnabled && ($forecast = $this->_cache->get("METAR-" . $id, "forecast"))) { // Wee... it was cached, let's have it... $forecastReturn = $forecast; $this->_forecast = $forecastReturn; $forecastReturn["cache"] = "HIT"; } else { // Set the source if ($this->_sourceTaf == "file") { $source = realpath($this->_sourcePathTaf . "/" . $id . ".TXT"); } else { $source = $this->_sourcePathTaf . "/" . $id . ".TXT"; } // Download and parse weather $forecastReturn = $this->_parseForecastData($source); if (Services_Weather::isError($forecastReturn)) { return $forecastReturn; } if ($this->_cacheEnabled) { // Cache weather $expire = constant("SERVICES_WEATHER_EXPIRES_FORECAST"); $this->_cache->extSave("METAR-" . $id, $forecastReturn, $unitsFormat, $expire, "forecast"); } $this->_forecast = $forecastReturn; $forecastReturn["cache"] = "MISS"; } $this->_convertReturn($forecastReturn, $units, $location); return $forecastReturn; }
$units["pres"] = " " . $units["pres"]; $units["rain"] = " " . $units["rain"]; $metar->setMetarSource($sourceMetar, $sourcePathMetar, $sourceTaf, $sourcePathTaf); // Set date-/time-format $metar->setDateTimeFormat($dateFormat, $timeFormat); // Search for defined location and fetch the first item found. // Bail out if something bad happens... $search = $metar->searchLocation($location, true); if (Services_Weather::isError($search)) { die("Error: " . $search->getMessage() . "\n"); } // Retrieve data, store in variables, bail out on error $fetch = array("location" => "getLocation", "weather" => "getWeather", "forecast" => "getForecast"); foreach ($fetch as $variable => $function) { ${$variable} = $metar->{$function}($search); if (Services_Weather::isError(${$variable})) { echo "Error: " . ${$variable}->getMessage() . "\n"; continue; } } // Calculate sunrise/-set for our location - UTC is used here! $gmt_offset = 0; $timestamp = gmmktime(); $location["sunrise"] = date_sunrise($timestamp, SUNFUNCS_RET_STRING, $location["latitude"], $location["longitude"], SUNFUNCS_SUNRISE_ZENITH, $gmt_offset); $location["sunset"] = date_sunset($timestamp, SUNFUNCS_RET_STRING, $location["latitude"], $location["longitude"], SUNFUNCS_SUNSET_ZENITH, $gmt_offset); // Now we output all the data, please don't expect extensive comments here, this is basic // HTML/CSS stuff. Also this isn't a very fancy design, it's just to show you, what // the script is able to do (and more ;-))... ?> <html> <head>
/** * serendipity_plugin_weather::generate_content() * * @param $title * @return */ function generate_content(&$title) { global $serendipity; $title = $this->get_config('title'); $metar_site = $this->get_config('metar', 'EDDK'); $timezone = $this->get_config('timezone', 0); $unitString = $this->get_config('units', 'metric'); $caching = $this->get_config('caching', 0); $directory = $this->get_config('cache_directory', '/tmp'); $pixdir = $this->get_config('pixel_directory'); if (@(include_once 'Services/Weather.php')) { $metar =& Services_Weather::service('METAR', array('debug' => 0)); if (Services_Weather::isError($metar)) { echo 'Weather Error: ' . $metar->getMessage(); } // Set the unit format for the data $metar->setUnitsFormat($unitString); // Set the time/date format // Do we have the date/time format set somewhere in s9y? then we should take this here // $metar->setDateTimeFormat('d.m.Y', 'H:i'); // $metar_data->setDateTimeFormat('j M Y', 'H:i'); if ($caching) { if (@(include_once "Cache.php")) { $status = $metar->setCache('file', array('cache_dir' => $serendipity['serendipityPath'] . $directory)); } else { echo 'Caching is enabled but PEAR:Cache does not seem to be installed.'; } } if (Services_Weather::isError($status)) { echo 'Error: ' . $status->getMessage(); } switch ($unitString) { case "metric": $units = array('wind' => 'km/h', 'vis' => 'km', 'height' => 'km', 'temp' => '°C', 'pres' => 'mb', 'rain' => 'mm'); break; case "standard": $units = array('wind' => 'mph', 'vis' => 'mi', 'height' => 'mi', 'temp' => '°F', 'pres' => 'in', 'rain' => 'in'); break; } $weather_data = $metar->getWeather($metar_site); if (Services_Weather::isError($weather_data)) { echo 'Error: ' . $weather_data->getMessage(); } $location_data = $metar->getLocation($metar_site); if (Services_Weather::isError($location_data)) { echo 'Error: ' . $location_data->getMessage(); } $forecast_data = $metar->getForecast($metar_site); if (Services_Weather::isError($forecast_data)) { echo 'Error: ' . $forecast_data->getMessage(); } // Do all that icon-stuff // FIXXME: URL-Prefix $windDir = $weather_data["windDirection"]; switch ($windDir) { case 'S': $windDirIcon = $pixdir . '/sss.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_S; break; case 'SSW': $windDirIcon = $pixdir . '/ssw.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_SSW; break; case 'SSE': $windDirIcon = $pixdir . '/sse.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_SSE; break; case 'SW': $windDirIcon = $pixdir . '/sw.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_SW; break; case 'WSW': $windDirIcon = $pixdir . '/sww.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_WSW; break; case 'E': $windDirIcon = $pixdir . '/eee.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_E; break; case 'ESE': $windDirIcon = $pixdir . '/see.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_ESE; break; case 'ENE': $windDirIcon = $pixdir . '/nee.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_ENE; break; case 'N': $windDirIcon = $pixdir . '/nnn.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_N; break; case 'NNW': $windDirIcon = $pixdir . '/nnw.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_NNW; break; case 'NNE': $windDirIcon = $pixdir . '/nne.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_NNE; break; case 'NW': $windDirIcon = $pixdir . '/nw.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_NW; break; case 'NE': $windDirIcon = $pixdir . '/ne.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_NE; break; case 'SE': $windDirIcon = $pixdir . '/se.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_SE; break; case 'W': $windDirIcon = $pixdir . '/www.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_W; break; case 'WNW': $windDirIcon = $pixdir . '/nww.png'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_WNW; break; case 'Variable': $windDirIcon = $pixdir . '/vrb.gif'; $windDir = PLUGIN_SIDEBAR_WEATHER_DATA_V; break; default: $windDirIcon = $pixdir . '/wind_nodata.png'; $windDir = "No recorded data."; } // Turn the GMT time from the update into a local time $localTime = date('j M Y H:i', strtotime($weather_data['updateRaw']) + 3600 * $timezone); // Get local hour to determing if it is night $hour = date('H', strtotime($weather_data['updateRaw']) + 3600 * $tz); if ($hour > 18 || $hour < 6) { $night = 'n_'; } else { $night = ''; } // Handle cloud data // We could be dealing with cloud at several levels, so find the heaviest // cover and go with that. $cloudData = $weather_data['clouds']; // See if we are dealing with an array of arrays or some information $cloudKeys = array_keys($cloudData); $testKey = $cloudKeys[0]; if (!is_array($cloudData["{$testKey}"])) { // we have information $amount = $cloudData['amount']; } else { // we have information on several levels - get highest $key = count($cloudKeys) - 1; $useArray = $cloudData[$key]; $amount = $useArray['amount']; } switch ($amount) { case "Clear Below": case "clear sky": case "no significant cloud": case "clear below 12,000 ft": case "vertical visibility": $cloudLevel = "0cloud"; break; case "few": case "scattered": $cloudLevel = "1cloud"; break; case "Cumulonimbus": $cloudLevel = "2cloud"; break; case "Towering Cumulus": case "broken": $cloudLevel = "3cloud"; break; case "overcast": $cloudLevel = "4cloud"; $night = ""; break; default: $cloudLevel = "0cloud"; } // Determine weather conditions (rain, snow etc); // We need some way to translate this $conditions = $weather_data["condition"]; switch ($cloudLevel) { case "0cloud": if (strstr($conditions, "fog") !== FALSE) { $condUse = "_fog"; } else { $condUse = ""; } break; case "1cloud": if (strstr($conditions, "fog") !== FALSE) { $condUse = "_fog"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "light") !== FALSE) { $condUse = "_lightrain"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "heavy") !== FALSE) { $condUse = "_heavyrain"; } elseif (strstr($conditions, "rain") !== FALSE) { $condUse = "_modrain"; } else { $condUse = "_norain"; } break; case "2cloud": if (strstr($conditions, "fog") !== FALSE) { $condUse = "_fog"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "light") !== FALSE) { $condUse = "_lightrain"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "heavy") !== FALSE) { $condUse = "_heavyrain"; } elseif (strstr($conditions, "rain") !== FALSE) { $condUse = "_modrain"; } elseif (strstr($conditions, "snow") !== FALSE) { $condUse = "_snow"; } elseif (strstr($conditions, "thunderstorm") !== FALSE) { $condUse = "_thunders"; } else { $condUse = "_norain"; } break; case "3cloud": if (strstr($conditions, "fog") !== FALSE) { $condUse = "_fog"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "light") !== FALSE) { $condUse = "_lightrain"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "heavy") !== FALSE) { $condUse = "_heavyrain"; } elseif (strstr($conditions, "rain") !== FALSE) { $condUse = "_modrain"; } elseif (strstr($conditions, "snow") !== FALSE) { $condUse = "_snow"; } elseif (strstr($conditions, "thunderstorm") !== FALSE) { $condUse = "_thunders"; } elseif (strstr($conditions, "hail") !== FALSE) { $condUse = "_hail"; } else { $condUse = "_norain"; } break; case "4cloud": if (strstr($conditions, "fog") !== FALSE) { $condUse = "_fog"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "light") !== FALSE) { $condUse = "_lightrain"; } elseif (strstr($conditions, "rain") !== FALSE && strstr($conditions, "heavy") !== FALSE) { $condUse = "_heavyrain"; } elseif (strstr($conditions, "rain") !== FALSE) { $condUse = "_modrain"; } elseif (strstr($conditions, "snow") !== FALSE && strstr($conditions, "light") !== FALSE) { $condUse = "_lightsnow"; } elseif (strstr($conditions, "snow") !== FALSE && strstr($conditions, "heavy") !== FALSE) { $condUse = "_heavysnow"; } elseif (strstr($conditions, "snow") !== FALSE) { $condUse = "_snow"; } elseif (strstr($conditions, "thunderstorm") !== FALSE) { $condUse = "_thunders"; } elseif (strstr($conditions, "hail") !== FALSE && strstr($conditions, "light") !== FALSE) { $condUse = "_lighthail"; } elseif (strstr($conditions, "hail") !== FALSE && strstr($conditions, "heavy") !== FALSE) { $condUse = "_heavyhail"; } elseif (strstr($conditions, "hail") !== FALSE) { $condUse = "_hail"; } else { $condUse = "_norain"; } break; default: $condUse = "_norain"; } // Construct icon name $conditionIcon = $pixdir . '/' . $night . $cloudLevel . $condUse . '.png'; $content = ''; $content .= '<img src="' . $conditionIcon . '" alt="" /><br />' . $conditions . '<br />'; // FIXXME: Translate the Winddirection $content .= '<dl><dt>' . PLUGIN_SIDEBAR_WEATHER_DATA_WINDDIRECTION . '</dt><dd><img src="' . $windDirIcon . '" alt="" /><dd>' . $windDir . ' at <dd>' . $weather_data["wind"] . ' ' . $units['wind'] . '</dd></dt>'; $content .= '<dt>' . PLUGIN_SIDEBAR_WEATHER_DATA_TEMPERATURE . '</dt><dd>' . $weather_data["temperature"] . ' ' . $units['temp'] . '</dd>'; $content .= '<dt>' . PLUGIN_SIDEBAR_WEATHER_DATA_FELT_TEMPERATURE . '</dt><dd>' . $weather_data["feltTemperature"] . ' ' . $units['temp'] . '</dd>'; $content .= '<dt>' . PLUGIN_SIDEBAR_WEATHER_DATA_HUMIDITY . '</dt><dd>' . $weather_data["humidity"] . ' ' . '%</dd>'; $content .= '<dt>' . PLUGIN_SIDEBAR_WEATHER_DATA_PRESSURE . '</dt><dd>' . $weather_data['pressure'] . ' ' . $units['pres'] . '</dd>'; $content .= '<dt>' . PLUGIN_SIDEBAR_WEATHER_DATA_VISIBILITY . '</dt><dd>' . $weather_data["visibility"] . ' ' . $units['vis'] . '</dd>'; $content .= '<dt>' . PLUGIN_SIDEBAR_WEATHER_DATA_UPDATE . '</dt><dd>' . $localTime . '</dd></dl>'; } else { $content = 'Loading the <a href=http://pear.php.net/package/Services_Weather/>PEAR Services/Weather module</a> failed. Please insure that the module is installed.'; } echo $content; }