Compare commits

..

2 Commits

2 changed files with 47 additions and 23 deletions

View File

@ -13,37 +13,42 @@ class AppDB {
public static function getLastInsertId() { public static function getLastInsertId() {
if ( is_null(self::$dbh) ) return 0; if ( is_null(self::$dbh) ) return 0;
return self::$dbh->lastInsertId(); return intval(self::$dbh->lastInsertId());
} }
public static function getSTH($query = "") { public static function getSTH($query = "") {
if ( is_null(self::$dbh) ) self::getDBH();
if ( $query == "" ) return false; if ( $query == "" ) return false;
if ( is_null(self::$dbh) ) self::getDBH();
return self::$dbh->prepare($query); return self::$dbh->prepare($query);
} }
private static function getDBH() { private static function getDBH() {
if ( !is_null(self::$dbh) ) return self::$dbh; if ( !is_null(self::$dbh) ) return self::$dbh;
$dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS); $options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
// Try to connect to the database // Try to connect to the database
try { try {
if ( DBTYPE == "mysql" ) { if ( DBTYPE == "mysql" ) {
$dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS); $dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME . ";charset=utf8mb4",
DBUSER, DBPASS, $options);
} else if ( DBTYPE == "sqlite" ) { } else if ( DBTYPE == "sqlite" ) {
$dbh = new PDO("sqlite:" . SQLITEDB); $dbh = new PDO("sqlite:" . SQLITEDB, null, null, $options);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("PRAGMA foreign_keys = ON"); $dbh->exec("PRAGMA foreign_keys = ON");
} else { } else {
throw new Exception("Bad database configuration in config file!"); throw new Exception("Bad database configuration in config file!");
exit();
} }
} catch (PDOException | Exception $e) { } catch (Exception $e) {
//header('Location: error_db.php?connection='); error_log("DB connection failed: " . $e->getMessage());
echo "Couldn't connect to DB!"; http_response_code(500);
header("Content-Type: application/json");
echo json_encode(["error" => true, "message" => "Bad database configuration in config file!"]);
exit(); exit();
} }
self::$dbh = $dbh; self::$dbh = $dbh;
return $dbh;
} }
} }

View File

@ -11,38 +11,54 @@ class Weather {
public $sunrise = null; // Equals DateTime of Sunrise public $sunrise = null; // Equals DateTime of Sunrise
public $sunset = null; // Equals DateTime of Sunset public $sunset = null; // Equals DateTime of Sunset
const WEATHERURL = "https://api.openweathermap.org/data/3.0/onecall" private static function weatherURL(): string {
. "?lat=" . WEATHERLATTITUDE return "https://api.openweathermap.org/data/3.0/onecall?" . http_build_query([
. "&lon=" . WEATHERLONGITUDE "lat" => WEATHERLATTITUDE,
. "&appid=" . WEATHERAPIKEY "lon" => WEATHERLONGITUDE,
. "&units=" . WEATHERUNITS; "appid" => WEATHERAPIKEY,
"units" => WEATHERUNITS,
"exclude" => "minutely,hourly,alerts", // only "current" and "daily" are used
]);
}
public static function deleteOldWeather($days = 10) { public static function deleteOldWeather(int $days = 10): bool {
if ( !is_int($days) ) return false; if ( !is_int($days) ) return false;
if ( $days < 0 ) return false; if ( $days < 0 ) return false;
$query = "DELETE FROM " . AppDB::TABLE_WEATHER . " WHERE DATEDIFF(NOW(), sampledate) > :days"; $query = "DELETE FROM " . AppDB::TABLE_WEATHER . " WHERE DATEDIFF(NOW(), sampledate) > :days";
$sth = AppDB::getSTH($query); $sth = AppDB::getSTH($query);
if ( $sth === false ) return false; if ( $sth === false ) return false;
$sth->bindValue(":days", $days, PDO::PARAM_INT); $sth->bindValue(":days", $days, PDO::PARAM_INT);
$sth->execute(); return $sth->execute();
} }
public static function fetchWeather() { public static function fetchWeather(): bool {
$weather = file_get_contents(Weather::WEATHERURL); $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)"; $query = "INSERT INTO " . AppDB::TABLE_WEATHER . " (sampledate, weather) VALUES(NOW(), :weather)";
$sth = AppDB::getSTH($query); $sth = AppDB::getSTH($query);
if ( $sth === false ) return false; if ( $sth === false ) return false;
$sth->bindValue(":weather", $weather, PDO::PARAM_STR); $sth->bindValue(":weather", $response, PDO::PARAM_STR);
$sth->execute(); return $sth->execute();
} }
public static function getWeather() { public static function getWeather(): bool|array {
$query = "SELECT weather FROM " . AppDB::TABLE_WEATHER . " ORDER BY sampledate DESC LIMIT 1"; $query = "SELECT weather FROM " . AppDB::TABLE_WEATHER . " ORDER BY sampledate DESC LIMIT 1";
$sth = AppDB::getSTH($query); $sth = AppDB::getSTH($query);
if ( $sth === false ) return false; if ( $sth === false ) return false;
$sth->execute(); $sth->execute();
if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) { if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
return json_decode($row['weather'], true); $json = json_decode($row['weather'], true);
if ( is_null($json) ) return false;
return $json;
} else { } else {
return false; return false;
} }
@ -50,6 +66,7 @@ class Weather {
public function __construct() { public function __construct() {
$weather = self::getWeather(); $weather = self::getWeather();
if ( $weather === false ) return;
$this->weather = $weather; $this->weather = $weather;
$this->coord = array("lat" => $weather["lat"], "lon" => $weather["lon"]); $this->coord = array("lat" => $weather["lat"], "lon" => $weather["lon"]);
$this->conditions = $weather["current"]["weather"][0]; $this->conditions = $weather["current"]["weather"][0];
@ -67,3 +84,5 @@ class Weather {
$this->sunset->setTimeZone(new DateTimeZone(date_default_timezone_get())); $this->sunset->setTimeZone(new DateTimeZone(date_default_timezone_get()));
} }
} }
// vim: et sw=4 ts=4 ai: