+
+require_once('include/network.php');
+require_once("mod/proxy.php");
+require_once('include/text.php');
+
+// get the weather data from OpenWeatherMap
+function getWeather( $loc, $units='metric', $lang='en', $appid='', $cachetime=0) {
+ $url = "http://api.openweathermap.org/data/2.5/weather?q=".$loc."&appid=".$appid."&lang=".$lang."&units=".$units."&mode=xml";
+ $cached = Cache::get('curweather'.md5($url));
+ $now = new DateTime();
+ if (!is_null($cached)) {
+ $cdate = get_pconfig(local_user(), 'curweather', 'last');
+ $cached = unserialize($cached);
+ if ($cdate + $cachetime > $now->getTimestamp()) {
+ return $cached;
+ }
+ }
+ try {
+ $res = new SimpleXMLElement(fetch_url($url));
+ } catch (Exception $e) {
+ info(t('Error fetching weather data.\nError was: '.$e->getMessage()));
+ return false;
+ }
+ if ((string)$res->temperature['unit']==='metric') {
+ $tunit = '°C';
+ $wunit = 'm/s';
+ } else {
+ $tunit = '°F';
+ $wunit = 'mph';
+ }
+ if ( trim((string)$res->weather['value']) == trim((string)$res->clouds['name']) ) {
+ $desc = (string)$res->clouds['name'];
+ } else {
+ $desc = (string)$res->weather['value'].', '.(string)$res->clouds['name'];
+ }
+ $r = array(
+ 'city'=> (string) $res->city['name'][0],
+ 'country' => (string) $res->city->country[0],
+ 'lat' => (string) $res->city->coord['lat'],
+ 'lon' => (string) $res->city->coord['lon'],
+ 'temperature' => (string) $res->temperature['value'][0].$tunit,
+ 'pressure' => (string) $res->pressure['value'].(string)$res->pressure['unit'],
+ 'humidity' => (string) $res->humidity['value'].(string)$res->humidity['unit'],
+ 'descripion' => $desc,
+ 'wind' => (string)$res->wind->speed['name'].' ('.(string)$res->wind->speed['value'].$wunit.')',
+ 'update' => (string)$res->lastupdate['value'],
+ 'icon' => (string)$res->weather['icon']
+ );
+ set_pconfig(local_user(), 'curweather', 'last', $now->getTimestamp());
+ Cache::set('curweather'.md5($url), serialize($r), CACHE_HOUR);
+ return $r;
+}