Compare commits

..

No commits in common. "main" and "v1.0.0-beta1" have entirely different histories.

35 changed files with 535 additions and 867 deletions

View File

@ -1,20 +1,10 @@
<?php <?php declare(strict_types=1);
/**
* Feed Reader Central Common Application Configuration
*
* This script sets up the environment required for the application and loads the user configuration
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{AutoId, Configuration}; use BitBadger\PDODocument\{AutoId, Configuration};
use FeedReaderCentral\Data; use FeedReaderCentral\Data;
/** The current Feed Reader Central version */ /** The current Feed Reader Central version */
const FRC_VERSION = '1.0.0-beta4'; const FRC_VERSION = '1.0.0-beta1';
/** /**
* Drop .0 or .0.0 from the end of the version to format it for display * Drop .0 or .0.0 from the end of the version to format it for display
@ -23,7 +13,7 @@ const FRC_VERSION = '1.0.0-beta4';
*/ */
function display_version(): string { function display_version(): string {
[$major, $minor, $rev] = explode('.', FRC_VERSION); [$major, $minor, $rev] = explode('.', FRC_VERSION);
$minor = $minor === '0' ? '' : ".$minor"; $minor = $minor == '0' ? '' : ".$minor";
$rev = match (true) { $rev = match (true) {
$rev == '0' => '', $rev == '0' => '',
str_starts_with($rev, '0-') => substr($rev, 1), str_starts_with($rev, '0-') => substr($rev, 1),
@ -35,7 +25,7 @@ function display_version(): string {
require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/vendor/autoload.php';
require 'user-config.php'; require 'user-config.php';
Configuration::useDSN('sqlite:' . implode(DIRECTORY_SEPARATOR, [__DIR__, 'data', DATABASE_NAME])); Configuration::$pdoDSN = 'sqlite:' . implode(DIRECTORY_SEPARATOR, [__DIR__, 'data', DATABASE_NAME]);
Configuration::$autoId = AutoId::Number; Configuration::$autoId = AutoId::Number;
Data::ensureDb(); Data::ensureDb();

View File

@ -1,14 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* Command Line Utility Start Script
*
* This loads the environment needed for a command line utility
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
require 'app-config.php'; require 'app-config.php';

View File

@ -1,6 +1,6 @@
{ {
"name": "bit-badger/feed-reader-central", "name": "bit-badger/feed-reader-central",
"minimum-stability": "beta", "minimum-stability": "dev",
"require": { "require": {
"php": ">=8.2", "php": ">=8.2",
"bit-badger/pdo-document": "^1", "bit-badger/pdo-document": "^1",

63
src/composer.lock generated
View File

@ -4,70 +4,23 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "2966efd32e555ad8b63351673e75b5a5", "content-hash": "4f0add59e384feb6787acf3685c9e031",
"packages": [ "packages": [
{
"name": "bit-badger/inspired-by-fsharp",
"version": "v1.0.0-beta2",
"source": {
"type": "git",
"url": "https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp",
"reference": "fad428a4e40b606987499b17bb2d5b7d4b04502d"
},
"require": {
"php": "^8.2"
},
"require-dev": {
"phpoption/phpoption": "^1",
"phpunit/phpunit": "^11"
},
"type": "library",
"autoload": {
"psr-4": {
"BitBadger\\InspiredByFSharp\\": "./src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Daniel J. Summers",
"email": "daniel@bitbadger.solutions",
"homepage": "https://bitbadger.solutions",
"role": "Developer"
}
],
"description": "PHP utility classes whose functionality is inspired by their F# counterparts",
"keywords": [
"option",
"result"
],
"support": {
"email": "daniel@bitbadger.solutions",
"rss": "https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp.rss",
"source": "https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp"
},
"time": "2024-07-29T17:58:33+00:00"
},
{ {
"name": "bit-badger/pdo-document", "name": "bit-badger/pdo-document",
"version": "v1.0.0-beta9", "version": "v1.0.0-alpha2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://git.bitbadger.solutions/bit-badger/pdo-document", "url": "https://git.bitbadger.solutions/bit-badger/pdo-document",
"reference": "9e0e663811d9dbbdb94a2c04ce8b874e91a7c85b" "reference": "330e27218756df8b93081a17dead8aaec789b071"
}, },
"require": { "require": {
"bit-badger/inspired-by-fsharp": "^1",
"ext-pdo": "*", "ext-pdo": "*",
"netresearch/jsonmapper": "^4", "netresearch/jsonmapper": "^4",
"php": ">=8.2" "php": ">=8.2"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^11", "phpunit/phpunit": "^11"
"square/pjson": "^0.5.0"
}, },
"type": "library", "type": "library",
"autoload": { "autoload": {
@ -89,21 +42,19 @@
"role": "Developer" "role": "Developer"
} }
], ],
"description": "Treat SQLite and PostgreSQL as document stores", "description": "Treat SQLite (and soon PostgreSQL) as a document store",
"keywords": [ "keywords": [
"database", "database",
"document", "document",
"pdo", "pdo",
"postgresql",
"sqlite" "sqlite"
], ],
"support": { "support": {
"docs": "https://bitbadger.solutions/open-source/pdo-document/",
"email": "daniel@bitbadger.solutions", "email": "daniel@bitbadger.solutions",
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss", "rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss",
"source": "https://git.bitbadger.solutions/bit-badger/pdo-document" "source": "https://git.bitbadger.solutions/bit-badger/pdo-document"
}, },
"time": "2024-07-29T20:57:51+00:00" "time": "2024-06-11T11:07:56+00:00"
}, },
{ {
"name": "netresearch/jsonmapper", "name": "netresearch/jsonmapper",
@ -159,7 +110,7 @@
], ],
"packages-dev": [], "packages-dev": [],
"aliases": [], "aliases": [],
"minimum-stability": "beta", "minimum-stability": "dev",
"stability-flags": [], "stability-flags": [],
"prefer-stable": false, "prefer-stable": false,
"prefer-lowest": false, "prefer-lowest": false,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,16 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* Bookmark Partial Handler * Bookmark Partial Handler
* *
* This will display a button which will either add or remove a bookmark for a given item. * This will display a button which will either add or remove a bookmark for a given item.
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
use BitBadger\InspiredByFSharp\Option;
use BitBadger\PDODocument\{DocumentException, Patch}; use BitBadger\PDODocument\{DocumentException, Patch};
use FeedReaderCentral\{ItemWithFeed, Table}; use FeedReaderCentral\{ItemWithFeed, Table};
@ -19,21 +14,23 @@ include '../start.php';
FeedReaderCentral\Security::verifyUser(); FeedReaderCentral\Security::verifyUser();
$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; $id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...));
if (!$item = ItemWithFeed::retrieveById($id)) not_found();
if (key_exists('action', $_GET)) { if (key_exists('action', $_GET)) {
(match ($_GET['action']) { $flag = match ($_GET['action']) {
'add' => Option::Some(1), 'add' => 1,
'remove' => Option::Some(0), 'remove' => 0,
default => Option::None(), default => null
})->iter(function (int $flag) use ($id, &$item) { };
if (isset($flag)) {
try { try {
Patch::byId(Table::Item, $id, ['is_bookmarked' => $flag]); Patch::byId(Table::ITEM, $id, ['is_bookmarked' => $flag]);
$item->is_bookmarked = $flag; $item->is_bookmarked = $flag;
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
add_error("$ex"); add_error("$ex");
} }
}); }
} }
$action = $item->isBookmarked() ? 'remove' : 'add'; $action = $item->isBookmarked() ? 'remove' : 'add';

View File

@ -1,10 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
include '../../start.php'; include '../../start.php';

View File

@ -1,10 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
include '../../start.php'; include '../../start.php';

View File

@ -1,10 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
include '../../start.php'; include '../../start.php';

View File

@ -1,10 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
include '../../start.php'; include '../../start.php';
@ -44,7 +38,7 @@ page_head('Security Modes | Documentation'); ?>
<p>In Single-User mode, the application uses a known e-mail address and password to mimic multi-user mode where that <p>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 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 <code>SECURITY_MODEL</code> in <code>user-config.php</code> to multi-user mode instead, you will need to update <code>SECURITY_MODEL</code> in <code>user-config.php</code> to
<code>Security::MultiUserMode</code>. <code>Security::MULTI_USER</code>.
<p>The e-mail address used for Single-User mode is not allowed to log on in Multi-User mode. If you want to preserve <p>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. the feeds defined by the single user, use the CLI to replace its e-mail address and password.
<p><code>php-cli utils/user.php migrate-single-user dave@example.com Dav3sPas$wort</code> <p><code>php-cli utils/user.php migrate-single-user dave@example.com Dav3sPas$wort</code>
@ -55,13 +49,13 @@ page_head('Security Modes | Documentation'); ?>
displays feeds from the Single-User mode user. The information for the other users remains in the database, 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. though, so this change is not destructive.
<h2 id=change-single-to-pw>Changing from Single-User to Single-User with Password Mode</h2> <h2 id=change-single-to-pw>Changing from Single-User to Single-User with Password Mode</h2>
<p>Set <code>SECURITY_MODEL</code> in <code>user-config.php</code> to <code>Security::SingleUserPasswordMode</code>, <p>Set <code>SECURITY_MODEL</code> in <code>user-config.php</code> to
then use the <code>user</code> CLI utility to set a password. <code>Security::SINGLE_USER_WITH_PASSWORD</code>, then use the <code>user</code> CLI utility to set a password.
<p><code>php-cli util/user.php set-single-password aNiceC0mplexPassw0rd</code> <p><code>php-cli util/user.php set-single-password aNiceC0mplexPassw0rd</code>
<h2 id=change-pw-to-single>Changing from Single-User with Password to Single-User Mode</h2> <h2 id=change-pw-to-single>Changing from Single-User with Password to Single-User Mode</h2>
<p>If you decide you do not want to enter a password, but want to maintain single-user mode, set <p>If you decide you do not want to enter a password, but want to maintain single-user mode, set
<code>SECURITY_MODEL</code> in <code>user-config.php</code> to <code>Security::SingleUserMode</code>, then run <code>SECURITY_MODEL</code> in <code>user-config.php</code> to <code>Security::SINGLE_USER</code>, then run the
the <code>user</code> CLI utility to reset the single user back to its expected default. <code>user</code> CLI utility to reset the single user back to its expected default.
<p><code>php-cli util/user.php reset-single-password</code> <p><code>php-cli util/user.php reset-single-password</code>
</article><?php </article><?php
page_foot(); page_foot();

View File

@ -1,10 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
include '../../start.php'; include '../../start.php';

View File

@ -1,16 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* Add/Edit/Delete Feed Page * Add/Edit/Delete Feed Page
* *
* Allows users to add, edit, and delete feeds * Allows users to add, edit, and delete feeds
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
use BitBadger\InspiredByFSharp\Result;
use BitBadger\PDODocument\{Delete, DocumentException, Field}; use BitBadger\PDODocument\{Delete, DocumentException, Field};
use FeedReaderCentral\{Feed, Security, Table}; use FeedReaderCentral\{Feed, Security, Table};
@ -20,40 +15,39 @@ Security::verifyUser();
$feedId = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; $feedId = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
switch ($_SERVER['REQUEST_METHOD']) { if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
case 'DELETE':
try { try {
$feed = Feed::retrieveById($feedId)->getOrCall(not_found(...)); if (!($feed = Feed::retrieveById($feedId))) not_found();
Delete::byFields(Table::Item, [Field::EQ('feed_id', $feed->id)]); Delete::byFields(Table::ITEM, [Field::EQ('feed_id', $feed->id)]);
Delete::byId(Table::Feed, $feed->id); Delete::byId(Table::FEED, $feed->id);
add_info('Feed &ldquo;' . htmlentities($feed->title) . '&rdquo; deleted successfully'); add_info('Feed &ldquo;' . htmlentities($feed->title) . '&rdquo; deleted successfully');
frc_redirect('/feeds'); frc_redirect('/feeds');
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
add_error("$ex"); add_error("$ex");
} }
break; }
case 'POST': if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try { try {
if ((int)$_POST['id'] === -1) { $isNew = $_POST['id'] == '-1';
if ($isNew) {
$result = Feed::add($_POST['url']); $result = Feed::add($_POST['url']);
} else { } else {
$feedId = (int)$_POST['id']; $feedId = (int)$_POST['id'];
$toEdit = Feed::retrieveById($feedId); $toEdit = Feed::retrieveById($feedId);
$result = $toEdit->isSome() $result = $toEdit
? Feed::update($toEdit->get(), $_POST['url']) ? Feed::update($toEdit, $_POST['url'])
: Result::Error("Feed $feedId not found"); : ['error' => "Feed $feedId not found"];
} }
$result->iter(function () { if (key_exists('ok', $result)) {
add_info('Feed saved successfully'); add_info('Feed saved successfully');
frc_redirect('/feeds'); frc_redirect('/feeds');
}); }
add_error($result->getError()); add_error($result['error']);
$feedId = 'error'; $feedId = 'error';
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
add_error("$ex"); add_error("$ex");
} }
break;
} }
if ($feedId == -1) { if ($feedId == -1) {
@ -61,9 +55,9 @@ if ($feedId == -1) {
$feed = new Feed(id: -1); $feed = new Feed(id: -1);
} else { } else {
$title = 'Edit RSS Feed'; $title = 'Edit RSS Feed';
$feed = $feedId == 'error' if ($feedId == 'error') {
? new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? '') $feed = new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? '');
: Feed::retrieveById((int)$feedId)->getOrCall(not_found(...)); } elseif (!($feed = Feed::retrieveById((int)$feedId))) not_found();
} }
page_head($title); ?> page_head($title); ?>

View File

@ -1,15 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* Feed Item List Page * Feed Item List Page
* *
* Lists items in a given feed (all, unread, or bookmarked) * Lists items in a given feed (all, unread, or bookmarked)
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
use FeedReaderCentral\{Feed, ItemList}; use FeedReaderCentral\{Feed, ItemList};
include '../../start.php'; include '../../start.php';
@ -17,7 +13,7 @@ include '../../start.php';
FeedReaderCentral\Security::verifyUser(); 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(...)); if (!($feed = Feed::retrieveById($id))) not_found();
$list = match (true) { $list = match (true) {
key_exists('unread', $_GET) => ItemList::unreadForFeed($feed->id), key_exists('unread', $_GET) => ItemList::unreadForFeed($feed->id),
@ -25,8 +21,8 @@ $list = match (true) {
default => ItemList::allForFeed($feed->id) default => ItemList::allForFeed($feed->id)
}; };
page_head(($list->itemType === '' ? '' : "$list->itemType Items | ") . strip_tags($feed->title)); page_head(($list->itemType != '' ? "$list->itemType Items | " : '') . strip_tags($feed->title));
if ($list->itemType === '') { if ($list->itemType == '') {
echo '<h1>' . htmlentities($feed->title) . '</h1>'; echo '<h1>' . htmlentities($feed->title) . '</h1>';
} else { } else {
echo '<h1 class=item_heading>' . htmlentities($feed->title) . '</h1>'; echo '<h1 class=item_heading>' . htmlentities($feed->title) . '</h1>';

View File

@ -1,15 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* Feed Maintenance Page * Feed Maintenance Page
* *
* List feeds and provide links for maintenance actions * List feeds and provide links for maintenance actions
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
use BitBadger\PDODocument\{Custom, Field, Query}; use BitBadger\PDODocument\{Custom, Field, Query};
use BitBadger\PDODocument\Mapper\{ArrayMapper, DocumentMapper}; use BitBadger\PDODocument\Mapper\{ArrayMapper, DocumentMapper};
use FeedReaderCentral\{Feed, Key, Table}; use FeedReaderCentral\{Feed, Key, Table};
@ -18,19 +14,19 @@ include '../start.php';
FeedReaderCentral\Security::verifyUser(); FeedReaderCentral\Security::verifyUser();
$field = Field::EQ('user_id', $_SESSION[Key::UserId], ':user'); $field = Field::EQ('user_id', $_SESSION[Key::USER_ID], ':user');
$feeds = Custom::list(Query\Find::byFields(Table::Feed, [$field]) . " ORDER BY lower(data->>'title')", $feeds = Custom::list(Query\Find::byFields(Table::FEED, [$field]) . " ORDER BY lower(data->>'title')",
$field->appendParameter([]), new DocumentMapper(Feed::class)); $field->appendParameter([]), new DocumentMapper(Feed::class));
page_head('Your Feeds'); page_head('Your Feeds');
echo '<h1>Your Feeds</h1><article><p class=action_buttons>' . hx_get('/feed/?id=-1', 'Add Feed') . '</p>'; echo '<h1>Your Feeds</h1><article><p class=action_buttons>' . hx_get('/feed/?id=-1', 'Add Feed') . '</p>';
$feeds->iter(function (Feed $feed) { foreach ($feeds->items() as /** @var Feed $feed */ $feed) {
$item = Table::Item; $item = Table::ITEM;
$counts = Custom::single(<<<SQL $counts = Custom::single(<<<SQL
SELECT (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed) AS total, 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_read' = 0) AS unread,
(SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_bookmarked' = 1) AS marked (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_bookmarked' = 1) AS marked
SQL, [':feed' => $feed->id], new ArrayMapper())->getOrDefault(['total' => 0, 'unread' => 0, 'marked' => 0]); SQL, [':feed' => $feed->id], new ArrayMapper()) ?? ['total' => 0, 'unread' => 0, 'marked' => 0];
echo '<p><strong>' . htmlentities($feed->title) . '</strong><br>' echo '<p><strong>' . htmlentities($feed->title) . '</strong><br>'
. '<span class=meta><em>Last Updated ' . date_time($feed->updated_on) . ' &bull; ' . '<span class=meta><em>Last Updated ' . date_time($feed->updated_on) . ' &bull; '
. 'As of ' . date_time($feed->checked_on) . '</em><br>' . hx_get("/feed/?id=$feed->id", 'Edit') . ' &bull; ' . 'As of ' . date_time($feed->checked_on) . '</em><br>' . hx_get("/feed/?id=$feed->id", 'Edit') . ' &bull; '
@ -43,6 +39,6 @@ $feeds->iter(function (Feed $feed) {
. ' hx-confirm="Are you sure you want to delete &ldquo;' . htmlspecialchars($feed->title) . ' hx-confirm="Are you sure you want to delete &ldquo;' . htmlspecialchars($feed->title)
. '&rdquo;? This will remove the feed and all its items, including unread and bookmarked.">Delete</a>' . '&rdquo;? This will remove the feed and all its items, including unread and bookmarked.">Delete</a>'
. '</span>'; . '</span>';
}); }
echo '</article>'; echo '</article>';
page_foot(); page_foot();

View File

@ -1,15 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* Home Page * Home Page
* *
* Displays a list of unread or bookmarked items for the current user * Displays a list of unread or bookmarked items for the current user
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
use FeedReaderCentral\{Feed, ItemList}; use FeedReaderCentral\{Feed, ItemList};
include '../start.php'; include '../start.php';
@ -18,16 +14,16 @@ FeedReaderCentral\Security::verifyUser();
if (key_exists('refresh', $_GET)) { if (key_exists('refresh', $_GET)) {
$refreshResult = Feed::refreshAll(); $refreshResult = Feed::refreshAll();
if ($refreshResult->isOK()) { if (key_exists('ok', $refreshResult)) {
add_info('All feeds refreshed successfully'); add_info('All feeds refreshed successfully');
} else { } else {
add_error(nl2br($refreshResult->getError())); add_error(nl2br($refreshResult['error']));
} }
} }
$list = match (true) { $list = match (true) {
key_exists('bookmarked', $_GET) => ItemList::allBookmarked(), key_exists('bookmarked', $_GET) => ItemList::allBookmarked(),
default => ItemList::allUnread(), default => ItemList::allUnread()
}; };
$title = "Your $list->itemType Items"; $title = "Your $list->itemType Items";

View File

@ -1,15 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* Item View Page * Item View Page
* *
* Retrieves and displays an item from a feed belonging to the current user * Retrieves and displays an item from a feed belonging to the current user
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
use BitBadger\PDODocument\{Delete, DocumentException, Patch}; use BitBadger\PDODocument\{Delete, DocumentException, Patch};
use FeedReaderCentral\{ItemWithFeed, Table}; use FeedReaderCentral\{ItemWithFeed, Table};
@ -20,38 +16,35 @@ FeedReaderCentral\Security::verifyUser();
$id = match (true) { $id = match (true) {
key_exists('id', $_POST) => (int)$_POST['id'], key_exists('id', $_POST) => (int)$_POST['id'],
key_exists('id', $_GET) => (int)$_GET['id'], key_exists('id', $_GET) => (int)$_GET['id'],
default => -1, default => -1
};
$from = match ($_SERVER['REQUEST_METHOD']) {
'POST' => $_POST['from'],
default => $_GET['from'] ?? '/',
}; };
switch ($_SERVER['REQUEST_METHOD']) { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
case 'POST':
try { try {
// "Keep as New" button sends a POST request to reset the is_read flag before going back to the item list // "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)) { if (ItemWithFeed::existsById($id)) {
Patch::byId(Table::Item, $id, ['is_read' => 0]); Patch::byId(Table::ITEM, $id, ['is_read' => 0]);
} }
frc_redirect($from); frc_redirect($_POST['from']);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
add_error("$ex"); add_error("$ex");
} }
break; }
case 'DELETE': $from = $_GET['from'] ?? '/';
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
try { try {
if (ItemWithFeed::existsById($id)) Delete::byId(Table::Item, $id); if (ItemWithFeed::existsById($id)) Delete::byId(Table::ITEM, $id);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
add_error("$ex"); add_error("$ex");
} }
frc_redirect($from); frc_redirect($from);
} }
$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...)); if (!$item = ItemWithFeed::retrieveById($id)) not_found();
try { try {
Patch::byId(Table::Item, $id, ['is_read' => 1]); Patch::byId(Table::ITEM, $id, ['is_read' => 1]);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
add_error("$ex"); add_error("$ex");
} }

View File

@ -1,15 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* Item Search Page * Item Search Page
* *
* Search for items across all feeds * Search for items across all feeds
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
include '../start.php'; include '../start.php';
FeedReaderCentral\Security::verifyUser(); FeedReaderCentral\Security::verifyUser();
@ -17,8 +13,8 @@ FeedReaderCentral\Security::verifyUser();
$search = $_GET['search'] ?? ''; $search = $_GET['search'] ?? '';
$items = $_GET['items'] ?? 'all'; $items = $_GET['items'] ?? 'all';
if ($search !== '') { if ($search != '') {
$list = FeedReaderCentral\ItemList::matchingSearch($search, $items === 'bookmarked'); $list = FeedReaderCentral\ItemList::matchingSearch($search, $items == 'bookmarked');
} }
page_head('Item Search'); ?> page_head('Item Search'); ?>
@ -32,8 +28,8 @@ page_head('Item Search'); ?>
<label> <label>
Items to Search Items to Search
<select name=items> <select name=items>
<option value=all <?=$items === 'all' ? ' selected' : ''?>>All</option> <option value=all <?=$items == 'all' ? ' selected' : ''?>>All</option>
<option value=bookmarked <?=$items === 'bookmarked' ? ' selected' : ''?>>Bookmarked</option> <option value=bookmarked <?=$items == 'bookmarked' ? ' selected' : ''?>>Bookmarked</option>
</select> </select>
</label> </label>
<span class=break></span> <span class=break></span>

View File

@ -1,15 +1,11 @@
<?php <?php declare(strict_types=1);
/** /**
* User Log Off Page * User Log Off Page
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
include '../../start.php'; include '../../start.php';
if (key_exists(FeedReaderCentral\Key::UserId, $_SESSION)) session_destroy(); if (key_exists(FeedReaderCentral\Key::USER_ID, $_SESSION)) session_destroy();
frc_redirect('/'); frc_redirect('/');

View File

@ -1,39 +1,34 @@
<?php <?php declare(strict_types=1);
/** /**
* User Log On Page * User Log On Page
* *
* Accepts the user's e-mail address (multi-user) and password (multi-user or single-user-with-password) and attempts * Accepts the user's e-mail address (multi-user) and password (multi-user or single-user-with-password) and attempts
* to log them on to Feed Reader Central * to log them on to Feed Reader Central
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/ */
declare(strict_types=1);
include '../../start.php'; include '../../start.php';
use BitBadger\InspiredByFSharp\Option;
use FeedReaderCentral\{Key, Security}; use FeedReaderCentral\{Key, Security};
Security::verifyUser(redirectIfAnonymous: false); Security::verifyUser(redirectIfAnonymous: false);
// Users already logged on have no need of this page // Users already logged on have no need of this page
if (key_exists(Key::UserId, $_SESSION)) frc_redirect('/'); if (key_exists(Key::USER_ID, $_SESSION)) frc_redirect('/');
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
Security::logOnUser($_POST['email'] ?? '', $_POST['password'], Option::of($_POST['returnTo'] ?? null)); Security::logOnUser($_POST['email'] ?? '', $_POST['password'], $_POST['returnTo'] ?? null);
// If we're still here, something didn't work; preserve the returnTo parameter // If we're still here, something didn't work; preserve the returnTo parameter
$_GET['returnTo'] = $_POST['returnTo']; $_GET['returnTo'] = $_POST['returnTo'];
} }
$isSingle = SECURITY_MODEL === Security::SingleUserPasswordMode; $isSingle = SECURITY_MODEL == Security::SINGLE_USER_WITH_PASSWORD;
page_head('Log On'); ?> page_head('Log On'); ?>
<h1>Log On</h1> <h1>Log On</h1>
<article> <article>
<form method=POST action=/user/log-on><?php <form method=POST action=/user/log-on><?php
if (($_GET['returnTo'] ?? '') !== '') { ?> if (($_GET['returnTo'] ?? '') != '') { ?>
<input type=hidden name=returnTo value="<?=$_GET['returnTo']?>"><?php <input type=hidden name=returnTo value="<?=$_GET['returnTo']?>"><?php
} }
if (!$isSingle) { ?> if (!$isSingle) { ?>

View File

@ -1,14 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* Web Request Start Script
*
* This loads the environment needed for a web request
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\Configuration; use BitBadger\PDODocument\Configuration;
use FeedReaderCentral\{Key, Security, User}; use FeedReaderCentral\{Key, Security, User};
@ -29,8 +19,8 @@ session_start([
*/ */
function add_message(string $level, string $message): void function add_message(string $level, string $message): void
{ {
if (!key_exists(Key::UserMsg, $_SESSION)) $_SESSION[Key::UserMsg] = []; if (!key_exists(Key::USER_MSG, $_SESSION)) $_SESSION[Key::USER_MSG] = array();
$_SESSION[Key::UserMsg][] = ['level' => $level, 'message' => $message]; $_SESSION[Key::USER_MSG][] = ['level' => $level, 'message' => $message];
} }
/** /**
@ -53,7 +43,7 @@ function add_info(string $message): void
add_message('INFO', $message); add_message('INFO', $message);
} }
/** True if this request was initiated by htmx, false if not */ /** @var bool $is_htmx 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); $is_htmx = key_exists('HTTP_HX_REQUEST', $_SERVER) && !key_exists('HTTP_HX_HISTORY_RESTORE_REQUEST', $_SERVER);
/** /**
@ -77,14 +67,14 @@ function title_bar(): void
echo "<header hx-target=#main hx-push-url=true>" echo "<header hx-target=#main hx-push-url=true>"
. "<div><a href=/ class=title>Feed Reader Central</a><span class=version>$version</span></div>" . "<div><a href=/ class=title>Feed Reader Central</a><span class=version>$version</span></div>"
. "<nav>"; . "<nav>";
if (key_exists(Key::UserId, $_SESSION)) { if (key_exists(Key::USER_ID, $_SESSION)) {
nav_link(hx_get('/feeds', 'Feeds'), true); nav_link(hx_get('/feeds', 'Feeds'), true);
if (User::hasBookmarks()) nav_link(hx_get('/?bookmarked', 'Bookmarked')); if (User::hasBookmarks()) nav_link(hx_get('/?bookmarked', 'Bookmarked'));
nav_link(hx_get('/search', 'Search')); nav_link(hx_get('/search', 'Search'));
nav_link(hx_get('/docs/', 'Docs')); nav_link(hx_get('/docs/', 'Docs'));
nav_link('<a href=/user/log-off>Log Off</a>'); nav_link('<a href=/user/log-off>Log Off</a>');
if ($_SESSION[Key::UserEmail] !== Security::SingleUserEmail) { if ($_SESSION[Key::USER_EMAIL] != Security::SINGLE_USER_EMAIL) {
nav_link($_SESSION[Key::UserEmail]); nav_link($_SESSION[Key::USER_EMAIL]);
} }
} else { } else {
nav_link(hx_get('/user/log-on', 'Log On'), true); nav_link(hx_get('/user/log-on', 'Log On'), true);
@ -110,15 +100,15 @@ function page_head(string $title): void
} }
echo '</head><body>'; echo '</head><body>';
if (!$is_htmx) title_bar(); if (!$is_htmx) title_bar();
if (sizeof($messages = $_SESSION[Key::UserMsg] ?? []) > 0) { if (sizeof($messages = $_SESSION[Key::USER_MSG] ?? []) > 0) {
echo '<div class=user_messages>'; echo '<div class=user_messages>';
array_walk($messages, function ($msg) { array_walk($messages, function ($msg) {
echo '<div class=user_message>' echo '<div class=user_message>'
. ($msg['level'] === 'INFO' ? '' : "<strong>{$msg['level']}</strong><br>") . ($msg['level'] == 'INFO' ? '' : "<strong>{$msg['level']}</strong><br>")
. $msg['message'] . '</div>'; . $msg['message'] . '</div>';
}); });
echo '</div>'; echo '</div>';
$_SESSION[Key::UserMsg] = []; $_SESSION[Key::USER_MSG] = [];
} }
} }
@ -174,7 +164,7 @@ function date_time(string $value): string
*/ */
function hx_get(string $url, string $text, string $extraAttrs = ''): string function hx_get(string $url, string $text, string $extraAttrs = ''): string
{ {
$attrs = $extraAttrs !== '' ? " $extraAttrs" : ''; $attrs = $extraAttrs != '' ? " $extraAttrs" : '';
return "<a href=\"$url\" hx-get=\"$url\"$attrs>$text</a>"; return "<a href=\"$url\" hx-get=\"$url\"$attrs>$text</a>";
} }

View File

@ -12,11 +12,11 @@ use FeedReaderCentral\{Feed, Security};
/** /**
* Which security model should the application use? Options are: * Which security model should the application use? Options are:
* - Security::SingleUserMode (no e-mail required, does not require a password) * - Security::SINGLE_USER (no e-mail required, does not require a password)
* - Security::SingleUserPasswordMode (no e-mail required, does require a password) * - Security::SINGLE_USER_WITH_PASSWORD (no e-mail required, does require a password)
* - Security::MultiUserMode (e-mail and password required for all users) * - Security::MULTI_USER (e-mail and password required for all users)
*/ */
const SECURITY_MODEL = 'ConfigureMe'; const SECURITY_MODEL = 'CONFIGURE_ME';
/** The name of the database file where users and feeds should be kept */ /** The name of the database file where users and feeds should be kept */
const DATABASE_NAME = 'frc.db'; const DATABASE_NAME = 'frc.db';
@ -30,12 +30,12 @@ const DATE_TIME_FORMAT = 'F j, Y \a\t g:ia';
/** /**
* How should item purging be done? (Purging never applies to bookmarked items.) Options are: * How should item purging be done? (Purging never applies to bookmarked items.) Options are:
* - Feed::PurgeNone - Do not purge items * - Feed::PURGE_NONE - Do not purge items
* - Feed::PurgeRead - Purge all read items whenever purging is run (will not purge unread items) * - Feed::PURGE_READ - Purge all read items whenever purging is run (will not purge unread items)
* - Feed::PurgeByDays - Purge read and unread items older than a number of days (PURGE_NUMBER below) * - Feed::PURGE_BY_DAYS - Purge read and unread items older than a number of days (PURGE_NUMBER below)
* - Feed::PurgeByCount - Purge read and unread items beyond the number to keep (PURGE_NUMBER below) * - Feed::PURGE_BY_COUNT - Purge read and unread items beyond the number to keep (PURGE_NUMBER below)
*/ */
const PURGE_TYPE = Feed::PurgeByDays; const PURGE_TYPE = Feed::PURGE_BY_DAYS;
/** /**
* For purge-by-days, how many days of items should be kept; for purge-by-count, how many items should be kept * For purge-by-days, how many days of items should be kept; for purge-by-count, how many items should be kept

View File

@ -1,16 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* Alpha 7 -> Beta 1 Database Update Utility
*
* Between these two versions, the data format changed; this utility migrates existing data to its new format.
*
* _It will be removed in v1.1._
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{Custom, Document, DocumentException}; use BitBadger\PDODocument\{Custom, Document, DocumentException};
use BitBadger\PDODocument\Mapper\{ArrayMapper, ExistsMapper}; use BitBadger\PDODocument\Mapper\{ArrayMapper, ExistsMapper};
@ -20,6 +8,8 @@ require __DIR__ . '/../cli-start.php';
cli_title('DATABASE UPDATE'); cli_title('DATABASE UPDATE');
//const PDO_DOC_DEBUG_SQL = true;
if ($argc < 2) display_help(); if ($argc < 2) display_help();
switch ($argv[1]) { switch ($argv[1]) {
@ -51,8 +41,7 @@ function display_help(): never
function json_column_exists(): bool function json_column_exists(): bool
{ {
try { 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());
->getOrDefault(['sql' => '']);
return $table && substr_compare(strtolower($table['sql']), 'data text not null', 0) >= 0; return $table && substr_compare(strtolower($table['sql']), 'data text not null', 0) >= 0;
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
printfn("ERR $ex"); printfn("ERR $ex");
@ -91,13 +80,13 @@ function run_update(): void
$users = Custom::list('SELECT * FROM old_user', [], new ArrayMapper()); $users = Custom::list('SELECT * FROM old_user', [], new ArrayMapper());
if (!$users->hasItems()) throw new DocumentException('Could not retrieve users'); if (!$users->hasItems()) throw new DocumentException('Could not retrieve users');
foreach ($users->items() as $user) { foreach ($users->items() as $user) {
Document::insert(Table::User, new User($user['id'], $user['email'], $user['password'])); Document::insert(Table::USER, new User($user['id'], $user['email'], $user['password']));
} }
printfn('Migrating feeds...'); printfn('Migrating feeds...');
$feeds = Custom::list('SELECT * FROM old_feed', [], new ArrayMapper()); $feeds = Custom::list('SELECT * FROM old_feed', [], new ArrayMapper());
if (!$feeds->hasItems()) throw new DocumentException('Could not retrieve feeds'); if (!$feeds->hasItems()) throw new DocumentException('Could not retrieve feeds');
foreach ($feeds->items() as $feed) { foreach ($feeds->items() as $feed) {
Document::insert(Table::Feed, Document::insert(Table::FEED,
new Feed($feed['id'], $feed['user_id'], $feed['url'], $feed['title'], $feed['updated_on'], new Feed($feed['id'], $feed['user_id'], $feed['url'], $feed['title'], $feed['updated_on'],
$feed['checked_on'])); $feed['checked_on']));
} }
@ -105,7 +94,7 @@ function run_update(): void
$items = Custom::list('SELECT * FROM old_item', [], new ArrayMapper()); $items = Custom::list('SELECT * FROM old_item', [], new ArrayMapper());
if (!$items->hasItems()) throw new DocumentException('Could not retrieve items'); if (!$items->hasItems()) throw new DocumentException('Could not retrieve items');
foreach ($items->items() as $item) { foreach ($items->items() as $item) {
Document::insert(Table::Item, Document::insert(Table::ITEM,
new Item($item['id'], $item['feed_id'], $item['title'], $item['item_guid'], $item['item_link'], new Item($item['id'], $item['feed_id'], $item['title'], $item['item_guid'], $item['item_link'],
$item['published_on'], $item['updated_on'], $item['content'], $item['is_read'], $item['published_on'], $item['updated_on'], $item['content'], $item['is_read'],
$item['is_bookmarked'])); $item['is_bookmarked']));

View File

@ -1,16 +1,5 @@
<?php <?php declare(strict_types=1);
/**
* Feed Refresh Utility
*
* This will refresh all known feeds in the database; it is suitable for executing via cron or as a scheduled task
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\InspiredByFSharp\Result;
use BitBadger\PDODocument\{DocumentException, Find}; use BitBadger\PDODocument\{DocumentException, Find};
use FeedReaderCentral\{Feed, Table, User}; use FeedReaderCentral\{Feed, Table, User};
@ -45,16 +34,13 @@ function refresh_all(): void
{ {
try { try {
$users = []; $users = [];
Feed::retrieveAll()->iter(function (Feed $feed) use (&$users) { iterator_apply(Feed::retrieveAll()->items(), function (Feed $feed) use (&$users) {
$result = Feed::refreshFeed($feed->id, $feed->url); $result = Feed::refreshFeed($feed->id, $feed->url);
$userKey = "$feed->user_id"; $userKey = "$feed->user_id";
if (!key_exists($userKey, $users)) { if (!key_exists($userKey, $users)) $users[$userKey] = Find::byId(Table::USER, $feed->user_id, User::class);
$users[$userKey] = Find::byId(Table::User, $feed->user_id, User::class) if (array_key_exists('error', $result)) {
->getOrDefault(new User(email: 'user-not-found'));
}
if ($result->isError()) {
printfn('ERR (%s) %s', $users[$userKey]->email, $feed->url); printfn('ERR (%s) %s', $users[$userKey]->email, $feed->url);
printfn(' %s', $result->getError()); printfn(' %s', $result['error']);
} else { } else {
printfn('OK (%s) %s', $users[$userKey]->email, $feed->url); printfn('OK (%s) %s', $users[$userKey]->email, $feed->url);
} }

View File

@ -1,14 +1,4 @@
<?php <?php declare(strict_types=1);
/**
* Search Maintenance Utility
*
* This allows on-demand refreshing of the search index (should be unnecessary in normal use)
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{Custom, DocumentException}; use BitBadger\PDODocument\{Custom, DocumentException};
use BitBadger\PDODocument\Mapper\ExistsMapper; use BitBadger\PDODocument\Mapper\ExistsMapper;

View File

@ -1,17 +1,5 @@
<?php <?php declare(strict_types=1);
/**
* User Maintenance Utility
*
* This provides several user maintenance functions for Feed Reader Central; none of these are available through the web
* interface
*
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\InspiredByFSharp\Option;
use BitBadger\PDODocument\{Count, Custom, Delete, DocumentException, Field, Parameters, Patch, Query}; use BitBadger\PDODocument\{Count, Custom, Delete, DocumentException, Field, Parameters, Patch, Query};
use FeedReaderCentral\{Security, Table, User}; use FeedReaderCentral\{Security, Table, User};
@ -48,10 +36,10 @@ switch ($argv[1]) {
printfn('Missing parameters: set-single-password requires a new password'); printfn('Missing parameters: set-single-password requires a new password');
exit(-1); exit(-1);
} }
set_password(Security::SingleUserEmail, $argv[2]); set_password(Security::SINGLE_USER_EMAIL, $argv[2]);
break; break;
case 'reset-single-password': case 'reset-single-password':
set_password(Security::SingleUserEmail, Security::SingleUserPassword); set_password(Security::SINGLE_USER_EMAIL, Security::SINGLE_USER_PASSWORD);
break; break;
case 'migrate-single-user': case 'migrate-single-user':
if ($argc < 4) { if ($argc < 4) {
@ -61,7 +49,7 @@ switch ($argv[1]) {
migrate_single_user(); migrate_single_user();
break; break;
case 'remove-single-user': case 'remove-single-user':
delete_user(Security::SingleUserEmail); delete_user(Security::SINGLE_USER_EMAIL);
break; break;
default: default:
printfn('Unrecognized option "%s"', $argv[1]); printfn('Unrecognized option "%s"', $argv[1]);
@ -104,7 +92,7 @@ function add_user(): void
try { try {
// Ensure there is not already a user with this e-mail address // Ensure there is not already a user with this e-mail address
$user = User::findByEmail($argv[2]); $user = User::findByEmail($argv[2]);
if ($user->isSome()) { if ($user) {
printfn('A user with e-mail address "%s" already exists', $argv[2]); printfn('A user with e-mail address "%s" already exists', $argv[2]);
return; return;
} }
@ -125,7 +113,7 @@ function add_user(): void
*/ */
function display_user(string $email): string function display_user(string $email): string
{ {
return $email === Security::SingleUserEmail ? 'single-user mode user' : "user \"$email\""; return $email == Security::SINGLE_USER_EMAIL ? 'single-user mode user' : "user \"$email\"";
} }
/** /**
@ -138,14 +126,14 @@ function set_password(string $email, string $password): void
// Ensure this user exists // Ensure this user exists
$user = User::findByEmail($email); $user = User::findByEmail($email);
if ($user->isNone()) { if (!$user) {
printfn('No %s exists', $displayUser); printfn('No %s exists', $displayUser);
return; return;
} }
Security::updatePassword($email, $password); Security::updatePassword($email, $password);
$msg = $email === Security::SingleUserEmail && $password === Security::SingleUserPassword $msg = $email == Security::SINGLE_USER_EMAIL && $password == Security::SINGLE_USER_PASSWORD
? 'reset' : sprintf('set to "%s"', $password); ? 'reset' : sprintf('set to "%s"', $password);
printfn('%s password %s successfully', init_cap($displayUser), $msg); printfn('%s password %s successfully', init_cap($displayUser), $msg);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
@ -164,15 +152,14 @@ function delete_user(string $email): void
$displayUser = display_user($email); $displayUser = display_user($email);
// Get the user for the provided e-mail address // Get the user for the provided e-mail address
$tryUser = User::findByEmail($email); $user = User::findByEmail($email);
if ($tryUser->isNone()) { if (!$user) {
printfn('No %s exists', $displayUser); printfn('No %s exists', $displayUser);
return; return;
} }
$user = $tryUser->get();
try { try {
$feedCount = Count::byFields(Table::Feed, [Field::EQ('user_id', $user->id)]); $feedCount = Count::byFields(Table::FEED, [Field::EQ('user_id', $user->id)]);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
printfn("$ex"); printfn("$ex");
return; return;
@ -185,12 +172,12 @@ function delete_user(string $email): void
} }
try { try {
$fields = [Field::EQ('user_id', $user->id, ':user')]; $fields = [Field::EQ('user_id', $user->id, '@user')];
Custom::nonQuery( Custom::nonQuery(
'DELETE FROM ' . Table::Item . " WHERE data->>'feed_id' IN (SELECT data->>'id' FROM " . Table::Feed 'DELETE FROM ' . Table::ITEM . " WHERE data->>'feed_id' IN (SELECT data->>'id' FROM " . Table::FEED
. ' WHERE ' . Query::whereByFields($fields) . ')', Parameters::addFields($fields, [])); . ' WHERE ' . Query::whereByFields($fields) . ')', Parameters::addFields($fields, []));
Delete::byFields(Table::Feed, $fields); Delete::byFields(Table::FEED, $fields);
Delete::byId(Table::User, $user->id); Delete::byId(Table::USER, $user->id);
printfn('%s deleted successfully', init_cap($displayUser)); printfn('%s deleted successfully', init_cap($displayUser));
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
@ -209,14 +196,13 @@ function migrate_single_user(): void
global $argv; global $argv;
try { try {
$single = User::findByEmail(Security::SingleUserEmail); if (!$single = User::findByEmail(Security::SINGLE_USER_EMAIL)) {
if ($single->isNone()) {
printfn('There is no single-user mode user to be migrated'); printfn('There is no single-user mode user to be migrated');
return; return;
} }
Patch::byId(Table::User, $single->get()->id, Patch::byId(Table::USER, $single->id,
['email' => $argv[2], 'password' => password_hash($argv[3], Security::PasswordAlgorithm)]); ['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]); printfn('The single user has been moved to "%s", with password "%s"', $argv[2], $argv[3]);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {