WEATHERLATTITUDE, "lon" => WEATHERLONGITUDE, "appid" => WEATHERAPIKEY, "units" => WEATHERUNITS, "exclude" => "minutely,hourly,alerts", // only "current" and "daily" are used ]); } public static function deleteOldWeather(int $days = 10): bool { if ( !is_int($days) ) return false; if ( $days < 0 ) return false; $query = "DELETE FROM " . AppDB::TABLE_WEATHER . " WHERE DATEDIFF(NOW(), sampledate) > :days"; $sth = AppDB::getSTH($query); if ( $sth === false ) return false; $sth->bindValue(":days", $days, PDO::PARAM_INT); return $sth->execute(); } public static function fetchWeather(): bool { $context = stream_context_create(["http" => ["timeout" => 10]]); $response = @file_get_contents(self::weatherURL(), false, $context); if ( $response === false ) { error_log("Tasks Weather: API request failed"); return false; } $json = json_decode($response); if ( !isset($data["current"]["dt"], $data["daily"][0]["temp"]) ) { error_log("Tasks Weather: API response could not be parsed"); return false; } $query = "INSERT INTO " . AppDB::TABLE_WEATHER . " (sampledate, weather) VALUES(NOW(), :weather)"; $sth = AppDB::getSTH($query); if ( $sth === false ) return false; $sth->bindValue(":weather", $response, PDO::PARAM_STR); return $sth->execute(); } public static function getWeather(): bool|array { $query = "SELECT weather FROM " . AppDB::TABLE_WEATHER . " ORDER BY sampledate DESC LIMIT 1"; $sth = AppDB::getSTH($query); if ( $sth === false ) return false; $sth->execute(); if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) { $json = json_decode($row['weather'], true); if ( is_null($json) ) return false; return $json; } else { return false; } } public function __construct() { $weather = self::getWeather(); if ( $weather === false ) return; $this->weather = $weather; $this->coord = array("lat" => $weather["lat"], "lon" => $weather["lon"]); $this->conditions = $weather["current"]["weather"][0]; $this->stats = $weather["current"]; unset($this->stats["weather"]); $this->temps = array("current" => $this->stats["temp"], "min" => $weather["daily"][0]["temp"]["min"], "max" => $weather["daily"][0]["temp"]["max"] ); $this->sampletime = new DateTime("@".$weather["current"]["dt"], new DateTimeZone('UTC')); $this->sampletime->setTimeZone(new DateTimeZone(date_default_timezone_get())); $this->sunrise = new DateTime("@".$weather["current"]["sunrise"], new DateTimeZone('UTC')); $this->sunrise->setTimeZone(new DateTimeZone(date_default_timezone_get())); $this->sunset = new DateTime("@".$weather["current"]["sunset"], new DateTimeZone('UTC')); $this->sunset->setTimeZone(new DateTimeZone(date_default_timezone_get())); } } // vim: et sw=4 ts=4 ai: