Add editing of feed URL (#4)

- Move feed-specific database calls to Feed class
- Detect when feed items have been updated
- Add const keys for $_REQUEST values
This commit is contained in:
Daniel J. Summers 2024-04-11 22:01:36 -04:00
parent 7d294b9be8
commit da9a569e4a
7 changed files with 275 additions and 144 deletions

View File

@ -8,7 +8,7 @@ class Data {
* Obtain a new connection to the database * Obtain a new connection to the database
* @return SQLite3 A new connection to the database * @return SQLite3 A new connection to the database
*/ */
private static function getConnection(): SQLite3 { public static function getConnection(): SQLite3 {
$db = new SQLite3('../data/' . DATABASE_NAME); $db = new SQLite3('../data/' . DATABASE_NAME);
$db->exec('PRAGMA foreign_keys = ON;'); $db->exec('PRAGMA foreign_keys = ON;');
return $db; return $db;
@ -74,15 +74,19 @@ class Data {
*/ */
public static function findUserByEmail(string $email): ?array { public static function findUserByEmail(string $email): ?array {
$db = self::getConnection(); $db = self::getConnection();
$query = $db->prepare('SELECT * FROM frc_user WHERE email = :email'); try {
$query->bindValue(':email', $email); $query = $db->prepare('SELECT * FROM frc_user WHERE email = :email');
$result = $query->execute(); $query->bindValue(':email', $email);
if ($result) { $result = $query->execute();
$user = $result->fetchArray(SQLITE3_ASSOC); if ($result) {
if ($user) return $user; $user = $result->fetchArray(SQLITE3_ASSOC);
if ($user) return $user;
return null;
}
return null; return null;
} finally {
$db->close();
} }
return null;
} }
/** /**
@ -93,10 +97,14 @@ class Data {
*/ */
public static function addUser(string $email, string $password): void { public static function addUser(string $email, string $password): void {
$db = self::getConnection(); $db = self::getConnection();
$query = $db->prepare('INSERT INTO frc_user (email, password) VALUES (:email, :password)'); try {
$query->bindValue(':email', $email); $query = $db->prepare('INSERT INTO frc_user (email, password) VALUES (:email, :password)');
$query->bindValue(':password', password_hash($password, PASSWORD_DEFAULT)); $query->bindValue(':email', $email);
$query->execute(); $query->bindValue(':password', password_hash($password, PASSWORD_DEFAULT));
$query->execute();
} finally {
$db->close();
}
} }
/** /**
@ -105,7 +113,7 @@ class Data {
* @param ?string $value The date/time to be parsed and formatted * @param ?string $value The date/time to be parsed and formatted
* @return string|null The date/time in `DateTimeInterface::ATOM` format, or `null` if the input cannot be parsed * @return string|null The date/time in `DateTimeInterface::ATOM` format, or `null` if the input cannot be parsed
*/ */
private static function formatDate(?string $value): ?string { public static function formatDate(?string $value): ?string {
try { try {
return $value ? (new DateTimeImmutable($value))->format(DateTimeInterface::ATOM) : null; return $value ? (new DateTimeImmutable($value))->format(DateTimeInterface::ATOM) : null;
} catch (Exception) { } catch (Exception) {
@ -114,77 +122,22 @@ class Data {
} }
/** /**
* Add an RSS feed * Retrieve a feed by its ID for the current user
* *
* @param string $url The URL for the RSS feed * @param int $feedId The ID of the feed to retrieve
* @param string $title The title of the RSS feed * @param ?SQLite3 $dbConn A database connection to use (optional; will use standalone if not provided)
* @param ?string $updatedOn The date/time the RSS feed was last updated (from the XML, not when we checked) * @return array|bool The data for the feed if found, false if not found
* @return int The ID of the added feed
*/ */
public static function addFeed(string $url, string $title, ?string $updatedOn): int { public static function retrieveFeedById(int $feedId, ?SQLite3 $dbConn = null): array|bool {
$db = self::getConnection(); $db = $dbConn ?? self::getConnection();
$query = $db->prepare(<<<'SQL' try {
INSERT INTO feed ( $query = $db->prepare('SELECT * FROM feed WHERE id = :id AND user_id = :user');
user_id, url, title, updated_on, checked_on $query->bindValue(':id', $feedId);
) VALUES ( $query->bindValue(':user', $_REQUEST[Key::USER_ID]);
:user, :url, :title, :updated, :checked $result = $query->execute();
) return $result ? $result->fetchArray(SQLITE3_ASSOC) : false;
SQL); } finally {
$query->bindValue(':user', $_REQUEST['FRC_USER_ID']); if (is_null($dbConn)) $db->close();
$query->bindValue(':url', $url); }
$query->bindValue(':title', $title);
$query->bindValue(':updated', self::formatDate($updatedOn));
$query->bindValue(':checked', self::formatDate('now'));
$result = $query->execute();
return $result ? $db->lastInsertRowID() : -1;
}
/**
* Does a feed item already exist?
*
* @param int $feedId The ID of the feed to which the item belongs
* @param string $guid The GUID from the RSS feed, uniquely identifying the item
* @return bool True if the item exists, false if not
*/
public static function itemExists(int $feedId, string $guid): bool {
$db = self::getConnection();
$query = $db->prepare('SELECT COUNT(*) FROM item WHERE feed_id = :feed AND item_guid = :guid');
$query->bindValue(':feed', $feedId);
$query->bindValue(':guid', $guid);
$result = $query->execute();
return $result && $result->fetchArray(SQLITE3_NUM)[0] == 1;
}
/**
* Add a feed item
*
* @param int $feedId The ID of the feed to which the item should be added
* @param string $guid The GUID from the RSS feed (uses link if `<guid>` not specified)
* @param string $link The link to this item
* @param string $title The title of the item
* @param string $publishedOn The date/time the item was published
* @param ?string $updatedOn The date/time the item was last updated
* @param string $content The content of the item
* @param bool $isEncoded Whether the content has HTML (true) or is plaintext (false)
*/
public static function addItem(int $feedId, string $guid, string $link, string $title, string $publishedOn,
?string $updatedOn, string $content, bool $isEncoded): void {
$db = self::getConnection();
$query = $db->prepare(<<<'SQL'
INSERT INTO item (
feed_id, item_guid, item_link, title, published_on, updated_on, content, is_encoded
) VALUES (
:feed, :guid, :link, :title, :published, :updated, :content, :encoded
)
SQL);
$query->bindValue(':feed', $feedId);
$query->bindValue(':guid', $guid);
$query->bindValue(':link', $link);
$query->bindValue(':title', $title);
$query->bindValue(':published', self::formatDate($publishedOn));
$query->bindValue(':updated', self::formatDate($updatedOn));
$query->bindValue(':content', $content);
$query->bindValue(':encoded', $isEncoded);
$query->execute();
} }
} }

View File

@ -29,16 +29,16 @@ class Feed {
* Parse a feed into an XML tree * Parse a feed into an XML tree
* *
* @param string $content The feed's RSS content * @param string $content The feed's RSS content
* @return array|DOMDocument[]|string[] [ 'ok' => feed ] if successful, [ 'error' => message] if not * @return array|DOMDocument[]|string[] ['ok' => feed] if successful, ['error' => message] if not
*/ */
public static function parseFeed(string $content): array { public static function parseFeed(string $content): array {
set_error_handler(self::xmlParseError(...)); set_error_handler(self::xmlParseError(...));
try { try {
$feed = new DOMDocument(); $feed = new DOMDocument();
$feed->loadXML($content); $feed->loadXML($content);
return [ 'ok' => $feed ]; return ['ok' => $feed];
} catch (DOMException $ex) { } catch (DOMException $ex) {
return [ 'error' => $ex->getMessage() ]; return ['error' => $ex->getMessage()];
} finally { } finally {
restore_error_handler(); restore_error_handler();
} }
@ -48,8 +48,8 @@ class Feed {
* Retrieve the feed * Retrieve the feed
* *
* @param string $url * @param string $url
* @return array|DOMDocument[]|string[] [ 'ok' => feedXml, 'url' => actualUrl ] if successful, * @return array|DOMDocument[]|string[] ['ok' => feedXml, 'url' => actualUrl] if successful, ['error' => message] if
* [ 'error' => message ] if not * not
*/ */
public static function retrieveFeed(string $url): array { public static function retrieveFeed(string $url): array {
$feedReq = curl_init($url); $feedReq = curl_init($url);
@ -93,53 +93,123 @@ class Feed {
return $tags->length == 0 ? "$tagName not found" : $tags->item(0)->textContent; return $tags->length == 0 ? "$tagName not found" : $tags->item(0)->textContent;
} }
/**
* Extract the fields we need to keep from the feed
*
* @param DOMElement $item The item from the feed
* @return array The fields for the item as an associative array
*/
private static function itemFields(DOMElement $item): array {
$itemGuid = self::eltValue($item, 'guid');
$updNodes = $item->getElementsByTagNameNS(self::ATOM_NS, 'updated');
$encNodes = $item->getElementsByTagNameNS(self::CONTENT_NS, 'encoded');
return [
'guid' => $itemGuid == 'guid not found' ? self::eltValue($item, 'link') : $itemGuid,
'title' => self::eltValue($item, 'title'),
'link' => self::eltValue($item, 'link'),
'published' => Data::formatDate(self::eltValue($item, 'pubDate')),
'updated' => Data::formatDate($updNodes->length > 0 ? $updNodes->item(0)->textContent : null),
'content' => $encNodes->length > 0 ? $encNodes->item(0)->textContent
: self::eltValue($item, 'description'),
'isEncoded' => $encNodes->length > 0
];
}
/**
* Update a feed item
*
* @param int $itemId The ID of the item to be updated
* @param array $item The fields from the updated item
* @param SQLite3 $db A database connection to use for the update
*/
private static function updateItem(int $itemId, array $item, SQLite3 $db): void {
$query = $db->prepare(<<<'SQL'
UPDATE item
SET title = :title,
published_on = :published,
updated_on = :updated,
content = :content,
is_encoded = :encoded,
is_read = 0
WHERE id = :id
SQL);
$query->bindValue(':title', $item['title']);
$query->bindValue(':published', $item['published']);
$query->bindValue(':updated', $item['updated']);
$query->bindValue(':content', $item['content']);
$query->bindValue(':encoded', $item['isEncoded']);
$query->bindValue(':id', $itemId);
$query->execute();
}
/**
* Add a feed item
*
* @param int $feedId The ID of the feed to which the item should be added
* @param array $item The fields for the item
* @param SQLite3 $db A database connection to use for the addition
*/
private static function addItem(int $feedId, array $item, SQLite3 $db): void {
$query = $db->prepare(<<<'SQL'
INSERT INTO item (
feed_id, item_guid, item_link, title, published_on, updated_on, content, is_encoded
) VALUES (
:feed, :guid, :link, :title, :published, :updated, :content, :encoded
)
SQL);
$query->bindValue(':feed', $feedId);
$query->bindValue(':guid', $item['guid']);
$query->bindValue(':link', $item['link']);
$query->bindValue(':title', $item['title']);
$query->bindValue(':published', $item['published']);
$query->bindValue(':updated', $item['updated']);
$query->bindValue(':content', $item['content']);
$query->bindValue(':encoded', $item['isEncoded']);
$query->execute();
}
/** /**
* Update a feed's items * Update a feed's items
* *
* @param int $feedId The ID of the feed to which these items belong * @param int $feedId The ID of the feed to which these items belong
* @param DOMElement $channel The RSS feed items * @param DOMElement $channel The RSS feed items
* @return array [ 'ok' => true ] if successful, [ 'error' => message ] if not * @return array ['ok' => true] if successful, ['error' => message] if not
*/ */
public static function updateItems(int $feedId, DOMElement $channel): array { public static function updateItems(int $feedId, DOMElement $channel, SQLite3 $db): array {
try { try {
foreach ($channel->getElementsByTagName('item') as $item) { foreach ($channel->getElementsByTagName('item') as $rawItem) {
$itemGuid = self::eltValue($item, 'guid'); $item = self::itemFields($rawItem);
if ($itemGuid == 'guid not found') $itemGuid = self::eltValue($item, 'link'); $existsQuery = $db->prepare(
$isNew = !Data::itemExists($feedId, $itemGuid); 'SELECT id, published_on, updated_on FROM item WHERE feed_id = :feed AND item_guid = :guid');
if ($isNew) { $existsQuery->bindValue(':feed', $feedId);
$title = self::eltValue($item, 'title'); $existsQuery->bindValue(':guid', $item['guid']);
$link = self::eltValue($item, 'link'); $exists = $existsQuery->execute();
$published = self::eltValue($item, 'pubDate'); if ($exists) {
$updNodes = $item->getElementsByTagNameNS(self::ATOM_NS, 'updated'); $existing = $exists->fetchArray(SQLITE3_ASSOC);
$updated = $updNodes->length > 0 ? $updNodes->item(0)->textContent : null; if ( $existing
$encNodes = $item->getElementsByTagNameNS(self::CONTENT_NS, 'encoded'); && ( $existing['published_on'] != $item['published']
if ($encNodes->length > 0) { || $existing['updated_on'] ?? '' != $item['updated'] ?? '')) {
$content = $encNodes->item(0)->textContent; self::updateItem($existing['id'], $item, $db);
$isEncoded = true;
} else {
$content = self::eltValue($item, 'description');
$isEncoded = false;
} }
Data::addItem($feedId, $itemGuid, $link, $title, $published, $updated, $content, $isEncoded); } else {
} // TODO: else check updated date; may want to return that from the isNew check instead self::addItem($feedId, $item, $db);
}
} }
} catch (Exception $ex) { } catch (Exception $ex) {
return [ 'error' => $ex->getMessage() ]; return ['error' => $ex->getMessage()];
} }
return [ 'ok', true ]; return ['ok', true];
} }
/** /**
* Add an RSS feed * Find the `<channel>` element and derive the published/last updated date from the feed
* *
* @param string $url The URL of the RSS feed to add * @param DOMDocument $feed The feed from which the information should be extracted
* @return array [ 'ok' => true ] if successful, [ 'error' => message ] if not * @return array|string[]|DOMElement[] ['channel' => channel, 'updated' => date] if successful, ['error' => message]
* if not
*/ */
public static function add(string $url): array { private static function findChannelAndDate(DOMDocument $feed): array {
$feed = self::retrieveFeed($url); $channel = $feed->getElementsByTagName('channel')->item(0);
if (array_key_exists('error', $feed)) return $feed;
$channel = $feed['ok']->getElementsByTagName('channel')->item(0);
if (!$channel instanceof DOMElement) return [ 'error' => "Channel element not found ($channel->nodeType)" ]; if (!$channel instanceof DOMElement) return [ 'error' => "Channel element not found ($channel->nodeType)" ];
// In Atom feeds, lastBuildDate contains the last time an item in the feed was updated; if that is not present, // In Atom feeds, lastBuildDate contains the last time an item in the feed was updated; if that is not present,
@ -149,11 +219,74 @@ class Feed {
$updated = self::eltValue($channel, 'pubDate'); $updated = self::eltValue($channel, 'pubDate');
if ($updated == 'pubDate not found') $updated = null; if ($updated == 'pubDate not found') $updated = null;
} }
$feedId = Data::addFeed($feed['url'], self::eltValue($channel, 'title'), $updated); return ['channel' => $channel, 'updated' => Data::formatDate($updated)];
}
$result = self::updateItems($feedId, $channel); /**
* Add an RSS feed
*
* @param string $url The URL of the RSS feed to add
* @return array ['ok' => feedId] if successful, ['error' => message] if not
*/
public static function add(string $url, SQLite3 $db): array {
$feed = self::retrieveFeed($url);
if (array_key_exists('error', $feed)) return $feed;
$channelAndDate = self::findChannelAndDate($feed['ok']);
if (array_key_exists('error', $channelAndDate)) return $channelAndDate;
$channel = $channelAndDate['channel'];
$query = $db->prepare(<<<'SQL'
INSERT INTO feed (user_id, url, title, updated_on, checked_on)
VALUES (:user, :url, :title, :updated, :checked)
SQL);
$query->bindValue(':user', $_REQUEST[Key::USER_ID]);
$query->bindValue(':url', $feed['url']);
$query->bindValue(':title', self::eltValue($channel, 'title'));
$query->bindValue(':updated', $channelAndDate['updated']);
$query->bindValue(':checked', Data::formatDate('now'));
$result = $query->execute();
$feedId = $result ? $db->lastInsertRowID() : -1;
if ($feedId < 0) return ['error' => $db->lastErrorMsg()];
$result = self::updateItems($feedId, $channel, $db);
if (array_key_exists('error', $result)) return $result; if (array_key_exists('error', $result)) return $result;
return [ 'ok' => true ]; return ['ok' => $feedId];
}
/**
* Update an RSS feed
*
* @param array $existing The existing RSS feed
* @param string $url The URL with which the existing feed should be modified
* @return bool[]|string[] [ 'ok' => true ] if successful, [ 'error' => message ] if not
*/
public static function update(array $existing, string $url, SQLite3 $db): array {
$feed = self::retrieveFeed($url);
if (array_key_exists('error', $feed)) return $feed;
$channelAndDate = self::findChannelAndDate($feed['ok']);
if (array_key_exists('error', $channelAndDate)) return $channelAndDate;
$channel = $channelAndDate['channel'];
$query = $db->prepare(<<<'SQL'
UPDATE feed
SET url = :url, title = :title, updated_on = :updated, checked_on = :checked
WHERE id = :id AND user_id = :user
SQL);
$query->bindValue(':url', $feed['url']);
$query->bindValue(':title', self::eltValue($channel, 'title'));
$query->bindValue(':updated', $channelAndDate['updated']);
$query->bindValue(':checked', Data::formatDate('now'));
$query->bindValue(':id', $existing['id']);
$query->bindValue(':user', $_REQUEST[Key::USER_ID]);
$query->execute();
$result = self::updateItems($existing['id'], $channel, $db);
if (array_key_exists('error', $result)) return $result;
return ['ok' => true];
} }
} }

13
src/lib/Key.php Normal file
View File

@ -0,0 +1,13 @@
<?php
class Key {
/** @var string The $_REQUEST key for teh current user's e-mail address */
public const string USER_EMAIL = 'FRC_USER_EMAIL';
/** @var string The $_REQUEST key for the current user's ID */
public const string USER_ID = 'FRC_USER_ID';
/** @var string The $_REQUEST key for the array of user messages to display */
public const string USER_MSG = 'FRC_USER_MSG';
}

View File

@ -31,11 +31,11 @@ class Security {
die('Unrecognized security model (' . SECURITY_MODEL . ')'); die('Unrecognized security model (' . SECURITY_MODEL . ')');
} }
if (!$user && $redirectIfAnonymous) { if (!$user && $redirectIfAnonymous) {
header('/logon?returnTo=' . $_SERVER["REQUEST_URI"], true, HTTP_REDIRECT_TEMP); header('/logon?returnTo=' . $_SERVER['REQUEST_URI'], true, HTTP_REDIRECT_TEMP);
die(); die();
} }
$_REQUEST['FRC_USER_ID'] = $user['id']; $_REQUEST[Key::USER_ID] = $user['id'];
$_REQUEST['FRC_USER_EMAIL'] = $user['email']; $_REQUEST[Key::USER_EMAIL] = $user['email'];
} }
/** /**

View File

@ -9,20 +9,35 @@ include '../start.php';
Security::verifyUser(); Security::verifyUser();
$feedId = array_key_exists('id', $_GET) ? $_GET['id'] : '';
$db = Data::getConnection();
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// TODO: get feed, add if new, reject if existing but not owned by this user, update otherwise $isNew = $_POST['id'] == 'new';
$result = Feed::add($_POST['url']); if ($isNew) {
if (array_key_exists('ok', $result)) { $result = Feed::add($_POST['url'], $db);
add_message('INFO', 'Feed added successfully');
} else { } else {
add_message('ERROR', $result['error']); $toEdit = Data::retrieveFeedById($_POST['id'], $db);
$result = $toEdit ? Feed::update($toEdit, $_POST['url'], $db) : [ 'error' => "Feed {$_POST['id']} not found" ];
} }
$feed = [ 'id' => $_POST['id'], 'url' => $_POST['url'] ]; if (array_key_exists('ok', $result)) {
$title = 'TODO'; add_info('Feed saved successfully');
} else { $feedId = $isNew ? $result['ok'] : $_POST['id'];
// TODO: Retrieve feed by ID if not new } else {
add_error($result['error']);
}
}
if ($feedId == 'new') {
$feed = [ 'id' => $_GET['id'], 'url' => '' ]; $feed = [ 'id' => $_GET['id'], 'url' => '' ];
$title = 'Add RSS Feed'; $title = 'Add RSS Feed';
} else {
$feed = Data::retrieveFeedById((int) $feedId, $db);
if (!$feed) {
http_response_code(404);
die();
}
$title = 'Edit RSS Feed';
} }
page_head($title); ?> page_head($title); ?>
@ -38,3 +53,4 @@ page_head($title); ?>
</form> </form>
</article><?php </article><?php
page_foot(); page_foot();
$db->close();

View File

@ -9,8 +9,6 @@ include '../start.php';
Security::verifyUser(); Security::verifyUser();
page_head('Welcome'); page_head('Welcome'); ?>
?> <p>Unread items go here</p><?php
<?php
page_foot(); page_foot();

View File

@ -19,8 +19,26 @@ Data::ensureDb();
* @param string $message The message itself * @param string $message The message itself
*/ */
function add_message(string $level, string $message): void { function add_message(string $level, string $message): void {
if (!array_key_exists('USER_MSG', $_REQUEST)) $_REQUEST['USER_MSG'] = array(); if (!array_key_exists(Key::USER_MSG, $_REQUEST)) $_REQUEST[Key::USER_MSG] = array();
$_REQUEST['USER_MSG'][] = ['level' => $level, 'message' => $message]; $_REQUEST[Key::USER_MSG][] = ['level' => $level, 'message' => $message];
}
/**
* Add an error message to be displayed at the top of the page
*
* @param string $message The message to be displayed
*/
function add_error(string $message): void {
add_message('ERROR', $message);
}
/**
* Add an error message to be displayed at the top of the page
*
* @param string $message The message to be displayed
*/
function add_info(string $message): void {
add_message('INFO', $message);
} }
/** /**
@ -38,15 +56,15 @@ function page_head(string $title): void {
<header> <header>
<a class=title href="/">Feed Reader Central</a> <a class=title href="/">Feed Reader Central</a>
<div><?php <div><?php
if (array_key_exists('FRC_USER_ID', $_REQUEST)) { if (array_key_exists(Key::USER_ID, $_REQUEST)) {
echo '<a href=/feed?id=new>Add Feed</a>'; echo '<a href=/feed?id=new>Add Feed</a>';
if ($_REQUEST['FRC_USER_EMAIL'] != 'solouser@example.com') echo " | {$_REQUEST['FRC_USER_EMAIL']}"; if ($_REQUEST[Key::USER_EMAIL] != 'solouser@example.com') echo " | {$_REQUEST[Key::USER_EMAIL]}";
} ?> } ?>
</div> </div>
</header> </header>
<main hx-target=this><?php <main hx-target=this><?php
if (array_key_exists('USER_MSG', $_REQUEST)) { if (array_key_exists(Key::USER_MSG, $_REQUEST)) {
foreach ($_REQUEST['USER_MSG'] as $msg) { ?> foreach ($_REQUEST[Key::USER_MSG] as $msg) { ?>
<div> <div>
<?=$msg['level'] == 'INFO' ? '' : "<strong>{$msg['level']}</strong><br>"?> <?=$msg['level'] == 'INFO' ? '' : "<strong>{$msg['level']}</strong><br>"?>
<?=$msg['message']?> <?=$msg['message']?>