and from output // heading=n - (default)='y' suppress printing of heading (forecast city/by/date) // icons=n - (default)='y' suppress printing of the icons+conditions+temp+wind+UV // text=n - (default)='y' suppress printing of the periods/forecast text // // // You can also invoke these options directly in the PHP like this // // $doIncludeOWM = true; // include("OWM-forecast.php"); for just the text // or ------------ // $doPrintOWM = false; // include("OWM-forecast.php"); for setting up the $OWMforecast... variables without printing // // or ------------ // $doIncludeOWM = true; // $doPrintConditions = true; // $doPrintHeadingOWM = true; // $doPrintIconsOWM = true; // $doPrintTextOWM = false // include("OWM-forecast.php"); include mode, print only heading and icon set // // Variables returned (useful for printing an icon or forecast or two...) // // $OWMforecastcity - Name of city from OWM Forecast header // // The following variables exist for $i=0 to $i= number of forecast periods minus 1 // a loop of for ($i=0;$i and Short legend. // $OWMforecastwarnings = styled text with hotlinks to advisories/warnings // $OWMcurrentConditions = table with current conds at point close to lat/long selected // // Settings --------------------------------------------------------------- // REQUIRED: a openweathermap.org API KEY.. sign up at https://www.openweathermap.org/api $OWMAPIkey = 'specify-for-standalone-use-here'; // use this only for standalone / non-template use // NOTE: if using the Saratoga template, add to Settings.php a line with: // $SITE['OWMAPIkey'] = 'your-api-key-here'; // and that will enable the script to operate correctly in your template // $iconDir ='./forecast/images/'; // directory for carterlake icons './forecast/images/' $iconType = '.jpg'; // default type='.jpg' // use '.gif' for animated icons from http://www.meteotreviglio.com/ // // The forecast(s) .. make sure the first entry is the default forecast location. // The contents will be replaced by $SITE['OWMforecasts'] if specified in your Settings.php $OWMforecasts = array( // Location|lat,long (separated by | characters) 'Saratoga, CA, USA|37.27465,-122.02295', 'Auckland, NZ|-36.910,174.771', // Awhitu, Waiuku New Zealand 'Assen, NL|53.02277,6.59037', 'Blankenburg, DE|51.8089941,10.9080649', 'Cheyenne, WY, USA|41.144259,-104.83497', 'Carcassonne, FR|43.2077801,2.2790407', 'Braniewo, PL|54.3793635,19.7853585', 'Omaha, NE, USA|41.19043,-96.13114', 'Johanngeorgenstadt, DE|50.439339,12.706085', 'Athens, GR|37.97830,23.715363', 'Haifa, IL|32.7996029,34.9467358', ); // $maxWidth = '640px'; // max width of tables (could be '100%') $maxIcons = 10; // max number of icons to display $maxForecasts = 14; // max number of Text forecast periods to display $maxForecastLegendWords = 4; // more words in forecast legend than this number will use our forecast words $numIconsInFoldedRow = 8; // if words cause overflow of $maxWidth pixels, then put this num of icons in rows $autoSetTemplate = true; // =true set icons based on wide/narrow template design $cacheFileDir = './'; // default cache file directory $cacheName = "OWM-forecast-json.txt"; // locally cached page from OWM $refetchSeconds = 3600; // cache lifetime (3600sec = 60 minutes) // // Units: Temp,Baro,Wind,Rain,Snow,Distance // 'si' = C,hPa,m/s,mm,mm,km // 'ca' = C,hPa,km/h,mm,mm,km // 'uk' = C,mb,mph,mm,mm,km // 'us' = F,inHg,mph,in,in,km // $showUnitsAs = 'ca'; // $charsetOutput = 'ISO-8859-1'; // default character encoding of output //$charsetOutput = 'UTF-8'; // for standalone use if desired $lang = 'en'; // default language $foldIconRow = false; // =true to display icons in rows of 5 if long texts are found $timeFormat = 'Y-m-d H:i T'; // default time display format $showConditions = true; // set to true to show current conditions box // ---- end of settings --------------------------------------------------- // overrides from Settings.php if available global $SITE; if (isset($SITE['OWMforecasts'])) {$OWMforecasts = $SITE['OWMforecasts']; } if (isset($SITE['OWMAPIkey'])) {$OWMAPIkey = $SITE['OWMAPIkey']; } // new V3.00 if (isset($SITE['OWMshowUnitsAs'])) { $showUnitsAs = $SITE['OWMshowUnitsAs']; } if (isset($SITE['fcsticonsdir'])) {$iconDir = $SITE['fcsticonsdir'];} if (isset($SITE['fcsticonstype'])) {$iconType = $SITE['fcsticonstype'];} if (isset($SITE['xlateCOP'])) {$xlateCOP = $SITE['xlateCOP'];} if (isset($LANGLOOKUP['Chance of precipitation'])) { $xlateCOP = $LANGLOOKUP['Chance of precipitation']; } if (isset($SITE['charset'])) {$charsetOutput = strtoupper($SITE['charset']); } if (isset($SITE['lang'])) {$lang = $SITE['lang'];} if (isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; } if (isset($SITE['foldIconRow'])) {$foldIconRow = $SITE['foldIconRow']; } if (isset($SITE['RTL-LANG'])) {$RTLlang = $SITE['RTL-LANG']; } if (isset($SITE['timeFormat'])) {$timeFormat = $SITE['timeFormat']; } if (isset($SITE['OWMshowConditions'])) {$showConditions = $SITE['OWMshowConditions'];} // new V1.05 // end of overrides from Settings.php // // -------------------begin code ------------------------------------------ $RTLlang = ',he,jp,cn,'; // languages that use right-to-left order if (isset($_REQUEST['sce']) && strtolower($_REQUEST['sce']) == 'view' ) { //--self downloader -- $filenameReal = __FILE__; $download_size = filesize($filenameReal); header('Pragma: public'); header('Cache-Control: private'); header('Cache-Control: no-cache, must-revalidate'); header("Content-type: text/plain"); header("Accept-Ranges: bytes"); header("Content-Length: $download_size"); header('Connection: close'); readfile($filenameReal); exit; } $Status = "\n"; $OWMcurrentConditions = ''; // HTML for table of current conditions //------------------------------------------------ if(preg_match('|specify|i',$OWMAPIkey)) { print "

Note: the OWM-forecast.php script requires an API key from openweathermap.org to operate.
"; print "Visit openweathermap.org to "; print "register for an API key.

\n"; if( isset($SITE['fcsturlOWM']) ) { print "

Insert in Settings.php an entry for:

\n"; print "\$SITE['OWMAPIkey'] = 'your-key-here';

\n"; print "replacing your-key-here with your OWM API key.

\n"; } return; } $UnitsTab = array( 'si' => array('U'=>'metric','T'=>'°C','W'=>'m/s','P'=>'hPa','R'=>'mm','D'=>'km','S'=>'mm'), 'ca' => array('U'=>'metric','T'=>'°C','W'=>'km/h','P'=>'hPa','R'=>'mm','D'=>'km','S'=>'mm'), 'uk' => array('U'=>'metric','T'=>'°C','W'=>'mph','P'=>'mb','R'=>'mm','D'=>'km','S'=>'cm'), 'us' => array('U'=>'imperial','T'=>'°F','W'=>'mph','P'=>'inHg','R'=>'in','D'=>'km','S'=>'in'), ); if(isset($UnitsTab[$showUnitsAs])) { $Units = $UnitsTab[$showUnitsAs]; } else { $Units = $UnitsTab['ca']; } if(!function_exists('langtransstr')) { // shim function if not running in template set function langtransstr($input) { return($input); } } if(!function_exists('json_last_error')) { // shim function if not running PHP 5.3+ function json_last_error() { return('- N/A'); } $Status .= "\n"; if(!defined('JSON_ERROR_NONE')) { define('JSON_ERROR_NONE',0); } if(!defined('JSON_ERROR_DEPTH')) { define('JSON_ERROR_DEPTH',1); } if(!defined('JSON_ERROR_STATE_MISMATCH')) { define('JSON_ERROR_STATE_MISMATCH',2); } if(!defined('JSON_ERROR_CTRL_CHAR')) { define('JSON_ERROR_CTRL_CHAR',3); } if(!defined('JSON_ERROR_SYNTAX')) { define('JSON_ERROR_SYNTAX',4); } if(!defined('JSON_ERROR_UTF8')) { define('JSON_ERROR_UTF8',5); } } OWM_loadLangDefaults (); // set up the language defaults if($charsetOutput == 'UTF-8') { foreach ($OWMlangCharsets as $l => $cs) { $OWMlangCharsets[$l] = 'UTF-8'; } $Status .= "\n"; $Status .= "\n"; } $OWMLANG = 'en'; // Default to English for API $lang = strtolower($lang); if( isset($OWMlanguages[$lang]) ) { // if $lang is specified, use it $SITE['lang'] = $lang; $OWMLANG = $OWMlanguages[$lang]; $charsetOutput = (isset($OWMlangCharsets[$lang]))?$OWMlangCharsets[$lang]:$charsetOutput; } if(isset($_GET['lang']) and isset($OWMlanguages[strtolower($_GET['lang'])]) ) { // template override $lang = strtolower($_GET['lang']); $SITE['lang'] = $lang; $OWMLANG = $OWMlanguages[$lang]; $charsetOutput = (isset($OWMlangCharsets[$lang]))?$OWMlangCharsets[$lang]:$charsetOutput; } $doRTL = (strpos($RTLlang,$lang) !== false)?true:false; // format RTL language in Right-to-left in output if(isset($SITE['copyr']) and $doRTL) { // running in a Saratoga template. Turn off $doRTL $Status .= "\n"; $doRTL = false; } if(isset($doShowConditions)) {$showConditions = $doShowConditions;} if($doRTL) {$RTLopt = ' style="direction: rtl;"'; } else {$RTLopt = '';}; // get the selected forecast location code $haveIndex = '0'; if (!empty($_GET['z']) && preg_match("/^[0-9]+$/i", htmlspecialchars($_GET['z']))) { $haveIndex = htmlspecialchars(strip_tags($_GET['z'])); // valid zone syntax from input } if(!isset($OWMforecasts[0])) { // print "\n"; $OWMforecasts = array("Saratoga|37.27465,-122.02295"); // create default entry } // print "\n"; // Set the default zone. The first entry in the $SITE['NWSforecasts'] array. list($Nl,$Nn) = explode('|',$OWMforecasts[0].'|||'); $FCSTlocation = $Nl; $OWM_LATLONG = $Nn; if(!isset($OWMforecasts[$haveIndex])) { $haveIndex = 0; } // locations added to the drop down menu and set selected zone values $dDownMenu = ''; for ($m=0;$m".langtransstr($Nlocation)."\n"; } // build the drop down menu $ddMenu = ''; // create menu if at least two locations are listed in the array if (isset($OWMforecasts[0]) and isset($OWMforecasts[1])) { $ddMenu .= '

'; } $Force = false; if (isset($_REQUEST['force']) and $_REQUEST['force']=="1" ) { $Force = true; } $doDebug = false; if (isset($_REQUEST['debug']) and strtolower($_REQUEST['debug'])=='y' ) { $doDebug = true; } list($OWMlat,$OWMlong) = explode(',',$OWM_LATLONG); $showUnitsAs = $Units['U']; // convert to 'imperial' or 'metric' (we don't use 'standard' for API) $showTempsAs = ($showUnitsAs == 'imperial')? 'F':'C'; $Status .= "\n"; $fileName = "https://api.openweathermap.org/data/3.0/onecall?lat=$OWMlat&lon=$OWMlong&exclude=minutely" . "&units=$showUnitsAs&lang=$OWMLANG&appid=$OWMAPIkey"; if ($doDebug) { $Status .= "\n"; } if ($autoSetTemplate and isset($_SESSION['CSSwidescreen'])) { if($_SESSION['CSSwidescreen'] == true) { $maxWidth = '900px'; $maxIcons = 8; $maxForecasts = 8; $numIconsInFoldedRow = 7; $Status .= "\n"; } if($_SESSION['CSSwidescreen'] == false) { $maxWidth = '640px'; $maxIcons = 8; $maxForecasts = 8; $numIconsInFoldedRow = 7; $Status .= "\n"; } } $cacheName = $cacheFileDir . $cacheName; $cacheName = preg_replace('|\.txt|is',"-$haveIndex-$showUnitsAs-$lang.txt",$cacheName); // unique cache per units & language used $APIfileName = $fileName; if($showConditions) { $refetchSeconds = 15*60; // shorter refresh time so conditions will be 'current' } if (! $Force and file_exists($cacheName) and filemtime($cacheName) + $refetchSeconds > time()) { $html = implode('', file($cacheName)); $Status .= "\n"; } else { $Status .= "\n"; $html = OWM_fetchUrlWithoutHanging($APIfileName,false); $RC = ''; if (preg_match("|^HTTP\/\S+ (.*)\r\n|",$html,$matches)) { $RC = trim($matches[1]); } $Status .= "\n"; if (preg_match('|30\d |',$RC)) { // handle possible blocked redirect preg_match('|Location: (\S+)|is',$html,$matches); if(isset($matches[1])) { $sURL = $matches[1]; if(preg_match('|opendns.com|i',$sURL)) { $Status .= "\n"; } else { $Status .= "\n"; $html = OWM_fetchUrlWithoutHanging($sURL,false); $RC = ''; if (preg_match("|^HTTP\/\S+ (.*)\r\n|",$html,$matches)) { $RC = trim($matches[1]); } $Status .= "\n"; } } } if(strpos($RC,'200') === false) { $stuff = explode("\r\n\r\n",$html); // maybe we have more than one header due to redirects. $content = (string)array_pop($stuff); // last one is the content $headers = (string)array_pop($stuff); // next-to-last-one is the headers $rawJSON = $content; $Status .= "\n"; $JSON = json_decode($rawJSON,true); if(isset($JSON['cod']) and isset($JSON['message'])) { print $Status; print "

Error: code=".$JSON['cod']."
\n"; print "Message: ".$JSON['message']."
\n"; print "Correct the error to obtain a forecast.

\n"; } else { print "

ERROR: Raw JSON returns
\n".$rawJSON."
Correct the error to obtain forecast.

\n"; } return; } if(preg_match('!pressure!is',$html)) { $fp = fopen($cacheName, "w"); if (!$fp) { $Status .= "\n"; } else { $write = fputs($fp, $html); fclose($fp); $Status .= "\n"; } } else { $Status .= "\n"; if(file_exists($cacheName) and filesize($cacheName) > 3000) { $html = implode('', file($cacheName)); $Status .= "\n"; } else { $Status .= "\n"; print $Status; print "

Sorry.. the OpenWeatherMap forecast is not available.

\n"; return; } } } $charsetInput = 'UTF-8'; $doIconv = ($charsetInput == $charsetOutput)?false:true; // only do iconv() if sets are different if($charsetOutput == 'UTF-8') { $doIconv = false; } $Status .= "\n"; $tranTab = OWM_loadTranslate($lang); // process the file .. select out the 7-day forecast part of the page $UnSupported = false; // -------------------------------------------------------------------------------------------------- $Status .= "\n"; $stuff = explode("\r\n\r\n",$html); // maybe we have more than one header due to redirects. $content = (string)array_pop($stuff); // last one is the content $headers = (string)array_pop($stuff); // next-to-last-one is the headers $rawJSON = $content; $Status .= "\n"; $rawJSON = OWM_prepareJSON($rawJSON); $JSON = json_decode($rawJSON,true); // get as associative array $Status .= OWM_decode_JSON_error(); if($doDebug) {$Status .= "\n";} if(isset($JSON['daily'][0]['dt'])) { // got good JSON .. process it $UnSupported = false; $OWMforecastcity = $FCSTlocation; if($doIconv) {$OWMforecastcity = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$OWMforecastcity);} if($doDebug) { $Status .= "\n"; } //$OWMtitle = langtransstr("Forecast"); $OWMtitle = $tranTab['OpenWeatherMap Forecast for:']; if($doIconv) {$OWMtitle = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$OWMtitle);} if($doDebug) { $Status .= "\n"; } /* "daily": [{ "dt": 1675195200, "sunrise": 1675177924, "sunset": 1675215051, "moonrise": 1675199160, "moonset": 1675165080, "moon_phase": 0.35, "temp": { "day": 12.89, "min": 2.92, "max": 14.35, "night": 5.47, "eve": 10.3, "morn": 3.07 }, "feels_like": { "day": 10.91, "night": 5.47, "eve": 8.3, "morn": 3.07 }, "pressure": 1021, "humidity": 26, "dew_point": -5.45, "wind_speed": 1.68, "wind_deg": 12, "wind_gust": 1.82, "weather": [{ "id": 800, "main": "Clear", "description": "clear sky", "icon": "01d" } ], "clouds": 8, "pop": 0, "uvi": 2.85 }, { */ if(isset($JSON['timezone'])) { date_default_timezone_set($JSON['timezone']); $Status .= "\n"; } if(isset($JSON['daily'][0]['dt'])) { $OWMupdated = $tranTab['Updated:']; if($doIconv) { $OWMupdated = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$OWMupdated). ' '; } if(isset($JSON['hourly'][0]['dt'])) { $OWMupdated .= date($timeFormat,$JSON['hourly'][0]['dt']); } else { $OWMupdated .= date($timeFormat,$JSON['daily'][0]['dt']); } } else { $OWMupdated = ''; } if($doDebug) { $Status .= "\n\n"; } $windUnit = $Units['W']; $Status .= "\n"; if(isset($tranTab[$windUnit])) { $windUnit = $tranTab[$windUnit]; $Status .= "\n"; } $n = 0; foreach ($JSON['daily'] as $i => $FCpart) { # process each daily entry list($tDay,$tTime) = explode(" ",date('l H:i:s',$FCpart['dt'])); if ($doDebug) { $Status .= "\n"; } $OWMforecastdayname[$n] = $tDay; if(isset($tranTab[$tDay])) { $OWMforecastday[$n] = $tranTab[$tDay]; } else { $OWMforecastday[$n] = $tDay; } if($doIconv) { $OWMforecastday[$n] = iconv("UTF-8",$charsetOutput.'//IGNORE',$OWMforecastday[$n]); } $OWMforecasttitles[$n] = $OWMforecastday[$n]; if ($doDebug) { $Status .= "\n"; } $OWMforecastcloudcover[$n] = $FCpart['clouds']; # extract the temperatures $OWMforecasttemp[$n] = "".OWM_round($FCpart['temp']['max'],0)."°$showTempsAs"; $OWMforecasttemp[$n] .= "
".OWM_round($FCpart['temp']['min'],0)."°$showTempsAs"; # extract the icon to use $OWMforecasticon[$n] = $FCpart['weather'][0]['icon']; if ($doDebug) { $Status .= "\n"; } $OWMforecastcode[$n] = $FCpart['weather'][0]['id']; if ($doDebug) { $Status .= "\n"; } if(isset($FCpart['pop'])) { $OWMforecastpop[$n] = round($FCpart['pop']*100,-1); } else { $OWMforecastpop[$n] = 0; } if ($doDebug) { $Status .= "\n"; } if(isset($FCpart['rain'])) { $OWMforecastpreciptype[$n] = 'rain,'; } else { $OWMforecastpreciptype[$n] = ''; } if(isset($FCpart['snow'])) { $OWMforecastpreciptype[$n] .= 'snow,'; } $OWMforecasttext[$n] = // replace problematic characters in forecast text str_replace( array('<', '>', '–','cm.','in.','.)'), array('<','>','-', 'cm', 'in',')'), trim($FCpart['weather'][0]['description'])). '. '; # Add info to the forecast text if($OWMforecastpop[$n] > 0) { $tstr = ''; if(!empty($OWMforecastpreciptype[$n])) { $t = explode(',',$OWMforecastpreciptype[$n].','); foreach ($t as $k => $ptype) { if(!empty($ptype)) { if($ptype == 'rain') {$useUnit = $Units['R'];} else {$useUnit = $Units['S'];} $tstr .= $tranTab[$ptype].' '.OWM_rain_convert($FCpart[$ptype],$useUnit).$useUnit.','; } } } if(strlen($tstr)>0) { $tstr = ' ('.substr($tstr,0,strlen($tstr)-1) .').'; } else { $tstr = '.'; } $OWMforecasttext[$n] .= " ". $tranTab['Chance of precipitation']." ".$OWMforecastpop[$n]."%$tstr"; } $OWMforecasttext[$n] .= " ".$tranTab['High:']." ".OWM_round($FCpart['temp']['max'],0)."°$showTempsAs. "; $OWMforecasttext[$n] .= " ".$tranTab['Low:']." ".OWM_round($FCpart['temp']['min'],0)."°$showTempsAs. "; $tWdir = OWM_WindDir(round($FCpart['wind_deg'],0)); $OWMforecasttext[$n] .= " ".$tranTab['Wind']." ".OWM_WindDirTrans($tWdir); $OWMforecasttext[$n] .= " ". OWM_wind_convert($FCpart['wind_speed'],$Units['W'])."->".OWM_wind_convert($FCpart['wind_gust'],$Units['W']) . " $windUnit."; if(isset($FCpart['uvi']) and $FCpart['uvi'] > 1) { $OWMforecasttext[$n] .= " ".$tranTab['UV index']." ".round($FCpart['uvi'],0)."."; } if($doIconv) { $OWMforecasttext[$n] = iconv("UTF-8",$charsetOutput.'//IGNORE',$OWMforecasttext[$n]); } if ($doDebug) { $Status .= "\n"; } $OWMforecastcond[$n] = $FCpart['weather'][0]['description']; if($doIconv) { $OWMforecastcond[$n] = iconv("UTF-8",$charsetOutput.'//IGNORE',$OWMforecastcond[$n]); } if ($doDebug) { $Status .= "\n"; } $OWMforecasticons[$n] = $OWMforecastday[$n] . "
" . OWM_img_replace( $OWMforecasticon[$n], $FCpart['weather'][0]['description'], $OWMforecastpop[$n], $OWMforecastcloudcover[$n], $OWMforecastcode[$n]) . "
" . $OWMforecastcond[$n]; $n++; } // end of process text forecasts // process alerts if any are available $OWMforecastwarnings = ''; if (isset($JSON['alerts']) and is_array($JSON['alerts']) and count($JSON['alerts']) > 0) { $Status.= "\n"; foreach($JSON['alerts'] as $i => $ALERT) { $expireUTC = $ALERT['end']; $expires = date('Y-m-d H:i T',$ALERT['end']); $Status.= "\n"; $regions = ''; if(isset($ALERT['regions']) and is_array($ALERT['regions'])) { foreach ($ALERT['regions'] as $i => $reg) { $regions .= $reg . ', '; } $regions = substr($regions,0,strlen($regions)-2); } if (time() < $expireUTC) { $OWMforecastwarnings .= '' . '' . $ALERT['event'] . "
\n"; } else { #$Status.= "\n"; } } } else { $Status.= "\n"; } // make the Current conditions table from $currently array $currently = $JSON['current']; /* "current": { "dt": 1675204434, "sunrise": 1675177924, "sunset": 1675215051, "temp": 14.35, "feels_like": 12.44, "pressure": 1020, "humidity": 23, "dew_point": -5.77, "uvi": 1.1, "clouds": 20, "visibility": 10000, "wind_speed": 2.57, "wind_deg": 300, "weather": [{ "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02d" } ] }, */ $nCols = 3; // number of columns in the conditions table if (isset($currently['dt']) ) { // only generate if we have the data if (isset($currently['weather'][0]['icon']) and ! $currently['weather'][0]['icon'] ) { $nCols = 2; }; $OWMcurrentConditions = '' . "\n"; $OWMcurrentConditions .= ' ' . "\n\n"; if (isset($currently['weather'][0]['icon'])) { $OWMcurrentConditions .= ' '; } // end of icon $OWMcurrentConditions .= " '; $OWMcurrentConditions .= ' '; if(isset($JSON['daily']['summary'])) { if($doRTL) { $OWMcurrentConditions .= ' '; } else { $OWMcurrentConditions .= ' '; } } $OWMcurrentConditions .= '
' . $tranTab['Currently'].': '. date($timeFormat,$currently['dt']) . "
\n"; # $t = $tranTab['Weather conditions at 999 from forecast point.']; # $t = str_replace('999',round($JSON['flags']['nearest-station'],1).' '.$Units['D'],$t); $OWMcurrentConditions .= '
' . OWM_img_replace( $currently['weather'][0]['icon'], $currently['weather'][0]['description'], 0, $currently['clouds'], $currently['weather'][0]['id']) . "
\n" . $currently['weather'][0]['description']; $OWMcurrentConditions .= '
\n"; if (isset($currently['temp'])) { $OWMcurrentConditions .= $tranTab['Temperature'].": ". OWM_round($currently['temp'],0) . $Units['T'] . "
\n"; } if (isset($currently['wind_chill'])) { $OWMcurrentConditions .= $tranTab['Wind chill'].": ". OWM_round($currently['wind_chill'],0) . $Units['T']. "
\n"; } if (isset($currently['heat_index'])) { $OWMcurrentConditions .= $tranTab['Heat index'].": " . OWM_round($currently['heat_index']) . $Units['T']. "
\n"; } if (isset($currently['wind_speed'])) { $tWdir = OWM_WindDir(round($currently['wind_deg'],0)); $OWMcurrentConditions .= $tranTab['Wind'].": ".OWM_WindDirTrans($tWdir); $OWMcurrentConditions .= " ".OWM_wind_convert($currently['wind_speed'],$Units['W']); if(isset($currently['wind_gust'])) { $OWMcurrentConditions .= "->".OWM_wind_convert($currently['wind_gust'],$Units['W']); } $OWMcurrentConditions .= " $windUnit.
\n"; } if (isset($currently['humidity'])) { $OWMcurrentConditions .= $tranTab['Humidity'].": ". round($currently['humidity'],1) . "%
\n"; } if (isset($currently['dew_point'])) { $OWMcurrentConditions .= $tranTab['Dew Point'].": ". OWM_round($currently['dew_point'],0) . $Units['T'] . "
\n"; } $OWMcurrentConditions .= $tranTab['Barometer'].": ". OWM_conv_baro($currently['pressure']) . " " . $Units['P'] . "
\n"; if (isset($currently['visibility'])) { $OWMcurrentConditions .= $tranTab['Visibility'].": ". round($currently['visibility'] / 1000.0,1) . " " . $Units['D']. "\n" ; } if (isset($currently['uvi'])) { $OWMcurrentConditions .= '
'.$tranTab['UV index'].": ". round($currently['uvi'],0) . "\n" ; } $OWMcurrentConditions .= '
'; if(isset($JSON['daily'][0]['sunrise']) and isset($JSON['daily'][0]['sunset']) ) { $OWMcurrentConditions .= $tranTab['Sunrise'].': '. date('H:i',$JSON['daily'][0]['sunrise']) . "
\n" . $tranTab['Sunset'].': '. date('H:i',$JSON['daily'][0]['sunset']) . "
\n" ; } $OWMcurrentConditions .= '
' . $JSON['daily']['summary'] . '
' . $JSON['daily']['summary'] . '
'; if($doIconv) { $OWMcurrentConditions = iconv('UTF-8',$charsetOutput.'//TRANSLIT',$OWMcurrentConditions); } } // end of if isset($currently['cityobserved']) // end of current conditions mods if(isset($JSON['hourly'][0]['dt'])) { // process Hourly forecast data /* "hourly": { "summary": "Mostly cloudy throughout the day.", "icon": "partly-cloudy-night", "data": [{ "time": 1548018000, "summary": "Mostly Cloudy", "icon": "partly-cloudy-day", "precipIntensity": 0.1422, "precipProbability": 0.29, "precipType": "rain", "temperature": 14.91, "apparentTemperature": 14.91, "dewPoint": 11.49, "humidity": 0.8, "pressure": 1017.89, "windSpeed": 10.8, "windGust": 24.54, "windBearing": 226, "cloudCover": 0.88, "uvIndex": 2, "visibility": 14.11, "ozone": 289.95 }, { */ foreach($JSON['hourly'] as $i => $FCpart) { $OWMforecasticonHR[$i] = OWM_gen_hourforecast($FCpart); if($doIconv) { $OWMforecasticonHR[$i]['icon'] = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$OWMforecasticonHR[$i]['icon']). ' '; $OWMforecasticonHR[$i]['temp'] = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$OWMforecasticonHR[$i]['temp']). ' '; $OWMforecasticonHR[$i]['wind'] = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$OWMforecasticonHR[$i]['wind']). ' '; $OWMforecasticonHR[$i]['precip'] = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$OWMforecasticonHR[$i]['precip']). ' '; } if($doDebug) { $Status .= "\n"; } } // end each hourly forecast parsing } // end process hourly forecast data } // end got good JSON decode/process // end process JSON style -------------------------------------------------------------------- // All finished with parsing, now prepare to print $wdth = intval(100/count($OWMforecasticons)); $ndays = intval(count($OWMforecasticon)/2); $doNumIcons = $maxIcons; if(count($OWMforecasticons) < $maxIcons) { $doNumIcons = count($OWMforecasticons); } $IncludeMode = false; $PrintMode = true; if (isset($doPrintOWM) && ! $doPrintOWM ) { print $Status; return; } if (isset($_REQUEST['inc']) && strtolower($_REQUEST['inc']) == 'noprint' ) { print $Status; return; } if (isset($_REQUEST['inc']) && strtolower($_REQUEST['inc']) == 'y') { $IncludeMode = true; } if (isset($doIncludeOWM)) { $IncludeMode = $doIncludeOWM; } $printHeading = true; $printIcons = true; $printText = true; if (isset($doPrintHeadingOWM)) { $printHeading = $doPrintHeadingOWM; } if (isset($_REQUEST['heading']) ) { $printHeading = substr(strtolower($_REQUEST['heading']),0,1) == 'y'; } if (isset($doPrintIconsOWM)) { $printIcons = $doPrintIconsOWM; } if (isset($_REQUEST['icons']) ) { $printIcons = substr(strtolower($_REQUEST['icons']),0,1) == 'y'; } if (isset($doPrintTextOWM)) { $printText = $doPrintTextOWM; } if (isset($_REQUEST['text']) ) { $printText = substr(strtolower($_REQUEST['text']),0,1) == 'y'; } if (! $IncludeMode and $PrintMode) { ?> <?php echo $OWMtitle . ' - ' . $OWMforecastcity; ?> Sorry.. this forecast can not be processed at this time. EONAG ; } if (strlen($OWMforecasttext[0])<2 and $PrintMode and ! $UnSupported ) { echo '

'.langtransstr('Forecast blank?').' ' . langtransstr('Force Update').'

'; } if ($PrintMode and ($printHeading or $printIcons)) { ?> \n"; } ?>
\n"; print $OWMcurrentConditions; print "
0) { echo "
$OWMupdated\n"; } ?>

 

\n"; $maxChars = 135; if($iTitleLen >= $maxChars or $iCondLen >= $maxChars or $iTempLen >= $maxChars ) { print "\n"; $doFoldRow = true; } } $startIcon = 0; $finIcon = $doNumIcons; $incr = $doNumIcons; $doFoldRow = false; if ($doFoldRow) { $wdth = $wdth*2; $incr = $numIconsInFoldedRow; } print "\n"; for ($k=$startIcon;$k<$doNumIcons-1;$k+=$incr) { // loop over icon rows, 5 at a time until done $startIcon = $k; if ($doFoldRow) { $finIcon = $startIcon+$numIconsInFoldedRow; } else { $finIcon = $doNumIcons; } $finIcon = min($finIcon,$doNumIcons); print "\n"; print " \n"; for ($i=$startIcon;$i<$finIcon;$i++) { $ni = $doRTL?$numIconsInFoldedRow-1-$i+$startIcon+$k:$i; print "\n"; print "\n"; } print " \n"; print " \n"; for ($i=$startIcon;$i<$finIcon;$i++) { $ni = $doRTL?$numIconsInFoldedRow-1-$i+$startIcon+$k:$i; print "\n"; } ?> $OWMforecastcond[$ni]\n"; } print " \n"; print " \n"; for ($i=$startIcon;$i<$finIcon;$i++) { $ni = $doRTL?$numIconsInFoldedRow-1-$i+$startIcon+$k:$i; print "\n"; } ?> \n"; for ($i=$startIcon;$i<$finIcon;$i++) { $ni = $doRTL?$numIconsInFoldedRow-1-$i+$startIcon+$k:$i; print "\n"; } ?> \n"; for ($i=$startIcon;$i<$finIcon;$i++) { print "\n"; } print "\n"; } // end doFoldRow ?>
$OWMforecasttitles[$ni]
" . OWM_img_replace($OWMforecasticon[$ni], $OWMforecastcond[$ni], $OWMforecastpop[$ni], $OWMforecastcloudcover[$ni], $OWMforecastcode[$ni]) . "
$OWMforecasttemp[$ni]
"; if($OWMforecastpop[$ni] > 0) { print "PoP: $OWMforecastpop[$ni]%"; } else { print " "; } print "
 

'') { if($doIconv) { $OWMforecastwarnings = iconv($charsetInput,$charsetOutput.'//IGNORE',$OWMforecastwarnings); } $tW = 'width: 640px;'; if($doRTL) {$tW .= 'direction: rtl;';} print "

$OWMforecastwarnings

\n"; } ?>
\n"; if(!$doRTL) { // normal Left-to-right print "\n"; print "\n"; } else { // print RTL format print "\n"; print "\n"; } print "\n"; } ?>
$OWMforecasttitles[$i]
 
$OWMforecasttext[$i]$OWMforecasttext[$i]$OWMforecasttitles[$i]
 

\n"; for ($n=$row*8;$n<$row*8+8;$n++) { $ni = $doRTL?($row+1)*8-$n-1+($row*8):$n; if(isset($OWMforecasticonHR[$ni]['icon'])) { print '";; } else { print ""; } } print "\n"; print " \n"; for ($n=$row*8;$n<$row*8+8;$n++) { $ni = $doRTL?($row+1)*8-$n-1+($row*8):$n; if(isset($OWMforecasticonHR[$ni]['temp'])) { print '";; } else { print ""; } } print "\n"; print " \n"; for ($n=$row*8;$n<$row*8+8;$n++) { $ni = $doRTL?($row+1)*8-$n-1+($row*8):$n; if(isset($OWMforecasticonHR[$ni]['UV'])) { print '";; } else { print ""; } } print "\n"; print " \n"; for ($n=$row*8;$n<$row*8+8;$n++) { $ni = $doRTL?($row+1)*8-$n-1+($row*8):$n; if(isset($OWMforecasticonHR[$ni]['wind'])) { print '";; } else { print ""; } } print "\n"; print " \n"; for ($n=$row*8;$n<$row*8+8;$n++) { $ni = $doRTL?($row+1)*8-$n-1+($row*8):$n; if(isset($OWMforecasticonHR[$ni]['precip'])) { print '";; } else { print ""; } } print "\n"; print "\n"; } // end rows ?>
'.$OWMforecasticonHR[$ni]['icon']." 
'.$OWMforecasticonHR[$ni]['temp']." 
'.$OWMforecasticonHR[$ni]['UV']." 
'.$OWMforecasticonHR[$ni]['wind']." 
'.$OWMforecasticonHR[$ni]['precip']." 

 

openweathermap.org. '.jpg') { print "
".langtransstr('Animated forecast icons courtesy of')." www.meteotreviglio.com."; } print "

\n"; ?> \n"; $ch = curl_init(); // initialize a cURL session curl_setopt($ch, CURLOPT_URL, $theURL); // connect to provided URL curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // don't verify peer certificate curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (OWM-forecast.php - saratoga-weather.org)'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $numberOfSeconds); // connection timeout curl_setopt($ch, CURLOPT_TIMEOUT, $numberOfSeconds); // data timeout curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the data transfer curl_setopt($ch, CURLOPT_NOBODY, false); // set nobody curl_setopt($ch, CURLOPT_HEADER, true); // include header information if (isset($needCookie[$domain])) { curl_setopt($ch, $needCookie[$domain]); // set the cookie for this request curl_setopt($ch, CURLOPT_COOKIESESSION, true); // and ignore prior cookies $Status .= "\n"; } $data = curl_exec($ch); // execute session if(curl_error($ch) <> '') { // IF there is an error $Status .= "\n"; // display error notice } $cinfo = curl_getinfo($ch); // get info on curl exec. /* curl info sample Array ( [url] => http://saratoga-weather.net/clientraw.txt [content_type] => text/plain [http_code] => 200 [header_size] => 266 [request_size] => 141 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.125 [namelookup_time] => 0.016 [connect_time] => 0.063 [pretransfer_time] => 0.063 [size_upload] => 0 [size_download] => 758 [speed_download] => 6064 [speed_upload] => 0 [download_content_length] => 758 [upload_content_length] => -1 [starttransfer_time] => 0.125 [redirect_time] => 0 [redirect_url] => [primary_ip] => 74.208.149.102 [certinfo] => Array ( ) [primary_port] => 80 [local_ip] => 192.168.1.104 [local_port] => 54156 ) */ $Status .= "\n"; //$Status .= "\n"; curl_close($ch); // close the cURL session //$Status .= "\n"; $i = strpos($data,"\r\n\r\n"); $headers = substr($data,0,$i); $content = substr($data,$i+4); if($cinfo['http_code'] <> 200) { $Status .= "\n"; } return $data; // return headers+contents } else { // print "\n"; $STRopts = array( 'http'=>array( 'method'=>"GET", 'protocol_version' => 1.1, 'header'=>"Cache-Control: no-cache, must-revalidate\r\n" . "Cache-control: max-age=0\r\n" . "Connection: close\r\n" . "User-agent: Mozilla/5.0 (OWM-forecast.php - saratoga-weather.org)\r\n" . "Accept: text/plain,text/html\r\n" ), 'https'=>array( 'method'=>"GET", 'protocol_version' => 1.1, 'header'=>"Cache-Control: no-cache, must-revalidate\r\n" . "Cache-control: max-age=0\r\n" . "Connection: close\r\n" . "User-agent: Mozilla/5.0 (OWM-forecast.php - saratoga-weather.org)\r\n" . "Accept: text/plain,text/html\r\n" ) ); $STRcontext = stream_context_create($STRopts); $T_start = OWM_fetch_microtime(); $xml = file_get_contents($url,false,$STRcontext); $T_close = OWM_fetch_microtime(); $headerarray = get_headers($url,0); $theaders = join("\r\n",$headerarray); $xml = $theaders . "\r\n\r\n" . $xml; $ms_total = sprintf("%01.3f",round($T_close - $T_start,3)); $Status .= "\n"; $Status .= "<-- get_headers returns\n".$theaders."\n -->\n"; // print " file() stats: total=$ms_total secs.\n"; $overall_end = time(); $overall_elapsed = $overall_end - $overall_start; $Status .= "\n"; // print "fetch function elapsed= $overall_elapsed secs.\n"; return($xml); } } // end OWM_fetch_URL // ------------------------------------------------------------------ function OWM_fetch_microtime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } // ------------------------------------------------------------------------------------------- function OWM_prepareJSON($input) { global $Status; //This will convert ASCII/ISO-8859-1 to UTF-8. //Be careful with the third parameter (encoding detect list), because //if set wrong, some input encodings will get garbled (including UTF-8!) list($isUTF8,$offset,$msg) = OWM_check_utf8($input); if(!$isUTF8) { $Status .= "\n"; $str = utf8_encode($input); list($isUTF8,$offset,$msg) = OWM_check_utf8($str); $Status .= "\n"; } else { $Status .= "\n"; $str = $input; } //Remove UTF-8 BOM if present, json_decode() does not like it. if(substr($str, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $str = substr($str, 3); return $str; } // ------------------------------------------------------------------------------------------- function OWM_check_utf8($str) { // check all the characters for UTF-8 compliance so json_decode() won't choke // Sometimes, an ISO international character slips in the OWM text string. $len = strlen($str); for($i = 0; $i < $len; $i++){ $c = ord($str[$i]); if ($c > 128) { if (($c > 247)) return array(false,$i,"c>247 c='$c'"); elseif ($c > 239) $bytes = 4; elseif ($c > 223) $bytes = 3; elseif ($c > 191) $bytes = 2; else return false; if (($i + $bytes) > $len) return array(false,$i,"i+bytes>len bytes=$bytes,len=$len"); while ($bytes > 1) { $i++; $b = ord($str[$i]); if ($b < 128 || $b > 191) return array(false,$i,"128191 b=$b"); $bytes--; } } } return array(true,$i,"Success. Valid UTF-8"); } // end of check_utf8 // ------------------------------------------------------------------------------------------- function OWM_decode_JSON_error() { $Status = ''; $Status .= "\n"; return($Status); } // ------------------------------------------------------------------------------------------- function OWM_fixup_text($text) { global $Status; // attempt to convert Imperial forecast temperatures to Metric in the text forecast if(preg_match_all('!([-|\d]+)([ º]*F)!s',$text,$m)) { //$newtext = str_replace('ºF','F',$text); $newtext = $text; foreach ($m[1] as $i => $tF) { $tI = $m[2][$i]; $tC = (float)(($tF - 32) / 1.8 ); $tC = round($tC,0); // $newtext = str_replace("{$tF}F","{$tC}C({$tF}F)",$newtext); $newtext = str_replace("{$tF}{$tI}","{$tC}C",$newtext); $Status .= "\n"; } return($newtext); } else { return($text); // no changes } } // ------------------------------------------------------------------------------------------- function OWM_loadLangDefaults () { global $OWMlanguages, $OWMlangCharsets; /* af Afrikaans al Albanian ar Arabic az Azerbaijani bg Bulgarian ca Catalan cz Czech da Danish de German el Greek en English eu Basque fa Persian (Farsi) fi Finnish fr French gl Galician he Hebrew hi Hindi hr Croatian hu Hungarian id Indonesian it Italian ja Japanese kr Korean la Latvian lt Lithuanian mk Macedonian no Norwegian nl Dutch pl Polish pt Portuguese pt_br Português Brasil ro Romanian ru Russian sv, se Swedish sk Slovak sl Slovenian sp, es Spanish sr Serbian th Thai tr Turkish ua, uk Ukrainian vi Vietnamese zh_cn Chinese Simplified zh_tw Chinese Traditional zu Zulu */ $OWMlanguages = array( // our template language codes v.s. lang:LL codes for JSON 'af' => 'af', 'bg' => 'bg', 'cs' => 'cz', 'ct' => 'ca', 'dk' => 'da', 'nl' => 'nl', 'en' => 'en', 'fi' => 'fi', 'fr' => 'fr', 'de' => 'de', 'el' => 'el', 'ga' => 'en', 'it' => 'it', 'he' => 'he', 'hu' => 'hu', 'no' => 'no', 'pl' => 'pl', 'pt' => 'pt', 'ro' => 'ro', 'es' => 'es', 'se' => 'sv', 'si' => 'sl', 'sk' => 'sk', 'sr' => 'sr', ); $OWMlangCharsets = array( 'bg' => 'ISO-8859-5', 'cs' => 'ISO-8859-2', 'el' => 'ISO-8859-7', 'he' => 'UTF-8', 'hu' => 'ISO-8859-2', 'ro' => 'ISO-8859-2', 'pl' => 'ISO-8859-2', 'si' => 'ISO-8859-2', 'sk' => 'Windows-1250', 'sr' => 'Windows-1250', 'ru' => 'ISO-8859-5', ); } // end loadLangDefaults // ------------------------------------------------------------------------------------------- function OWM_loadTranslate ($lang) { global $Status; /* Note: We packed up the translation array as it is a mix of various character set types and editing the raw text can easily change the character presentation. The TRANTABLE was created by using $transSerial = serialize($transArray); $b64 = base64_encode($transSerial); print "\n"; $tArr = str_split($b64,72); print "define('TRANTABLE',\n'"; $tStr = ''; foreach($tArr as $rec) { $tStr .= $rec."\n"; } $tStr = trim($tStr); print $tStr; print "'); // end of TRANTABLE encoded\n"; and that result included here. It will reconstitute with unserialize(base64_decode(TRANTABLE)) to look like: ... 'dk' => array ( 'charset' => 'ISO-8859-1', 'Sunday' => 'Søndag', 'Monday' => 'Mandag', 'Tuesday' => 'Tirsdag', 'Wednesday' => 'Onsdag', 'Thursday' => 'Torsdag', 'Friday' => 'Fredag', 'Saturday' => 'Lørdag', 'Sunday night' => 'Søndag nat', 'Monday night' => 'Mandag nat', 'Tuesday night' => 'Tirsdag nat', 'Wednesday night' => 'Onsdag nat', 'Thursday night' => 'Torsdag nat', 'Friday night' => 'Fredag nat', 'Saturday night' => 'Lørdag nat', 'Today' => 'I dag', 'Tonight' => 'I nat', 'This afternoon' => 'I eftermiddag', 'Rest of tonight' => 'Resten af natten', ), // end dk ... and the array for the chosen language will be returned, or the English version if the language is not in the array. */ if(!file_exists("OWM-forecast-lang.php")) { print "

Warning: OWM-forecast-lang.php translation file was not found. It is required"; print " to be in the same directory as OWM-forecast.php.

\n"; exit; } include_once("OWM-forecast-lang.php"); $default = array( 'charset' => 'ISO-8859-1', 'Sunday' => 'Sunday', 'Monday' => 'Monday', 'Tuesday' => 'Tuesday', 'Wednesday' => 'Wednesday', 'Thursday' => 'Thursday', 'Friday' => 'Friday', 'Saturday' => 'Saturday', 'Sunday night' => 'Sunday night', 'Monday night' => 'Monday night', 'Tuesday night' => 'Tuesday night', 'Wednesday night' => 'Wednesday night', 'Thursday night' => 'Thursday night', 'Friday night' => 'Friday night', 'Saturday night' => 'Saturday night', 'Today' => 'Today', 'Tonight' => 'Tonight', 'This afternoon' => 'This afternoon', 'Rest of tonight' => 'Rest of tonight', 'High:' => 'High:', 'Low:' => 'Low:', 'Updated:' => 'Updated:', 'OpenWeatherMap Forecast for:' => 'OpenWeatherMap Forecast for:', 'NESW' => 'NESW', // cardinal wind directions 'Wind' => 'Wind', 'UV index' => 'UV Index', 'Chance of precipitation' => 'Chance of precipitation', 'mph' => 'mph', 'kph' => 'km/h', 'mps' => 'm/s', 'Temperature' => 'Temperature', 'Barometer' => 'Barometer', 'Dew Point' => 'Dew Point', 'Humidity' => 'Humidity', 'Visibility' => 'Visibility', 'Wind chill' => 'Wind chill', 'Heat index' => 'Heat index', 'Humidex' => 'Humidex', 'Sunrise' => 'Sunrise', 'Sunset' => 'Sunset', 'Currently' => 'Currently', 'rain' => 'rain', 'snow' => 'snow', 'sleet' => 'sleet', 'Weather conditions at 999 from forecast point.' => 'Weather conditions at 999 from forecast point.', 'Daily Forecast' => 'Daily Forecast', 'Hourly Forecast' => 'Hourly Forecast', 'Meteogram' => 'Meteogram', ); $t = unserialize(base64_decode(TRANTABLE)); if(isset($t[$lang])) { $Status .= "\n"; return($t[$lang]); } else { $Status .= "\n"; return($default); } } // ------------------------------------------------------------------ function OWM_WindDir ($degrees) { // convert degrees into wind direction abbreviation // figure out a text value for compass direction // Given the wind direction, return the text label // for that value. 16 point compass $winddir = $degrees; if ($winddir == "n/a") { return($winddir); } if (!isset($winddir)) { return "---"; } if (!is_numeric($winddir)) { return($winddir); } $windlabel = array ("N","NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW","SW", "WSW", "W", "WNW", "NW", "NNW"); $dir = $windlabel[ (integer)fmod((($winddir + 11) / 22.5),16) ]; return($dir); } // end function OWM_WindDir // ------------------------------------------------------------------ function OWM_WindDirTrans($inwdir) { global $tranTab, $Status; $wdirs = $tranTab['NESW']; // default directions $tstr = $inwdir; $Status .= "\n"; return($tstr); } // ------------------------------------------------------------------ function OWM_round($item,$dp) { $t = round($item,$dp); if ($t == '-0') { $t = 0; } return ($t); } // ------------------------------------------------------------------ function OWM_octets ($coverage) { global $Status; $octets = round($coverage*100 / 12.5,1); $Status .= "\n"; return('skc'); } elseif ($octets < 3.0) { $Status .= " clouds=few -->\n"; return('few'); } elseif ($octets < 5.0) { $Status .= " clouds=sct -->\n"; return('sct'); } elseif ($octets < 8.0) { $Status .= " clouds=bkn -->\n"; return('bkn'); } else { $Status .= " clouds=ovc -->\n"; return('ovc'); } } // ------------------------------------------------------------------ function OWM_conv_baro($hPa) { # even 'us' imperial returns pressure in hPa so we need to convert global $showUnitsAs; if($showUnitsAs == 'imperial') { $t = (float)$hPa * 0.02952998751; return(sprintf("%01.2f",$t)); } else { return( sprintf("%01.1f",$hPa) ); } } // ------------------------------------------------------------------ function OWM_gen_hourforecast($FCpart) { global $doDebug,$Status,$showTempsAs,$tranTab,$windUnit,$Units,$showUnitsAs; /* $FCpart = "hourly": [ { "dt": 1675206000, "temp": 13.77, "feels_like": 11.88, "pressure": 1020, "humidity": 26, "dew_point": -4.77, "uvi": 1.1, "clouds": 16, "visibility": 10000, "wind_speed": 1.68, "wind_deg": 12, "wind_gust": 1.82, "weather": [ { "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02d" } ], "pop": 0 }, */ $OWMH = array(); //$newIcon = ''; if($showUnitsAs == 'imperial') { $t = explode(' ',date('g:ia n/j l',$FCpart['dt'])); } else { $t = explode(' ',date('H:i j/n l',$FCpart['dt'])); } $newIcon = ''.$t[0].'
'.$tranTab[$t[2]]."

\n"; $cloudcover = $FCpart['clouds']; if(isset($FCpart['pop'])) { $pop = round($FCpart['pop']*100,-1); } else { $pop = 0; } $temp = explode('.',$FCpart['weather'][0]['description'].'.'); // split as sentences (sort of). $condition = trim($temp[0]); // take first one as summary. $icon = $FCpart['weather'][0]['icon']; $code = $FCpart['weather'][0]['id']; $newIcon .= "
" . OWM_img_replace( $icon,$condition,$pop,$cloudcover,$code) . "
" . $condition; $OWMH['icon'] = $newIcon; $OWMH['temp'] = ''.OWM_round($FCpart['temp'],0)."°$showTempsAs"; $OWMH['UV'] = 'UV: '.$FCpart['uvi'].""; $tWdir = OWM_WindDir(round($FCpart['wind_deg'],0)); $OWMH['wind'] = $tranTab['Wind']." ".OWM_WindDirTrans($tWdir); $OWMH['wind'] .= " ". OWM_wind_convert($FCpart['wind_speed'],$Units['W'])."->".OWM_wind_convert($FCpart['wind_gust'],$Units['W']) . " $windUnit\n"; $preciptype = ''; if(isset($FCpart['rain']['1h'])) { $preciptype .= $tranTab['rain'] . ': '. OWM_rain_convert($FCpart['rain']['1h'],$Units['R']) . $Units['R'].','; } if(isset($FCpart['snow']['1h'])) { $preciptype .= $tranTab['snow'] . ': '. OWM_rain_convert($FCpart['snow']['1h'],$Units['S']) . $Units['S'].','; } $accum = ''; if($pop > 0) { if(!empty($preciptype)) { $t = explode(',',$preciptype.','); foreach ($t as $k => $ptype) { if(!empty($ptype)) { $accum = ' ' . $ptype.""; } } } } $OWMH['precip'] = "$accum"; //$newIcon .= "\n"; return($OWMH); } // ------------------------------------------------------------------ Function OWM_rain_convert($in,$unit) { // input is always in MM if(strpos($unit,'in') !== false) { return (sprintf("%01.2f",round($in/25.4,2))); } elseif(strpos($unit,'cm') !== false) { return(sprintf("%01.1f",round($in,1)/10.0)); } else { return (sprintf("%01.1f",round($in,1))); } } // ------------------------------------------------------------------ function OWM_img_replace ( $OWMimage, $OWMcondtext,$OWMpop,$OWMcloudcover,$code) { global $NWSiconlist,$iconDir,$iconType,$Status; list($dayicon,$nighticon) = OWM_code_to_icon($code); $curicon = (strpos($OWMimage,'n') !== false)?$nighticon:$dayicon; if (!$curicon) { // no change.. use OWM icon return(""); } if($iconType <> '.jpg') { $curicon = preg_replace('|\.jpg|',$iconType,$curicon); } $Status .= "\n"; return("\"$OWMcondtext\""); } // ------------------------------------------------------------------------------------------- function OWM_wind_convert ($in,$unit) { global $showUnitsAs; if ($showUnitsAs == 'imperial') { return(round($in,0)); } switch ($unit) { case '': return(round($in,0)); break; case 'm/s': return(round($in,1)); break; case 'km/h': return(round($in*3.6,0)); break; case 'mph': return(round($in*2.237,0)); break; default: return(round($in,0)); } return(round($in,1)); // for standard in m/s } // ------------------------------------------------------------------------------------------- function OWM_code_to_icon($code) { $Codes = array( // ID Main Description Icon '200' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm thunderstorm with light rain 11d '201' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm thunderstorm with rain 11d '202' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm thunderstorm with heavy rain 11d '210' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm light thunderstorm 11d '211' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm thunderstorm 11d '212' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm heavy thunderstorm 11d '221' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm ragged thunderstorm 11d '230' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm thunderstorm with light drizzle 11d '231' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm thunderstorm with drizzle 11d '232' => array('tsra.jpg','ntsra.jpg'), // Thunderstorm thunderstorm with heavy drizzle 11d '300' => array('ra.jpg','nra.jpg'), // Drizzle light intensity drizzle 09d '301' => array('ra.jpg','nra.jpg'), // Drizzle drizzle 09d '302' => array('ra.jpg','nra.jpg'), // Drizzle heavy intensity drizzle 09d '310' => array('ra.jpg','nra.jpg'), // Drizzle light intensity drizzle rain 09d '311' => array('ra.jpg','nra.jpg'), // Drizzle drizzle rain 09d '312' => array('ra.jpg','nra.jpg'), // Drizzle heavy intensity drizzle rain 09d '313' => array('ra.jpg','nra.jpg'), // Drizzle shower rain and drizzle 09d '314' => array('ra.jpg','nra.jpg'), // Drizzle heavy shower rain and drizzle 09d '321' => array('ra.jpg','nra.jpg'), // Drizzle shower drizzle 09d '500' => array('ra.jpg','nra.jpg'), // Rain light rain 10d '501' => array('ra.jpg','nra.jpg'), // Rain moderate rain 10d '502' => array('ra.jpg','nra.jpg'), // Rain heavy intensity rain 10d '503' => array('ra.jpg','nra.jpg'), // Rain very heavy rain 10d '504' => array('ra.jpg','nra.jpg'), // Rain extreme rain 10d '511' => array('ra.jpg','nra.jpg'), // Rain freezing rain 13d '520' => array('ra.jpg','nra.jpg'), // Rain light intensity shower rain 09d '521' => array('ra.jpg','nra.jpg'), // Rain shower rain 09d '522' => array('ra.jpg','nra.jpg'), // Rain heavy intensity shower rain 09d '531' => array('ra.jpg','nra.jpg'), // Rain ragged shower rain 09d '600' => array('sn.jpg','nsn.jpg'), // Snow light snow 13d '601' => array('sn.jpg','nsn.jpg'), // Snow Snow 13d '602' => array('sn.jpg','nsn.jpg'), // Snow Heavy snow 13d '611' => array('ip.jpg','nip.jpg'), // Snow Sleet 13d '612' => array('ip.jpg','nip.jpg'), // Snow Light shower sleet 13d '613' => array('ip.jpg','nip.jpg'), // Snow Shower sleet 13d '615' => array('rasn.jpg','nrasn.jpg'), // Snow Light rain and snow 13d '616' => array('rasn.jpg','nrasn.jpg'), // Snow Rain and snow 13d '620' => array('sn.jpg','nsn.jpg'), // Snow Light shower snow 13d '621' => array('sn.jpg','nsn.jpg'), // Snow Shower snow 13d '622' => array('sn.jpg','nsn.jpg'), // Snow Heavy shower snow 13d '701' => array('mist.jpg','nmist.jpg'), // Mist mist 50d '711' => array('fu.jpg','nfu.jpg'), // Smoke Smoke 50d '721' => array('hz.jpg','nhz.jpg'), // Haze Haze 50d '731' => array('du.jpg','ndu.jpg'), // Dust sand/ dust whirls 50d '741' => array('fg.jpg','nfg.jpg'), // Fog fog 50d '751' => array('du.jpg','ndu.jpg'), // Sand sand 50d '761' => array('du.jpg','ndu.jpg'), // Dust dust 50d '762' => array('du.jpg','ndu.jpg'), // Ash volcanic ash 50d '771' => array('na.jpg','na.jpg'), // Squall squalls 50d '781' => array('tor.jpg','ntor.jpg'), // Tornado tornado 50d '800' => array('skc.jpg','nskc.jpg'), // Clear clear sky 01d 01n '801' => array('few.jpg','nfew.jpg'), // Clouds few clouds: 11-25% 02d 02n '802' => array('sct.jpg','nsct.jpg'), // Clouds scattered clouds: 25-50% 03d 03n '803' => array('bkn.jpg','nbkn.jpg'), // Clouds broken clouds: 51-84% 04d 04n '804' => array('ovc.jpg','novc.jpg'), // Clouds overcast clouds: 85-100% 04d 04n ); if(isset($Codes[$code])) { return $Codes[$code]; } else { return array('na.jpg','na.jpg'); } } // ------------------------------------------------------------------ function setup_tabber() { ?>