beta4 changes (#26)

These changes are mostly in underlying libraries; however, this now uses the [inspired by F#](https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp) library to handle the feed parsing pipeline and optional return values

Reviewed-on: #26
This commit was merged in pull request #26.
This commit is contained in:
2024-08-06 23:20:17 +00:00
parent dfd9a873f8
commit d06249aecd
35 changed files with 867 additions and 535 deletions

View File

@@ -1,4 +1,10 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
@@ -13,6 +19,9 @@ use Exception;
*/
class Data
{
/** Prevent instances of this class */
private function __construct() {}
/**
* Create the search index and synchronization triggers for the item table
*
@@ -56,17 +65,17 @@ class Data
public static function ensureDb(): void
{
$tables = Custom::array("SELECT name FROM sqlite_master WHERE type = 'table'", [], new StringMapper('name'));
if (!in_array(Table::USER, $tables)) {
Definition::ensureTable(Table::USER);
Definition::ensureFieldIndex(Table::USER, 'email', ['email']);
if (!in_array(Table::User, $tables)) {
Definition::ensureTable(Table::User);
Definition::ensureFieldIndex(Table::User, 'email', ['email']);
}
if (!in_array(Table::FEED, $tables)) {
Definition::ensureTable(Table::FEED);
Definition::ensureFieldIndex(Table::FEED, 'user', ['user_id']);
if (!in_array(Table::Feed, $tables)) {
Definition::ensureTable(Table::Feed);
Definition::ensureFieldIndex(Table::Feed, 'user', ['user_id']);
}
if (!in_array(Table::ITEM, $tables)) {
Definition::ensureTable(Table::ITEM);
Definition::ensureFieldIndex(Table::ITEM, 'feed', ['feed_id', 'item_link']);
if (!in_array(Table::Item, $tables)) {
Definition::ensureTable(Table::Item);
Definition::ensureFieldIndex(Table::Item, 'feed', ['feed_id', 'item_link']);
self::createSearchIndex();
}
$journalMode = Custom::scalar("PRAGMA journal_mode", [], new StringMapper('journal_mode'));
@@ -122,7 +131,7 @@ class Data
*/
public static function userIdField(string $qualifier = ''): Field
{
$userField = Field::EQ('user_id', $_SESSION[Key::USER_ID], ':user');
$userField = Field::EQ('user_id', $_SESSION[Key::UserId], ':user');
$userField->qualifier = $qualifier;
return $userField;
}

View File

@@ -1,7 +1,14 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
use BitBadger\InspiredByFSharp\{Option, Result};
use BitBadger\PDODocument\{
Configuration, Custom, Document, DocumentException, DocumentList, Exists, Field, Find, Parameters, Patch, Query
};
@@ -15,15 +22,39 @@ class Feed
// ***** CONSTANTS *****
/** @var int Do not purge items */
public const PURGE_NONE = 0;
public const PurgeNone = 0;
/** @var int Purge all read items (will not purge unread items) */
public const PURGE_READ = 1;
public const PurgeRead = 1;
/** @var int Purge items older than the specified number of days */
public const PURGE_BY_DAYS = 2;
public const PurgeByDays = 2;
/** @var int Purge items in number greater than the specified number of items to keep */
public const PurgeByCount = 3;
/**
* @var int Do not purge items
* @deprecated Use Feed::PurgeNone instead
*/
public const PURGE_NONE = 0;
/**
* @var int Purge all read items (will not purge unread items)
* @deprecated Use Feed::PurgeRead instead
*/
public const PURGE_READ = 1;
/**
* @var int Purge items older than the specified number of days
* @deprecated Use Feed::PurgeByDays instead
*/
public const PURGE_BY_DAYS = 2;
/**
* @var int Purge items in number greater than the specified number of items to keep
* @deprecated Use Feed::PurgeByCount instead
*/
public const PURGE_BY_COUNT = 3;
/**
@@ -46,12 +77,12 @@ class Feed
* Create a document from the parsed feed
*
* @param ParsedFeed $parsed The parsed feed
* @return static The document constructed from the parsed feed
* @return Feed The document constructed from the parsed feed
*/
public static function fromParsed(ParsedFeed $parsed): static
public static function fromParsed(ParsedFeed $parsed): self
{
return new static(
user_id: $_SESSION[Key::USER_ID],
return new self(
user_id: $_SESSION[Key::UserId],
url: $parsed->url,
title: $parsed->title,
updated_on: $parsed->updatedOn,
@@ -64,72 +95,77 @@ class Feed
* @param int $feedId The ID of the feed to which these items belong
* @param ParsedFeed $parsed The extracted Atom or RSS feed items
* @param DateTimeInterface $lastChecked When this feed was last checked (only new items will be added)
* @return array ['ok' => true] if successful, ['error' => message] if not
* @return Result<true, string> True if successful, an error message if not
*/
public static function updateItems(int $feedId, ParsedFeed $parsed, DateTimeInterface $lastChecked): array
public static function updateItems(int $feedId, ParsedFeed $parsed, DateTimeInterface $lastChecked): Result
{
$results =
array_map(function ($item) use ($feedId) {
try {
$existing = Find::firstByFields(Table::ITEM,
$tryExisting = Find::firstByFields(Table::Item,
[Field::EQ('feed_id', $feedId), Field::EQ('item_guid', $item->guid)], Item::class);
if ($existing) {
if ($existing->published_on != $item->publishedOn
|| ($existing->updated_on != ($item->updatedOn ?? ''))) {
if ($tryExisting->isSome()) {
$existing = $tryExisting->get();
if ($existing->published_on !== $item->publishedOn
|| ($existing->updated_on !== ($item->updatedOn ?? ''))) {
Item::update($existing->id, $item);
}
} else {
Item::add($feedId, $item);
}
return ['ok' => true];
return Result::OK(true);
} catch (DocumentException $ex) {
return ['error' => "$ex"];
return Result::Error("$ex");
}
}, array_filter($parsed->items,
fn($it) => date_create_immutable($it->updatedOn ?? $it->publishedOn) >= $lastChecked));
$errors = array_map(fn($it) => $it['error'], array_filter($results, fn($it) => array_key_exists('error', $it)));
return sizeof($errors) > 0 ? ['error' => implode("\n", $errors)] : ['ok' => true];
fn(ParsedItem $it) => date_create_immutable($it->updatedOn ?? $it->publishedOn) >= $lastChecked));
$errors = array_map(fn(Result $it) => $it->getError(), array_filter($results, fn($it) => $it->isError()));
return sizeof($errors) > 0 ? Result::Error(implode("\n", $errors)) : Result::OK(true);
}
/**
* Purge items for a feed
*
* @param int $feedId The ID of the feed to be purged
* @return array|string[]|true[] ['ok' => true] if purging was successful, ['error' => message] if not
* @return Result<true, string> True if purging was successful, an error message if not
* @throws DocumentException If any is encountered
*/
private static function purgeItems(int $feedId): array
private static function purgeItems(int $feedId): Result
{
if (!array_search(PURGE_TYPE, [self::PURGE_READ, self::PURGE_BY_DAYS, self::PURGE_BY_COUNT])) {
return ['error' => 'Unrecognized purge type ' . PURGE_TYPE];
}
$fields = [Field::EQ('feed_id', $feedId, ':feed'), Data::bookmarkField(false)];
$sql = Query\Delete::byFields(Table::ITEM, $fields);
if (PURGE_TYPE == self::PURGE_READ) {
$readField = Field::EQ('is_read', 1, ':read');
$fields[] = $readField;
$sql .= ' AND ' . Query::whereByFields([$readField]);
} elseif (PURGE_TYPE == self::PURGE_BY_DAYS) {
$fields[] = Field::EQ('', Data::formatDate('-' . PURGE_NUMBER . ' day'), ':oldest');
$sql .= " AND date(coalesce(data->>'updated_on', data->>'published_on')) < date(:oldest)";
} elseif (PURGE_TYPE == self::PURGE_BY_COUNT) {
$fields[] = Field::EQ('', PURGE_NUMBER, ':keep');
$id = Configuration::$idField;
$table = Table::ITEM;
$sql .= ' ' . <<<SQL
AND data->>'$id' IN (
SELECT data->>'$id' FROM $table
WHERE data->>'feed_id' = :feed
ORDER BY date(coalesce(data->>'updated_on', data->>'published_on')) DESC
LIMIT -1 OFFSET :keep
)
SQL;
$sql = Query\Delete::byFields(Table::Item, $fields);
switch (PURGE_TYPE) {
case self::PurgeRead:
$readField = Field::EQ('is_read', 1, ':read');
$fields[] = $readField;
$sql .= ' AND ' . Query::whereByFields([$readField]);
break;
case self::PurgeByDays:
$fields[] = Field::EQ('', Data::formatDate('-' . PURGE_NUMBER . ' day'), ':oldest');
$sql .= " AND date(coalesce(data->>'updated_on', data->>'published_on')) < date(:oldest)";
break;
case self::PurgeByCount:
$fields[] = Field::EQ('', PURGE_NUMBER, ':keep');
$id = Configuration::$idField;
$table = Table::Item;
$sql .= ' ' . <<<SQL
AND data->>'$id' IN (
SELECT data->>'$id' FROM $table
WHERE data->>'feed_id' = :feed
ORDER BY date(coalesce(data->>'updated_on', data->>'published_on')) DESC
LIMIT -1 OFFSET :keep
)
SQL;
break;
default:
return Result::Error('Unrecognized purge type ' . PURGE_TYPE);
}
try {
Custom::nonQuery($sql, Parameters::addFields($fields, []));
return ['ok' => true];
return Result::OK(true);
} catch (DocumentException $ex) {
return ['error' => "$ex"];
return Result::Error("$ex");
}
}
@@ -138,67 +174,62 @@ class Feed
*
* @param int $feedId The ID of the feed to be refreshed
* @param string $url The URL of the feed to be refreshed
* @return array|string[]|true[] ['ok' => true] if successful, ['error' => message] if not
* @return Result<true, string> True if successful, an error message if not
*/
public static function refreshFeed(int $feedId, string $url): array
public static function refreshFeed(int $feedId, string $url): Result
{
$feedRetrieval = ParsedFeed::retrieve($url);
if (key_exists('error', $feedRetrieval)) return $feedRetrieval;
$feed = $feedRetrieval['ok'];
return ParsedFeed::retrieve($url)
->bind(function (ParsedFeed $feed) use ($feedId, $url) {
try {
$feedDoc = Find::byId(Table::Feed, $feedId, self::class);
if ($feedDoc->isNone()) return Result::Error('Could not derive date last checked for feed');
$lastChecked = date_create_immutable($feedDoc->get()->checked_on ?? WWW_EPOCH);
try {
$feedDoc = Find::byId(Table::FEED, $feedId, self::class);
if (!$feedDoc) return ['error' => 'Could not derive date last checked for feed'];
$lastChecked = date_create_immutable($feedDoc->checked_on ?? WWW_EPOCH);
$itemUpdate = self::updateItems($feedId, $feed, $lastChecked);
if (key_exists('error', $itemUpdate)) return $itemUpdate;
$patch = [
'title' => $feed->title,
'updated_on' => $feed->updatedOn,
'checked_on' => Data::formatDate('now')
];
if ($url == $feed->url) $patch['url'] = $feed->url;
Patch::byId(Table::FEED, $feedId, $patch);
} catch (DocumentException $ex) {
return ['error' => "$ex"];
}
return PURGE_TYPE == self::PURGE_NONE ? ['ok' => true] : self::purgeItems($feedId);
return self::updateItems($feedId, $feed, $lastChecked)
->bind(function () use ($feed, $feedId, $url) {
$patch = [
'title' => $feed->title,
'updated_on' => $feed->updatedOn,
'checked_on' => Data::formatDate('now')
];
if ($url !== $feed->url) $patch['url'] = $feed->url;
Patch::byId(Table::Feed, $feedId, $patch);
return Result::OK(true);
})
->bind(fn() => PURGE_TYPE === self::PurgeNone ? Result::OK(true) : self::purgeItems($feedId));
} catch (DocumentException $ex) {
return Result::Error("$ex");
}
});
}
/**
* 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
* @return Result<int, string> The feed ID if successful, an error message if not
*/
public static function add(string $url): array
public static function add(string $url): Result
{
$feedExtract = ParsedFeed::retrieve($url);
if (key_exists('error', $feedExtract)) return $feedExtract;
return ParsedFeed::retrieve($url)
->bind(function (ParsedFeed $feed) {
try {
$fields = [Field::EQ('user_id', $_SESSION[Key::UserId]), Field::EQ('url', $feed->url)];
if (Exists::byFields(Table::Feed, $fields)) {
return Result::Error("Already subscribed to feed $feed->url");
}
$feed = $feedExtract['ok'];
Document::insert(Table::Feed, self::fromParsed($feed));
try {
$fields = [Field::EQ('user_id', $_SESSION[Key::USER_ID]), Field::EQ('url', $feed->url)];
if (Exists::byFields(Table::FEED, $fields)) {
return ['error' => "Already subscribed to feed $feed->url"];
}
$doc = Find::firstByFields(Table::Feed, $fields, self::class);
if ($doc->isNone()) return Result::Error('Could not retrieve inserted feed');
Document::insert(Table::FEED, self::fromParsed($feed));
$doc = Find::firstByFields(Table::FEED, $fields, static::class);
if (!$doc) return ['error' => 'Could not retrieve inserted feed'];
$result = self::updateItems($doc->id, $feed, date_create_immutable(WWW_EPOCH));
if (key_exists('error', $result)) return $result;
return ['ok' => $doc->id];
} catch (DocumentException $ex) {
return ['error' => "$ex"];
}
return self::updateItems($doc->get()->id, $feed, date_create_immutable(WWW_EPOCH))
->bind(fn() => Result::OK($doc->get()->id));
} catch (DocumentException $ex) {
return Result::Error("$ex");
}
});
}
/**
@@ -206,18 +237,17 @@ class Feed
*
* @param Feed $existing The existing 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
* @return Result<true, string> True if successful, an error message if not
*/
public static function update(Feed $existing, string $url): array
public static function update(Feed $existing, string $url): Result
{
try {
Patch::byFields(Table::FEED,
[Field::EQ(Configuration::$idField, $existing->id), Field::EQ('user_id', $_SESSION[Key::USER_ID])],
Patch::byFields(Table::Feed,
[Field::EQ(Configuration::$idField, $existing->id), Field::EQ('user_id', $_SESSION[Key::UserId])],
['url' => $url]);
return self::refreshFeed($existing->id, $url);
} catch (DocumentException $ex) {
return ['error' => "$ex"];
return Result::Error("$ex");
}
}
@@ -230,44 +260,42 @@ class Feed
*/
public static function retrieveAll(int $user = 0): DocumentList
{
return $user == 0
? Find::all(Table::FEED, self::class)
: Find::byFields(Table::FEED, [Field::EQ('user_id', $user)], self::class);
return $user === 0
? Find::all(Table::Feed, self::class)
: Find::byFields(Table::Feed, [Field::EQ('user_id', $user)], self::class);
}
/**
* Refresh all feeds
*
* @return array|true[]|string[] ['ok' => true] if successful,
* ['error' => message] if not (may have multiple error lines)
* @return Result<true, string> True if successful an error message if not (may have multiple error lines)
*/
public static function refreshAll(): array
public static function refreshAll(): Result
{
try {
$feeds = self::retrieveAll($_SESSION[Key::USER_ID]);
$errors = [];
$errors = [];
foreach ($feeds->items() as $feed) {
$result = self::refreshFeed($feed->id, $feed->url);
if (key_exists('error', $result)) $errors[] = $result['error'];
}
try {
self::retrieveAll($_SESSION[Key::UserId])->iter(function (Feed $feed) use (&$errors) {
self::refreshFeed($feed->id, $feed->url)
->mapError(function (string $err) use (&$errors) { $errors[] = $err; });
});
} catch (DocumentException $ex) {
return ['error' => "$ex"];
return Result::Error("$ex");
}
return sizeof($errors) == 0 ? ['ok' => true] : ['error' => implode("\n", $errors)];
return empty($errors) ? Result::OK(true) : Result::Error(implode("\n", $errors));
}
/**
* Retrieve a feed by its ID for the current user
*
* @param int $feedId The ID of the feed to retrieve
* @return static|false The data for the feed if found, false if not found
* @return Option<Feed> A `Some` value with the data for the feed if found, `None` otherwise
* @throws DocumentException If any is encountered
*/
public static function retrieveById(int $feedId): static|false
public static function retrieveById(int $feedId): Option
{
$doc = Find::byId(Table::FEED, $feedId, static::class);
return $doc && $doc->user_id == $_SESSION[Key::USER_ID] ? $doc : false;
return Find::byId(Table::Feed, $feedId, static::class)
->filter(fn($it) => $it->user_id === $_SESSION[Key::UserId]);
}
}

View File

@@ -1,4 +1,10 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
@@ -57,7 +63,7 @@ class Item
*/
public static function add(int $feedId, ParsedItem $parsed): void
{
Document::insert(Table::ITEM, new static(
Document::insert(Table::Item, new self(
feed_id: $feedId,
title: $parsed->title,
item_guid: $parsed->guid,
@@ -76,7 +82,7 @@ class Item
*/
public static function update(int $id, ParsedItem $parsed): void
{
Patch::byId(Table::ITEM, $id, [
Patch::byId(Table::Item, $id, [
'title' => $parsed->title,
'published_on' => $parsed->publishedOn,
'updated_on' => $parsed->updatedOn,

View File

@@ -1,7 +1,14 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
use BitBadger\InspiredByFSharp\Option;
use BitBadger\PDODocument\{Configuration, Custom, DocumentException, DocumentList, Field, Parameters, Query};
use BitBadger\PDODocument\Mapper\DocumentMapper;
@@ -15,18 +22,8 @@ class ItemList
/** @var DocumentList<ItemWithFeed> The items matching the criteria, lazily iterable */
private DocumentList $dbList;
/** @var string The error message generated by executing a query */
public string $error = '';
/**
* Is there an error condition associated with this list?
*
* @return bool True if there is an error condition associated with this list, false if not
*/
public function isError(): bool
{
return $this->error != '';
}
/** @var Option<string> The error message generated by executing a query */
private Option $error;
/** @var bool Whether to render a link to the feed to which the item belongs */
public bool $linkFeed = false;
@@ -42,32 +39,33 @@ class ItemList
*
* @param string $itemType The type of item being displayed (unread, bookmark, etc.)
* @param string $returnURL The URL to which the item page should return once the item has been viewed
* @param array|Field[] $fields The fields to use to restrict the results
* @param Field[] $fields The fields to use to restrict the results
* @param string $searchWhere Additional WHERE clause to use for searching
*/
private function __construct(public string $itemType, public string $returnURL = '', array $fields = [],
string $searchWhere = '')
{
$allFields = [Data::userIdField(Table::FEED), ...$fields];
$this->error = Option::None();
$allFields = [Data::userIdField(Table::Feed), ...$fields];
try {
$this->dbList = Custom::list(
ItemWithFeed::SELECT_WITH_FEED . ' WHERE '
. Query::whereByFields(array_filter($allFields, fn($it) => $it->paramName <> ':search'))
. Query::whereByFields(array_filter($allFields, fn($it) => $it->paramName !== ':search'))
. "$searchWhere ORDER BY coalesce(item.data->>'updated_on', item.data->>'published_on') DESC",
Parameters::addFields($allFields, []), new DocumentMapper(ItemWithFeed::class));
} catch (DocumentException $ex) {
$this->error = "$ex";
$this->error = Option::Some("$ex");
}
}
/**
* Create an item list with all the current user's bookmarked items
*
* @return static An item list with all bookmarked items
* @return ItemList An item list with all bookmarked items
*/
public static function allBookmarked(): static
public static function allBookmarked(): self
{
$list = new static('Bookmarked', '/?bookmarked', [Data::bookmarkField(qualifier: Table::ITEM)]);
$list = new self('Bookmarked', '/?bookmarked', [Data::bookmarkField(qualifier: Table::Item)]);
$list->linkFeed = true;
return $list;
}
@@ -75,11 +73,11 @@ class ItemList
/**
* Create an item list with all the current user's unread items
*
* @return static An item list with all unread items
* @return ItemList An item list with all unread items
*/
public static function allUnread(): static
public static function allUnread(): self
{
$list = new static('Unread', fields: [Data::unreadField(Table::ITEM)]);
$list = new self('Unread', fields: [Data::unreadField(Table::Item)]);
$list->linkFeed = true;
return $list;
}
@@ -88,11 +86,11 @@ class ItemList
* Create an item list with all items for the given feed
*
* @param int $feedId The ID of the feed for which items should be retrieved
* @return static An item list with all items for the given feed
* @return ItemList An item list with all items for the given feed
*/
public static function allForFeed(int $feedId): static
public static function allForFeed(int $feedId): self
{
$list = new static('', "/feed/items?id=$feedId", [Data::feedField($feedId, Table::FEED)]);
$list = new self('', "/feed/items?id=$feedId", [Data::feedField($feedId, Table::Feed)]);
$list->showIndicators = true;
return $list;
}
@@ -101,24 +99,24 @@ class ItemList
* Create an item list with unread items for the given feed
*
* @param int $feedId The ID of the feed for which items should be retrieved
* @return static An item list with unread items for the given feed
* @return ItemList An item list with unread items for the given feed
*/
public static function unreadForFeed(int $feedId): static
public static function unreadForFeed(int $feedId): self
{
return new static('Unread', "/feed/items?id=$feedId&unread",
[Data::feedField($feedId, Table::FEED), Data::unreadField(Table::ITEM)]);
return new self('Unread', "/feed/items?id=$feedId&unread",
[Data::feedField($feedId, Table::Feed), Data::unreadField(Table::Item)]);
}
/**
* Create an item list with bookmarked items for the given feed
*
* @param int $feedId The ID of the feed for which items should be retrieved
* @return static An item list with bookmarked items for the given feed
* @return ItemList An item list with bookmarked items for the given feed
*/
public static function bookmarkedForFeed(int $feedId): static
public static function bookmarkedForFeed(int $feedId): self
{
return new static('Bookmarked', "/feed/items?id=$feedId&bookmarked",
[Data::feedField($feedId, Table::FEED), Data::bookmarkField(qualifier: Table::ITEM)]);
return new self('Bookmarked', "/feed/items?id=$feedId&bookmarked",
[Data::feedField($feedId, Table::Feed), Data::bookmarkField(qualifier: Table::Item)]);
}
/**
@@ -126,15 +124,15 @@ class ItemList
*
* @param string $search The item search terms / query
* @param bool $isBookmarked Whether to restrict the search to bookmarked items
* @return static An item list match the given search terms
* @return ItemList An item list match the given search terms
*/
public static function matchingSearch(string $search, bool $isBookmarked): static
public static function matchingSearch(string $search, bool $isBookmarked): self
{
$fields = [Field::EQ('content', $search, ':search')];
if ($isBookmarked) $fields[] = Data::bookmarkField(qualifier: Table::ITEM);
$list = new static('Matching' . ($isBookmarked ? ' Bookmarked' : ''),
if ($isBookmarked) $fields[] = Data::bookmarkField(qualifier: Table::Item);
$list = new self('Matching' . ($isBookmarked ? ' Bookmarked' : ''),
"/search?search=$search&items=" . ($isBookmarked ? 'bookmarked' : 'all'), $fields,
' AND ' . Table::ITEM . ".data->>'" . Configuration::$idField . "' IN "
' AND ' . Table::Item . ".data->>'" . Configuration::$idField . "' IN "
. '(SELECT ROWID FROM item_search WHERE content MATCH :search)');
$list->showIndicators = true;
$list->displayFeed = true;
@@ -146,29 +144,29 @@ class ItemList
*/
public function render(): void
{
if ($this->isError()) {
echo "<p>Error retrieving list:<br>$this->error";
if ($this->error->isSome()) {
echo "<p>Error retrieving list:<br>{$this->error->get()}";
return;
}
$return = $this->returnURL == '' ? '' : '&from=' . urlencode($this->returnURL);
$return = $this->returnURL === '' ? '' : '&from=' . urlencode($this->returnURL);
echo '<article>';
if ($this->dbList->hasItems()) {
foreach ($this->dbList->items() as $it) {
echo '<p>' . hx_get("/item?id=$it->id$return", strip_tags($it->title)) . '<br><small>';
$this->dbList->iter(function (ItemWithFeed $item) use ($return) {
echo '<p>' . hx_get("/item?id=$item->id$return", strip_tags($item->title)) . '<br><small>';
if ($this->showIndicators) {
if (!$it->isRead()) echo '<strong>Unread</strong> &nbsp; ';
if ($it->isBookmarked()) echo '<strong>Bookmarked</strong> &nbsp; ';
if (!$item->isRead()) echo '<strong>Unread</strong> &nbsp; ';
if ($item->isBookmarked()) echo '<strong>Bookmarked</strong> &nbsp; ';
}
echo '<em>' . date_time($it->updated_on ?? $it->published_on) . '</em>';
echo '<em>' . date_time($item->updated_on ?? $item->published_on) . '</em>';
if ($this->linkFeed) {
echo ' &bull; ' .
hx_get("/feed/items?id={$it->feed->id}&" . strtolower($this->itemType),
htmlentities($it->feed->title));
hx_get("/feed/items?id={$item->feed->id}&" . strtolower($this->itemType),
htmlentities($item->feed->title));
} elseif ($this->displayFeed) {
echo ' &bull; ' . htmlentities($it->feed->title);
echo ' &bull; ' . htmlentities($item->feed->title);
}
echo '</small>';
}
});
} else {
echo '<p><em>There are no ' . strtolower($this->itemType) . ' items</em>';
}

View File

@@ -1,7 +1,14 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
use BitBadger\InspiredByFSharp\Option;
use BitBadger\PDODocument\{Configuration, Custom, DocumentException, Field, Parameters, Query};
use BitBadger\PDODocument\Mapper\{DocumentMapper, ExistsMapper};
@@ -11,12 +18,12 @@ use BitBadger\PDODocument\Mapper\{DocumentMapper, ExistsMapper};
class ItemWithFeed extends Item
{
/** @var string The body of the `FROM` clause to join item and feed */
public const FROM_WITH_JOIN = Table::ITEM . ' INNER JOIN ' . Table::FEED
. ' ON ' . Table::ITEM . ".data->>'feed_id' = " . Table::FEED . ".data->>'id'";
public const FROM_WITH_JOIN = Table::Item . ' INNER JOIN ' . Table::Feed
. ' ON ' . Table::Item . ".data->>'feed_id' = " . Table::Feed . ".data->>'id'";
/** @var string The `SELECT` clause to add the feed as a property to the item's document */
public const SELECT_WITH_FEED =
'SELECT json_set(' . Table::ITEM . ".data, '$.feed', json(" . Table::FEED . '.data)) AS data FROM '
'SELECT json_set(' . Table::Item . ".data, '$.feed', json(" . Table::Feed . '.data)) AS data FROM '
. self::FROM_WITH_JOIN;
/** @var Feed The feed to which this item belongs */
@@ -31,9 +38,9 @@ class ItemWithFeed extends Item
private static function idAndUserFields(int $id): array
{
$idField = Field::EQ(Configuration::$idField, $id, ':id');
$idField->qualifier = Table::ITEM;
$userField = Field::EQ('user_id', $_SESSION[Key::USER_ID], ':user');
$userField->qualifier = Table::FEED;
$idField->qualifier = Table::Item;
$userField = Field::EQ('user_id', $_SESSION[Key::UserId], ':user');
$userField->qualifier = Table::Feed;
return [$idField, $userField];
}
@@ -55,10 +62,10 @@ class ItemWithFeed extends Item
* Retrieve an item via its ID
*
* @param int $id The ID of the item to be retrieved
* @return ItemWithFeed|false The item if it is found, false if not
* @return Option<ItemWithFeed> A `Some` value with the item if it is found, `None` otherwise
* @throws DocumentException If any is encountered
*/
public static function retrieveById(int $id): ItemWithFeed|false
public static function retrieveById(int $id): Option
{
$fields = self::idAndUserFields($id);
return Custom::single(self::SELECT_WITH_FEED . ' WHERE ' . Query::whereByFields($fields),

View File

@@ -1,18 +1,27 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
/**
* Session and other keys used for array indexes
*/
class Key {
readonly class Key
{
/** @var string The $_SESSION key for the current user's e-mail address */
public const USER_EMAIL = 'FRC_USER_EMAIL';
public const UserEmail = 'FRC_USER_EMAIL';
/** @var string The $_SESSION key for the current user's ID */
public const USER_ID = 'FRC_USER_ID';
public const UserId = 'FRC_USER_ID';
/** @var string The $_REQUEST key for the array of user messages to display */
public const USER_MSG = 'FRC_USER_MSG';
public const UserMsg = 'FRC_USER_MSG';
/** Prevent instances of this class */
private function __construct() {}
}

View File

@@ -1,25 +1,34 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
use BitBadger\InspiredByFSharp\Result;
use DOMDocument;
use DOMElement;
use DOMException;
use DOMNode;
class ParsedFeed
/**
* A feed, as parsed from the Atom or RSS XML
*/
readonly class ParsedFeed
{
/** @var string The URL for the feed */
public string $url = '';
/** @var string The title of the feed */
public string $title = '';
/** @var ?string When the feed was last updated */
public ?string $updatedOn = null;
/** @var ParsedItem[] The items contained in the feed */
public array $items = [];
/**
* Constructor
*
* @param string $url The URL for the feed
* @param string $title The title of the feed
* @param string|null $updatedOn When the feed was last updated
* @param ParsedItem[] $items The items contained in the feed
*/
public function __construct(public string $url = '', public string $title = '', public ?string $updatedOn = null,
public array $items = []) {}
/** @var string The XML namespace for Atom feeds */
public const ATOM_NS = 'http://www.w3.org/2005/Atom';
@@ -42,8 +51,9 @@ class ParsedFeed
* @return bool False, to delegate to the next error handler in the chain
* @throws DOMException If the error is a warning
*/
private static function xmlParseError(int $errno, string $errstr): bool {
if ($errno == E_WARNING && substr_count($errstr, 'DOMDocument::loadXML()') > 0) {
private static function xmlParseError(int $errno, string $errstr): bool
{
if ($errno === E_WARNING && substr_count($errstr, 'DOMDocument::loadXML()') > 0) {
throw new DOMException($errstr, $errno);
}
return false;
@@ -53,16 +63,17 @@ class ParsedFeed
* Parse a feed into an XML tree
*
* @param string $content The feed's RSS content
* @return array|DOMDocument[]|string[] ['ok' => feed] if successful, ['error' => message] if not
* @return Result<DOMDocument, string> The feed if successful, an error message if not
*/
public static function parseFeed(string $content): array {
public static function parseFeed(string $content): Result
{
set_error_handler(self::xmlParseError(...));
try {
$feed = new DOMDocument();
$feed->loadXML($content);
return ['ok' => $feed];
return Result::OK($feed);
} catch (DOMException $ex) {
return ['error' => $ex->getMessage()];
return Result::Error($ex->getMessage());
} finally {
restore_error_handler();
}
@@ -75,9 +86,10 @@ class ParsedFeed
* @param string $tagName The name of the tag whose value should be obtained
* @return string The value of the element (or "[element] not found" if that element does not exist)
*/
public static function rssValue(DOMNode $element, string $tagName): string {
public static function rssValue(DOMNode $element, string $tagName): string
{
$tags = $element->getElementsByTagName($tagName);
return $tags->length == 0 ? "$tagName not found" : $tags->item(0)->textContent;
return $tags->length === 0 ? "$tagName not found" : $tags->item(0)->textContent;
}
/**
@@ -85,13 +97,14 @@ class ParsedFeed
*
* @param DOMDocument $xml The XML received from the feed
* @param string $url The actual URL for the feed
* @return array|Feed[]|string[] ['ok' => feed] if successful, ['error' => message] if not
* @return Result<ParsedFeed, string> The feed if successful, an error message if not
*/
private static function fromRSS(DOMDocument $xml, string $url): array {
private static function fromRSS(DOMDocument $xml, string $url): Result
{
$channel = $xml->getElementsByTagName('channel')->item(0);
if (!($channel instanceof DOMElement)) {
$type = $channel?->nodeType ?? -1;
return ['error' => "Channel element not found ($type)"];
return Result::Error("Channel element not found ($type)");
}
// The Atom namespace provides a lastBuildDate, which contains the last time an item in the feed was updated; if
@@ -102,13 +115,11 @@ class ParsedFeed
}
}
$feed = new static();
$feed->title = self::rssValue($channel, 'title');
$feed->url = $url;
$feed->updatedOn = Data::formatDate($updatedOn);
foreach ($channel->getElementsByTagName('item') as $item) $feed->items[] = ParsedItem::fromRSS($item);
return ['ok' => $feed];
return Result::OK(new self(
url: $url,
title: self::rssValue($channel, 'title'),
updatedOn: Data::formatDate($updatedOn),
items: array_map(ParsedItem::fromRSS(...), iterator_to_array($channel->getElementsByTagName('item')))));
}
/**
@@ -118,10 +129,11 @@ class ParsedFeed
* @param string $name The name of the attribute whose value should be obtained
* @return string The attribute value if it exists, an empty string if not
*/
private static function attrValue(DOMNode $node, string $name): string {
private static function attrValue(DOMNode $node, string $name): string
{
return ($node->hasAttributes() ? $node->attributes->getNamedItem($name)?->value : null) ?? '';
}
/**
* Get the value of a child element by its tag name for an Atom feed
*
@@ -132,14 +144,15 @@ class ParsedFeed
* @param string $tagName The name of the tag whose value should be obtained
* @return string The value of the element (or "[element] not found" if that element does not exist)
*/
public static function atomValue(DOMNode $element, string $tagName): string {
public static function atomValue(DOMNode $element, string $tagName): string
{
$tags = $element->getElementsByTagName($tagName);
if ($tags->length == 0) return "$tagName not found";
if ($tags->length === 0) return "$tagName not found";
$tag = $tags->item(0);
if (!($tag instanceof DOMElement)) return $tag->textContent;
if (self::attrValue($tag, 'type') == 'xhtml') {
$div = $tag->getElementsByTagNameNS(self::XHTML_NS, 'div');
if ($div->length == 0) return "-- invalid XHTML content --";
if ($div->length === 0) return "-- invalid XHTML content --";
return $div->item(0)->textContent;
}
return $tag->textContent;
@@ -150,103 +163,114 @@ class ParsedFeed
*
* @param DOMDocument $xml The XML received from the feed
* @param string $url The actual URL for the feed
* @return array|Feed[] ['ok' => feed]
* @return Result<ParsedFeed, string> The feed (does not have any error handling)
*/
private static function fromAtom(DOMDocument $xml, string $url): array {
private static function fromAtom(DOMDocument $xml, string $url): Result
{
$root = $xml->getElementsByTagNameNS(self::ATOM_NS, 'feed')->item(0);
if (($updatedOn = self::atomValue($root, 'updated')) == 'pubDate not found') $updatedOn = null;
$feed = new static();
$feed->title = self::atomValue($root, 'title');
$feed->url = $url;
$feed->updatedOn = Data::formatDate($updatedOn);
foreach ($root->getElementsByTagName('entry') as $entry) $feed->items[] = ParsedItem::fromAtom($entry);
return ['ok' => $feed];
return Result::OK(new self(
url: $url,
title: self::atomValue($root, 'title'),
updatedOn: Data::formatDate($updatedOn),
items: array_map(ParsedItem::fromAtom(...), iterator_to_array($root->getElementsByTagName('entry')))));
}
/**
* Retrieve a document (http/https)
*
* @param string $url The URL of the document to retrieve
* @return array ['content' => document content, 'error' => error message, 'code' => HTTP response code,
* 'url' => effective URL]
* @return Result<array, string> ['content' => doc content, 'code' => HTTP response code, 'url' => effective URL] if
* successful, an error message if not
*/
private static function retrieveDocument(string $url): array {
private static function retrieveDocument(string $url): Result
{
$docReq = curl_init($url);
curl_setopt($docReq, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($docReq, CURLOPT_RETURNTRANSFER, true);
curl_setopt($docReq, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($docReq, CURLOPT_TIMEOUT, 15);
curl_setopt($docReq, CURLOPT_USERAGENT, self::USER_AGENT);
try {
curl_setopt($docReq, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($docReq, CURLOPT_RETURNTRANSFER, true);
curl_setopt($docReq, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($docReq, CURLOPT_TIMEOUT, 15);
curl_setopt($docReq, CURLOPT_USERAGENT, self::USER_AGENT);
$result = [
'content' => curl_exec($docReq),
'error' => curl_error($docReq),
'code' => curl_getinfo($docReq, CURLINFO_RESPONSE_CODE),
'url' => curl_getinfo($docReq, CURLINFO_EFFECTIVE_URL)
];
$error = curl_error($docReq);
if ($error !== '') return Result::Error($error);
curl_close($docReq);
return $result;
return Result::OK([
'content' => curl_exec($docReq),
'code' => curl_getinfo($docReq, CURLINFO_RESPONSE_CODE),
'url' => curl_getinfo($docReq, CURLINFO_EFFECTIVE_URL)
]);
} finally {
curl_close($docReq);
}
}
/**
* Derive a feed URL from an HTML document
*
* @param string $content The HTML document content from which to derive a feed URL
* @return array|string[] ['ok' => feed URL] if successful, ['error' => message] if not
* @return Result<string, string> The feed URL if successful, an error message if not
*/
private static function deriveFeedFromHTML(string $content): array {
private static function deriveFeedFromHTML(string $content): Result
{
$html = new DOMDocument();
$html->loadHTML(substr($content, 0, strpos($content, '</head>') + 7));
$headTags = $html->getElementsByTagName('head');
if ($headTags->length < 1) return ['error' => 'Cannot find feed at this URL'];
if ($headTags->length < 1) return Result::Error('Cannot find feed at this URL');
$head = $headTags->item(0);
foreach ($head->getElementsByTagName('link') as $link) {
if (self::attrValue($link, 'rel') == 'alternate') {
if (self::attrValue($link, 'rel') === 'alternate') {
$type = self::attrValue($link, 'type');
if ($type == 'application/rss+xml' || $type == 'application/atom+xml') {
return ['ok' => self::attrValue($link, 'href')];
if ($type === 'application/rss+xml' || $type === 'application/atom+xml') {
return Result::OK(self::attrValue($link, 'href'));
}
}
}
return ['error' => 'Cannot find feed at this URL'];
return Result::Error('Cannot find feed at this URL');
}
/**
* Retrieve the feed
*
* @param string $url The URL of the feed to retrieve
* @return array|ParsedFeed[]|string[] ['ok' => feed] if successful, ['error' => message] if not
* @return Result<ParsedFeed, string> The feed if successful, an error message if not
*/
public static function retrieve(string $url): array {
$doc = self::retrieveDocument($url);
if ($doc['error'] != '') return ['error' => $doc['error']];
if ($doc['code'] != 200) {
return ['error' => "Prospective feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}"];
}
$start = strtolower(strlen($doc['content']) >= 9 ? substr($doc['content'], 0, 9) : $doc['content']);
if ($start == '<!doctype' || str_starts_with($start, '<html')) {
$derivedURL = self::deriveFeedFromHTML($doc['content']);
if (key_exists('error', $derivedURL)) return ['error' => $derivedURL['error']];
$feedURL = $derivedURL['ok'];
if (!str_starts_with($feedURL, 'http')) {
// Relative URL; feed should be retrieved in the context of the original URL
$original = parse_url($url);
$port = key_exists('port', $original) ? ":{$original['port']}" : '';
$feedURL = $original['scheme'] . '://' . $original['host'] . $port . $feedURL;
}
$doc = self::retrieveDocument($feedURL);
}
$parsed = self::parseFeed($doc['content']);
if (key_exists('error', $parsed)) return ['error' => $parsed['error']];
$extract = $parsed['ok']->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0
? self::fromAtom(...) : self::fromRSS(...);
return $extract($parsed['ok'], $doc['url']);
public static function retrieve(string $url): Result
{
$doc = self::retrieveDocument($url)
->bind(fn(array $doc) => match ($doc['code']) {
200 => Result::OK($doc),
default => Result::Error(
"Prospective feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}"),
})
->bind(function (array $doc) use ($url) {
$start = strtolower(strlen($doc['content']) >= 9 ? substr($doc['content'], 0, 9) : $doc['content']);
return $start === '<!doctype' || str_starts_with($start, '<html')
? self::deriveFeedFromHTML($doc['content'])
->bind(function (string $feedURL) use ($url) {
if (!str_starts_with($feedURL, 'http')) {
// Relative URL; feed should be retrieved in the context of the original URL
$original = parse_url($url);
$port = key_exists('port', $original) ? ":{$original['port']}" : '';
$feedURL = $original['scheme'] . '://' . $original['host'] . $port . $feedURL;
}
return self::retrieveDocument($feedURL);
})
->bind(fn($doc) => match ($doc['code']) {
200 => Result::OK($doc),
default => Result::Error(
"Derived feed URL {$doc['url']} returned HTTP Code {$doc['code']}: {$doc['content']}"),
})
: Result::OK($doc);
});
return $doc
->bind(fn($doc) => self::parseFeed($doc['content']))
->bind(function (DOMDocument $parsed) use ($doc) {
$extract = $parsed->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0
? self::fromAtom(...) : self::fromRSS(...);
return $extract($parsed, $doc->getOK()['url']);
});
}
}

View File

@@ -1,4 +1,10 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
@@ -7,7 +13,7 @@ use DOMNode;
/**
* Information for a feed item
*/
class ParsedItem
readonly class ParsedItem
{
/**
* Constructor
@@ -27,24 +33,24 @@ class ParsedItem
* Construct a feed item from an Atom feed's `<entry>` tag
*
* @param DOMNode $node The XML node from which a feed item should be constructed
* @return static A feed item constructed from the given node
* @return ParsedItem A feed item constructed from the given node
*/
public static function fromAtom(DOMNode $node): static
public static function fromAtom(DOMNode $node): self
{
$guid = ParsedFeed::atomValue($node, 'id');
$link = '';
foreach ($node->getElementsByTagName('link') as $linkElt) {
if ($linkElt->hasAttributes()) {
$relAttr = $linkElt->attributes->getNamedItem('rel');
if ($relAttr && $relAttr->value == 'alternate') {
if ($relAttr && $relAttr->value === 'alternate') {
$link = $linkElt->attributes->getNamedItem('href')->value;
break;
}
}
}
if ($link == '' && str_starts_with($guid, 'http')) $link = $guid;
if ($link === '' && str_starts_with($guid, 'http')) $link = $guid;
return new static(
return new self(
guid: $guid,
title: ParsedFeed::atomValue($node, 'title'),
link: $link,
@@ -57,15 +63,15 @@ class ParsedItem
* Construct a feed item from an RSS feed's `<item>` tag
*
* @param DOMNode $node The XML node from which a feed item should be constructed
* @return static A feed item constructed from the given node
* @return ParsedItem A feed item constructed from the given node
*/
public static function fromRSS(DOMNode $node): static
public static function fromRSS(DOMNode $node): self
{
$itemGuid = ParsedFeed::rssValue($node, 'guid');
$updNodes = $node->getElementsByTagNameNS(ParsedFeed::ATOM_NS, 'updated');
$encNodes = $node->getElementsByTagNameNS(ParsedFeed::CONTENT_NS, 'encoded');
return new static(
return new self(
guid: $itemGuid == 'guid not found' ? ParsedFeed::rssValue($node, 'link') : $itemGuid,
title: ParsedFeed::rssValue($node, 'title'),
link: ParsedFeed::rssValue($node, 'link'),

View File

@@ -1,49 +1,77 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
use BitBadger\InspiredByFSharp\Option;
use BitBadger\PDODocument\{DocumentException, Field, Patch};
/**
* Security functions
*/
class Security
readonly class Security
{
/** @var int Run as a single user requiring no password */
public const SINGLE_USER = 0;
public const SingleUserMode = 0;
/** @var int Run as a single user requiring a password */
public const SINGLE_USER_WITH_PASSWORD = 1;
public const SingleUserPasswordMode = 1;
/** @var int Require users to provide e-mail address and password */
public const MultiUserMode = 2;
/**
* @var int Run as a single user requiring no password
* @deprecated Use Security::SingleUserMode instead
*/
public const SINGLE_USER = 0;
/**
* @var int Run as a single user requiring a password
* @deprecated Use Security::SingleUserPasswordMode instead
*/
public const SINGLE_USER_WITH_PASSWORD = 1;
/**
* @var int Require users to provide e-mail address and password
* @deprecated Use Security::MultiUserMode instead
*/
public const MULTI_USER = 2;
/** @var string The e-mail address for the single user */
public const SINGLE_USER_EMAIL = 'solouser@example.com';
public const SingleUserEmail = 'solouser@example.com';
/** @var string The password for the single user with no password */
public const SINGLE_USER_PASSWORD = 'no-password-required';
public const SingleUserPassword = 'no-password-required';
/** @var string The password algorithm to use for our passwords */
public const PW_ALGORITHM = PASSWORD_DEFAULT;
public const PasswordAlgorithm = PASSWORD_DEFAULT;
/** Prevent instances of this class */
private function __construct() {}
/**
* Verify a user's password
*
* @param User $user The user information retrieved from the database
* @param string $password The password provided by the user
* @param string|null $returnTo The URL to which the user should be redirected
* @param Option<string> $returnTo The URL to which the user should be redirected
* @throws DocumentException if any is encountered
*/
private static function verifyPassword(User $user, string $password, ?string $returnTo): void
private static function verifyPassword(User $user, string $password, Option $returnTo): void
{
if (password_verify($password, $user->password)) {
if (password_needs_rehash($user->password, self::PW_ALGORITHM)) {
Patch::byId(Table::USER, $user->id, ['password' => password_hash($password, self::PW_ALGORITHM)]);
if (password_needs_rehash($user->password, self::PasswordAlgorithm)) {
Patch::byId(Table::User, $user->id, ['password' => password_hash($password, self::PasswordAlgorithm)]);
}
$_SESSION[Key::USER_ID] = $user->id;
$_SESSION[Key::USER_EMAIL] = $user->email;
frc_redirect($returnTo ?? '/');
$_SESSION[Key::UserId] = $user->id;
$_SESSION[Key::UserEmail] = $user->email;
frc_redirect($returnTo->getOrDefault('/'));
}
}
@@ -52,21 +80,21 @@ class Security
*
* @param string $email The e-mail address for the user (cannot be the single-user mode user)
* @param string $password The password provided by the user
* @param string|null $returnTo The URL to which the user should be redirected
* @param Option<string> $returnTo The URL to which the user should be redirected
* @throws DocumentException If any is encountered
*/
public static function logOnUser(string $email, string $password, ?string $returnTo): void {
if (SECURITY_MODEL == self::SINGLE_USER_WITH_PASSWORD) {
$dbEmail = self::SINGLE_USER_EMAIL;
public static function logOnUser(string $email, string $password, Option $returnTo): void
{
if (SECURITY_MODEL === self::SingleUserPasswordMode) {
$dbEmail = self::SingleUserEmail;
} else {
if ($email == self::SINGLE_USER_EMAIL) {
if ($email === self::SingleUserEmail) {
add_error('Invalid credentials; log on unsuccessful');
return;
}
$dbEmail = $email;
}
$user = User::findByEmail($dbEmail);
if ($user) self::verifyPassword($user, $password, $returnTo);
User::findByEmail($dbEmail)->iter(fn(User $it) => self::verifyPassword($it, $password, $returnTo));
add_error('Invalid credentials; log on unsuccessful');
}
@@ -77,9 +105,10 @@ class Security
* @param string $password The new password for this user
* @throws DocumentException If any is encountered
*/
public static function updatePassword(string $email, string $password): void {
Patch::byFields(Table::USER, [Field::EQ('email', $email)],
['password' => password_hash($password, self::PW_ALGORITHM)]);
public static function updatePassword(string $email, string $password): void
{
Patch::byFields(Table::User, [Field::EQ('email', $email)],
['password' => password_hash($password, self::PasswordAlgorithm)]);
}
/**
@@ -87,13 +116,13 @@ class Security
*
* @throws DocumentException If any is encountered
*/
private static function logOnSingleUser(): void {
$user = User::findByEmail(self::SINGLE_USER_EMAIL);
if (!$user) {
User::add(self::SINGLE_USER_EMAIL, self::SINGLE_USER_PASSWORD);
$user = User::findByEmail(self::SINGLE_USER_EMAIL);
}
self::verifyPassword($user, self::SINGLE_USER_PASSWORD, $_GET['returnTo']);
private static function logOnSingleUser(): void
{
$user = User::findByEmail(self::SingleUserEmail)->getOrCall(function () {
User::add(self::SingleUserEmail, self::SingleUserPassword);
return User::findByEmail(self::SingleUserEmail)->get();
});
self::verifyPassword($user, self::SingleUserPassword, $_GET['returnTo']);
}
/**
@@ -102,12 +131,13 @@ class Security
* @param bool $redirectIfAnonymous Whether to redirect the request if there is no user logged on
* @throws DocumentException If any is encountered
*/
public static function verifyUser(bool $redirectIfAnonymous = true): void {
if (key_exists(Key::USER_ID, $_SESSION)) return;
public static function verifyUser(bool $redirectIfAnonymous = true): void
{
if (key_exists(Key::UserId, $_SESSION)) return;
if (SECURITY_MODEL == self::SINGLE_USER) self::logOnSingleUser();
if (SECURITY_MODEL === self::SingleUserMode) self::logOnSingleUser();
if (SECURITY_MODEL != self::SINGLE_USER_WITH_PASSWORD && SECURITY_MODEL != self::MULTI_USER) {
if (SECURITY_MODEL !== self::SingleUserPasswordMode && SECURITY_MODEL != self::MultiUserMode) {
die('Unrecognized security model (' . SECURITY_MODEL . ')');
}

View File

@@ -1,18 +1,27 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
/**
* Constants to use when accessing tables
*/
class Table
readonly class Table
{
/** @var string The user table */
public const USER = 'frc_user';
public const User = 'frc_user';
/** @var string The feed table */
public const FEED = 'feed';
public const Feed = 'feed';
/** @var string The item table */
public const ITEM = 'item';
public const Item = 'item';
/** Prevent instances of this class */
private function __construct() {}
}

View File

@@ -1,7 +1,14 @@
<?php declare(strict_types=1);
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace FeedReaderCentral;
use BitBadger\InspiredByFSharp\Option;
use BitBadger\PDODocument\{Custom, Document, DocumentException, Field, Find, Parameters, Query};
use BitBadger\PDODocument\Mapper\ExistsMapper;
@@ -23,12 +30,12 @@ class User
* Find a user by their e=mail address
*
* @param string $email The e-mail address of the user to retrieve
* @return User|false The user information, or null if the user is not found
* @return Option<User> A `Some` value with the user information if found, `None` otherwise
* @throws DocumentException If any is encountered
*/
public static function findByEmail(string $email): User|false
public static function findByEmail(string $email): Option
{
return Find::firstByFields(Table::USER, [Field::EQ('email', $email)], User::class);
return Find::firstByFields(Table::User, [Field::EQ('email', $email)], User::class);
}
/**
@@ -40,7 +47,7 @@ class User
*/
public static function add(string $email, string $password): void
{
Document::insert(Table::USER, new User(email: $email, password: $password));
Document::insert(Table::User, new User(email: $email, password: $password));
}
/**
@@ -51,7 +58,7 @@ class User
*/
public static function hasBookmarks(): bool
{
$fields = [Data::userIdField(Table::FEED), Data::bookmarkField(true, Table::ITEM)];
$fields = [Data::userIdField(Table::Feed), Data::bookmarkField(true, Table::Item)];
return Custom::scalar(Query\Exists::query(ItemWithFeed::FROM_WITH_JOIN, Query::whereByFields($fields)),
Parameters::addFields($fields, []), new ExistsMapper());
}