From 1d5a3c1c7a207bf738b40e8fd2c9338256bda044 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 25 Jun 2024 18:37:00 -0400 Subject: [PATCH 1/7] WIP with option and result types --- src/composer.json | 5 +- src/composer.lock | 153 ++++++++++++++++++++++++++++++++++++-- src/lib/Feed.php | 105 +++++++++++++------------- src/lib/ItemWithFeed.php | 5 +- src/lib/ParsedFeed.php | 99 +++++++++++++----------- src/lib/Security.php | 6 +- src/lib/User.php | 5 +- src/public/bookmark.php | 5 +- src/public/feed/index.php | 19 ++--- src/public/feed/items.php | 2 +- src/public/feeds.php | 2 +- src/public/index.php | 4 +- src/public/item.php | 2 +- src/util/db-update.php | 3 +- src/util/refresh.php | 9 ++- src/util/user.php | 14 ++-- 16 files changed, 302 insertions(+), 136 deletions(-) diff --git a/src/composer.json b/src/composer.json index 298c72f..2fd67db 100644 --- a/src/composer.json +++ b/src/composer.json @@ -1,6 +1,6 @@ { "name": "bit-badger/feed-reader-central", - "minimum-stability": "dev", + "minimum-stability": "beta", "require": { "php": ">=8.2", "bit-badger/pdo-document": "^1", @@ -8,7 +8,8 @@ "ext-dom": "*", "ext-pdo": "*", "ext-readline": "*", - "ext-sqlite3": "*" + "ext-sqlite3": "*", + "graham-campbell/result-type": "^1.1" }, "autoload": { "psr-4": { diff --git a/src/composer.lock b/src/composer.lock index a51a4d6..5601313 100644 --- a/src/composer.lock +++ b/src/composer.lock @@ -4,20 +4,21 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4f0add59e384feb6787acf3685c9e031", + "content-hash": "d5b7f01ef79cdce09364eed3dca3281d", "packages": [ { "name": "bit-badger/pdo-document", - "version": "v1.0.0-alpha2", + "version": "v1.0.0-beta2", "source": { "type": "git", "url": "https://git.bitbadger.solutions/bit-badger/pdo-document", - "reference": "330e27218756df8b93081a17dead8aaec789b071" + "reference": "50854275a8b39074966cf00370f30b3e68edc6e7" }, "require": { "ext-pdo": "*", "netresearch/jsonmapper": "^4", - "php": ">=8.2" + "php": ">=8.2", + "phpoption/phpoption": "^1.9" }, "require-dev": { "phpunit/phpunit": "^11" @@ -42,11 +43,12 @@ "role": "Developer" } ], - "description": "Treat SQLite (and soon PostgreSQL) as a document store", + "description": "Treat SQLite and PostgreSQL as document stores", "keywords": [ "database", "document", "pdo", + "postgresql", "sqlite" ], "support": { @@ -54,7 +56,69 @@ "rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss", "source": "https://git.bitbadger.solutions/bit-badger/pdo-document" }, - "time": "2024-06-11T11:07:56+00:00" + "time": "2024-06-25T14:42:26+00:00" + }, + { + "name": "graham-campbell/result-type", + "version": "v1.1.2", + "source": { + "type": "git", + "url": "https://github.com/GrahamCampbell/Result-Type.git", + "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862", + "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.9.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "An Implementation Of The Result Type", + "keywords": [ + "Graham Campbell", + "GrahamCampbell", + "Result Type", + "Result-Type", + "result" + ], + "support": { + "issues": "https://github.com/GrahamCampbell/Result-Type/issues", + "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", + "type": "tidelift" + } + ], + "time": "2023-11-12T22:16:48+00:00" }, { "name": "netresearch/jsonmapper", @@ -106,11 +170,86 @@ "source": "https://github.com/cweiske/jsonmapper/tree/v4.4.1" }, "time": "2024-01-31T06:18:54+00:00" + }, + { + "name": "phpoption/phpoption", + "version": "1.9.2", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-option.git", + "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820", + "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true + }, + "branch-alias": { + "dev-master": "1.9-dev" + } + }, + "autoload": { + "psr-4": { + "PhpOption\\": "src/PhpOption/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "https://github.com/schmittjoh" + }, + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "Option Type for PHP", + "keywords": [ + "language", + "option", + "php", + "type" + ], + "support": { + "issues": "https://github.com/schmittjoh/php-option/issues", + "source": "https://github.com/schmittjoh/php-option/tree/1.9.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption", + "type": "tidelift" + } + ], + "time": "2023-11-12T21:59:55+00:00" } ], "packages-dev": [], "aliases": [], - "minimum-stability": "dev", + "minimum-stability": "beta", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, diff --git a/src/lib/Feed.php b/src/lib/Feed.php index f24ed87..0f2309c 100644 --- a/src/lib/Feed.php +++ b/src/lib/Feed.php @@ -6,6 +6,10 @@ use BitBadger\PDODocument\{ Configuration, Custom, Document, DocumentException, DocumentList, Exists, Field, Find, Parameters, Patch, Query }; use DateTimeInterface; +use GrahamCampbell\ResultType\Error; +use GrahamCampbell\ResultType\Result; +use GrahamCampbell\ResultType\Success; +use PhpOption\Option; /** * An RSS or Atom feed @@ -64,16 +68,17 @@ 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 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 ($tryExisting->isDefined()) { + $existing = $tryExisting->get(); if ($existing->published_on != $item->publishedOn || ($existing->updated_on != ($item->updatedOn ?? ''))) { Item::update($existing->id, $item); @@ -81,26 +86,28 @@ class Feed } else { Item::add($feedId, $item); } - return ['ok' => true]; + return Success::create(true); } catch (DocumentException $ex) { - return ['error' => "$ex"]; + return Error::create("$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->error()->get(), + array_filter($results, fn(Result $it) => $it->error()->isDefined())); + return sizeof($errors) > 0 ? Error::create(implode("\n", $errors)) : Success::create(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 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]; + return Error::create('Unrecognized purge type ' . PURGE_TYPE); } $fields = [Field::EQ('feed_id', $feedId, ':feed'), Data::bookmarkField(false)]; @@ -127,9 +134,9 @@ class Feed } try { Custom::nonQuery($sql, Parameters::addFields($fields, [])); - return ['ok' => true]; + return Success::create(true); } catch (DocumentException $ex) { - return ['error' => "$ex"]; + return Error::create("$ex"); } } @@ -138,21 +145,22 @@ 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 if successful, an error message if not + * @throws DocumentException If any is encountered */ - 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']; + $tryRetrieve = ParsedFeed::retrieve($url); + if ($tryRetrieve->error()->isDefined()) return $tryRetrieve->error()->get(); + $feed = $tryRetrieve->success()->get(); 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); + if ($feedDoc->isEmpty()) return Error::create('Could not derive date last checked for feed'); + $lastChecked = date_create_immutable($feedDoc->get()->checked_on ?? WWW_EPOCH); $itemUpdate = self::updateItems($feedId, $feed, $lastChecked); - if (key_exists('error', $itemUpdate)) return $itemUpdate; + if ($itemUpdate->error()->isDefined()) return $itemUpdate->error()->get(); $patch = [ 'title' => $feed->title, @@ -162,42 +170,40 @@ class Feed if ($url == $feed->url) $patch['url'] = $feed->url; Patch::byId(Table::FEED, $feedId, $patch); } catch (DocumentException $ex) { - return ['error' => "$ex"]; + return Error::create("$ex"); } - return PURGE_TYPE == self::PURGE_NONE ? ['ok' => true] : self::purgeItems($feedId); + return PURGE_TYPE == self::PURGE_NONE ? Success::create(true) : self::purgeItems($feedId); } /** * 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 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; - - $feed = $feedExtract['ok']; + $tryRetrieve = ParsedFeed::retrieve($url); + if ($tryRetrieve->error()->isDefined()) return $tryRetrieve->error()->get(); + $feed = $tryRetrieve->success()->get(); 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"]; + return Error::create("Already subscribed to feed $feed->url"); } Document::insert(Table::FEED, self::fromParsed($feed)); - $doc = Find::firstByFields(Table::FEED, $fields, static::class); - if (!$doc) return ['error' => 'Could not retrieve inserted feed']; + $tryDoc = Find::firstByFields(Table::FEED, $fields, static::class); + if ($tryDoc->isEmpty()) return Error::create('Could not retrieve inserted feed'); + $doc = $tryDoc->get(); $result = self::updateItems($doc->id, $feed, date_create_immutable(WWW_EPOCH)); - if (key_exists('error', $result)) return $result; - - return ['ok' => $doc->id]; + return $result->error()->isDefined() ? $result->error()->get() : Success::create($doc->id); } catch (DocumentException $ex) { - return ['error' => "$ex"]; + return Error::create("$ex"); } } @@ -206,9 +212,9 @@ 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 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, @@ -217,7 +223,7 @@ class Feed return self::refreshFeed($existing->id, $url); } catch (DocumentException $ex) { - return ['error' => "$ex"]; + return Error::create("$ex"); } } @@ -238,10 +244,9 @@ class Feed /** * Refresh all feeds * - * @return array|true[]|string[] ['ok' => true] if successful, - * ['error' => message] if not (may have multiple error lines) + * @return Result 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]); @@ -249,25 +254,25 @@ class Feed $errors = []; foreach ($feeds->items() as $feed) { $result = self::refreshFeed($feed->id, $feed->url); - if (key_exists('error', $result)) $errors[] = $result['error']; + if ($result->error()->isDefined()) $errors[] = $result->error()->get(); } } catch (DocumentException $ex) { - return ['error' => "$ex"]; + return Error::create("$ex"); } - return sizeof($errors) == 0 ? ['ok' => true] : ['error' => implode("\n", $errors)]; + return sizeof($errors) == 0 ? Success::create(true) : Error::create(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 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::USER_ID]); } } diff --git a/src/lib/ItemWithFeed.php b/src/lib/ItemWithFeed.php index 602626b..3e9734d 100644 --- a/src/lib/ItemWithFeed.php +++ b/src/lib/ItemWithFeed.php @@ -4,6 +4,7 @@ namespace FeedReaderCentral; use BitBadger\PDODocument\{Configuration, Custom, DocumentException, Field, Parameters, Query}; use BitBadger\PDODocument\Mapper\{DocumentMapper, ExistsMapper}; +use PhpOption\Option; /** * A combined item and feed (used for lists) @@ -55,10 +56,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 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), diff --git a/src/lib/ParsedFeed.php b/src/lib/ParsedFeed.php index 947c389..955b66a 100644 --- a/src/lib/ParsedFeed.php +++ b/src/lib/ParsedFeed.php @@ -6,6 +6,9 @@ use DOMDocument; use DOMElement; use DOMException; use DOMNode; +use GrahamCampbell\ResultType\Error; +use GrahamCampbell\ResultType\Result; +use GrahamCampbell\ResultType\Success; class ParsedFeed { @@ -53,16 +56,16 @@ 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 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 Success::create($feed); } catch (DOMException $ex) { - return ['error' => $ex->getMessage()]; + return Error::create($ex->getMessage()); } finally { restore_error_handler(); } @@ -85,13 +88,13 @@ 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 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 Error::create("Channel element not found ($type)"); } // The Atom namespace provides a lastBuildDate, which contains the last time an item in the feed was updated; if @@ -108,7 +111,7 @@ class ParsedFeed $feed->updatedOn = Data::formatDate($updatedOn); foreach ($channel->getElementsByTagName('item') as $item) $feed->items[] = ParsedItem::fromRSS($item); - return ['ok' => $feed]; + return Success::create($feed); } /** @@ -150,7 +153,7 @@ 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 The feed (does not have any error handling) */ private static function fromAtom(DOMDocument $xml, string $url): array { $root = $xml->getElementsByTagNameNS(self::ATOM_NS, 'feed')->item(0); @@ -162,91 +165,101 @@ class ParsedFeed $feed->updatedOn = Data::formatDate($updatedOn); foreach ($root->getElementsByTagName('entry') as $entry) $feed->items[] = ParsedItem::fromAtom($entry); - return ['ok' => $feed]; + return Success::create($feed); } /** * 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 ['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 Error::create($error); - curl_close($docReq); - return $result; + return Success::create([ + '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 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, '') + 7)); $headTags = $html->getElementsByTagName('head'); - if ($headTags->length < 1) return ['error' => 'Cannot find feed at this URL']; + if ($headTags->length < 1) return Error::create('Cannot find feed at this URL'); $head = $headTags->item(0); foreach ($head->getElementsByTagName('link') as $link) { 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')]; + return Success::create(self::attrValue($link, 'href')); } } } - return ['error' => 'Cannot find feed at this URL']; + return Error::create('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 The feed if successful, an error message if not */ - public static function retrieve(string $url): array { - $doc = self::retrieveDocument($url); + public static function retrieve(string $url): Result { + $tryDoc = self::retrieveDocument($url); - if ($doc['error'] != '') return ['error' => $doc['error']]; + if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get(); + $doc = $tryDoc->success()->get(); if ($doc['code'] != 200) { - return ['error' => "Prospective feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}"]; + return Error::create("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 == ' $derivedURL['error']]; - $feedURL = $derivedURL['ok']; + if ($derivedURL->error()->isDefined()) return $derivedURL->error()->get(); + $feedURL = $derivedURL->success()->get(); 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); + $tryDoc = self::retrieveDocument($feedURL); + if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get(); + $doc = $tryDoc->success()->get(); + if ($doc['code'] != 200) { + return Error::create("Derived feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}"); + } } - $parsed = self::parseFeed($doc['content']); - if (key_exists('error', $parsed)) return ['error' => $parsed['error']]; + $tryParse = self::parseFeed($doc['content']); + if ($tryParse->error()->isDefined()) return $tryParse->error()->get(); - $extract = $parsed['ok']->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0 + $parsed = $tryParse->success()->get(); + $extract = $parsed->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0 ? self::fromAtom(...) : self::fromRSS(...); - return $extract($parsed['ok'], $doc['url']); + return $extract($parsed, $doc['url']); } } diff --git a/src/lib/Security.php b/src/lib/Security.php index 8e74926..a63b1c8 100644 --- a/src/lib/Security.php +++ b/src/lib/Security.php @@ -66,7 +66,7 @@ class Security $dbEmail = $email; } $user = User::findByEmail($dbEmail); - if ($user) self::verifyPassword($user, $password, $returnTo); + if ($user->isDefined()) self::verifyPassword($user->get(), $password, $returnTo); add_error('Invalid credentials; log on unsuccessful'); } @@ -89,11 +89,11 @@ class Security */ private static function logOnSingleUser(): void { $user = User::findByEmail(self::SINGLE_USER_EMAIL); - if (!$user) { + if ($user->isEmpty()) { 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']); + self::verifyPassword($user->get(), self::SINGLE_USER_PASSWORD, $_GET['returnTo']); } /** diff --git a/src/lib/User.php b/src/lib/User.php index 4549ce2..a53ec74 100644 --- a/src/lib/User.php +++ b/src/lib/User.php @@ -4,6 +4,7 @@ namespace FeedReaderCentral; use BitBadger\PDODocument\{Custom, Document, DocumentException, Field, Find, Parameters, Query}; use BitBadger\PDODocument\Mapper\ExistsMapper; +use PhpOption\Option; /** * A user of Feed Reader Central @@ -23,10 +24,10 @@ 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 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); } diff --git a/src/public/bookmark.php b/src/public/bookmark.php index 14a543a..c31df94 100644 --- a/src/public/bookmark.php +++ b/src/public/bookmark.php @@ -13,9 +13,8 @@ include '../start.php'; FeedReaderCentral\Security::verifyUser(); -$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; - -if (!$item = ItemWithFeed::retrieveById($id)) not_found(); +$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; +$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...)); if (key_exists('action', $_GET)) { $flag = match ($_GET['action']) { diff --git a/src/public/feed/index.php b/src/public/feed/index.php index d7e29e2..7675612 100644 --- a/src/public/feed/index.php +++ b/src/public/feed/index.php @@ -8,6 +8,7 @@ use BitBadger\PDODocument\{Delete, DocumentException, Field}; use FeedReaderCentral\{Feed, Security, Table}; +use GrahamCampbell\ResultType\Error; include '../../start.php'; @@ -17,7 +18,7 @@ $feedId = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; if ($_SERVER['REQUEST_METHOD'] == 'DELETE') { try { - if (!($feed = Feed::retrieveById($feedId))) not_found(); + $feed = Feed::retrieveById($feedId)->getOrCall(not_found(...)); Delete::byFields(Table::ITEM, [Field::EQ('feed_id', $feed->id)]); Delete::byId(Table::FEED, $feed->id); add_info('Feed “' . htmlentities($feed->title) . '” deleted successfully'); @@ -35,15 +36,15 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else { $feedId = (int)$_POST['id']; $toEdit = Feed::retrieveById($feedId); - $result = $toEdit - ? Feed::update($toEdit, $_POST['url']) - : ['error' => "Feed $feedId not found"]; + $result = $toEdit->isDefined() + ? Feed::update($toEdit->get(), $_POST['url']) + : Error::create("Feed $feedId not found"); } - if (key_exists('ok', $result)) { + if ($result->success()->isDefined()) { add_info('Feed saved successfully'); frc_redirect('/feeds'); } - add_error($result['error']); + add_error($result->error()->get()); $feedId = 'error'; } catch (DocumentException $ex) { add_error("$ex"); @@ -55,9 +56,9 @@ if ($feedId == -1) { $feed = new Feed(id: -1); } else { $title = 'Edit RSS Feed'; - if ($feedId == 'error') { - $feed = new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? ''); - } elseif (!($feed = Feed::retrieveById((int)$feedId))) not_found(); + $feed = $feedId == 'error' + ? new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? '') + : Feed::retrieveById((int)$feedId)->getOrCall(not_found(...)); } page_head($title); ?> diff --git a/src/public/feed/items.php b/src/public/feed/items.php index 2a9fd02..64d28d5 100644 --- a/src/public/feed/items.php +++ b/src/public/feed/items.php @@ -13,7 +13,7 @@ include '../../start.php'; FeedReaderCentral\Security::verifyUser(); $id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; -if (!($feed = Feed::retrieveById($id))) not_found(); +$feed = Feed::retrieveById($id)->getOrCall(not_found(...)); $list = match (true) { key_exists('unread', $_GET) => ItemList::unreadForFeed($feed->id), diff --git a/src/public/feeds.php b/src/public/feeds.php index 8cd5cfc..44d521d 100644 --- a/src/public/feeds.php +++ b/src/public/feeds.php @@ -26,7 +26,7 @@ foreach ($feeds->items() as /** @var Feed $feed */ $feed) { SELECT (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed) AS total, (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_read' = 0) AS unread, (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_bookmarked' = 1) AS marked - SQL, [':feed' => $feed->id], new ArrayMapper()) ?? ['total' => 0, 'unread' => 0, 'marked' => 0]; + SQL, [':feed' => $feed->id], new ArrayMapper())->getOrElse(['total' => 0, 'unread' => 0, 'marked' => 0]); echo '

' . htmlentities($feed->title) . '
' . 'Last Updated ' . date_time($feed->updated_on) . ' • ' . 'As of ' . date_time($feed->checked_on) . '
' . hx_get("/feed/?id=$feed->id", 'Edit') . ' • ' diff --git a/src/public/index.php b/src/public/index.php index 3c9e241..7cc074f 100644 --- a/src/public/index.php +++ b/src/public/index.php @@ -14,10 +14,10 @@ FeedReaderCentral\Security::verifyUser(); if (key_exists('refresh', $_GET)) { $refreshResult = Feed::refreshAll(); - if (key_exists('ok', $refreshResult)) { + if ($refreshResult->success()->isDefined()) { add_info('All feeds refreshed successfully'); } else { - add_error(nl2br($refreshResult['error'])); + add_error(nl2br($refreshResult->error()->get())); } } diff --git a/src/public/item.php b/src/public/item.php index cb90263..d9222f4 100644 --- a/src/public/item.php +++ b/src/public/item.php @@ -42,7 +42,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'DELETE') { frc_redirect($from); } -if (!$item = ItemWithFeed::retrieveById($id)) not_found(); +!$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...)); try { Patch::byId(Table::ITEM, $id, ['is_read' => 1]); } catch (DocumentException $ex) { diff --git a/src/util/db-update.php b/src/util/db-update.php index 0fa4088..52d73bf 100644 --- a/src/util/db-update.php +++ b/src/util/db-update.php @@ -41,7 +41,8 @@ function display_help(): never function json_column_exists(): bool { try { - $table = Custom::single("SELECT sql FROM sqlite_master WHERE tbl_name='frc_user'", [], new ArrayMapper()); + $table = Custom::single("SELECT sql FROM sqlite_master WHERE tbl_name='frc_user'", [], new ArrayMapper()) + ->getOrElse(['sql' => '']); return $table && substr_compare(strtolower($table['sql']), 'data text not null', 0) >= 0; } catch (DocumentException $ex) { printfn("ERR $ex"); diff --git a/src/util/refresh.php b/src/util/refresh.php index f7e933c..0390d76 100644 --- a/src/util/refresh.php +++ b/src/util/refresh.php @@ -37,10 +37,13 @@ function refresh_all(): void foreach (Feed::retrieveAll()->items() as /** @var Feed $feed */ $feed) { $result = Feed::refreshFeed($feed->id, $feed->url); $userKey = "$feed->user_id"; - if (!key_exists($userKey, $users)) $users[$userKey] = Find::byId(Table::USER, $feed->user_id, User::class); - if (array_key_exists('error', $result)) { + if (!key_exists($userKey, $users)) { + $users[$userKey] = Find::byId(Table::USER, $feed->user_id, User::class) + ->getOrElse(new User(email: 'user-not-found')); + } + if ($result->error()->isDefined()) { printfn('ERR (%s) %s', $users[$userKey]->email, $feed->url); - printfn(' %s', $result['error']); + printfn(' %s', $result->error()->get()); } else { printfn('OK (%s) %s', $users[$userKey]->email, $feed->url); } diff --git a/src/util/user.php b/src/util/user.php index 5de49d0..62358f2 100644 --- a/src/util/user.php +++ b/src/util/user.php @@ -92,7 +92,7 @@ function add_user(): void try { // Ensure there is not already a user with this e-mail address $user = User::findByEmail($argv[2]); - if ($user) { + if ($user->isDefined()) { printfn('A user with e-mail address "%s" already exists', $argv[2]); return; } @@ -126,7 +126,7 @@ function set_password(string $email, string $password): void // Ensure this user exists $user = User::findByEmail($email); - if (!$user) { + if ($user->isEmpty()) { printfn('No %s exists', $displayUser); return; } @@ -152,12 +152,13 @@ function delete_user(string $email): void $displayUser = display_user($email); // Get the user for the provided e-mail address - $user = User::findByEmail($email); - if (!$user) { + $tryUser = User::findByEmail($email); + if ($tryUser->isEmpty()) { printfn('No %s exists', $displayUser); return; } + $user = $tryUser->get(); try { $feedCount = Count::byFields(Table::FEED, [Field::EQ('user_id', $user->id)]); } catch (DocumentException $ex) { @@ -196,12 +197,13 @@ function migrate_single_user(): void global $argv; try { - if (!$single = User::findByEmail(Security::SINGLE_USER_EMAIL)) { + $single = User::findByEmail(Security::SINGLE_USER_EMAIL); + if ($single->isEmpty()) { printfn('There is no single-user mode user to be migrated'); return; } - Patch::byId(Table::USER, $single->id, + Patch::byId(Table::USER, $single->get()->id, ['email' => $argv[2], 'password' => password_hash($argv[3], Security::PW_ALGORITHM)]); printfn('The single user has been moved to "%s", with password "%s"', $argv[2], $argv[3]); -- 2.45.1 From 6dc264d34c0d740fcd7e18df9c43f7d63312eff1 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Thu, 25 Jul 2024 21:14:57 -0400 Subject: [PATCH 2/7] Completed result/option migration - Change casing on exposed constants - Add file-level phpdoc --- src/app-config.php | 18 +++- src/cli-start.php | 12 ++- src/composer.lock | 42 +++++---- src/lib/Data.php | 31 ++++--- src/lib/Feed.php | 142 +++++++++++++++++------------ src/lib/Item.php | 12 ++- src/lib/ItemList.php | 80 ++++++++-------- src/lib/ItemWithFeed.php | 20 ++-- src/lib/Key.php | 21 +++-- src/lib/ParsedFeed.php | 114 +++++++++++++---------- src/lib/ParsedItem.php | 26 ++++-- src/lib/Security.php | 85 +++++++++++------ src/lib/Table.php | 19 +++- src/lib/User.php | 14 ++- src/public/bookmark.php | 10 +- src/public/docs/feeds.php | 8 +- src/public/docs/index.php | 8 +- src/public/docs/items.php | 8 +- src/public/docs/security-modes.php | 18 ++-- src/public/docs/the-cli.php | 8 +- src/public/feed/index.php | 71 ++++++++------- src/public/feed/items.php | 14 ++- src/public/feeds.php | 18 ++-- src/public/index.php | 8 +- src/public/item.php | 53 ++++++----- src/public/search.php | 16 ++-- src/public/user/log-off.php | 10 +- src/public/user/log-on.php | 16 ++-- src/start.php | 32 ++++--- src/user-config.dist.php | 18 ++-- src/util/db-update.php | 22 +++-- src/util/refresh.php | 18 +++- src/util/search.php | 12 ++- src/util/user.php | 37 +++++--- 34 files changed, 658 insertions(+), 383 deletions(-) diff --git a/src/app-config.php b/src/app-config.php index f78d6c3..ca9ea16 100644 --- a/src/app-config.php +++ b/src/app-config.php @@ -1,10 +1,20 @@ - + * @license MIT + */ + +declare(strict_types=1); use BitBadger\PDODocument\{AutoId, Configuration}; use FeedReaderCentral\Data; /** The current Feed Reader Central version */ -const FRC_VERSION = '1.0.0-beta3'; +const FRC_VERSION = '1.0.0-beta4'; /** * Drop .0 or .0.0 from the end of the version to format it for display @@ -13,7 +23,7 @@ const FRC_VERSION = '1.0.0-beta3'; */ function display_version(): string { [$major, $minor, $rev] = explode('.', FRC_VERSION); - $minor = $minor == '0' ? '' : ".$minor"; + $minor = $minor === '0' ? '' : ".$minor"; $rev = match (true) { $rev == '0' => '', str_starts_with($rev, '0-') => substr($rev, 1), @@ -25,7 +35,7 @@ function display_version(): string { require __DIR__ . '/vendor/autoload.php'; require 'user-config.php'; -Configuration::$pdoDSN = 'sqlite:' . implode(DIRECTORY_SEPARATOR, [__DIR__, 'data', DATABASE_NAME]); +Configuration::useDSN('sqlite:' . implode(DIRECTORY_SEPARATOR, [__DIR__, 'data', DATABASE_NAME])); Configuration::$autoId = AutoId::Number; Data::ensureDb(); diff --git a/src/cli-start.php b/src/cli-start.php index 7dcd8a3..3ddf02a 100644 --- a/src/cli-start.php +++ b/src/cli-start.php @@ -1,4 +1,14 @@ - + * @license MIT + */ + +declare(strict_types=1); require 'app-config.php'; diff --git a/src/composer.lock b/src/composer.lock index 5601313..fabfe15 100644 --- a/src/composer.lock +++ b/src/composer.lock @@ -8,11 +8,11 @@ "packages": [ { "name": "bit-badger/pdo-document", - "version": "v1.0.0-beta2", + "version": "v1.0.0-beta7", "source": { "type": "git", "url": "https://git.bitbadger.solutions/bit-badger/pdo-document", - "reference": "50854275a8b39074966cf00370f30b3e68edc6e7" + "reference": "57d8f9ddc17169883f7dd77e51dea1443040858b" }, "require": { "ext-pdo": "*", @@ -21,7 +21,8 @@ "phpoption/phpoption": "^1.9" }, "require-dev": { - "phpunit/phpunit": "^11" + "phpunit/phpunit": "^11", + "square/pjson": "^0.5.0" }, "type": "library", "autoload": { @@ -52,32 +53,33 @@ "sqlite" ], "support": { + "docs": "https://bitbadger.solutions/open-source/pdo-document/", "email": "daniel@bitbadger.solutions", "rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss", "source": "https://git.bitbadger.solutions/bit-badger/pdo-document" }, - "time": "2024-06-25T14:42:26+00:00" + "time": "2024-07-25T00:57:23+00:00" }, { "name": "graham-campbell/result-type", - "version": "v1.1.2", + "version": "v1.1.3", "source": { "type": "git", "url": "https://github.com/GrahamCampbell/Result-Type.git", - "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862" + "reference": "3ba905c11371512af9d9bdd27d99b782216b6945" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862", - "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862", + "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/3ba905c11371512af9d9bdd27d99b782216b6945", + "reference": "3ba905c11371512af9d9bdd27d99b782216b6945", "shasum": "" }, "require": { "php": "^7.2.5 || ^8.0", - "phpoption/phpoption": "^1.9.2" + "phpoption/phpoption": "^1.9.3" }, "require-dev": { - "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + "phpunit/phpunit": "^8.5.39 || ^9.6.20 || ^10.5.28" }, "type": "library", "autoload": { @@ -106,7 +108,7 @@ ], "support": { "issues": "https://github.com/GrahamCampbell/Result-Type/issues", - "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2" + "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.3" }, "funding": [ { @@ -118,7 +120,7 @@ "type": "tidelift" } ], - "time": "2023-11-12T22:16:48+00:00" + "time": "2024-07-20T21:45:45+00:00" }, { "name": "netresearch/jsonmapper", @@ -173,16 +175,16 @@ }, { "name": "phpoption/phpoption", - "version": "1.9.2", + "version": "1.9.3", "source": { "type": "git", "url": "https://github.com/schmittjoh/php-option.git", - "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820" + "reference": "e3fac8b24f56113f7cb96af14958c0dd16330f54" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820", - "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/e3fac8b24f56113f7cb96af14958c0dd16330f54", + "reference": "e3fac8b24f56113f7cb96af14958c0dd16330f54", "shasum": "" }, "require": { @@ -190,13 +192,13 @@ }, "require-dev": { "bamarni/composer-bin-plugin": "^1.8.2", - "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + "phpunit/phpunit": "^8.5.39 || ^9.6.20 || ^10.5.28" }, "type": "library", "extra": { "bamarni-bin": { "bin-links": true, - "forward-command": true + "forward-command": false }, "branch-alias": { "dev-master": "1.9-dev" @@ -232,7 +234,7 @@ ], "support": { "issues": "https://github.com/schmittjoh/php-option/issues", - "source": "https://github.com/schmittjoh/php-option/tree/1.9.2" + "source": "https://github.com/schmittjoh/php-option/tree/1.9.3" }, "funding": [ { @@ -244,7 +246,7 @@ "type": "tidelift" } ], - "time": "2023-11-12T21:59:55+00:00" + "time": "2024-07-20T21:41:07+00:00" } ], "packages-dev": [], diff --git a/src/lib/Data.php b/src/lib/Data.php index 4174b5d..9b96a30 100644 --- a/src/lib/Data.php +++ b/src/lib/Data.php @@ -1,4 +1,10 @@ - + * @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; } diff --git a/src/lib/Feed.php b/src/lib/Feed.php index 0f2309c..a9913b8 100644 --- a/src/lib/Feed.php +++ b/src/lib/Feed.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); namespace FeedReaderCentral; @@ -6,9 +12,7 @@ use BitBadger\PDODocument\{ Configuration, Custom, Document, DocumentException, DocumentList, Exists, Field, Find, Parameters, Patch, Query }; use DateTimeInterface; -use GrahamCampbell\ResultType\Error; -use GrahamCampbell\ResultType\Result; -use GrahamCampbell\ResultType\Success; +use GrahamCampbell\ResultType\{Error, Result, Success}; use PhpOption\Option; /** @@ -19,15 +23,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; /** @@ -50,12 +78,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, @@ -75,12 +103,12 @@ class Feed $results = array_map(function ($item) use ($feedId) { try { - $tryExisting = Find::firstByFields(Table::ITEM, + $tryExisting = Find::firstByFields(Table::Item, [Field::EQ('feed_id', $feedId), Field::EQ('item_guid', $item->guid)], Item::class); if ($tryExisting->isDefined()) { $existing = $tryExisting->get(); - if ($existing->published_on != $item->publishedOn - || ($existing->updated_on != ($item->updatedOn ?? ''))) { + if ($existing->published_on !== $item->publishedOn + || ($existing->updated_on !== ($item->updatedOn ?? ''))) { Item::update($existing->id, $item); } } else { @@ -106,31 +134,34 @@ class Feed */ 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::create('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 .= ' ' . <<>'$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 .= ' ' . <<>'$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 Error::create('Unrecognized purge type ' . PURGE_TYPE); } try { Custom::nonQuery($sql, Parameters::addFields($fields, [])); @@ -155,7 +186,7 @@ class Feed $feed = $tryRetrieve->success()->get(); try { - $feedDoc = Find::byId(Table::FEED, $feedId, self::class); + $feedDoc = Find::byId(Table::Feed, $feedId, self::class); if ($feedDoc->isEmpty()) return Error::create('Could not derive date last checked for feed'); $lastChecked = date_create_immutable($feedDoc->get()->checked_on ?? WWW_EPOCH); @@ -167,13 +198,13 @@ class Feed 'updated_on' => $feed->updatedOn, 'checked_on' => Data::formatDate('now') ]; - if ($url == $feed->url) $patch['url'] = $feed->url; - Patch::byId(Table::FEED, $feedId, $patch); + if ($url !== $feed->url) $patch['url'] = $feed->url; + Patch::byId(Table::Feed, $feedId, $patch); } catch (DocumentException $ex) { return Error::create("$ex"); } - return PURGE_TYPE == self::PURGE_NONE ? Success::create(true) : self::purgeItems($feedId); + return PURGE_TYPE === self::PurgeNone ? Success::create(true) : self::purgeItems($feedId); } /** @@ -189,14 +220,14 @@ class Feed $feed = $tryRetrieve->success()->get(); try { - $fields = [Field::EQ('user_id', $_SESSION[Key::USER_ID]), Field::EQ('url', $feed->url)]; - if (Exists::byFields(Table::FEED, $fields)) { + $fields = [Field::EQ('user_id', $_SESSION[Key::UserId]), Field::EQ('url', $feed->url)]; + if (Exists::byFields(Table::Feed, $fields)) { return Error::create("Already subscribed to feed $feed->url"); } - Document::insert(Table::FEED, self::fromParsed($feed)); + Document::insert(Table::Feed, self::fromParsed($feed)); - $tryDoc = Find::firstByFields(Table::FEED, $fields, static::class); + $tryDoc = Find::firstByFields(Table::Feed, $fields, self::class); if ($tryDoc->isEmpty()) return Error::create('Could not retrieve inserted feed'); $doc = $tryDoc->get(); @@ -217,10 +248,9 @@ class Feed 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::create("$ex"); @@ -236,9 +266,9 @@ 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); } /** @@ -249,7 +279,7 @@ class Feed public static function refreshAll(): Result { try { - $feeds = self::retrieveAll($_SESSION[Key::USER_ID]); + $feeds = self::retrieveAll($_SESSION[Key::UserId]); $errors = []; foreach ($feeds->items() as $feed) { @@ -260,7 +290,7 @@ class Feed return Error::create("$ex"); } - return sizeof($errors) == 0 ? Success::create(true) : Error::create(implode("\n", $errors)); + return empty($errors) ? Success::create(true) : Error::create(implode("\n", $errors)); } /** @@ -272,7 +302,7 @@ class Feed */ public static function retrieveById(int $feedId): Option { - return Find::byId(Table::FEED, $feedId, static::class) - ->filter(fn ($it) => $it->user_id == $_SESSION[Key::USER_ID]); + return Find::byId(Table::Feed, $feedId, static::class) + ->filter(fn($it) => $it->user_id === $_SESSION[Key::UserId]); } } diff --git a/src/lib/Item.php b/src/lib/Item.php index 757d1cb..c24bb04 100644 --- a/src/lib/Item.php +++ b/src/lib/Item.php @@ -1,4 +1,10 @@ - + * @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, diff --git a/src/lib/ItemList.php b/src/lib/ItemList.php index 0a4292a..d692858 100644 --- a/src/lib/ItemList.php +++ b/src/lib/ItemList.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); namespace FeedReaderCentral; @@ -25,7 +31,7 @@ class ItemList */ public function isError(): bool { - return $this->error != ''; + return $this->error !== ''; } /** @var bool Whether to render a link to the feed to which the item belongs */ @@ -42,17 +48,17 @@ 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]; + $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) { @@ -63,11 +69,11 @@ class ItemList /** * 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 +81,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 +94,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 +107,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 +132,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; @@ -150,25 +156,25 @@ class ItemList echo "

Error retrieving list:
$this->error"; return; } - $return = $this->returnURL == '' ? '' : '&from=' . urlencode($this->returnURL); + $return = $this->returnURL === '' ? '' : '&from=' . urlencode($this->returnURL); echo '

'; if ($this->dbList->hasItems()) { - foreach ($this->dbList->items() as $it) { - echo '

' . hx_get("/item?id=$it->id$return", strip_tags($it->title)) . '
'; + $this->dbList->iter(function (ItemWithFeed $item) use ($return) { + echo '

' . hx_get("/item?id=$item->id$return", strip_tags($item->title)) . '
'; if ($this->showIndicators) { - if (!$it->isRead()) echo 'Unread   '; - if ($it->isBookmarked()) echo 'Bookmarked   '; + if (!$item->isRead()) echo 'Unread   '; + if ($item->isBookmarked()) echo 'Bookmarked   '; } - echo '' . date_time($it->updated_on ?? $it->published_on) . ''; + echo '' . date_time($item->updated_on ?? $item->published_on) . ''; if ($this->linkFeed) { echo ' • ' . - 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 ' • ' . htmlentities($it->feed->title); + echo ' • ' . htmlentities($item->feed->title); } echo ''; - } + }); } else { echo '

There are no ' . strtolower($this->itemType) . ' items'; } diff --git a/src/lib/ItemWithFeed.php b/src/lib/ItemWithFeed.php index 3e9734d..4ce96a2 100644 --- a/src/lib/ItemWithFeed.php +++ b/src/lib/ItemWithFeed.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); namespace FeedReaderCentral; @@ -12,12 +18,12 @@ use PhpOption\Option; 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 */ @@ -32,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]; } diff --git a/src/lib/Key.php b/src/lib/Key.php index d68ba38..f8848cb 100644 --- a/src/lib/Key.php +++ b/src/lib/Key.php @@ -1,18 +1,27 @@ - + * @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() {} } diff --git a/src/lib/ParsedFeed.php b/src/lib/ParsedFeed.php index 955b66a..8b15f4d 100644 --- a/src/lib/ParsedFeed.php +++ b/src/lib/ParsedFeed.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); namespace FeedReaderCentral; @@ -10,19 +16,21 @@ use GrahamCampbell\ResultType\Error; use GrahamCampbell\ResultType\Result; use GrahamCampbell\ResultType\Success; -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'; @@ -45,8 +53,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; @@ -58,7 +67,8 @@ class ParsedFeed * @param string $content The feed's RSS content * @return Result The feed if successful, an error message if not */ - public static function parseFeed(string $content): Result { + public static function parseFeed(string $content): Result + { set_error_handler(self::xmlParseError(...)); try { $feed = new DOMDocument(); @@ -78,9 +88,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; } /** @@ -88,9 +99,10 @@ class ParsedFeed * * @param DOMDocument $xml The XML received from the feed * @param string $url The actual URL for the feed - * @return Result The feed if successful, an error message if not + * @return Result The feed if successful, an error message if not */ - private static function fromRSS(DOMDocument $xml, string $url): Result { + private static function fromRSS(DOMDocument $xml, string $url): Result + { $channel = $xml->getElementsByTagName('channel')->item(0); if (!($channel instanceof DOMElement)) { $type = $channel?->nodeType ?? -1; @@ -105,13 +117,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 Success::create($feed); + return Success::create(new self( + url: $url, + title: self::rssValue($channel, 'title'), + updatedOn: Data::formatDate($updatedOn), + items: array_map(ParsedItem::fromRSS(...), iterator_to_array($channel->getElementsByTagName('item'))))); } /** @@ -121,10 +131,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 * @@ -135,14 +146,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; @@ -153,19 +165,18 @@ class ParsedFeed * * @param DOMDocument $xml The XML received from the feed * @param string $url The actual URL for the feed - * @return Result The feed (does not have any error handling) + * @return Result 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 Success::create($feed); + return Success::create(new self( + url: $url, + title: self::atomValue($root, 'title'), + updatedOn: Data::formatDate($updatedOn), + items: array_map(ParsedItem::fromAtom(...), iterator_to_array($root->getElementsByTagName('entry'))))); } /** @@ -175,7 +186,8 @@ class ParsedFeed * @return Result ['content' => doc content, 'code' => HTTP response code, 'url' => effective URL] if * successful, an error message if not */ - private static function retrieveDocument(string $url): Result { + private static function retrieveDocument(string $url): Result + { $docReq = curl_init($url); try { curl_setopt($docReq, CURLOPT_FOLLOWLOCATION, true); @@ -185,7 +197,7 @@ class ParsedFeed curl_setopt($docReq, CURLOPT_USERAGENT, self::USER_AGENT); $error = curl_error($docReq); - if ($error <> '') return Error::create($error); + if ($error !== '') return Error::create($error); return Success::create([ 'content' => curl_exec($docReq), @@ -203,16 +215,17 @@ class ParsedFeed * @param string $content The HTML document content from which to derive a feed URL * @return Result The feed URL if successful, an error message if not */ - private static function deriveFeedFromHTML(string $content): Result { + private static function deriveFeedFromHTML(string $content): Result + { $html = new DOMDocument(); $html->loadHTML(substr($content, 0, strpos($content, '') + 7)); $headTags = $html->getElementsByTagName('head'); if ($headTags->length < 1) return Error::create('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') { + if ($type === 'application/rss+xml' || $type === 'application/atom+xml') { return Success::create(self::attrValue($link, 'href')); } } @@ -226,17 +239,18 @@ class ParsedFeed * @param string $url The URL of the feed to retrieve * @return Result The feed if successful, an error message if not */ - public static function retrieve(string $url): Result { + public static function retrieve(string $url): Result + { $tryDoc = self::retrieveDocument($url); if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get(); $doc = $tryDoc->success()->get(); - if ($doc['code'] != 200) { + if ($doc['code'] !== 200) { return Error::create("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 == 'error()->isDefined()) return $derivedURL->error()->get(); $feedURL = $derivedURL->success()->get(); @@ -249,7 +263,7 @@ class ParsedFeed $tryDoc = self::retrieveDocument($feedURL); if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get(); $doc = $tryDoc->success()->get(); - if ($doc['code'] != 200) { + if ($doc['code'] !== 200) { return Error::create("Derived feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}"); } } diff --git a/src/lib/ParsedItem.php b/src/lib/ParsedItem.php index 7287506..ead9431 100644 --- a/src/lib/ParsedItem.php +++ b/src/lib/ParsedItem.php @@ -1,4 +1,10 @@ - + * @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 `` 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 `` 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'), diff --git a/src/lib/Security.php b/src/lib/Security.php index a63b1c8..20ea88c 100644 --- a/src/lib/Security.php +++ b/src/lib/Security.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); namespace FeedReaderCentral; @@ -7,25 +13,46 @@ 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 @@ -38,11 +65,11 @@ class Security private static function verifyPassword(User $user, string $password, ?string $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; + $_SESSION[Key::UserId] = $user->id; + $_SESSION[Key::UserEmail] = $user->email; frc_redirect($returnTo ?? '/'); } } @@ -55,11 +82,12 @@ class Security * @param string|null $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, ?string $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; } @@ -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,14 @@ class Security * * @throws DocumentException If any is encountered */ - private static function logOnSingleUser(): void { - $user = User::findByEmail(self::SINGLE_USER_EMAIL); + private static function logOnSingleUser(): void + { + $user = User::findByEmail(self::SingleUserEmail); if ($user->isEmpty()) { - User::add(self::SINGLE_USER_EMAIL, self::SINGLE_USER_PASSWORD); - $user = User::findByEmail(self::SINGLE_USER_EMAIL); + User::add(self::SingleUserEmail, self::SingleUserPassword); + $user = User::findByEmail(self::SingleUserEmail); } - self::verifyPassword($user->get(), self::SINGLE_USER_PASSWORD, $_GET['returnTo']); + self::verifyPassword($user->get(), self::SingleUserPassword, $_GET['returnTo']); } /** @@ -102,12 +132,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 . ')'); } diff --git a/src/lib/Table.php b/src/lib/Table.php index b4f62b0..555b685 100644 --- a/src/lib/Table.php +++ b/src/lib/Table.php @@ -1,18 +1,27 @@ - + * @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() {} } diff --git a/src/lib/User.php b/src/lib/User.php index a53ec74..85a12ce 100644 --- a/src/lib/User.php +++ b/src/lib/User.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); namespace FeedReaderCentral; @@ -29,7 +35,7 @@ class User */ 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); } /** @@ -41,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)); } /** @@ -52,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()); } diff --git a/src/public/bookmark.php b/src/public/bookmark.php index c31df94..41e99ea 100644 --- a/src/public/bookmark.php +++ b/src/public/bookmark.php @@ -1,11 +1,15 @@ - + * @license MIT */ +declare(strict_types=1); + use BitBadger\PDODocument\{DocumentException, Patch}; use FeedReaderCentral\{ItemWithFeed, Table}; @@ -24,7 +28,7 @@ if (key_exists('action', $_GET)) { }; if (isset($flag)) { try { - Patch::byId(Table::ITEM, $id, ['is_bookmarked' => $flag]); + Patch::byId(Table::Item, $id, ['is_bookmarked' => $flag]); $item->is_bookmarked = $flag; } catch (DocumentException $ex) { add_error("$ex"); diff --git a/src/public/docs/feeds.php b/src/public/docs/feeds.php index 625f578..555cd2f 100644 --- a/src/public/docs/feeds.php +++ b/src/public/docs/feeds.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); include '../../start.php'; diff --git a/src/public/docs/index.php b/src/public/docs/index.php index 436f47f..0b6c82f 100644 --- a/src/public/docs/index.php +++ b/src/public/docs/index.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); include '../../start.php'; diff --git a/src/public/docs/items.php b/src/public/docs/items.php index 933b7b3..418e47c 100644 --- a/src/public/docs/items.php +++ b/src/public/docs/items.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); include '../../start.php'; diff --git a/src/public/docs/security-modes.php b/src/public/docs/security-modes.php index 157fc73..d66f9d5 100644 --- a/src/public/docs/security-modes.php +++ b/src/public/docs/security-modes.php @@ -1,4 +1,10 @@ - + * @license MIT + */ + +declare(strict_types=1); include '../../start.php'; @@ -38,7 +44,7 @@ page_head('Security Modes | Documentation'); ?>

In Single-User mode, the application uses a known e-mail address and password to mimic multi-user mode where that user is always logged on. If you have been using the application this way, and decide that you want to run in multi-user mode instead, you will need to update SECURITY_MODEL in user-config.php to - Security::MULTI_USER. + Security::MultiUserMode.

The e-mail address used for Single-User mode is not allowed to log on in Multi-User mode. If you want to preserve the feeds defined by the single user, use the CLI to replace its e-mail address and password.

php-cli utils/user.php migrate-single-user dave@example.com Dav3sPas$wort @@ -49,13 +55,13 @@ page_head('Security Modes | Documentation'); ?> displays feeds from the Single-User mode user. The information for the other users remains in the database, though, so this change is not destructive.

Changing from Single-User to Single-User with Password Mode

-

Set SECURITY_MODEL in user-config.php to - Security::SINGLE_USER_WITH_PASSWORD, then use the user CLI utility to set a password. +

Set SECURITY_MODEL in user-config.php to Security::SingleUserPasswordMode, + then use the user CLI utility to set a password.

php-cli util/user.php set-single-password aNiceC0mplexPassw0rd

Changing from Single-User with Password to Single-User Mode

If you decide you do not want to enter a password, but want to maintain single-user mode, set - SECURITY_MODEL in user-config.php to Security::SINGLE_USER, then run the - user CLI utility to reset the single user back to its expected default. + SECURITY_MODEL in user-config.php to Security::SingleUserMode, then run + the user CLI utility to reset the single user back to its expected default.

php-cli util/user.php reset-single-password

+ * @license MIT + */ + +declare(strict_types=1); include '../../start.php'; diff --git a/src/public/feed/index.php b/src/public/feed/index.php index 7675612..04bfc7b 100644 --- a/src/public/feed/index.php +++ b/src/public/feed/index.php @@ -1,11 +1,15 @@ - + * @license MIT */ +declare(strict_types=1); + use BitBadger\PDODocument\{Delete, DocumentException, Field}; use FeedReaderCentral\{Feed, Security, Table}; use GrahamCampbell\ResultType\Error; @@ -16,39 +20,40 @@ Security::verifyUser(); $feedId = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; -if ($_SERVER['REQUEST_METHOD'] == 'DELETE') { - try { - $feed = Feed::retrieveById($feedId)->getOrCall(not_found(...)); - Delete::byFields(Table::ITEM, [Field::EQ('feed_id', $feed->id)]); - Delete::byId(Table::FEED, $feed->id); - add_info('Feed “' . htmlentities($feed->title) . '” deleted successfully'); - frc_redirect('/feeds'); - } catch (DocumentException $ex) { - add_error("$ex"); - } -} - -if ($_SERVER['REQUEST_METHOD'] == 'POST') { - try { - $isNew = $_POST['id'] == '-1'; - if ($isNew) { - $result = Feed::add($_POST['url']); - } else { - $feedId = (int)$_POST['id']; - $toEdit = Feed::retrieveById($feedId); - $result = $toEdit->isDefined() - ? Feed::update($toEdit->get(), $_POST['url']) - : Error::create("Feed $feedId not found"); - } - if ($result->success()->isDefined()) { - add_info('Feed saved successfully'); +switch ($_SERVER['REQUEST_METHOD']) { + case 'DELETE': + try { + $feed = Feed::retrieveById($feedId)->getOrCall(not_found(...)); + Delete::byFields(Table::Item, [Field::EQ('feed_id', $feed->id)]); + Delete::byId(Table::Feed, $feed->id); + add_info('Feed “' . htmlentities($feed->title) . '” deleted successfully'); frc_redirect('/feeds'); + } catch (DocumentException $ex) { + add_error("$ex"); } - add_error($result->error()->get()); - $feedId = 'error'; - } catch (DocumentException $ex) { - add_error("$ex"); - } + break; + + case 'POST': + try { + if ((int)$_POST['id'] === -1) { + $result = Feed::add($_POST['url']); + } else { + $feedId = (int)$_POST['id']; + $toEdit = Feed::retrieveById($feedId); + $result = $toEdit->isDefined() + ? Feed::update($toEdit->get(), $_POST['url']) + : Error::create("Feed $feedId not found"); + } + if ($result->success()->isDefined()) { + add_info('Feed saved successfully'); + frc_redirect('/feeds'); + } + add_error($result->error()->get()); + $feedId = 'error'; + } catch (DocumentException $ex) { + add_error("$ex"); + } + break; } if ($feedId == -1) { diff --git a/src/public/feed/items.php b/src/public/feed/items.php index 64d28d5..317d837 100644 --- a/src/public/feed/items.php +++ b/src/public/feed/items.php @@ -1,18 +1,22 @@ - + * @license MIT */ +declare(strict_types=1); + use FeedReaderCentral\{Feed, ItemList}; include '../../start.php'; FeedReaderCentral\Security::verifyUser(); -$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; +$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; $feed = Feed::retrieveById($id)->getOrCall(not_found(...)); $list = match (true) { @@ -21,8 +25,8 @@ $list = match (true) { default => ItemList::allForFeed($feed->id) }; -page_head(($list->itemType != '' ? "$list->itemType Items | " : '') . strip_tags($feed->title)); -if ($list->itemType == '') { +page_head(($list->itemType === '' ? '' : "$list->itemType Items | ") . strip_tags($feed->title)); +if ($list->itemType === '') { echo '

' . htmlentities($feed->title) . '

'; } else { echo '

' . htmlentities($feed->title) . '

'; diff --git a/src/public/feeds.php b/src/public/feeds.php index 44d521d..a883050 100644 --- a/src/public/feeds.php +++ b/src/public/feeds.php @@ -1,11 +1,15 @@ - + * @license MIT */ +declare(strict_types=1); + use BitBadger\PDODocument\{Custom, Field, Query}; use BitBadger\PDODocument\Mapper\{ArrayMapper, DocumentMapper}; use FeedReaderCentral\{Feed, Key, Table}; @@ -14,14 +18,14 @@ include '../start.php'; FeedReaderCentral\Security::verifyUser(); -$field = Field::EQ('user_id', $_SESSION[Key::USER_ID], ':user'); -$feeds = Custom::list(Query\Find::byFields(Table::FEED, [$field]) . " ORDER BY lower(data->>'title')", +$field = Field::EQ('user_id', $_SESSION[Key::UserId], ':user'); +$feeds = Custom::list(Query\Find::byFields(Table::Feed, [$field]) . " ORDER BY lower(data->>'title')", $field->appendParameter([]), new DocumentMapper(Feed::class)); page_head('Your Feeds'); echo '

Your Feeds

' . hx_get('/feed/?id=-1', 'Add Feed') . '

'; -foreach ($feeds->items() as /** @var Feed $feed */ $feed) { - $item = Table::ITEM; +$feeds->iter(function (Feed $feed) { + $item = Table::Item; $counts = Custom::single(<<>'feed_id' = :feed) AS total, (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_read' = 0) AS unread, @@ -39,6 +43,6 @@ foreach ($feeds->items() as /** @var Feed $feed */ $feed) { . ' hx-confirm="Are you sure you want to delete “' . htmlspecialchars($feed->title) . '”? This will remove the feed and all its items, including unread and bookmarked.">Delete' . ''; -} +}); echo '
'; page_foot(); diff --git a/src/public/index.php b/src/public/index.php index 7cc074f..d398049 100644 --- a/src/public/index.php +++ b/src/public/index.php @@ -1,11 +1,15 @@ - + * @license MIT */ +declare(strict_types=1); + use FeedReaderCentral\{Feed, ItemList}; include '../start.php'; diff --git a/src/public/item.php b/src/public/item.php index d9222f4..f937a8a 100644 --- a/src/public/item.php +++ b/src/public/item.php @@ -1,11 +1,15 @@ - + * @license MIT */ +declare(strict_types=1); + use BitBadger\PDODocument\{Delete, DocumentException, Patch}; use FeedReaderCentral\{ItemWithFeed, Table}; @@ -16,35 +20,38 @@ FeedReaderCentral\Security::verifyUser(); $id = match (true) { key_exists('id', $_POST) => (int)$_POST['id'], key_exists('id', $_GET) => (int)$_GET['id'], - default => -1 + default => -1, +}; +$from = match ($_SERVER['REQUEST_METHOD']) { + 'POST' => $_POST['from'], + default => $_GET['from'] ?? '/', }; -if ($_SERVER['REQUEST_METHOD'] == 'POST') { - try { - // "Keep as New" button sends a POST request to reset the is_read flag before going back to the item list - if (ItemWithFeed::existsById($id)) { - Patch::byId(Table::ITEM, $id, ['is_read' => 0]); +switch ($_SERVER['REQUEST_METHOD']) { + case 'POST': + try { + // "Keep as New" button sends a POST request to reset the is_read flag before going back to the item list + if (ItemWithFeed::existsById($id)) { + Patch::byId(Table::Item, $id, ['is_read' => 0]); + } + frc_redirect($from); + } catch (DocumentException $ex) { + add_error("$ex"); } - frc_redirect($_POST['from']); - } catch (DocumentException $ex) { - add_error("$ex"); - } -} + break; -$from = $_GET['from'] ?? '/'; - -if ($_SERVER['REQUEST_METHOD'] == 'DELETE') { - try { - if (ItemWithFeed::existsById($id)) Delete::byId(Table::ITEM, $id); - } catch (DocumentException $ex) { - add_error("$ex"); - } - frc_redirect($from); + case 'DELETE': + try { + if (ItemWithFeed::existsById($id)) Delete::byId(Table::Item, $id); + } catch (DocumentException $ex) { + add_error("$ex"); + } + frc_redirect($from); } !$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...)); try { - Patch::byId(Table::ITEM, $id, ['is_read' => 1]); + Patch::byId(Table::Item, $id, ['is_read' => 1]); } catch (DocumentException $ex) { add_error("$ex"); } diff --git a/src/public/search.php b/src/public/search.php index 2352774..1e28247 100644 --- a/src/public/search.php +++ b/src/public/search.php @@ -1,11 +1,15 @@ - + * @license MIT */ +declare(strict_types=1); + include '../start.php'; FeedReaderCentral\Security::verifyUser(); @@ -13,8 +17,8 @@ FeedReaderCentral\Security::verifyUser(); $search = $_GET['search'] ?? ''; $items = $_GET['items'] ?? 'all'; -if ($search != '') { - $list = FeedReaderCentral\ItemList::matchingSearch($search, $items == 'bookmarked'); +if ($search !== '') { + $list = FeedReaderCentral\ItemList::matchingSearch($search, $items === 'bookmarked'); } page_head('Item Search'); ?> @@ -28,8 +32,8 @@ page_head('Item Search'); ?> diff --git a/src/public/user/log-off.php b/src/public/user/log-off.php index d99df31..18125a3 100644 --- a/src/public/user/log-off.php +++ b/src/public/user/log-off.php @@ -1,11 +1,15 @@ - + * @license MIT */ +declare(strict_types=1); + include '../../start.php'; -if (key_exists(FeedReaderCentral\Key::USER_ID, $_SESSION)) session_destroy(); +if (key_exists(FeedReaderCentral\Key::UserId, $_SESSION)) session_destroy(); frc_redirect('/'); diff --git a/src/public/user/log-on.php b/src/public/user/log-on.php index 44bc257..57cb9f3 100644 --- a/src/public/user/log-on.php +++ b/src/public/user/log-on.php @@ -1,12 +1,16 @@ - + * @license MIT */ +declare(strict_types=1); + include '../../start.php'; use FeedReaderCentral\{Key, Security}; @@ -14,21 +18,21 @@ use FeedReaderCentral\{Key, Security}; Security::verifyUser(redirectIfAnonymous: false); // Users already logged on have no need of this page -if (key_exists(Key::USER_ID, $_SESSION)) frc_redirect('/'); +if (key_exists(Key::UserId, $_SESSION)) frc_redirect('/'); -if ($_SERVER['REQUEST_METHOD'] == 'POST') { +if ($_SERVER['REQUEST_METHOD'] === 'POST') { Security::logOnUser($_POST['email'] ?? '', $_POST['password'], $_POST['returnTo'] ?? null); // If we're still here, something didn't work; preserve the returnTo parameter $_GET['returnTo'] = $_POST['returnTo']; } -$isSingle = SECURITY_MODEL == Security::SINGLE_USER_WITH_PASSWORD; +$isSingle = SECURITY_MODEL === Security::SingleUserPasswordMode; page_head('Log On'); ?>

Log On

+ if (($_GET['returnTo'] ?? '') !== '') { ?> diff --git a/src/start.php b/src/start.php index 05082d6..54ea35b 100644 --- a/src/start.php +++ b/src/start.php @@ -1,4 +1,14 @@ - + * @license MIT + */ + +declare(strict_types=1); use BitBadger\PDODocument\Configuration; use FeedReaderCentral\{Key, Security, User}; @@ -19,8 +29,8 @@ session_start([ */ function add_message(string $level, string $message): void { - if (!key_exists(Key::USER_MSG, $_SESSION)) $_SESSION[Key::USER_MSG] = array(); - $_SESSION[Key::USER_MSG][] = ['level' => $level, 'message' => $message]; + if (!key_exists(Key::UserMsg, $_SESSION)) $_SESSION[Key::UserMsg] = []; + $_SESSION[Key::UserMsg][] = ['level' => $level, 'message' => $message]; } /** @@ -43,7 +53,7 @@ function add_info(string $message): void add_message('INFO', $message); } -/** @var bool $is_htmx True if this request was initiated by htmx, false if not */ +/** True if this request was initiated by htmx, false if not */ $is_htmx = key_exists('HTTP_HX_REQUEST', $_SERVER) && !key_exists('HTTP_HX_HISTORY_RESTORE_REQUEST', $_SERVER); /** @@ -67,14 +77,14 @@ function title_bar(): void echo "
" . "" . "