Compare commits

..

No commits in common. "develop" and "v0.19" have entirely different histories.

748 changed files with 33441 additions and 26169 deletions

View file

@ -1,21 +1,18 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true root = true
# Unix-style newlines with a newline ending every file
[*] [*]
charset = utf-8
end_of_line = lf end_of_line = lf
indent_size = 4 charset = utf-8
indent_style = space
insert_final_newline = true insert_final_newline = true
trim_trailing_whitespace = true trim_trailing_whitespace = true
indent_style = space
[*.{js,css}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4 indent_size = 4
# Tab indentation
[Makefile]
indent_style = tab
tab_width = 4

14
.env.dusk.testing Normal file
View file

@ -0,0 +1,14 @@
APP_ENV=testing
APP_DEBUG=true
APP_KEY=base64:6DJhvZLVjE6dD4Cqrteh+6Z5vZlG+v/soCKcDHLOAH0=
APP_URL=http://localhost:8000
APP_LONGURL=localhost
APP_SHORTURL=local
DB_CONNECTION=travis
CACHE_DRIVER=array
SESSION_DRIVER=file
QUEUE_DRIVER=sync
SCOUT_DRIVER=pgsql

View file

@ -1,90 +1,64 @@
APP_NAME=Laravel APP_NAME=Laravel
APP_ENV=local APP_ENV=production
APP_KEY= APP_KEY=SomeRandomString # Leave this
APP_DEBUG=true APP_DEBUG=false
APP_TIMEZONE=UTC APP_LOG_LEVEL=warning
APP_URL=https://example.com
APP_LOCALE=en DB_CONNECTION=pgsql
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1 DB_HOST=127.0.0.1
DB_PORT=3306 DB_PORT=5432
DB_DATABASE=laravel DB_DATABASE=
DB_USERNAME=root DB_USERNAME=
DB_PASSWORD= DB_PASSWORD=
SESSION_DRIVER=database BROADCAST_DRIVER=log
SESSION_LIFETIME=120 CACHE_DRIVER=file
SESSION_ENCRYPT=false SESSION_DRIVER=file
SESSION_PATH=/ QUEUE_DRIVER=sync
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1 REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null REDIS_PASSWORD=null
REDIS_PORT=6379 REDIS_PORT=6379
MAIL_MAILER=log MAIL_DRIVER=smtp
MAIL_SCHEME=null MAIL_HOST=smtp.mailtrap.io
MAIL_HOST=127.0.0.1
MAIL_PORT=2525 MAIL_PORT=2525
MAIL_USERNAME=null MAIL_USERNAME=null
MAIL_PASSWORD=null MAIL_PASSWORD=null
MAIL_ENCRYPTION=null MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID= PUSHER_APP_ID=
AWS_SECRET_ACCESS_KEY= PUSHER_APP_KEY=
AWS_DEFAULT_REGION=us-east-1 PUSHER_APP_SECRET=
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}" AWS_S3_KEY=your-key
AWS_S3_SECRET=your-secret
AWS_S3_REGION=region
AWS_S3_BUCKET=your-bucket
AWS_S3_URL=https://xxxxxxx.s3-region.amazonaws.com
ADMIN_USER=admin# pick something better, this is used for `/admin` APP_URL=https://example.com # This one is necessary
APP_LONGURL=example.com
APP_SHORTURL=examp.le
ADMIN_USER=admin # pick something better, this is used for `/admin`
ADMIN_PASS=password ADMIN_PASS=password
DISPLAY_NAME='Joe Bloggs'# This is used for example in the header and titles DISPLAY_NAME='Joe Bloggs' # This is used for example in the header and titles
TWITTER_CONSUMER_KEY= TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET= TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN= TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET= TWITTER_ACCESS_TOKEN_SECRET=
SCOUT_DRIVER=database SCOUT_DRIVER=pgsql
SCOUT_QUEUE=false
SESSION_SECURE_COOKIE=true PIWIK=false
SESSION_SAME_SITE=strict PIWIK_ID=1
PIWIK_URL=https://analytics.jmb.lv/piwik.php
LOG_SLACK_WEBHOOK_URL= APP_TIMEZONE=UTC
APP_LANG=en
APP_LOG=daily
SECURE_SESSION_COOKIE=true
FLARE_KEY= SLACK_WEBHOOK_URL=
IGNITION_OPEN_AI_KEY=
BRIDGY_MASTODON_TOKEN=

17
.env.travis Normal file
View file

@ -0,0 +1,17 @@
APP_ENV=testing
APP_DEBUG=true
APP_KEY=base64:6DJhvZLVjE6dD4Cqrteh+6Z5vZlG+v/soCKcDHLOAH0=
APP_URL=http://jonnybarnes.localhost:8000
APP_LONGURL=jonnybarnes.localhost
APP_SHORTURL=jmb.localhost
DB_CONNECTION=travis
CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync
SCOUT_DRIVER=pgsql
DISPLAY_NAME='Travis Test'
USER_NAME=travis

24
.eslintrc.yml Normal file
View file

@ -0,0 +1,24 @@
parserOptions:
sourceType: 'module'
extends: 'eslint:recommended'
env:
browser: true
es6: true
rules:
indent:
- error
- 4
linebreak-style:
- error
- unix
quotes:
- error
- single
semi:
- error
- always
no-console:
- error
- allow:
- warn
- error

12
.gitattributes vendored
View file

@ -1,7 +1,5 @@
* text=auto eol=lf * text=auto
*.css linguist-vendored
*.blade.php diff=html *.scss linguist-vendored
*.css diff=css *.js linguist-vendored
*.html diff=html CHANGELOG.md export-ignore
*.md diff=markdown
*.php diff=php

17
.gitignore vendored
View file

@ -1,24 +1,15 @@
/.phpunit.cache
/node_modules /node_modules
/public/build
/public/coverage
/public/hot /public/hot
/public/files
/public/storage /public/storage
/storage/*.key /storage/*.key
/vendor /vendor
.env .env
.env.backup
.env.production
.phpunit.result.cache .phpunit.result.cache
Homestead.json Homestead.json
Homestead.yaml Homestead.yaml
auth.json
npm-debug.log npm-debug.log
yarn-error.log yarn-error.log
/.fleet # Custom paths in /public
/.idea /public/coverage
/.vscode /public/files
ray.php /public/keybase.txt
/public/gpg.key
/public/assets/img/favicon.png

9
.styleci.yml Normal file
View file

@ -0,0 +1,9 @@
preset: laravel
disabled:
- concat_without_spaces
- simplified_null_return
- single_import_per_statement
finder:
path: app/

View file

@ -1,3 +1,6 @@
{ {
"extends": ["stylelint-config-standard"] "extends": "stylelint-config-standard",
"rules": {
"indentation": 4
}
} }

70
.travis.yml Normal file
View file

@ -0,0 +1,70 @@
language: php
sudo: false
dist: trusty
cache:
- apt
addons:
hosts:
- jmb.localhost
- jonnybarnes.localhost
postgresql: "9.6"
apt:
packages:
- nginx-full
- realpath
- postgresql-9.6-postgis-2.3
- imagemagick
#- google-chrome-stable
artifacts:
s3_region: "eu-west-1"
paths:
- $(ls tests/Browser/screenshots/*.png | tr "\n" ":")
- $(ls tests/Browser/console/*.log | tr "\n" ":")
- $(ls storage/logs/*.log | tr "\n" ":")
- $(ls /tmp/*.log | tr "\n" ":")
services:
- postgresql
env:
global:
- setup=basic
php:
- 7.2
- 7.3
before_install:
- printf "\n" | pecl install imagick
- cp .env.travis .env
- echo 'error_log = "/tmp/php.error.log"' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini
- psql -U travis -c 'create database travis_ci_test'
- psql -U travis -d travis_ci_test -c 'create extension postgis'
- travis_retry composer self-update --preview
- curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
install:
- if [[ $setup = 'basic' ]]; then travis_retry composer install --no-interaction --prefer-dist; fi
- if [[ $setup = 'stable' ]]; then travis_retry composer update --no-interaction --prefer-dist --prefer-stable; fi
- if [[ $setup = 'lowest' ]]; then travis_retry composer update --no-interaction --prefer-dist --prefer-lowest --prefer-stable; fi
- travis/install-nginx.sh
- . $HOME/.nvm/nvm.sh
- nvm install stable
- nvm use stable
- npm i puppeteer
before_script:
- php artisan key:generate
- php artisan migrate
- php artisan db:seed
#- google-chrome-stable --headless --disable-gpu --remote-debugging-port=9515 http://localhost:8000 &
#- sleep 5
script:
- php vendor/bin/phpunit
- php phpcs.phar
#- php artisan dusk
- php vendor/bin/security-checker security:check --end-point=http://security.sensiolabs.org/check_lock

View file

@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
namespace App\CommonMark\Generators;
use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface;
use League\CommonMark\Extension\Mention\Mention;
use League\CommonMark\Node\Inline\AbstractInline;
class MentionGenerator implements MentionGeneratorInterface
{
public function generateMention(Mention $mention): ?AbstractInline
{
return $mention;
}
}

View file

@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
namespace App\CommonMark\Renderers;
use App\Models\Contact;
use League\CommonMark\Node\Node;
use League\CommonMark\Renderer\ChildNodeRendererInterface;
use League\CommonMark\Renderer\NodeRendererInterface;
use League\CommonMark\Util\HtmlElement;
class MentionRenderer implements NodeRendererInterface
{
public function render(Node $node, ChildNodeRendererInterface $childRenderer): HtmlElement|string
{
$contact = Contact::where('nick', $node->getIdentifier())->first();
// If we have a contact, render a mini-hcard
if ($contact) {
// rendering a blade template to a string, so cant be an HtmlElement
return trim(view('templates.mini-hcard', ['contact' => $contact])->render());
}
// Otherwise, check the link is to the Mastodon profile
$mentionText = $node->getIdentifier();
$parts = explode('@', $mentionText);
// This is not [@]handle@instance, so return a Twitter link
if (count($parts) === 1) {
return new HtmlElement('a', ['href' => 'https://twitter.com/' . $parts[0]], '@' . $mentionText);
}
// Render the Mastodon profile link
return new HtmlElement('a', ['href' => 'https://' . $parts[1] . '/@' . $parts[0]], '@' . $mentionText);
}
}

View file

@ -1,69 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Media;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class CopyMediaToLocal extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:copy-media-to-local';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Copy any historic media saved to S3 to the local filesystem';
/**
* Execute the console command.
*/
public function handle()
{
// Load all the Media records
$media = Media::all();
// Loop through each media record and copy the file from S3 to the local filesystem
foreach ($media as $mediaItem) {
$filename = $mediaItem->path;
$this->info('Processing: ' . $filename);
// If the file is already saved locally skip to next one
if (Storage::disk('local')->exists('public/' . $filename)) {
$this->info('File already exists locally, skipping');
continue;
}
// Copy the file from S3 to the local filesystem
if (! Storage::disk('s3')->exists($filename)) {
$this->error('File does not exist on S3');
continue;
}
$contents = Storage::disk('s3')->get($filename);
Storage::disk('local')->put('public/' . $filename, $contents);
// Copy -medium and -small versions if they exist
$filenameParts = explode('.', $filename);
$extension = array_pop($filenameParts);
$basename = trim(implode('.', $filenameParts), '.');
$mediumFilename = $basename . '-medium.' . $extension;
$smallFilename = $basename . '-small.' . $extension;
if (Storage::disk('s3')->exists($mediumFilename)) {
Storage::disk('local')->put('public/' . $mediumFilename, Storage::disk('s3')->get($mediumFilename));
}
if (Storage::disk('s3')->exists($smallFilename)) {
Storage::disk('local')->put('public/' . $smallFilename, Storage::disk('s3')->get($smallFilename));
}
}
}
}

View file

@ -1,75 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Place;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* @codeCoverageIgnore
*/
class MigratePlaceDataFromPostgis extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'places:migratefrompostgis';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Copy Postgis data to normal latitude longitude fields';
/**
* Execute the console command.
*/
public function handle(): int
{
$locationColumn = DB::selectOne(DB::raw("
SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_name = 'places'
AND column_name = 'location'
)
"));
if (! $locationColumn->exists) {
$this->info('There is no Postgis location data in the table. Exiting.');
return 0;
}
$latitudeColumn = DB::selectOne(DB::raw("
SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_name = 'places'
AND column_name = 'latitude'
)
"));
if (! $latitudeColumn->exists) {
$this->error('Latitude and longitude columns have not been created yet');
return 1;
}
$places = Place::all();
$places->each(function ($place) {
$this->info('Extracting Postgis data for place: ' . $place->name);
$place->latitude = $place->location->getLat();
$place->longitude = $place->location->getLng();
$place->save();
});
return 0;
}
}

View file

@ -6,7 +6,6 @@ namespace App\Console\Commands;
use App\Models\WebMention; use App\Models\WebMention;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\FileSystem\FileSystem; use Illuminate\FileSystem\FileSystem;
class ParseCachedWebMentions extends Command class ParseCachedWebMentions extends Command
@ -25,22 +24,32 @@ class ParseCachedWebMentions extends Command
*/ */
protected $description = 'Re-parse the webmentions cached HTML'; protected $description = 'Re-parse the webmentions cached HTML';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/** /**
* Execute the console command. * Execute the console command.
* *
* @throws FileNotFoundException * @return mixed
*/ */
public function handle(FileSystem $filesystem): void public function handle(FileSystem $filesystem)
{ {
$htmlFiles = $filesystem->allFiles(storage_path() . '/HTML'); $HTMLfiles = $filesystem->allFiles(storage_path() . '/HTML');
foreach ($htmlFiles as $file) { foreach ($HTMLfiles as $file) {
if ($file->getExtension() !== 'backup') { // we dont want to parse `.backup` files if ($file->getExtension() != 'backup') { //we dont want to parse.backup files
$filepath = $file->getPathname(); $filepath = $file->getPathname();
$this->info('Loading HTML from: ' . $filepath); $this->info('Loading HTML from: ' . $filepath);
$html = $filesystem->get($filepath); $html = $filesystem->get($filepath);
$url = $this->urlFromFilename($filepath); $url = $this->URLFromFilename($filepath);
$webmention = WebMention::where('source', $url)->firstOrFail();
$microformats = \Mf2\parse($html, $url); $microformats = \Mf2\parse($html, $url);
$webmention = WebMention::where('source', $url)->firstOrFail();
$webmention->mf2 = json_encode($microformats); $webmention->mf2 = json_encode($microformats);
$webmention->save(); $webmention->save();
$this->info('Saved the microformats to the database.'); $this->info('Saved the microformats to the database.');
@ -50,13 +59,16 @@ class ParseCachedWebMentions extends Command
/** /**
* Determine the source URL from a filename. * Determine the source URL from a filename.
*
* @param string
* @return string
*/ */
private function urlFromFilename(string $filepath): string private function URLFromFilename(string $filepath): string
{ {
$dir = mb_substr($filepath, mb_strlen(storage_path() . '/HTML/')); $dir = mb_substr($filepath, mb_strlen(storage_path() . '/HTML/'));
$url = str_replace(['http/', 'https/'], ['http://', 'https://'], $dir); $url = str_replace(['http/', 'https/'], ['http://', 'https://'], $dir);
if (mb_substr($url, -10) === 'index.html') { if (mb_substr($url, -10) == 'index.html') {
$url = mb_substr($url, 0, -10); $url = mb_substr($url, 0, mb_strlen($url) - 10);
} }
return $url; return $url;

View file

@ -4,9 +4,9 @@ declare(strict_types=1);
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Jobs\DownloadWebMention;
use App\Models\WebMention; use App\Models\WebMention;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use App\Jobs\DownloadWebMention;
class ReDownloadWebMentions extends Command class ReDownloadWebMentions extends Command
{ {
@ -25,9 +25,21 @@ class ReDownloadWebMentions extends Command
protected $description = 'Redownload the HTML content of webmentions'; protected $description = 'Redownload the HTML content of webmentions';
/** /**
* Execute the console command. * Create a new command instance.
*
* @return void
*/ */
public function handle(): void public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{ {
$webmentions = WebMention::all(); $webmentions = WebMention::all();
foreach ($webmentions as $webmention) { foreach ($webmentions as $webmention) {

View file

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use Illuminate\Console\Command;
use SensioLabs\Security\SecurityChecker;
/**
* @codeCoverageIgnore
*/
class SecurityCheck extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'security:check';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run the SensioLabs Security Check tool';
/**
* The Security Checker intergation service.
*
* @var SecurityChecker
*/
protected $securityChecker;
/**
* Create a new command instance.
*
* @param SecurityChecker $SecurityChecker
* @return void
*/
public function __construct(SecurityChecker $securityChecker)
{
parent::__construct();
$this->securityChecker = $securityChecker;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle(): int
{
$alerts = $this->securityChecker->check(base_path() . '/composer.lock');
if (count($alerts) === 0) {
$this->info('No security vulnerabilities found.');
return 0;
}
$this->error('vulnerabilities found');
return 1;
}
}

View file

@ -1,36 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Note;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UpdateWebmentionsRelationship extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'webmentions:update-model-relationship';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Update webmentions to relate to the correct note model class';
/**
* Execute the console command.
*/
public function handle()
{
DB::table('webmentions')
->where('commentable_type', '=', 'App\Model\Note')
->update(['commentable_type' => Note::class]);
$this->info('All webmentions updated to relate to the correct note model class');
}
}

View file

@ -8,18 +8,33 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel
{ {
/** /**
* Define the application's command schedule. * The Artisan commands provided by your application.
*
* @var array
*/ */
protected function schedule(Schedule $schedule): void protected $commands = [
Commands\SecurityCheck::class,
Commands\ParseCachedWebMentions::class,
Commands\ReDownloadWebMentions::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{ {
$schedule->command('horizon:snapshot')->everyFiveMinutes(); $schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->command('cache:prune-stale-tags')->hourly();
} }
/** /**
* Register the commands for the application. * Register the commands for the application.
*
* @return void
*/ */
protected function commands(): void protected function commands()
{ {
$this->load(__DIR__.'/Commands'); $this->load(__DIR__.'/Commands');

View file

@ -2,18 +2,88 @@
namespace App\Exceptions; namespace App\Exceptions;
use App;
use Exception;
use Illuminate\Support\Facades\Route;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
/**
* @codeCoverageIgnore
*/
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
{ {
/** /**
* Register the exception handling callbacks for the application. * A list of the exception types that are not reported.
*
* @var array
*/ */
public function register(): void protected $dontReport = [
\Symfony\Component\HttpKernel\Exception\HttpException::class,
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{ {
$this->reportable(function (Throwable $_e) { $guzzle = new \GuzzleHttp\Client([
// 'headers' => [
}); 'Content-Type' => 'application/json',
],
]);
$guzzle->post(
env('SLACK_WEBHOOK_URL'),
[
'body' => json_encode([
'attachments' => [[
'fallback' => 'There was an exception.',
'pretext' => 'There was an exception.',
'color' => '#d00000',
'author_name' => App::environment(),
'author_link' => config('app.url'),
'fields' => [[
'title' => get_class($exception) ?? 'Unkown Exception',
'value' => $exception->getMessage() ?? '',
]],
'ts' => time(),
]],
]),
]
);
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if ($exception instanceof TokenMismatchException) {
Route::getRoutes()->match($request);
}
return parent::render($request, $exception);
} }
} }

View file

@ -2,4 +2,6 @@
namespace App\Exceptions; namespace App\Exceptions;
class InternetArchiveException extends \Exception {} class InternetArchiveException extends \Exception
{
}

View file

@ -0,0 +1,13 @@
<?php
namespace App\Exceptions;
use Exception;
class InvalidTokenException extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View file

@ -1,7 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Exceptions;
class InvalidTokenScopeException extends \Exception {}

View file

@ -1,7 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Exceptions;
class MicropubHandlerException extends \Exception {}

View file

@ -6,5 +6,5 @@ use Exception;
class RemoteContentNotFoundException extends Exception class RemoteContentNotFoundException extends Exception
{ {
// used when guzzle cant find the remote content //used when guzzle cant find the remote content
} }

View file

@ -0,0 +1,7 @@
<?php
namespace App\Exceptions;
class TwitterContentException extends \Exception
{
}

View file

@ -4,13 +4,19 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Article; use App\Models\Article;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
class ArticlesController extends Controller class ArticlesController extends Controller
{ {
/**
* List the articles that can be edited.
*
* @return \Illuminate\View\View
*/
public function index(): View public function index(): View
{ {
$posts = Article::select('id', 'title', 'published')->orderBy('id', 'desc')->get(); $posts = Article::select('id', 'title', 'published')->orderBy('id', 'desc')->get();
@ -18,6 +24,11 @@ class ArticlesController extends Controller
return view('admin.articles.index', ['posts' => $posts]); return view('admin.articles.index', ['posts' => $posts]);
} }
/**
* Show the new article form.
*
* @return \Illuminate\View\View
*/
public function create(): View public function create(): View
{ {
$message = session('message'); $message = session('message');
@ -25,29 +36,55 @@ class ArticlesController extends Controller
return view('admin.articles.create', ['message' => $message]); return view('admin.articles.create', ['message' => $message]);
} }
/**
* Process an incoming request for a new article and save it.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(): RedirectResponse public function store(): RedirectResponse
{ {
// if a `.md` is attached use that for the main content. //if a `.md` is attached use that for the main content.
if (request()->hasFile('article')) { if (request()->hasFile('article')) {
$file = request()->file('article')->openFile(); $file = request()->file('article')->openFile();
$content = $file->fread($file->getSize()); $content = $file->fread($file->getSize());
} }
$main = $content ?? request()->input('main'); $main = $content ?? request()->input('main');
Article::create([ $article = Article::create(
'url' => request()->input('url'), [
'title' => request()->input('title'), 'url' => request()->input('url'),
'main' => $main, 'title' => request()->input('title'),
'published' => request()->input('published') ?? 0, 'main' => $main,
]); 'published' => request()->input('published') ?? 0,
]
);
return redirect('/admin/blog'); return redirect('/admin/blog');
} }
public function edit(Article $article): View /**
* Show the edit form for an existing article.
*
* @param int $articleId
* @return \Illuminate\View\View
*/
public function edit(int $articleId): View
{ {
return view('admin.articles.edit', ['article' => $article]); $post = Article::select(
'title',
'main',
'url',
'published'
)->where('id', $articleId)->get();
return view('admin.articles.edit', ['id' => $articleId, 'post' => $post]);
} }
/**
* Process an incoming request to edit an article.
*
* @param int $articleId
* @return \Illuminate\Http\RedirectResponse
*/
public function update(int $articleId): RedirectResponse public function update(int $articleId): RedirectResponse
{ {
$article = Article::find($articleId); $article = Article::find($articleId);
@ -60,6 +97,12 @@ class ArticlesController extends Controller
return redirect('/admin/blog'); return redirect('/admin/blog');
} }
/**
* Process a request to delete an aricle.
*
* @param int $articleId
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(int $articleId): RedirectResponse public function destroy(int $articleId): RedirectResponse
{ {
Article::where('id', $articleId)->delete(); Article::where('id', $articleId)->delete();

View file

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Bio;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class BioController extends Controller
{
public function show(): View
{
$bio = Bio::first();
return view('admin.bio.show', [
'bioEntry' => $bio,
]);
}
public function update(Request $request): RedirectResponse
{
$bio = Bio::firstOrNew();
$bio->content = $request->input('content');
$bio->save();
return redirect()->route('admin.bio.show');
}
}

View file

@ -4,15 +4,18 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\MicropubClient;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Models\MicropubClient;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
class ClientsController extends Controller class ClientsController extends Controller
{ {
/** /**
* Show a list of known clients. * Show a list of known clients.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -23,6 +26,8 @@ class ClientsController extends Controller
/** /**
* Show form to add a client name. * Show form to add a client name.
*
* @return \Illuminate\View\View
*/ */
public function create(): View public function create(): View
{ {
@ -31,6 +36,8 @@ class ClientsController extends Controller
/** /**
* Process the request to adda new client name. * Process the request to adda new client name.
*
* @return \Illuminate\Http\RedirectResponse
*/ */
public function store(): RedirectResponse public function store(): RedirectResponse
{ {
@ -44,6 +51,9 @@ class ClientsController extends Controller
/** /**
* Show a form to edit a client name. * Show a form to edit a client name.
*
* @param int $clientId
* @return \Illuminate\View\View
*/ */
public function edit(int $clientId): View public function edit(int $clientId): View
{ {
@ -58,6 +68,9 @@ class ClientsController extends Controller
/** /**
* Process the request to edit a client name. * Process the request to edit a client name.
*
* @param int $clientId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function update(int $clientId): RedirectResponse public function update(int $clientId): RedirectResponse
{ {
@ -71,6 +84,9 @@ class ClientsController extends Controller
/** /**
* Process a request to delete a client. * Process a request to delete a client.
*
* @param int $clientId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function destroy(int $clientId): RedirectResponse public function destroy(int $clientId): RedirectResponse
{ {

View file

@ -4,18 +4,21 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use App\Models\Contact;
use Illuminate\View\View;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Filesystem\Filesystem; use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Arr;
use Illuminate\View\View;
class ContactsController extends Controller class ContactsController extends Controller
{ {
/** /**
* List the currect contacts that can be edited. * List the currect contacts that can be edited.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -26,6 +29,8 @@ class ContactsController extends Controller
/** /**
* Display the form to add a new contact. * Display the form to add a new contact.
*
* @return \Illuminate\View\View
*/ */
public function create(): View public function create(): View
{ {
@ -34,10 +39,12 @@ class ContactsController extends Controller
/** /**
* Process the request to add a new contact. * Process the request to add a new contact.
*
* @return \Illuminate\Http\RedirectResponse
*/ */
public function store(): RedirectResponse public function store(): RedirectResponse
{ {
$contact = new Contact; $contact = new Contact();
$contact->name = request()->input('name'); $contact->name = request()->input('name');
$contact->nick = request()->input('nick'); $contact->nick = request()->input('nick');
$contact->homepage = request()->input('homepage'); $contact->homepage = request()->input('homepage');
@ -50,6 +57,9 @@ class ContactsController extends Controller
/** /**
* Show the form to edit an existing contact. * Show the form to edit an existing contact.
*
* @param int $contactId
* @return \Illuminate\View\View
*/ */
public function edit(int $contactId): View public function edit(int $contactId): View
{ {
@ -62,6 +72,9 @@ class ContactsController extends Controller
* Process the request to edit a contact. * Process the request to edit a contact.
* *
* @todo Allow saving profile pictures for people without homepages * @todo Allow saving profile pictures for people without homepages
*
* @param int $contactId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function update(int $contactId): RedirectResponse public function update(int $contactId): RedirectResponse
{ {
@ -76,7 +89,7 @@ class ContactsController extends Controller
if (request()->hasFile('avatar') && (request()->input('homepage') != '')) { if (request()->hasFile('avatar') && (request()->input('homepage') != '')) {
$dir = parse_url(request()->input('homepage'), PHP_URL_HOST); $dir = parse_url(request()->input('homepage'), PHP_URL_HOST);
$destination = public_path() . '/assets/profile-images/' . $dir; $destination = public_path() . '/assets/profile-images/' . $dir;
$filesystem = new Filesystem; $filesystem = new Filesystem();
if ($filesystem->isDirectory($destination) === false) { if ($filesystem->isDirectory($destination) === false) {
$filesystem->makeDirectory($destination); $filesystem->makeDirectory($destination);
} }
@ -88,6 +101,9 @@ class ContactsController extends Controller
/** /**
* Process the request to delete a contact. * Process the request to delete a contact.
*
* @param int $contactId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function destroy(int $contactId): RedirectResponse public function destroy(int $contactId): RedirectResponse
{ {
@ -103,6 +119,7 @@ class ContactsController extends Controller
* This method attempts to find the microformat marked-up profile image * This method attempts to find the microformat marked-up profile image
* from a given homepage and save it accordingly * from a given homepage and save it accordingly
* *
* @param int $contactId
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/ */
public function getAvatar(int $contactId) public function getAvatar(int $contactId)
@ -121,8 +138,8 @@ class ContactsController extends Controller
} }
$mf2 = \Mf2\parse((string) $response->getBody(), $contact->homepage); $mf2 = \Mf2\parse((string) $response->getBody(), $contact->homepage);
foreach ($mf2['items'] as $microformat) { foreach ($mf2['items'] as $microformat) {
if (Arr::get($microformat, 'type.0') === 'h-card') { if (Arr::get($microformat, 'type.0') == 'h-card') {
$avatarURL = Arr::get($microformat, 'properties.photo.0.value'); $avatarURL = Arr::get($microformat, 'properties.photo.0');
break; break;
} }
} }
@ -136,7 +153,7 @@ class ContactsController extends Controller
} }
if ($avatar !== null) { if ($avatar !== null) {
$directory = public_path() . '/assets/profile-images/' . parse_url($contact->homepage, PHP_URL_HOST); $directory = public_path() . '/assets/profile-images/' . parse_url($contact->homepage, PHP_URL_HOST);
$filesystem = new Filesystem; $filesystem = new Filesystem();
if ($filesystem->isDirectory($directory) === false) { if ($filesystem->isDirectory($directory) === false) {
$filesystem->makeDirectory($directory); $filesystem->makeDirectory($directory);
} }

View file

@ -4,13 +4,15 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\View\View; use Illuminate\View\View;
use App\Http\Controllers\Controller;
class HomeController extends Controller class HomeController extends Controller
{ {
/** /**
* Show the homepage of the admin CP. * Show the homepage of the admin CP.
*
* @return \Illuminate\View\View
*/ */
public function welcome(): View public function welcome(): View
{ {

View file

@ -4,16 +4,18 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Jobs\ProcessLike;
use App\Models\Like; use App\Models\Like;
use Illuminate\Http\RedirectResponse; use App\Jobs\ProcessLike;
use Illuminate\View\View; use Illuminate\View\View;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
class LikesController extends Controller class LikesController extends Controller
{ {
/** /**
* List the likes that can be edited. * List the likes that can be edited.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -24,6 +26,8 @@ class LikesController extends Controller
/** /**
* Show the form to make a new like. * Show the form to make a new like.
*
* @return \Illuminate\View\View
*/ */
public function create(): View public function create(): View
{ {
@ -32,6 +36,8 @@ class LikesController extends Controller
/** /**
* Process a request to make a new like. * Process a request to make a new like.
*
* @return \Illuminate\Http\RedirectResponse
*/ */
public function store(): RedirectResponse public function store(): RedirectResponse
{ {
@ -45,6 +51,9 @@ class LikesController extends Controller
/** /**
* Display the form to edit a specific like. * Display the form to edit a specific like.
*
* @param int $likeId
* @return \Illuminate\View\View
*/ */
public function edit(int $likeId): View public function edit(int $likeId): View
{ {
@ -58,6 +67,9 @@ class LikesController extends Controller
/** /**
* Process a request to edit a like. * Process a request to edit a like.
*
* @param int $likeId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function update(int $likeId): RedirectResponse public function update(int $likeId): RedirectResponse
{ {
@ -71,6 +83,9 @@ class LikesController extends Controller
/** /**
* Process the request to delete a like. * Process the request to delete a like.
*
* @param int $likeId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function destroy(int $likeId): RedirectResponse public function destroy(int $likeId): RedirectResponse
{ {

View file

@ -4,17 +4,19 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Jobs\SendWebMentions;
use App\Models\Note; use App\Models\Note;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Jobs\SendWebMentions;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
class NotesController extends Controller class NotesController extends Controller
{ {
/** /**
* List the notes that can be edited. * List the notes that can be edited.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -28,6 +30,8 @@ class NotesController extends Controller
/** /**
* Show the form to make a new note. * Show the form to make a new note.
*
* @return \Illuminate\View\View
*/ */
public function create(): View public function create(): View
{ {
@ -36,12 +40,14 @@ class NotesController extends Controller
/** /**
* Process a request to make a new note. * Process a request to make a new note.
*
* @return \Illuminate\Http\RedirectResponse
*/ */
public function store(Request $request): RedirectResponse public function store(): RedirectResponse
{ {
Note::create([ Note::create([
'in_reply_to' => $request->input('in-reply-to'), 'in-reply-to' => request()->input('in-reply-to'),
'note' => $request->input('content'), 'note' => request()->input('content'),
]); ]);
return redirect('/admin/notes'); return redirect('/admin/notes');
@ -49,6 +55,9 @@ class NotesController extends Controller
/** /**
* Display the form to edit a specific note. * Display the form to edit a specific note.
*
* @param int $noteId
* @return \Illuminate\View\View
*/ */
public function edit(int $noteId): View public function edit(int $noteId): View
{ {
@ -61,10 +70,13 @@ class NotesController extends Controller
/** /**
* Process a request to edit a note. Easy since this can only be done * Process a request to edit a note. Easy since this can only be done
* from the admin CP. * from the admin CP.
*
* @param int $noteId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function update(int $noteId): RedirectResponse public function update(int $noteId): RedirectResponse
{ {
// update note data //update note data
$note = Note::findOrFail($noteId); $note = Note::findOrFail($noteId);
$note->note = request()->input('content'); $note->note = request()->input('content');
$note->in_reply_to = request()->input('in-reply-to'); $note->in_reply_to = request()->input('in-reply-to');
@ -79,6 +91,9 @@ class NotesController extends Controller
/** /**
* Delete the note. * Delete the note.
*
* @param int $noteId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function destroy(int $noteId): RedirectResponse public function destroy(int $noteId): RedirectResponse
{ {

View file

@ -1,326 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Passkey;
use App\Models\User;
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\ECDSA\ES256;
use Cose\Algorithm\Signature\EdDSA\Ed25519;
use Cose\Algorithm\Signature\RSA\RS256;
use Cose\Algorithms;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Random\RandomException;
use Throwable;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
use Webauthn\AttestationStatement\NoneAttestationStatementSupport;
use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAssertionResponseValidator;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\AuthenticatorAttestationResponseValidator;
use Webauthn\AuthenticatorSelectionCriteria;
use Webauthn\CeremonyStep\CeremonyStepManagerFactory;
use Webauthn\Denormalizer\WebauthnSerializerFactory;
use Webauthn\Exception\WebauthnException;
use Webauthn\PublicKeyCredential;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialParameters;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialRpEntity;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\PublicKeyCredentialUserEntity;
class PasskeysController extends Controller
{
public function index(): View
{
/** @var User $user */
$user = auth()->user();
$passkeys = $user->passkey;
return view('admin.passkeys.index', compact('passkeys'));
}
/**
* @throws RandomException
* @throws \JsonException
*/
public function getCreateOptions(Request $request): JsonResponse
{
/** @var User $user */
$user = auth()->user();
// RP Entity i.e. the application
$rpEntity = PublicKeyCredentialRpEntity::create(
name: config('app.name'),
id: config('app.url'),
);
// User Entity
$userEntity = PublicKeyCredentialUserEntity::create(
name: $user->name,
id: (string) $user->id,
displayName: $user->name,
);
// Challenge
$challenge = random_bytes(16);
// List of supported public key parameters
$pubKeyCredParams = collect([
Algorithms::COSE_ALGORITHM_EDDSA,
Algorithms::COSE_ALGORITHM_ES256,
Algorithms::COSE_ALGORITHM_RS256,
])->map(
fn ($algorithm) => PublicKeyCredentialParameters::create('public-key', $algorithm)
)->toArray();
$authenticatorSelectionCriteria = AuthenticatorSelectionCriteria::create(
userVerification: AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED,
residentKey: AuthenticatorSelectionCriteria::RESIDENT_KEY_REQUIREMENT_REQUIRED,
);
$publicKeyCredentialCreationOptions = PublicKeyCredentialCreationOptions::create(
rp: $rpEntity,
user: $userEntity,
challenge: $challenge,
pubKeyCredParams: $pubKeyCredParams,
authenticatorSelection: $authenticatorSelectionCriteria,
attestation: PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE
);
$attestationStatementSupportManager = new AttestationStatementSupportManager;
$attestationStatementSupportManager->add(new NoneAttestationStatementSupport);
$webauthnSerializerFactory = new WebauthnSerializerFactory(
attestationStatementSupportManager: $attestationStatementSupportManager
);
$webauthnSerializer = $webauthnSerializerFactory->create();
$publicKeyCredentialCreationOptions = $webauthnSerializer->serialize(
data: $publicKeyCredentialCreationOptions,
format: 'json'
);
$request->session()->put('create_options', $publicKeyCredentialCreationOptions);
return JsonResponse::fromJsonString($publicKeyCredentialCreationOptions);
}
/**
* @throws Throwable
* @throws WebauthnException
* @throws \JsonException
*/
public function create(Request $request): JsonResponse
{
/** @var User $user */
$user = auth()->user();
$publicKeyCredentialCreationOptionsData = session('create_options');
// Unset session data to mitigate replay attacks
$request->session()->forget('create_options');
if (empty($publicKeyCredentialCreationOptionsData)) {
throw new WebAuthnException('No public key credential request options found');
}
$attestationStatementSupportManager = new AttestationStatementSupportManager;
$attestationStatementSupportManager->add(new NoneAttestationStatementSupport);
$webauthnSerializerFactory = new WebauthnSerializerFactory(
attestationStatementSupportManager: $attestationStatementSupportManager
);
$webauthnSerializer = $webauthnSerializerFactory->create();
$publicKeyCredential = $webauthnSerializer->deserialize(
json_encode($request->all(), JSON_THROW_ON_ERROR),
PublicKeyCredential::class,
'json'
);
if (! $publicKeyCredential->response instanceof AuthenticatorAttestationResponse) {
throw new WebAuthnException('Invalid response type');
}
$algorithmManager = new Manager;
$algorithmManager->add(new Ed25519);
$algorithmManager->add(new ES256);
$algorithmManager->add(new RS256);
$ceremonyStepManagerFactory = new CeremonyStepManagerFactory;
$ceremonyStepManagerFactory->setAlgorithmManager($algorithmManager);
$ceremonyStepManagerFactory->setAttestationStatementSupportManager(
$attestationStatementSupportManager
);
$ceremonyStepManagerFactory->setExtensionOutputCheckerHandler(
ExtensionOutputCheckerHandler::create()
);
$allowedOrigins = [];
if (App::environment('local', 'development')) {
$allowedOrigins = [config('app.url')];
}
$ceremonyStepManagerFactory->setAllowedOrigins($allowedOrigins);
$authenticatorAttestationResponseValidator = AuthenticatorAttestationResponseValidator::create(
ceremonyStepManager: $ceremonyStepManagerFactory->creationCeremony()
);
$publicKeyCredentialCreationOptions = $webauthnSerializer->deserialize(
$publicKeyCredentialCreationOptionsData,
PublicKeyCredentialCreationOptions::class,
'json'
);
$publicKeyCredentialSource = $authenticatorAttestationResponseValidator->check(
authenticatorAttestationResponse: $publicKeyCredential->response,
publicKeyCredentialCreationOptions: $publicKeyCredentialCreationOptions,
host: config('app.url')
);
$user->passkey()->create([
'passkey_id' => Base64UrlSafe::encodeUnpadded($publicKeyCredentialSource->publicKeyCredentialId),
'passkey' => json_encode($publicKeyCredentialSource, JSON_THROW_ON_ERROR),
]);
return response()->json([
'success' => true,
'message' => 'Passkey created successfully',
]);
}
/**
* @throws RandomException
* @throws \JsonException
*/
public function getRequestOptions(Request $request): JsonResponse
{
$publicKeyCredentialRequestOptions = PublicKeyCredentialRequestOptions::create(
challenge: random_bytes(16),
userVerification: PublicKeyCredentialRequestOptions::USER_VERIFICATION_REQUIREMENT_REQUIRED
);
$attestationStatementSupportManager = AttestationStatementSupportManager::create();
$attestationStatementSupportManager->add(NoneAttestationStatementSupport::create());
$factory = new WebauthnSerializerFactory(
attestationStatementSupportManager: $attestationStatementSupportManager
);
$serializer = $factory->create();
$publicKeyCredentialRequestOptions = $serializer->serialize(data: $publicKeyCredentialRequestOptions, format: 'json');
$request->session()->put('request_options', $publicKeyCredentialRequestOptions);
return JsonResponse::fromJsonString($publicKeyCredentialRequestOptions);
}
/**
* @throws \JsonException
*/
public function login(Request $request): JsonResponse
{
$requestOptions = session('request_options');
$request->session()->forget('request_options');
if (empty($requestOptions)) {
return response()->json([
'success' => false,
'message' => 'No request options found',
], 400);
}
$attestationStatementSupportManager = new AttestationStatementSupportManager;
$attestationStatementSupportManager->add(new NoneAttestationStatementSupport);
$webauthnSerializerFactory = new WebauthnSerializerFactory(
attestationStatementSupportManager: $attestationStatementSupportManager
);
$webauthnSerializer = $webauthnSerializerFactory->create();
$publicKeyCredential = $webauthnSerializer->deserialize(
json_encode($request->all(), JSON_THROW_ON_ERROR),
PublicKeyCredential::class,
'json'
);
if (! $publicKeyCredential->response instanceof AuthenticatorAssertionResponse) {
return response()->json([
'success' => false,
'message' => 'Invalid response type',
], 400);
}
$passkey = Passkey::firstWhere('passkey_id', $publicKeyCredential->id);
if (! $passkey) {
return response()->json([
'success' => false,
'message' => 'Passkey not found',
], 404);
}
$publicKeyCredentialSource = $webauthnSerializer->deserialize(
$passkey->passkey,
PublicKeyCredentialSource::class,
'json'
);
$algorithmManager = new Manager;
$algorithmManager->add(new Ed25519);
$algorithmManager->add(new ES256);
$algorithmManager->add(new RS256);
$attestationStatementSupportManager = new AttestationStatementSupportManager;
$attestationStatementSupportManager->add(new NoneAttestationStatementSupport);
$ceremonyStepManagerFactory = new CeremonyStepManagerFactory;
$ceremonyStepManagerFactory->setAlgorithmManager($algorithmManager);
$ceremonyStepManagerFactory->setAttestationStatementSupportManager(
$attestationStatementSupportManager
);
$ceremonyStepManagerFactory->setExtensionOutputCheckerHandler(
ExtensionOutputCheckerHandler::create()
);
$allowedOrigins = [];
if (App::environment('local', 'development')) {
$allowedOrigins = [config('app.url')];
}
$ceremonyStepManagerFactory->setAllowedOrigins($allowedOrigins);
$authenticatorAssertionResponseValidator = AuthenticatorAssertionResponseValidator::create(
ceremonyStepManager: $ceremonyStepManagerFactory->requestCeremony()
);
$publicKeyCredentialRequestOptions = $webauthnSerializer->deserialize(
$requestOptions,
PublicKeyCredentialRequestOptions::class,
'json'
);
try {
$authenticatorAssertionResponseValidator->check(
publicKeyCredentialSource: $publicKeyCredentialSource,
authenticatorAssertionResponse: $publicKeyCredential->response,
publicKeyCredentialRequestOptions: $publicKeyCredentialRequestOptions,
host: config('app.url'),
userHandle: null,
);
} catch (Throwable) {
return response()->json([
'success' => false,
'message' => 'Passkey could not be verified',
], 500);
}
$user = User::find($passkey->user_id);
Auth::login($user);
return response()->json([
'success' => true,
'message' => 'Passkey verified successfully',
]);
}
}

View file

@ -4,15 +4,17 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Place; use App\Models\Place;
use App\Services\PlaceService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Services\PlaceService;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Phaza\LaravelPostgis\Geometries\Point;
class PlacesController extends Controller class PlacesController extends Controller
{ {
protected PlaceService $placeService; protected $placeService;
public function __construct(PlaceService $placeService) public function __construct(PlaceService $placeService)
{ {
@ -21,6 +23,8 @@ class PlacesController extends Controller
/** /**
* List the places that can be edited. * List the places that can be edited.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -31,6 +35,8 @@ class PlacesController extends Controller
/** /**
* Show the form to make a new place. * Show the form to make a new place.
*
* @return \Illuminate\View\View
*/ */
public function create(): View public function create(): View
{ {
@ -39,23 +45,22 @@ class PlacesController extends Controller
/** /**
* Process a request to make a new place. * Process a request to make a new place.
*
* @return \Illuminate\Http\RedirectResponse
*/ */
public function store(): RedirectResponse public function store(): RedirectResponse
{ {
$this->placeService->createPlace( $data = request()->only(['name', 'description', 'latitude', 'longitude']);
request()->only([ $place = $this->placeService->createPlace($data);
'name',
'description',
'latitude',
'longitude',
])
);
return redirect('/admin/places'); return redirect('/admin/places');
} }
/** /**
* Display the form to edit a specific place. * Display the form to edit a specific place.
*
* @param int $placeId
* @return \Illuminate\View\View
*/ */
public function edit(int $placeId): View public function edit(int $placeId): View
{ {
@ -66,14 +71,19 @@ class PlacesController extends Controller
/** /**
* Process a request to edit a place. * Process a request to edit a place.
*
* @param int $placeId
* @return \Illuminate\Http\RedirectResponse
*/ */
public function update(int $placeId): RedirectResponse public function update(int $placeId): RedirectResponse
{ {
$place = Place::findOrFail($placeId); $place = Place::findOrFail($placeId);
$place->name = request()->input('name'); $place->name = request()->input('name');
$place->description = request()->input('description'); $place->description = request()->input('description');
$place->latitude = request()->input('latitude'); $place->location = new Point(
$place->longitude = request()->input('longitude'); (float) request()->input('latitude'),
(float) request()->input('longitude')
);
$place->icon = request()->input('icon'); $place->icon = request()->input('icon');
$place->save(); $place->save();
@ -82,11 +92,14 @@ class PlacesController extends Controller
/** /**
* List the places we can merge with the current place. * List the places we can merge with the current place.
*
* @param int $placeId
* @return \Illuminate\View\View
*/ */
public function mergeIndex(int $placeId): View public function mergeIndex(int $placeId): View
{ {
$first = Place::find($placeId); $first = Place::find($placeId);
$results = Place::near((object) ['latitude' => $first->latitude, 'longitude' => $first->longitude])->get(); $results = Place::near(new Point($first->latitude, $first->longitude))->get();
$places = []; $places = [];
foreach ($results as $place) { foreach ($results as $place) {
if ($place->slug !== $first->slug) { if ($place->slug !== $first->slug) {
@ -99,6 +112,10 @@ class PlacesController extends Controller
/** /**
* Show a form for merging two specific places. * Show a form for merging two specific places.
*
* @param int $placeId1
* @param int $placeId2
* @return \Illuminate\View\View
*/ */
public function mergeEdit(int $placeId1, int $placeId2): View public function mergeEdit(int $placeId1, int $placeId2): View
{ {
@ -110,6 +127,8 @@ class PlacesController extends Controller
/** /**
* Process the request to merge two places. * Process the request to merge two places.
*
* @return \Illuminate\Http\RedirectResponse
*/ */
public function mergeStore(): RedirectResponse public function mergeStore(): RedirectResponse
{ {

View file

@ -1,94 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\SyndicationTarget;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class SyndicationTargetsController extends Controller
{
/**
* Show a list of known syndication targets.
*/
public function index(): View
{
$targets = SyndicationTarget::all();
return view('admin.syndication.index', compact('targets'));
}
/**
* Show form to add a syndication target.
*/
public function create(): View
{
return view('admin.syndication.create');
}
/**
* Process the request to adda new syndication target.
*/
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'uid' => 'required|string',
'name' => 'required|string',
'service_name' => 'nullable|string',
'service_url' => 'nullable|string',
'service_photo' => 'nullable|string',
'user_name' => 'nullable|string',
'user_url' => 'nullable|string',
'user_photo' => 'nullable|string',
]);
SyndicationTarget::create($validated);
return redirect('/admin/syndication');
}
/**
* Show a form to edit a syndication target.
*/
public function edit(SyndicationTarget $syndicationTarget): View
{
return view('admin.syndication.edit', [
'syndication_target' => $syndicationTarget,
]);
}
/**
* Process the request to edit a client name.
*/
public function update(Request $request, SyndicationTarget $syndicationTarget): RedirectResponse
{
$validated = $request->validate([
'uid' => 'required|string',
'name' => 'required|string',
'service_name' => 'nullable|string',
'service_url' => 'nullable|string',
'service_photo' => 'nullable|string',
'user_name' => 'nullable|string',
'user_url' => 'nullable|string',
'user_photo' => 'nullable|string',
]);
$syndicationTarget->update($validated);
return redirect('/admin/syndication');
}
/**
* Process a request to delete a client.
*/
public function destroy(SyndicationTarget $syndicationTarget): RedirectResponse
{
$syndicationTarget->delete();
return redirect('/admin/syndication');
}
}

View file

@ -5,54 +5,60 @@ declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Article; use App\Models\Article;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View; use Illuminate\View\View;
use Jonnybarnes\IndieWeb\Numbers; use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Http\RedirectResponse;
class ArticlesController extends Controller class ArticlesController extends Controller
{ {
/** /**
* Show all articles (with pagination). * Show all articles (with pagination).
*
* @param int $year
* @param int $month
* @return \Illuminate\View\View
*/ */
public function index(?int $year = null, ?int $month = null): View public function index(int $year = null, int $month = null): View
{ {
$articles = Article::where('published', '1') $articles = Article::where('published', '1')
->date($year, $month) ->date($year, $month)
->orderBy('updated_at', 'desc') ->orderBy('updated_at', 'desc')
->simplePaginate(5); ->simplePaginate(5);
return view('articles.index', compact('articles')); return view('articles.index', compact('articles'));
} }
/** /**
* Show a single article. * Show a single article.
*
* @param int $year
* @param int $month
* @param string $slug
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/ */
public function show(int $year, int $month, string $slug): RedirectResponse|View public function show(int $year, int $month, string $slug)
{ {
try { $article = Article::where('titleurl', $slug)->firstOrFail();
$article = Article::where('titleurl', $slug)->firstOrFail();
} catch (ModelNotFoundException $exception) {
abort(404);
}
if ($article->updated_at->year != $year || $article->updated_at->month != $month) { if ($article->updated_at->year != $year || $article->updated_at->month != $month) {
return redirect('/blog/' return redirect('/blog/'
. $article->updated_at->year . $article->updated_at->year
. '/' . $article->updated_at->format('m') . '/' . $article->updated_at->format('m')
. '/' . $slug); .'/' . $slug);
} }
return view('articles.show', compact('article')); return view('articles.show', compact('article'));
} }
/** /**
* We only have the ID, work out post title, year and month and redirect to it. * We only have the ID, work out post title, year and month
* and redirect to it.
*
* @param int $idFromUrl
* @return \Illuminte\Http\RedirectResponse
*/ */
public function onlyIdInUrl(string $idFromUrl): RedirectResponse public function onlyIdInUrl(int $idFromUrl): RedirectResponse
{ {
$realId = resolve(Numbers::class)->b60tonum($idFromUrl); $realId = resolve(Numbers::class)->b60tonum($idFromUrl);
$article = Article::findOrFail($realId); $article = Article::findOrFail($realId);
return redirect($article->link); return redirect($article->link);

View file

@ -4,59 +4,39 @@ declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
class AuthController extends Controller class AuthController extends Controller
{ {
/** /**
* Show the login form. * Show the login form.
*
* @return \Illuminate\View\View
*/ */
public function showLogin(): View|RedirectResponse public function showLogin(): View
{ {
if (Auth::check()) {
return redirect('/');
}
return view('login'); return view('login');
} }
/** /**
* Log in a user, set a session variable, check credentials against the `.env` file. * Log in a user, set a sesion variable, check credentials against
* the .env file.
*
* @return \Illuminate\Http\RedirectResponse
*/ */
public function login(Request $request): RedirectResponse public function login(): RedirectResponse
{ {
$credentials = $request->only('name', 'password'); if (request()->input('username') === config('admin.user')
&&
request()->input('password') === config('admin.pass')
) {
session(['loggedin' => true]);
if (Auth::attempt($credentials, true)) { return redirect()->intended('admin');
return redirect()->intended('/admin');
} }
return redirect()->route('login'); return redirect()->route('login');
} }
/**
* Show the form to allow a user to log-out.
*/
public function showLogout(): View|RedirectResponse
{
if (Auth::check() === false) {
// The user is not logged in, just redirect them home
return redirect('/');
}
return view('logout');
}
/**
* Log the user out from their current session.
*/
public function logout(): RedirectResponse
{
Auth::logout();
return redirect('/');
}
} }

View file

@ -11,6 +11,8 @@ class BookmarksController extends Controller
{ {
/** /**
* Show the most recent bookmarks. * Show the most recent bookmarks.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -21,6 +23,9 @@ class BookmarksController extends Controller
/** /**
* Show a single bookmark. * Show a single bookmark.
*
* @param \App\Models\Bookmark $bookmark
* @return \Illuminate\View\View
*/ */
public function show(Bookmark $bookmark): View public function show(Bookmark $bookmark): View
{ {
@ -28,16 +33,4 @@ class BookmarksController extends Controller
return view('bookmarks.show', compact('bookmark')); return view('bookmarks.show', compact('bookmark'));
} }
/**
* Show bookmarks tagged with a specific tag.
*/
public function tagged(string $tag): View
{
$bookmarks = Bookmark::whereHas('tags', function ($query) use ($tag) {
$query->where('tag', $tag);
})->latest()->with('tags')->withCount('tags')->paginate(10);
return view('bookmarks.tagged', compact('bookmarks', 'tag'));
}
} }

View file

@ -5,17 +5,19 @@ declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Contact; use App\Models\Contact;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Filesystem\Filesystem;
class ContactsController extends Controller class ContactsController extends Controller
{ {
/** /**
* Show all the contacts. * Show all the contacts.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
$filesystem = new Filesystem; $filesystem = new Filesystem();
$contacts = Contact::all(); $contacts = Contact::all();
foreach ($contacts as $contact) { foreach ($contacts as $contact) {
$contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST); $contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST);
@ -31,13 +33,18 @@ class ContactsController extends Controller
/** /**
* Show a single contact. * Show a single contact.
*
* @todo Use implicit model binding.
*
* @param string $nick The nickname associated with contact
* @return \Illuminate\View\View
*/ */
public function show(Contact $contact): View public function show(string $nick): View
{ {
$filesystem = new Filesystem();
$contact = Contact::where('nick', '=', $nick)->firstOrFail();
$contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST); $contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST);
$file = public_path() . '/assets/profile-images/' . $contact->homepageHost . '/image'; $file = public_path() . '/assets/profile-images/' . $contact->homepageHost . '/image';
$filesystem = new Filesystem;
$image = ($filesystem->exists($file)) ? $image = ($filesystem->exists($file)) ?
'/assets/profile-images/' . $contact->homepageHost . '/image' '/assets/profile-images/' . $contact->homepageHost . '/image'
: :

View file

@ -2,7 +2,12 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
abstract class Controller use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{ {
// use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
} }

View file

@ -4,15 +4,15 @@ declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Note;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use App\Models\{Article, Note};
class FeedsController extends Controller class FeedsController extends Controller
{ {
/** /**
* Returns the blog RSS feed. * Returns the blog RSS feed.
*
* @return \Illuminate\Http\Response
*/ */
public function blogRss(): Response public function blogRss(): Response
{ {
@ -20,24 +20,28 @@ class FeedsController extends Controller
$buildDate = $articles->first()->updated_at->toRssString(); $buildDate = $articles->first()->updated_at->toRssString();
return response() return response()
->view('articles.rss', compact('articles', 'buildDate')) ->view('articles.rss', compact('articles', 'buildDate'))
->header('Content-Type', 'application/rss+xml; charset=utf-8'); ->header('Content-Type', 'application/rss+xml; charset=utf-8');
} }
/** /**
* Returns the blog Atom feed. * Returns the blog Atom feed.
*
* @return \Illuminate\Http\Response
*/ */
public function blogAtom(): Response public function blogAtom(): Response
{ {
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get(); $articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
return response() return response()
->view('articles.atom', compact('articles')) ->view('articles.atom', compact('articles'))
->header('Content-Type', 'application/atom+xml; charset=utf-8'); ->header('Content-Type', 'application/atom+xml; charset=utf-8');
} }
/** /**
* Returns the notes RSS feed. * Returns the notes RSS feed.
*
* @return \Illuminate\Http\Response
*/ */
public function notesRss(): Response public function notesRss(): Response
{ {
@ -45,41 +49,39 @@ class FeedsController extends Controller
$buildDate = $notes->first()->updated_at->toRssString(); $buildDate = $notes->first()->updated_at->toRssString();
return response() return response()
->view('notes.rss', compact('notes', 'buildDate')) ->view('notes.rss', compact('notes', 'buildDate'))
->header('Content-Type', 'application/rss+xml; charset=utf-8'); ->header('Content-Type', 'application/rss+xml; charset=utf-8');
} }
/** /**
* Returns the notes Atom feed. * Returns the notes Atom feed.
*
* @return \Illuminate\Http\Response
*/ */
public function notesAtom(): Response public function notesAtom(): Response
{ {
$notes = Note::latest()->take(20)->get(); $notes = Note::latest()->take(20)->get();
return response() return response()
->view('notes.atom', compact('notes')) ->view('notes.atom', compact('notes'))
->header('Content-Type', 'application/atom+xml; charset=utf-8'); ->header('Content-Type', 'application/atom+xml; charset=utf-8');
} }
/** @todo sort out return type for json responses */ /** @todo sort out return type for json responses */
/** /**
* Returns the blog JSON feed. * Returns the blog JSON feed.
*
* @return \Illuminate\Http\JsonResponse
*/ */
public function blogJson(): array public function blogJson()
{ {
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get(); $articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
$data = [ $data = [
'version' => 'https://jsonfeed.org/version/1.1', 'version' => 'https://jsonfeed.org/version/1',
'title' => 'The JSON Feed for ' . config('user.display_name') . 's blog', 'title' => 'The JSON Feed for ' . config('app.display_name') . 's blog',
'home_page_url' => config('app.url') . '/blog', 'home_page_url' => config('app.url') . '/blog',
'feed_url' => config('app.url') . '/blog/feed.json', 'feed_url' => config('app.url') . '/blog/feed.json',
'authors' => [
[
'name' => config('user.display_name'),
'url' => config('app.url'),
],
],
'items' => [], 'items' => [],
]; ];
@ -91,6 +93,9 @@ class FeedsController extends Controller
'content_html' => $article->main, 'content_html' => $article->main,
'date_published' => $article->created_at->tz('UTC')->toRfc3339String(), 'date_published' => $article->created_at->tz('UTC')->toRfc3339String(),
'date_modified' => $article->updated_at->tz('UTC')->toRfc3339String(), 'date_modified' => $article->updated_at->tz('UTC')->toRfc3339String(),
'author' => [
'name' => config('app.display_name'),
],
]; ];
} }
@ -99,109 +104,33 @@ class FeedsController extends Controller
/** /**
* Returns the notes JSON feed. * Returns the notes JSON feed.
*
* @return \Illuminate\Http\JsonResponse
*/ */
public function notesJson(): array public function notesJson()
{ {
$notes = Note::latest()->with('media', 'place', 'tags')->take(20)->get(); $notes = Note::latest()->take(20)->get();
$data = [ $data = [
'version' => 'https://jsonfeed.org/version/1.1', 'version' => 'https://jsonfeed.org/version/1',
'title' => 'The JSON Feed for ' . config('user.display_name') . 's notes', 'title' => 'The JSON Feed for ' . config('app.display_name') . 's notes',
'home_page_url' => config('app.url') . '/notes', 'home_page_url' => config('app.url') . '/notes',
'feed_url' => config('app.url') . '/notes/feed.json', 'feed_url' => config('app.url') . '/notes/feed.json',
'authors' => [
[
'name' => config('user.display_name'),
'url' => config('app.url'),
],
],
'items' => [], 'items' => [],
]; ];
foreach ($notes as $key => $note) { foreach ($notes as $key => $note) {
$data['items'][$key] = [ $data['items'][$key] = [
'id' => $note->uri, 'id' => $note->longurl,
'url' => $note->uri, 'url' => $note->longurl,
'content_text' => $note->content, 'content_html' => $note->content,
'date_published' => $note->created_at->tz('UTC')->toRfc3339String(), 'date_published' => $note->created_at->tz('UTC')->toRfc3339String(),
'date_modified' => $note->updated_at->tz('UTC')->toRfc3339String(), 'date_modified' => $note->updated_at->tz('UTC')->toRfc3339String(),
'author' => [
'name' => config('app.display_name'),
],
]; ];
if ($note->tags->count() > 0) {
$data['items'][$key]['tags'] = implode(',', $note->tags->pluck('tag')->toArray());
}
} }
return $data; return $data;
} }
/**
* Returns the blog JF2 feed.
*/
public function blogJf2(): JsonResponse
{
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
$items = [];
foreach ($articles as $article) {
$items[] = [
'type' => 'entry',
'published' => $article->created_at,
'uid' => config('app.url') . $article->link,
'url' => config('app.url') . $article->link,
'content' => [
'text' => $article->main,
'html' => $article->html,
],
'post-type' => 'article',
];
}
return response()->json([
'type' => 'feed',
'name' => 'Blog feed for ' . config('app.name'),
'url' => url('/blog'),
'author' => [
'type' => 'card',
'name' => config('user.display_name'),
'url' => config('app.url'),
],
'children' => $items,
], 200, [
'Content-Type' => 'application/jf2feed+json',
]);
}
/**
* Returns the notes JF2 feed.
*/
public function notesJf2(): JsonResponse
{
$notes = Note::latest()->take(20)->get();
$items = [];
foreach ($notes as $note) {
$items[] = [
'type' => 'entry',
'published' => $note->created_at,
'uid' => $note->uri,
'url' => $note->uri,
'content' => [
'text' => $note->getRawOriginal('note'),
'html' => $note->note,
],
'post-type' => 'note',
];
}
return response()->json([
'type' => 'feed',
'name' => 'Notes feed for ' . config('app.name'),
'url' => url('/notes'),
'author' => [
'type' => 'card',
'name' => config('user.display_name'),
'url' => config('app.url'),
],
'children' => $items,
], 200, [
'Content-Type' => 'application/jf2feed+json',
]);
}
} }

View file

@ -1,47 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Bio;
use App\Models\Bookmark;
use App\Models\Like;
use App\Models\Note;
use Illuminate\Http\Response;
use Illuminate\View\View;
class FrontPageController extends Controller
{
/**
* Show all the recent activity.
*/
public function index(): Response|View
{
$notes = Note::latest()->with(['media', 'client', 'place'])->withCount(['webmentions AS replies' => function ($query) {
$query->where('type', 'in-reply-to');
}])
->withCount(['webmentions AS likes' => function ($query) {
$query->where('type', 'like-of');
}])
->withCount(['webmentions AS reposts' => function ($query) {
$query->where('type', 'repost-of');
}])->get();
$articles = Article::latest()->get();
$bookmarks = Bookmark::latest()->with('tags')->get();
$likes = Like::latest()->get();
$items = collect($notes)
->merge($articles)
->merge($bookmarks)
->merge($likes)
->sortByDesc('updated_at')
->paginate(10);
$bio = Bio::first()?->content;
return view('front-page', [
'items' => $items,
'bio' => $bio,
]);
}
}

View file

@ -1,327 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Services\TokenService;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Uri;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;
use Random\RandomException;
use SodiumException;
class IndieAuthController extends Controller
{
public function indieAuthMetadataEndpoint(): JsonResponse
{
return response()->json([
'issuer' => config('app.url'),
'authorization_endpoint' => route('indieauth.start'),
'token_endpoint' => route('indieauth.token'),
'code_challenge_methods_supported' => ['S256'],
// 'introspection_endpoint' => route('indieauth.introspection'),
// 'introspection_endpoint_auth_methods_supported' => ['none'],
]);
}
/**
* Process a GET request to the IndieAuth endpoint.
*
* This is the first step in the IndieAuth flow, where the client app sends the user to the IndieAuth endpoint.
*/
public function start(Request $request): View
{
// First check all required params are present
$validator = Validator::make($request->all(), [
'response_type' => 'required:string',
'client_id' => 'required',
'redirect_uri' => 'required',
'state' => 'required',
'code_challenge' => 'required:string',
'code_challenge_method' => 'required:string',
], [
'response_type' => 'response_type is required',
'client_id.required' => 'client_id is required to display which app is asking for authentication',
'redirect_uri.required' => 'redirect_uri is required so we can progress successful requests',
'state.required' => 'state is required',
'code_challenge.required' => 'code_challenge is required',
'code_challenge_method.required' => 'code_challenge_method is required',
]);
if ($validator->fails()) {
return view('indieauth.error')->withErrors($validator);
}
if ($request->get('response_type') !== 'code') {
return view('indieauth.error')->withErrors(['response_type' => 'only a response_type of "code" is supported']);
}
if (mb_strtoupper($request->get('code_challenge_method')) !== 'S256') {
return view('indieauth.error')->withErrors(['code_challenge_method' => 'only a code_challenge_method of "S256" is supported']);
}
if (! $this->isValidRedirectUri($request->get('client_id'), $request->get('redirect_uri'))) {
return view('indieauth.error')->withErrors(['redirect_uri' => 'redirect_uri is not valid for this client_id']);
}
$scopes = $request->get('scope', '');
$scopes = explode(' ', $scopes);
return view('indieauth.start', [
'me' => $request->get('me'),
'client_id' => $request->get('client_id'),
'redirect_uri' => $request->get('redirect_uri'),
'state' => $request->get('state'),
'scopes' => $scopes,
'code_challenge' => $request->get('code_challenge'),
'code_challenge_method' => $request->get('code_challenge_method'),
]);
}
/**
* Confirm an IndieAuth approval request.
*
* Generates an auth code and redirects the user back to the client app.
*
* @throws RandomException
*/
public function confirm(Request $request): RedirectResponse
{
$authCode = bin2hex(random_bytes(16));
$cacheKey = hash('xxh3', $request->get('client_id'));
$indieAuthRequestData = [
'code_challenge' => $request->get('code_challenge'),
'code_challenge_method' => $request->get('code_challenge_method'),
'client_id' => $request->get('client_id'),
'redirect_uri' => $request->get('redirect_uri'),
'auth_code' => $authCode,
'scope' => implode(' ', $request->get('scope', '')),
];
Cache::put($cacheKey, $indieAuthRequestData, now()->addMinutes(10));
$redirectUri = new Uri($request->get('redirect_uri'));
$redirectUri = Uri::withQueryValues($redirectUri, [
'code' => $authCode,
'state' => $request->get('state'),
'iss' => config('app.url'),
]);
return redirect()->away($redirectUri);
}
/**
* Process a POST request to the IndieAuth auth endpoint.
*
* This is one possible second step in the IndieAuth flow, where the client app sends the auth code to the IndieAuth
* endpoint. As it is to the auth endpoint we return profile information. A similar request can be made to the token
* endpoint to get an access token.
*/
public function processCodeExchange(Request $request): JsonResponse
{
$invalidCodeResponse = $this->validateAuthorizationCode($request);
if ($invalidCodeResponse instanceof JsonResponse) {
return $invalidCodeResponse;
}
return response()->json([
'me' => config('app.url'),
]);
}
/**
* Process a POST request to the IndieAuth token endpoint.
*
* This is another possible second step in the IndieAuth flow, where the client app sends the auth code to the
* IndieAuth token endpoint. As it is to the token endpoint we return an access token.
*
* @throws SodiumException
*/
public function processTokenRequest(Request $request): JsonResponse
{
$indieAuthData = $this->validateAuthorizationCode($request);
if ($indieAuthData instanceof JsonResponse) {
return $indieAuthData;
}
if ($indieAuthData['scope'] === '') {
return response()->json(['errors' => [
'scope' => [
'The scope property must be non-empty for an access token to be issued.',
],
]], 400);
}
$tokenData = [
'me' => config('app.url'),
'client_id' => $request->get('client_id'),
'scope' => $indieAuthData['scope'],
];
$tokenService = resolve(TokenService::class);
$token = $tokenService->getNewToken($tokenData);
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
'scope' => $indieAuthData['scope'],
'me' => config('app.url'),
]);
}
protected function isValidRedirectUri(string $clientId, string $redirectUri): bool
{
// If client_id is not a valid URL, then it's not valid
$clientIdParsed = \Mf2\parseUriToComponents($clientId);
if (! isset($clientIdParsed['authority'])) {
return false;
}
// If redirect_uri is not a valid URL, then it's not valid
$redirectUriParsed = \Mf2\parseUriToComponents($redirectUri);
if (! isset($redirectUriParsed['authority'])) {
return false;
}
// If client_id and redirect_uri are the same host, then it's valid
if ($clientIdParsed['authority'] === $redirectUriParsed['authority']) {
return true;
}
// Otherwise we need to check the redirect_uri is in the client_id's redirect_uris
$guzzle = resolve(Client::class);
try {
$clientInfo = $guzzle->get($clientId);
} catch (Exception) {
return false;
}
$clientInfoParsed = \Mf2\parse($clientInfo->getBody()->getContents(), $clientId);
$redirectUris = $clientInfoParsed['rels']['redirect_uri'] ?? [];
return in_array($redirectUri, $redirectUris, true);
}
/**
* @throws SodiumException
*/
protected function validateAuthorizationCode(Request $request): JsonResponse|array
{
// First check all the data is present
$validator = Validator::make($request->all(), [
'grant_type' => 'required:string',
'code' => 'required:string',
'client_id' => 'required',
'redirect_uri' => 'required',
'code_verifier' => 'required',
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 400);
}
if ($request->get('grant_type') !== 'authorization_code') {
return response()->json(['errors' => [
'grant_type' => [
'Only a grant type of "authorization_code" is supported.',
],
]], 400);
}
// Check cache for auth code
$cacheKey = hash('xxh3', $request->get('client_id'));
$indieAuthRequestData = Cache::pull($cacheKey);
if ($indieAuthRequestData === null) {
return response()->json(['errors' => [
'code' => [
'The code is invalid.',
],
]], 404);
}
// Check the IndieAuth code
if (! array_key_exists('auth_code', $indieAuthRequestData)) {
return response()->json(['errors' => [
'code' => [
'The code is invalid.',
],
]], 400);
}
if ($indieAuthRequestData['auth_code'] !== $request->get('code')) {
return response()->json(['errors' => [
'code' => [
'The code is invalid.',
],
]], 400);
}
// Check code verifier
if (! array_key_exists('code_challenge', $indieAuthRequestData)) {
return response()->json(['errors' => [
'code_verifier' => [
'The code verifier is invalid.',
],
]], 400);
}
if (! hash_equals(
$indieAuthRequestData['code_challenge'],
sodium_bin2base64(
hash('sha256', $request->get('code_verifier'), true),
SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING
)
)) {
return response()->json(['errors' => [
'code_verifier' => [
'The code verifier is invalid.',
],
]], 400);
}
// Check redirect_uri
if (! array_key_exists('redirect_uri', $indieAuthRequestData)) {
return response()->json(['errors' => [
'redirect_uri' => [
'The redirect uri is invalid.',
],
]], 400);
}
if ($indieAuthRequestData['redirect_uri'] !== $request->get('redirect_uri')) {
return response()->json(['errors' => [
'redirect_uri' => [
'The redirect uri is invalid.',
],
]], 400);
}
// Check client_id
if (! array_key_exists('client_id', $indieAuthRequestData)) {
return response()->json(['errors' => [
'client_id' => [
'The client id is invalid.',
],
]], 400);
}
if ($indieAuthRequestData['client_id'] !== $request->get('client_id')) {
return response()->json(['errors' => [
'client_id' => [
'The client id is invalid.',
],
]], 400);
}
return $indieAuthRequestData;
}
}

View file

@ -11,6 +11,8 @@ class LikesController extends Controller
{ {
/** /**
* Show the latest likes. * Show the latest likes.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -21,6 +23,9 @@ class LikesController extends Controller
/** /**
* Show a single like. * Show a single like.
*
* @param \App\Models\Like $like
* @return \Illuminate\View\View
*/ */
public function show(Like $like): View public function show(Like $like): View
{ {

View file

@ -4,109 +4,139 @@ declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Exceptions\InvalidTokenScopeException; use Monolog\Logger;
use App\Exceptions\MicropubHandlerException; use Ramsey\Uuid\Uuid;
use App\Http\Requests\MicropubRequest; use Illuminate\Http\File;
use App\Models\Place; use App\Jobs\ProcessMedia;
use App\Models\SyndicationTarget; use App\Services\TokenService;
use App\Services\Micropub\MicropubHandlerRegistry;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\UploadedFile;
use Lcobucci\JWT\Token; use Monolog\Handler\StreamHandler;
use Intervention\Image\ImageManager;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\{Request, Response};
use App\Exceptions\InvalidTokenException;
use App\Models\{Like, Media, Note, Place};
use Phaza\LaravelPostgis\Geometries\Point;
use Intervention\Image\Exception\NotReadableException;
use App\Services\Micropub\{HCardService, HEntryService, UpdateService};
class MicropubController extends Controller class MicropubController extends Controller
{ {
protected MicropubHandlerRegistry $handlerRegistry; protected $tokenService;
protected $hentryService;
protected $hcardService;
protected $updateService;
public function __construct(MicropubHandlerRegistry $handlerRegistry) public function __construct(
{ TokenService $tokenService,
$this->handlerRegistry = $handlerRegistry; HEntryService $hentryService,
HCardService $hcardService,
UpdateService $updateService
) {
$this->tokenService = $tokenService;
$this->hentryService = $hentryService;
$this->hcardService = $hcardService;
$this->updateService = $updateService;
} }
/** /**
* Respond to a POST request to the micropub endpoint. * This function receives an API request, verifies the authenticity
* then passes over the info to the relavent Service class.
* *
* The request is initially processed by the MicropubRequest form request * @return \Illuminate\Http\JsonResponse
* class. The normalizes the data, so we can pass it into the handlers for
* the different micropub requests, h-entry or h-card, for example.
*/ */
public function post(MicropubRequest $request): JsonResponse public function post(): JsonResponse
{ {
$type = $request->getType();
if (! $type) {
return response()->json([
'error' => 'invalid_request',
'error_description' => 'Microformat object type is missing, for example: h-entry or h-card',
], 400);
}
try { try {
$handler = $this->handlerRegistry->getHandler($type); $tokenData = $this->tokenService->validateToken(request()->input('access_token'));
$result = $handler->handle($request->getMicropubData()); } catch (InvalidTokenException $e) {
return $this->invalidTokenResponse();
// Return appropriate response based on the handler result
return response()->json([
'response' => $result['response'],
'location' => $result['url'] ?? null,
], 201)->header('Location', $result['url']);
} catch (\InvalidArgumentException $e) {
return response()->json([
'error' => 'invalid_request',
'error_description' => $e->getMessage(),
], 400);
} catch (MicropubHandlerException) {
return response()->json([
'error' => 'Unknown Micropub type',
'error_description' => 'The request could not be processed by this server',
], 500);
} catch (InvalidTokenScopeException) {
return response()->json([
'error' => 'invalid_scope',
'error_description' => 'The token does not have the required scope for this request',
], 403);
} catch (\Exception) {
return response()->json([
'error' => 'server_error',
'error_description' => 'An error occurred processing the request',
], 500);
} }
if ($tokenData->hasClaim('scope') === false) {
return $this->tokenHasNoScopeResponse();
}
$this->logMicropubRequest(request()->all());
if ((request()->input('h') == 'entry') || (request()->input('type.0') == 'h-entry')) {
if (stristr($tokenData->getClaim('scope'), 'create') === false) {
return $this->insufficientScopeResponse();
}
$location = $this->hentryService->process(request()->all(), $this->getCLientId());
return response()->json([
'response' => 'created',
'location' => $location,
], 201)->header('Location', $location);
}
if (request()->input('h') == 'card' || request()->input('type')[0] == 'h-card') {
if (stristr($tokenData->getClaim('scope'), 'create') === false) {
return $this->insufficientScopeResponse();
}
$location = $this->hcardService->process(request()->all());
return response()->json([
'response' => 'created',
'location' => $location,
], 201)->header('Location', $location);
}
if (request()->input('action') == 'update') {
if (stristr($tokenData->getClaim('scope'), 'update') === false) {
return $this->insufficientScopeResponse();
}
return $this->updateService->process(request()->all());
}
return response()->json([
'response' => 'error',
'error_description' => 'unsupported_request_type',
], 500);
} }
/** /**
* Respond to a GET request to the micropub endpoint. * Respond to a GET request to the micropub endpoint.
* *
* A GET request has been made to `api/post` with an accompanying * A GET request has been made to `api/post` with an accompanying
* token, here we check whether the token is valid and respond * token, here we check wether the token is valid and respond
* appropriately. Further if the request has the query parameter * appropriately. Further if the request has the query parameter
* syndicate-to we respond with the known syndication endpoints. * synidicate-to we respond with the known syndication endpoints.
*
* @return \Illuminate\Http\JsonResponse
*/ */
public function get(Request $request): JsonResponse public function get(): JsonResponse
{ {
if ($request->input('q') === 'syndicate-to') { try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
} catch (InvalidTokenException $e) {
return $this->invalidTokenResponse();
}
if (request()->input('q') === 'syndicate-to') {
return response()->json([ return response()->json([
'syndicate-to' => SyndicationTarget::all(), 'syndicate-to' => config('syndication.targets'),
]); ]);
} }
if ($request->input('q') === 'config') { if (request()->input('q') == 'config') {
return response()->json([ return response()->json([
'syndicate-to' => SyndicationTarget::all(), 'syndicate-to' => config('syndication.targets'),
'media-endpoint' => route('media-endpoint'), 'media-endpoint' => route('media-endpoint'),
]); ]);
} }
if ($request->has('q') && str_starts_with($request->input('q'), 'geo:')) { if (request()->has('q') && substr(request()->input('q'), 0, 4) === 'geo:') {
preg_match_all( preg_match_all(
'/([0-9.\-]+)/', '/([0-9\.\-]+)/',
$request->input('q'), request()->input('q'),
$matches $matches
); );
$distance = (count($matches[0]) === 3) ? 100 * $matches[0][2] : 1000; $distance = (count($matches[0]) == 3) ? 100 * $matches[0][2] : 1000;
$places = Place::near( $places = Place::near(new Point($matches[0][0], $matches[0][1]))->get();
(object) ['latitude' => $matches[0][0], 'longitude' => $matches[0][1]],
$distance
)->get();
return response()->json([ return response()->json([
'response' => 'places', 'response' => 'places',
@ -114,17 +144,213 @@ class MicropubController extends Controller
]); ]);
} }
// the default response is just to return the token data // default response is just to return the token data
/** @var Token $tokenData */
$tokenData = $request->input('token_data');
return response()->json([ return response()->json([
'response' => 'token', 'response' => 'token',
'token' => [ 'token' => [
'me' => $tokenData['me'], 'me' => $tokenData->getClaim('me'),
'scope' => $tokenData['scope'], 'scope' => $tokenData->getClaim('scope'),
'client_id' => $tokenData['client_id'], 'client_id' => $tokenData->getClaim('client_id'),
], ],
]); ]);
} }
/**
* Process a media item posted to the media endpoint.
*
* @return Illuminate\Http\JsonResponse
*/
public function media(): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
} catch (InvalidTokenException $e) {
return $this->invalidTokenResponse();
}
if ($tokenData->hasClaim('scope') === false) {
return $this->tokenHasNoScopeResponse();
}
if (stristr($tokenData->getClaim('scope'), 'create') === false) {
return $this->insufficientScopeResponse();
}
if ((request()->hasFile('file') && request()->file('file')->isValid()) === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'The uploaded file failed validation',
], 400);
}
$this->logMicropubRequest(request()->all());
$filename = $this->saveFile(request()->file('file'));
$manager = resolve(ImageManager::class);
try {
$image = $manager->make(request()->file('file'));
$width = $image->width();
} catch (NotReadableException $exception) {
// not an image
$width = null;
}
$media = Media::create([
'token' => request()->bearerToken(),
'path' => 'media/' . $filename,
'type' => $this->getFileTypeFromMimeType(request()->file('file')->getMimeType()),
'image_widths' => $width,
]);
// put the file on S3 initially, the ProcessMedia job may edit this
Storage::disk('s3')->putFileAs(
'media',
new File(storage_path('app') . '/' . $filename),
$filename
);
ProcessMedia::dispatch($filename);
return response()->json([
'response' => 'created',
'location' => $media->url,
], 201)->header('Location', $media->url);
}
/**
* Return the relavent CORS headers to a pre-flight OPTIONS request.
*
* @return \Illuminate\Http\Response
*/
public function mediaOptionsResponse(): Response
{
return response('OK', 200);
}
/**
* Get the file type from the mimetype of the uploaded file.
*
* @param string $mimetype
* @return string
*/
private function getFileTypeFromMimeType(string $mimetype): string
{
//try known images
$imageMimeTypes = [
'image/gif',
'image/jpeg',
'image/png',
'image/svg+xml',
'image/tiff',
'image/webp',
];
if (in_array($mimetype, $imageMimeTypes)) {
return 'image';
}
//try known video
$videoMimeTypes = [
'video/mp4',
'video/mpeg',
'video/ogg',
'video/quicktime',
'video/webm',
];
if (in_array($mimetype, $videoMimeTypes)) {
return 'video';
}
//try known audio types
$audioMimeTypes = [
'audio/midi',
'audio/mpeg',
'audio/ogg',
'audio/x-m4a',
];
if (in_array($mimetype, $audioMimeTypes)) {
return 'audio';
}
return 'download';
}
/**
* Determine the client id from the access token sent with the request.
*
* @return string
*/
private function getClientId(): string
{
return resolve(TokenService::class)
->validateToken(request()->input('access_token'))
->getClaim('client_id');
}
/**
* Save the details of the micropub request to a log file.
*
* @param array $request This is the info from request()->all()
*/
private function logMicropubRequest(array $request)
{
$logger = new Logger('micropub');
$logger->pushHandler(new StreamHandler(storage_path('logs/micropub.log')), Logger::DEBUG);
$logger->debug('MicropubLog', $request);
}
/**
* Save an uploaded file to the local disk.
*
* @param \Illuminate\Http\UploadedFele $file
* @return string $filename
*/
private function saveFile(UploadedFile $file): string
{
$filename = Uuid::uuid4() . '.' . $file->extension();
Storage::disk('local')->putFileAs('', $file, $filename);
return $filename;
}
/**
* Generate a response to be returned when the token has insufficient scope.
*
* @return \Illuminate\Http\JsonRepsonse
*/
private function insufficientScopeResponse()
{
return response()->json([
'response' => 'error',
'error' => 'insufficient_scope',
'error_description' => 'The tokens scope does not have the necessary requirements.',
], 401);
}
/**
* Generate a response to be returned when the token is invalid.
*
* @return \Illuminate\Http\JsonRepsonse
*/
private function invalidTokenResponse()
{
return response()->json([
'response' => 'error',
'error' => 'invalid_token',
'error_description' => 'The provided token did not pass validation',
], 400);
}
/**
* Generate a response to be returned when the token has no scope.
*
* @return \Illuminate\Http\JsonRepsonse
*/
private function tokenHasNoScopeResponse()
{
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'The provided token has no scopes',
], 400);
}
} }

View file

@ -1,201 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Http\Responses\MicropubResponses;
use App\Jobs\ProcessMedia;
use App\Models\Media;
use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;
use Ramsey\Uuid\Uuid;
class MicropubMediaController extends Controller
{
public function getHandler(Request $request): JsonResponse
{
$tokenData = $request->input('token_data');
$scopes = $tokenData['scope'];
if (is_string($scopes)) {
$scopes = explode(' ', $scopes);
}
if (! in_array('create', $scopes, true)) {
return (new MicropubResponses)->insufficientScopeResponse();
}
if ($request->input('q') === 'last') {
$media = Media::where('created_at', '>=', Carbon::now()->subMinutes(30))
->where('token', $request->input('access_token'))
->latest()
->first();
$mediaUrl = $media?->url;
return response()->json(['url' => $mediaUrl]);
}
if ($request->input('q') === 'source') {
$limit = $request->input('limit', 10);
$offset = $request->input('offset', 0);
$media = Media::latest()->offset($offset)->limit($limit)->get();
$media->transform(function ($mediaItem) {
return [
'url' => $mediaItem->url,
'published' => $mediaItem->created_at->toW3cString(),
'mime_type' => $mediaItem->mimetype,
];
});
return response()->json(['items' => $media]);
}
if ($request->has('q')) {
return response()->json([
'error' => 'invalid_request',
'error_description' => sprintf(
'This server does not know how to handle this q parameter (%s)',
$request->input('q')
),
], 400);
}
return response()->json(['status' => 'OK']);
}
/**
* Process a media item posted to the media endpoint.
*
* @throws BindingResolutionException
* @throws Exception
*/
public function media(Request $request): JsonResponse
{
$tokenData = $request->input('token_data');
$scopes = $tokenData['scope'];
if (is_string($scopes)) {
$scopes = explode(' ', $scopes);
}
if (! in_array('create', $scopes, true)) {
return (new MicropubResponses)->insufficientScopeResponse();
}
if ($request->hasFile('file') === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'No file was sent with the request',
], 400);
}
/** @var UploadedFile $file */
$file = $request->file('file');
if ($file->isValid() === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'The uploaded file failed validation',
], 400);
}
$filename = Storage::disk('local')->putFile('media', $file);
/** @var ImageManager $manager */
$manager = resolve(ImageManager::class);
try {
$image = $manager->read($request->file('file'));
$width = $image->width();
} catch (Exception) {
// not an image
$width = null;
}
$media = Media::create([
'token' => $request->input('access_token'),
'path' => $filename,
'type' => $this->getFileTypeFromMimeType($request->file('file')->getMimeType()),
'image_widths' => $width,
]);
ProcessMedia::dispatch($filename);
return response()->json([
'response' => 'created',
'location' => $media->url,
], 201)->header('Location', $media->url);
}
/**
* Return the relevant CORS headers to a pre-flight OPTIONS request.
*/
public function mediaOptionsResponse(): Response
{
return response('OK', 200);
}
/**
* Get the file type from the mime-type of the uploaded file.
*/
private function getFileTypeFromMimeType(string $mimeType): string
{
// try known images
$imageMimeTypes = [
'image/gif',
'image/jpeg',
'image/png',
'image/svg+xml',
'image/tiff',
'image/webp',
];
if (in_array($mimeType, $imageMimeTypes)) {
return 'image';
}
// try known video
$videoMimeTypes = [
'video/mp4',
'video/mpeg',
'video/ogg',
'video/quicktime',
'video/webm',
];
if (in_array($mimeType, $videoMimeTypes)) {
return 'video';
}
// try known audio types
$audioMimeTypes = [
'audio/midi',
'audio/mpeg',
'audio/ogg',
'audio/x-m4a',
];
if (in_array($mimeType, $audioMimeTypes)) {
return 'audio';
}
return 'download';
}
/**
* Save an uploaded file to the local disk.
*
* @throws Exception
*/
private function saveFileToLocal(UploadedFile $file): string
{
$filename = Uuid::uuid4()->toString() . '.' . $file->extension();
Storage::disk('local')->putFileAs('', $file, $filename);
return $filename;
}
}

View file

@ -5,33 +5,31 @@ declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Note; use App\Models\Note;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Http\Request;
use Jonnybarnes\IndieWeb\Numbers; use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Http\RedirectResponse;
use App\Services\ActivityStreamsService;
// Need to sort out Twitter and webmentions!
/**
* @todo Need to sort out Twitter and webmentions!
*/
class NotesController extends Controller class NotesController extends Controller
{ {
/** /**
* Show all the notes. This is also the homepage. * Show all the notes. This is also the homepage.
*
* @return \Illuminate\View\View|\Illuminate\Http\JsonResponse
*/ */
public function index(): View|Response public function index()
{ {
if (request()->wantsActivityStream()) {
return (new ActivityStreamsService)->siteOwnerResponse();
}
$notes = Note::latest() $notes = Note::latest()
->with('place', 'media', 'client') ->with('place', 'media', 'client')
->withCount(['webmentions AS replies' => function ($query) { ->withCount(['webmentions As replies' => function ($query) {
$query->where('type', 'in-reply-to'); $query->where('type', 'in-reply-to');
}])
->withCount(['webmentions AS likes' => function ($query) {
$query->where('type', 'like-of');
}])
->withCount(['webmentions AS reposts' => function ($query) {
$query->where('type', 'repost-of');
}])->paginate(10); }])->paginate(10);
return view('notes.index', compact('notes')); return view('notes.index', compact('notes'));
@ -39,22 +37,16 @@ class NotesController extends Controller
/** /**
* Show a single note. * Show a single note.
*
* @param string $urlId The id of the note
* @return \Illuminate\View\View|\Illuminate\Http\JsonResponse
*/ */
public function show(string $urlId): View|JsonResponse|Response public function show(string $urlId)
{ {
try { $note = Note::nb60($urlId)->with('webmentions')->firstOrFail();
$note = Note::nb60($urlId)->with('place', 'media', 'client')
->withCount(['webmentions AS replies' => function ($query) { if (request()->wantsActivityStream()) {
$query->where('type', 'in-reply-to'); return (new ActivityStreamsService)->singleNoteResponse($note);
}])
->withCount(['webmentions AS likes' => function ($query) {
$query->where('type', 'like-of');
}])
->withCount(['webmentions AS reposts' => function ($query) {
$query->where('type', 'repost-of');
}])->firstOrFail();
} catch (ModelNotFoundException $exception) {
abort(404);
} }
return view('notes.show', compact('note')); return view('notes.show', compact('note'));
@ -62,14 +54,20 @@ class NotesController extends Controller
/** /**
* Redirect /note/{decID} to /notes/{nb60id}. * Redirect /note/{decID} to /notes/{nb60id}.
*
* @param int $decId The decimal id of the note
* @return \Illuminate\Http\RedirectResponse
*/ */
public function redirect(int $decId): RedirectResponse public function redirect(int $decId): RedirectResponse
{ {
return redirect(config('app.url') . '/notes/' . (new Numbers)->numto60($decId)); return redirect(config('app.url') . '/notes/' . (new Numbers())->numto60($decId));
} }
/** /**
* Show all notes tagged with {tag}. * Show all notes tagged with {tag}.
*
* @param string $tag
* @return \Illuminate\View\View
*/ */
public function tagged(string $tag): View public function tagged(string $tag): View
{ {
@ -79,14 +77,4 @@ class NotesController extends Controller
return view('notes.tagged', compact('notes', 'tag')); return view('notes.tagged', compact('notes', 'tag'));
} }
/**
* Page to create a new note.
*
* Dummy page for now.
*/
public function create(): View
{
return view('notes.create');
}
} }

View file

@ -11,6 +11,8 @@ class PlacesController extends Controller
{ {
/** /**
* Show all the places. * Show all the places.
*
* @return \Illuminate\View\View
*/ */
public function index(): View public function index(): View
{ {
@ -21,9 +23,14 @@ class PlacesController extends Controller
/** /**
* Show a specific place. * Show a specific place.
*
* @param string $slug
* @return \Illuminate\View\View
*/ */
public function show(Place $place): View public function show(string $slug): View
{ {
$place = Place::where('slug', '=', $slug)->firstOrFail();
return view('singleplace', ['place' => $place]); return view('singleplace', ['place' => $place]);
} }
} }

View file

@ -1,34 +1,23 @@
<?php <?php
declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Note; use App\Models\Note;
use Illuminate\Http\Request;
use Illuminate\View\View; use Illuminate\View\View;
class SearchController extends Controller class SearchController extends Controller
{ {
public function search(Request $request): View /**
* Display search results.
*
* @return \Illuminate\View\View
*/
public function search(): View
{ {
$search = $request->input('q'); $notes = Note::search(request()->input('terms'))->paginate(10);
$notes = Note::search($search) return view('search', compact('notes'));
->paginate();
/** @var Note $note */
foreach ($notes as $note) {
$note->load('place', 'media', 'client')
->loadCount(['webmentions AS replies' => function ($query) {
$query->where('type', 'in-reply-to');
}])
->loadCount(['webmentions AS likes' => function ($query) {
$query->where('type', 'like-of');
}])
->loadCount(['webmentions AS reposts' => function ($query) {
$query->where('type', 'repost-of');
}]);
}
return view('search', compact('search', 'notes'));
} }
} }

View file

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
class SessionStoreController extends Controller
{
/**
* Save the selected colour scheme in the session.
*
* @return \Illuminate\Http\JsonResponse
*/
public function saveColour()
{
$css = request()->input('css');
session(['css' => $css]);
return ['status' => 'ok'];
}
}

View file

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
class ShortURLsController extends Controller
{
/*
|--------------------------------------------------------------------------
| Short URL Controller
|--------------------------------------------------------------------------
|
| This redirects the short urls to long ones
|
*/
/**
* Redirect from '/' to the long url.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function baseURL(): RedirectResponse
{
return redirect(config('app.url'));
}
/**
* Redirect from '/@' to a twitter profile.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function twitter(): RedirectResponse
{
return redirect('https://twitter.com/jonnybarnes');
}
/**
* Redirect from '/+' to a Google+ profile.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function googlePlus(): RedirectResponse
{
return redirect('https://plus.google.com/u/0/117317270900655269082/about');
}
/**
* Redirect a short url of this site out to a long one based on post type.
* Further redirects may happen.
*
* @param string Post type
* @param string Post ID
* @return \Illuminate\Http\RedirectResponse
*/
public function expandType(string $type, string $postId): RedirectResponse
{
if ($type == 't') {
$type = 'notes';
}
if ($type == 'b') {
$type = 'blog/s';
}
return redirect(config('app.url') . '/' . $type . '/' . $postId);
}
}

View file

@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use IndieAuth\Client;
use App\Services\TokenService;
use Illuminate\Http\JsonResponse;
class TokenEndpointController extends Controller
{
/**
* The IndieAuth Client.
*/
protected $client;
/**
* The Token handling service.
*/
protected $tokenService;
/**
* Inject the dependencies.
*
* @param \IndieAuth\Client $client
* @param \App\Services\TokenService $tokenService
*/
public function __construct(
Client $client,
TokenService $tokenService
) {
$this->client = $client;
$this->tokenService = $tokenService;
}
/**
* If the user has authd via the IndieAuth protocol, issue a valid token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function create(): JsonResponse
{
$authorizationEndpoint = $this->client->discoverAuthorizationEndpoint(normalize_url(request()->input('me')));
if ($authorizationEndpoint) {
$auth = $this->client->verifyIndieAuthCode(
$authorizationEndpoint,
request()->input('code'),
request()->input('me'),
request()->input('redirect_uri'),
request()->input('client_id')
);
if (array_key_exists('me', $auth)) {
$scope = $auth['scope'] ?? '';
$tokenData = [
'me' => request()->input('me'),
'client_id' => request()->input('client_id'),
'scope' => $scope,
];
$token = $this->tokenService->getNewToken($tokenData);
$content = [
'me' => request()->input('me'),
'scope' => $scope,
'access_token' => $token,
];
return response()->json($content);
}
return response()->json([
'error' => 'There was an error verifying the authorisation code.',
], 401);
}
return response()->json([
'error' => 'Cant determine the authorisation endpoint.',
], 400);
}
}

View file

@ -4,13 +4,12 @@ declare(strict_types=1);
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Jobs\ProcessWebMention;
use App\Models\Note; use App\Models\Note;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View; use Illuminate\View\View;
use Illuminate\Http\Response;
use App\Jobs\ProcessWebMention;
use Jonnybarnes\IndieWeb\Numbers; use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class WebMentionsController extends Controller class WebMentionsController extends Controller
{ {
@ -19,6 +18,8 @@ class WebMentionsController extends Controller
* *
* This is probably someone looking for information about what * This is probably someone looking for information about what
* webmentions are, or about my particular implementation. * webmentions are, or about my particular implementation.
*
* @return \Illuminate\View\View
*/ */
public function get(): View public function get(): View
{ {
@ -27,27 +28,29 @@ class WebMentionsController extends Controller
/** /**
* Receive and process a webmention. * Receive and process a webmention.
*
* @return \Illuminate\Http\Respone
*/ */
public function receive(Request $request): Response public function receive(): Response
{ {
// first we trivially reject requests that lack all required inputs //first we trivially reject requets that lack all required inputs
if (($request->has('target') !== true) || ($request->has('source') !== true)) { if ((request()->has('target') !== true) || (request()->has('source') !== true)) {
return response( return response(
'You need both the target and source parameters', 'You need both the target and source parameters',
400 400
); );
} }
// next check the $target is valid //next check the $target is valid
$path = parse_url($request->input('target'), PHP_URL_PATH); $path = parse_url(request()->input('target'), PHP_URL_PATH);
$pathParts = explode('/', $path); $pathParts = explode('/', $path);
if ($pathParts[1] === 'notes') { if ($pathParts[1] == 'notes') {
// we have a note //we have a note
$noteId = $pathParts[2]; $noteId = $pathParts[2];
try { try {
$note = Note::findOrFail(resolve(Numbers::class)->b60tonum($noteId)); $note = Note::findOrFail(resolve(Numbers::class)->b60tonum($noteId));
dispatch(new ProcessWebMention($note, $request->input('source'))); dispatch(new ProcessWebMention($note, request()->input('source')));
} catch (ModelNotFoundException $e) { } catch (ModelNotFoundException $e) {
return response('This note doesnt exist.', 400); return response('This note doesnt exist.', 400);
} }
@ -57,7 +60,7 @@ class WebMentionsController extends Controller
202 202
); );
} }
if ($pathParts[1] === 'blog') { if ($pathParts[1] == 'blog') {
return response( return response(
'I dont accept webmentions for blog posts yet.', 'I dont accept webmentions for blog posts yet.',
501 501

87
app/Http/Kernel.php Normal file
View file

@ -0,0 +1,87 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\LinkHeadersMiddleware::class,
\App\Http\Middleware\LocalhostSessionMiddleware::class,
\App\Http\Middleware\ActivityStreamLinks::class,
\App\Http\Middleware\CSPHeader::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'micropub.token' => \App\Http\Middleware\VerifyMicropubToken::class,
'myauth' => \App\Http\Middleware\MyAuthMiddleware::class,
'cors' => \App\Http\Middleware\CorsHeaders::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}

View file

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ActivityStreamLinks
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$response = $next($request);
if ($request->path() === '/') {
$response->header('Link', '<' . config('app.url') . '>; rel="application/activity+json"', false);
}
if ($request->is('notes/*')) {
$response->header('Link', '<' . $request->url() . '>; rel="application/activity+json"', false);
}
return $response;
}
}

View file

@ -3,18 +3,19 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
/**
* @codeCoverageIgnore
*/
class Authenticate extends Middleware class Authenticate extends Middleware
{ {
/** /**
* Get the path the user should be redirected to when they are not authenticated. * Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/ */
protected function redirectTo(Request $request): ?string protected function redirectTo($request)
{ {
return $request->expectsJson() ? null : route('login'); if (! $request->expectsJson()) {
return route('login');
}
} }
} }

View file

@ -0,0 +1,73 @@
<?php
namespace App\Http\Middleware;
use Closure;
class CSPHeader
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// headers have to be single-line strings,
// so we concat multiple lines
//return $next($request);
return $next($request)
->header(
'Content-Security-Policy',
str_replace("\\\n", '', "default-src 'self'; \
script-src 'self' 'unsafe-inline' 'unsafe-eval' \
https://api.mapbox.com \
https://analytics.jmb.lv \
blob:; \
style-src 'self' 'unsafe-inline' \
https://api.mapbox.com \
https://fonts.googleapis.com \
use.typekit.net \
p.typekit.net; \
img-src 'self' data: blob: \
https://pbs.twimg.com \
https://api.mapbox.com \
https://*.tiles.mapbox.com \
https://jbuk-media.s3-eu-west-1.amazonaws.com \
https://jbuk-media-dev.s3-eu-west-1.amazonaws.com \
https://secure.gravatar.com \
https://graph.facebook.com *.fbcdn.net \
https://*.cdninstagram.com \
analytics.jmb.lv \
https://*.4sqi.net \
https://upload.wikimedia.org \
p.typekit.net; \
font-src 'self' \
https://fonts.gstatic.com \
use.typekit.net \
fonts.typekit.net \
data:; \
connect-src 'self' \
https://api.mapbox.com \
https://*.tiles.mapbox.com \
performance.typekit.net \
data: blob:; \
worker-src 'self' blob:; \
frame-src 'self' https://www.youtube.com blob:; \
child-src blob:; \
upgrade-insecure-requests; \
block-all-mixed-content; \
report-to csp-endpoint; \
report-uri https://jonnybarnes.report-uri.io/r/default/csp/enforce;")
)->header(
'Report-To',
'{' .
"'url': 'https://jonnybarnes.report-uri.io/r/default/csp/enforce', " .
"'group': 'csp-endpoint'," .
"'max-age': 10886400" .
'}'
);
}
}

View file

@ -2,14 +2,14 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware; use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class PreventRequestsDuringMaintenance extends Middleware class CheckForMaintenanceMode extends Middleware
{ {
/** /**
* The URIs that should be reachable while maintenance mode is enabled. * The URIs that should be reachable while maintenance mode is enabled.
* *
* @var array<int, string> * @var array
*/ */
protected $except = [ protected $except = [
// //

View file

@ -3,15 +3,17 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use Closure; use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CorsHeaders class CorsHeaders
{ {
/** /**
* Handle an incoming request. * Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/ */
public function handle(Request $request, Closure $next): Response public function handle($request, Closure $next)
{ {
$response = $next($request); $response = $next($request);
if ($request->path() === 'api/media') { if ($request->path() === 'api/media') {

View file

@ -9,7 +9,7 @@ class EncryptCookies extends Middleware
/** /**
* The names of the cookies that should not be encrypted. * The names of the cookies that should not be encrypted.
* *
* @var array<int, string> * @var array
*/ */
protected $except = [ protected $except = [
// //

View file

@ -3,22 +3,23 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use Closure; use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class LinkHeadersMiddleware class LinkHeadersMiddleware
{ {
/** /**
* Handle an incoming request. * Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/ */
public function handle(Request $request, Closure $next): Response public function handle($request, Closure $next)
{ {
$response = $next($request); $response = $next($request);
$response->header('Link', '<' . route('indieauth.metadata') . '>; rel="indieauth-metadata"', false); $response->header('Link', '<https://indieauth.com/auth>; rel="authorization_endpoint"', false);
$response->header('Link', '<' . route('indieauth.start') . '>; rel="authorization_endpoint"', false); $response->header('Link', '<' . config('app.url') . '/api/token>; rel="token_endpoint"', false);
$response->header('Link', '<' . route('indieauth.token') . '>; rel="token_endpoint"', false); $response->header('Link', '<' . config('app.url') . '/api/post>; rel="micropub"', false);
$response->header('Link', '<' . route('micropub-endpoint') . '>; rel="micropub"', false); $response->header('Link', '<' . config('app.url') . '/webmention>; rel="webmention"', false);
$response->header('Link', '<' . route('webmention-endpoint') . '>; rel="webmention"', false);
return $response; return $response;
} }

View file

@ -6,7 +6,6 @@ namespace App\Http\Middleware;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class LocalhostSessionMiddleware class LocalhostSessionMiddleware
{ {
@ -14,8 +13,12 @@ class LocalhostSessionMiddleware
* Whilst we are developing locally, automatically log in as * Whilst we are developing locally, automatically log in as
* `['me' => config('app.url')]` as I cant manually log in as * `['me' => config('app.url')]` as I cant manually log in as
* a .localhost domain. * a .localhost domain.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/ */
public function handle(Request $request, Closure $next): Response public function handle(Request $request, Closure $next)
{ {
if (config('app.env') !== 'production') { if (config('app.env') !== 'production') {
session(['me' => config('app.url')]); session(['me' => config('app.url')]);

View file

@ -1,24 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class LogMicropubRequest
{
public function handle(Request $request, Closure $next): Response|JsonResponse
{
$logger = new Logger('micropub');
$logger->pushHandler(new StreamHandler(storage_path('logs/micropub.log')));
$logger->debug('MicropubLog', $request->all());
return $next($request);
}
}

View file

@ -6,20 +6,20 @@ namespace App\Http\Middleware;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class MyAuthMiddleware class MyAuthMiddleware
{ {
/** /**
* Check the user is logged in. * Check the user is logged in.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/ */
public function handle(Request $request, Closure $next): Response public function handle(Request $request, Closure $next)
{ {
if (Auth::check() === false) { if ($request->session()->has('loggedin') !== true) {
// theyre not logged in, so send them to login form //theyre not logged in, so send them to login form
redirect()->setIntendedUrl($request->fullUrl());
return redirect()->route('login'); return redirect()->route('login');
} }

View file

@ -2,11 +2,8 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure; use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
/** /**
* @codeCoverageIgnore * @codeCoverageIgnore
@ -16,16 +13,15 @@ class RedirectIfAuthenticated
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next * @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/ */
public function handle(Request $request, Closure $next, string ...$guards): Response public function handle($request, Closure $next, $guard = null)
{ {
$guards = empty($guards) ? [null] : $guards; if (Auth::guard($guard)->check()) {
return redirect('/home');
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
} }
return $next($request); return $next($request);

View file

@ -9,10 +9,9 @@ class TrimStrings extends Middleware
/** /**
* The names of the attributes that should not be trimmed. * The names of the attributes that should not be trimmed.
* *
* @var array<int, string> * @var array
*/ */
protected $except = [ protected $except = [
'current_password',
'password', 'password',
'password_confirmation', 'password_confirmation',
]; ];

View file

@ -1,23 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
/**
* @codeCoverageIgnore
*/
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View file

@ -2,27 +2,22 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware class TrustProxies extends Middleware
{ {
/** /**
* The trusted proxies for this application. * The trusted proxies for this application.
* *
* @var array<int, string>|string|null * @var array
*/ */
protected $proxies; protected $proxies;
/** /**
* The header that should be used to detect proxies. * The header that should be used to detect proxies.
* *
* @var int * @var string
*/ */
protected $headers = protected $headers = Request::HEADER_X_FORWARDED_ALL;
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
} }

View file

@ -1,22 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View file

@ -9,7 +9,7 @@ class VerifyCsrfToken extends Middleware
/** /**
* The URIs that should be excluded from CSRF verification. * The URIs that should be excluded from CSRF verification.
* *
* @var array<int, string> * @var array
*/ */
protected $except = [ protected $except = [
'api/media', 'api/media',

View file

@ -4,78 +4,34 @@ declare(strict_types=1);
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Http\Responses\MicropubResponses;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Encoding\CannotDecodeContent;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\Token\InvalidTokenStructure;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Symfony\Component\HttpFoundation\Response;
class VerifyMicropubToken class VerifyMicropubToken
{ {
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param Closure(Request): (Response) $next * @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/ */
public function handle(Request $request, Closure $next): Response public function handle(Request $request, Closure $next)
{ {
$rawToken = null;
if ($request->input('access_token')) { if ($request->input('access_token')) {
$rawToken = $request->input('access_token'); return $next($request);
} elseif ($request->bearerToken()) {
$rawToken = $request->bearerToken();
} }
if (! $rawToken) { if ($request->bearerToken()) {
return response()->json([ return $next($request->merge([
'response' => 'error', 'access_token' => $request->bearerToken(),
'error' => 'unauthorized', ]));
'error_description' => 'No access token was provided in the request',
], 401);
} }
try { return response()->json([
$tokenData = $this->validateToken($rawToken); 'response' => 'error',
} catch (RequiredConstraintsViolated|InvalidTokenStructure|CannotDecodeContent) { 'error' => 'unauthorized',
$micropubResponses = new MicropubResponses; 'error_description' => 'No access token was provided in the request',
], 401);
return $micropubResponses->invalidTokenResponse();
}
if ($tokenData->claims()->has('scope') === false) {
$micropubResponses = new MicropubResponses;
return $micropubResponses->tokenHasNoScopeResponse();
}
return $next($request->merge([
'access_token' => $rawToken,
'token_data' => [
'me' => $tokenData->claims()->get('me'),
'scope' => $tokenData->claims()->get('scope'),
'client_id' => $tokenData->claims()->get('client_id'),
],
]));
}
/**
* Check the token signature is valid.
*/
private function validateToken(string $bearerToken): Token
{
$config = resolve(Configuration::class);
$token = $config->parser()->parse($bearerToken);
$constraints = $config->validationConstraints();
$config->validator()->assert($token, ...$constraints);
return $token;
} }
} }

View file

@ -1,106 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
class MicropubRequest extends FormRequest
{
protected array $micropubData = [];
public function rules(): array
{
return [
// Validation rules
];
}
public function getMicropubData(): array
{
return $this->micropubData;
}
public function getType(): ?string
{
// Return consistent type regardless of input format
return $this->micropubData['type'] ?? null;
}
protected function prepareForValidation(): void
{
// Normalize the request data based on content type
if ($this->isJson()) {
$this->normalizeMicropubJson();
} else {
$this->normalizeMicropubForm();
}
}
private function normalizeMicropubJson(): void
{
$json = $this->json();
if ($json === null) {
throw new \InvalidArgumentException('`isJson()` passed but there is no json data');
}
$data = $json->all();
// Convert JSON type (h-entry) to simple type (entry)
if (isset($data['type']) && is_array($data['type'])) {
$type = current($data['type']);
if (strpos($type, 'h-') === 0) {
$this->micropubData['type'] = substr($type, 2);
}
}
// Or set the type to update
elseif (isset($data['action']) && $data['action'] === 'update') {
$this->micropubData['type'] = 'update';
}
// Add in the token data
$this->micropubData['token_data'] = $data['token_data'];
// Add h-entry values
$this->micropubData['content'] = Arr::get($data, 'properties.content.0');
$this->micropubData['in-reply-to'] = Arr::get($data, 'properties.in-reply-to.0');
$this->micropubData['published'] = Arr::get($data, 'properties.published.0');
$this->micropubData['location'] = Arr::get($data, 'location');
$this->micropubData['bookmark-of'] = Arr::get($data, 'properties.bookmark-of.0');
$this->micropubData['like-of'] = Arr::get($data, 'properties.like-of.0');
$this->micropubData['mp-syndicate-to'] = Arr::get($data, 'properties.mp-syndicate-to');
// Add h-card values
$this->micropubData['name'] = Arr::get($data, 'properties.name.0');
$this->micropubData['description'] = Arr::get($data, 'properties.description.0');
$this->micropubData['geo'] = Arr::get($data, 'properties.geo.0');
// Add checkin value
$this->micropubData['checkin'] = Arr::get($data, 'checkin');
$this->micropubData['syndication'] = Arr::get($data, 'properties.syndication.0');
}
private function normalizeMicropubForm(): void
{
// Convert form h=entry to type=entry
if ($h = $this->input('h')) {
$this->micropubData['type'] = $h;
}
// Add some fields to the micropub data with default null values
$this->micropubData['in-reply-to'] = null;
$this->micropubData['published'] = null;
$this->micropubData['location'] = null;
$this->micropubData['description'] = null;
$this->micropubData['geo'] = null;
$this->micropubData['latitude'] = null;
$this->micropubData['longitude'] = null;
// Map form fields to micropub data
foreach ($this->except(['h', 'access_token']) as $key => $value) {
$this->micropubData[$key] = $value;
}
}
}

View file

@ -1,46 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Responses;
use Illuminate\Http\JsonResponse;
class MicropubResponses
{
/**
* Generate a response to be returned when the token has insufficient scope.
*/
public function insufficientScopeResponse(): JsonResponse
{
return response()->json([
'response' => 'error',
'error' => 'insufficient_scope',
'error_description' => 'The tokens scope does not have the necessary requirements.',
], 401);
}
/**
* Generate a response to be returned when the token is invalid.
*/
public function invalidTokenResponse(): JsonResponse
{
return response()->json([
'response' => 'error',
'error' => 'invalid_token',
'error_description' => 'The provided token did not pass validation',
], 400);
}
/**
* Generate a response to be returned when the token has no scope.
*/
public function tokenHasNoScopeResponse(): JsonResponse
{
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'The provided token has no scopes',
], 400);
}
}

View file

@ -4,37 +4,38 @@ declare(strict_types=1);
namespace App\Jobs; namespace App\Jobs;
use App\Models\MicropubClient;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use App\Models\MicropubClient;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class AddClientToDatabase implements ShouldQueue class AddClientToDatabase implements ShouldQueue
{ {
use Dispatchable; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
protected string $client_id; protected $client_id;
/** /**
* Create a new job instance. * Create a new job instance.
*
* @param string $client_id
*/ */
public function __construct(string $clientId) public function __construct(string $client_id)
{ {
$this->client_id = $clientId; $this->client_id = $client_id;
} }
/** /**
* Execute the job. * Execute the job.
*
* @return void
*/ */
public function handle(): void public function handle()
{ {
if (MicropubClient::where('client_url', $this->client_id)->count() === 0) { if (MicropubClient::where('client_url', $this->client_id)->count() == 0) {
MicropubClient::create([ $client = MicropubClient::create([
'client_url' => $this->client_id, 'client_url' => $this->client_id,
'client_name' => $this->client_id, // default client name is the URL 'client_name' => $this->client_id, // default client name is the URL
]); ]);

View file

@ -5,62 +5,67 @@ declare(strict_types=1);
namespace App\Jobs; namespace App\Jobs;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\FileSystem\FileSystem; use Illuminate\FileSystem\FileSystem;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class DownloadWebMention implements ShouldQueue class DownloadWebMention implements ShouldQueue
{ {
use InteractsWithQueue; use InteractsWithQueue, Queueable, SerializesModels;
use Queueable;
use SerializesModels; /**
* The webmention source URL.
*
* @var
*/
protected $source;
/** /**
* Create a new job instance. * Create a new job instance.
*
* @param string $source
*/ */
public function __construct( public function __construct(string $source)
protected string $source {
) {} $this->source = $source;
}
/** /**
* Execute the job. * Execute the job.
* *
* @throws GuzzleException * @param \GuzzleHttp\Client $guzzle
* @throws FileNotFoundException
*/ */
public function handle(Client $guzzle): void public function handle(Client $guzzle)
{ {
$response = $guzzle->request('GET', $this->source); $response = $guzzle->request('GET', $this->source);
// 4XX and 5XX responses should get Guzzle to throw an exception, //4XX and 5XX responses should get Guzzle to throw an exception,
// Laravel should catch and retry these automatically. //Laravel should catch and retry these automatically.
if ($response->getStatusCode() === 200) { if ($response->getStatusCode() == '200') {
$filesystem = new FileSystem; $filesystem = new FileSystem();
$filename = storage_path('HTML') . '/' . $this->createFilenameFromURL($this->source); $filename = storage_path('HTML') . '/' . $this->createFilenameFromURL($this->source);
// backup file first //backup file first
$filenameBackup = $filename . '.' . date('Y-m-d') . '.backup'; $filenameBackup = $filename . '.' . date('Y-m-d') . '.backup';
if ($filesystem->exists($filename)) { if ($filesystem->exists($filename)) {
$filesystem->copy($filename, $filenameBackup); $filesystem->copy($filename, $filenameBackup);
} }
// check if base directory exists //check if base directory exists
if (! $filesystem->exists($filesystem->dirname($filename))) { if (! $filesystem->exists($filesystem->dirname($filename))) {
$filesystem->makeDirectory( $filesystem->makeDirectory(
$filesystem->dirname($filename), $filesystem->dirname($filename),
0755, // mode 0755, //mode
true // recursive true //recursive
); );
} }
// save new HTML //save new HTML
$filesystem->put( $filesystem->put(
$filename, $filename,
(string) $response->getBody() (string) $response->getBody()
); );
// remove backup if the same //remove backup if the same
if ($filesystem->exists($filenameBackup)) { if ($filesystem->exists($filenameBackup)) {
if ($filesystem->get($filename) === $filesystem->get($filenameBackup)) { if ($filesystem->get($filename) == $filesystem->get($filenameBackup)) {
$filesystem->delete($filenameBackup); $filesystem->delete($filenameBackup);
} }
} }
@ -68,12 +73,16 @@ class DownloadWebMention implements ShouldQueue
} }
/** /**
* Create a file path from a URL. This is used when caching the HTML response. * Create a file path from a URL. This is used when caching the HTML
* response.
*
* @param string The URL
* @return string The path name
*/ */
private function createFilenameFromURL(string $url): string private function createFilenameFromURL($url)
{ {
$filepath = str_replace(['https://', 'http://'], ['https/', 'http/'], $url); $filepath = str_replace(['https://', 'http://'], ['https/', 'http/'], $url);
if (str_ends_with($filepath, '/')) { if (substr($filepath, -1) == '/') {
$filepath .= 'index.html'; $filepath .= 'index.html';
} }

View file

@ -4,39 +4,44 @@ declare(strict_types=1);
namespace App\Jobs; namespace App\Jobs;
use App\Exceptions\InternetArchiveException;
use App\Models\Bookmark; use App\Models\Bookmark;
use App\Services\BookmarkService;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use App\Services\BookmarkService;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue; use App\Exceptions\InternetArchiveException;
use Illuminate\Queue\SerializesModels;
class ProcessBookmark implements ShouldQueue class ProcessBookmark implements ShouldQueue
{ {
use Dispatchable; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable; protected $bookmark;
use SerializesModels;
/** /**
* Create a new job instance. * Create a new job instance.
*
* @param \App\Models\Bookmark $bookmark
*/ */
public function __construct( public function __construct(Bookmark $bookmark)
protected Bookmark $bookmark {
) {} $this->bookmark = $bookmark;
}
/** /**
* Execute the job. * Execute the job.
*
* @return void
*/ */
public function handle(): void public function handle()
{ {
SaveScreenshot::dispatch($this->bookmark); $uuid = (resolve(BookmarkService::class))->saveScreenshot($this->bookmark->url);
$this->bookmark->screenshot = $uuid;
try { try {
$archiveLink = (resolve(BookmarkService::class))->getArchiveLink($this->bookmark->url); $archiveLink = (resolve(BookmarkService::class))->getArchiveLink($this->bookmark->url);
} catch (InternetArchiveException) { } catch (InternetArchiveException $e) {
$archiveLink = null; $archiveLink = null;
} }
$this->bookmark->archive = $archiveLink; $this->bookmark->archive = $archiveLink;

View file

@ -5,53 +5,53 @@ declare(strict_types=1);
namespace App\Jobs; namespace App\Jobs;
use App\Models\Like; use App\Models\Like;
use Codebird\Codebird;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException; use Illuminate\Support\Arr;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Thujohn\Twitter\Facades\Twitter;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Jonnybarnes\WebmentionsParser\Authorship; use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException; use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
class ProcessLike implements ShouldQueue class ProcessLike implements ShouldQueue
{ {
use Dispatchable; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable; protected $like;
use SerializesModels;
/** /**
* Create a new job instance. * Create a new job instance.
*
* @param \App\Models\Like $like
*/ */
public function __construct( public function __construct(Like $like)
protected Like $like {
) {} $this->like = $like;
}
/** /**
* Execute the job. * Execute the job.
* *
* @throws GuzzleException * @param \GuzzleHttp\Client $client
* @param \Jonnybarnes\WebmentionsParser\Authorship $authorship
* @return int
*/ */
public function handle(Client $client, Authorship $authorship): int public function handle(Client $client, Authorship $authorship): int
{ {
if ($this->isTweet($this->like->url)) { if ($this->isTweet($this->like->url)) {
$codebird = resolve(Codebird::class); $tweet = Twitter::getOembed(['url' => $this->like->url]);
$tweet = $codebird->statuses_oembed(['url' => $this->like->url]);
$this->like->author_name = $tweet->author_name; $this->like->author_name = $tweet->author_name;
$this->like->author_url = $tweet->author_url; $this->like->author_url = $tweet->author_url;
$this->like->content = $tweet->html; $this->like->content = $tweet->html;
$this->like->save(); $this->like->save();
// POSSE like //POSSE like
try { try {
$client->request( $response = $client->request(
'POST', 'POST',
'https://brid.gy/publish/webmention', 'https://brid.gy/publish/webmention',
[ [
@ -61,8 +61,8 @@ class ProcessLike implements ShouldQueue
], ],
] ]
); );
} catch (RequestException) { } catch (RequestException $exception) {
return 0; //no biggie
} }
return 0; return 0;
@ -94,6 +94,9 @@ class ProcessLike implements ShouldQueue
/** /**
* Determine if a given URL is that of a Tweet. * Determine if a given URL is that of a Tweet.
*
* @param string $url
* @return bool
*/ */
private function isTweet(string $url): bool private function isTweet(string $url): bool
{ {

View file

@ -5,65 +5,66 @@ declare(strict_types=1);
namespace App\Jobs; namespace App\Jobs;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue; use Intervention\Image\ImageManager;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Intervention\Image\Exceptions\DecoderException; use Illuminate\Queue\InteractsWithQueue;
use Intervention\Image\ImageManager; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Intervention\Image\Exception\NotReadableException;
class ProcessMedia implements ShouldQueue class ProcessMedia implements ShouldQueue
{ {
use Dispatchable; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable; protected $filename;
use SerializesModels;
/** /**
* Create a new job instance. * Create a new job instance.
*
* @param string $filename
*/ */
public function __construct( public function __construct(string $filename)
protected string $filename {
) {} $this->filename = $filename;
}
/** /**
* Execute the job. * Execute the job.
*
* @param \Intervention\Image\ImageManager $manager
*/ */
public function handle(ImageManager $manager): void public function handle(ImageManager $manager)
{ {
// Load file //open file
$file = Storage::disk('local')->get('media/' . $this->filename);
// Open file
try { try {
$image = $manager->read($file); $image = $manager->make(storage_path('app') . '/' . $this->filename);
} catch (DecoderException) { } catch (NotReadableException $exception) {
// not an image; delete file and end job // not an image; delete file and end job
Storage::disk('local')->delete('media/' . $this->filename); unlink(storage_path('app') . '/' . $this->filename);
return; return;
} }
//create smaller versions if necessary
// Save the file publicly
Storage::disk('public')->put('media/' . $this->filename, $file);
// Create smaller versions if necessary
if ($image->width() > 1000) { if ($image->width() > 1000) {
$filenameParts = explode('.', $this->filename); $filenameParts = explode('.', $this->filename);
$extension = array_pop($filenameParts); $extension = array_pop($filenameParts);
// the following achieves this data flow // the following acheives this data flow
// foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar // foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar
$basename = trim(implode('.', $filenameParts), '.'); $basename = ltrim(array_reduce($filenameParts, function ($carry, $item) {
return $carry . '.' . $item;
$medium = $image->resize(width: 1000); }, ''), '.');
Storage::disk('public')->put('media/' . $basename . '-medium.' . $extension, (string) $medium->encode()); $medium = $image->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
$small = $image->resize(width: 500); });
Storage::disk('public')->put('media/' . $basename . '-small.' . $extension, (string) $small->encode()); Storage::disk('s3')->put('media/'. $basename . '-medium.' . $extension, (string) $medium->encode());
$small = $image->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
});
Storage::disk('s3')->put('media/' . $basename . '-small.' . $extension, (string) $small->encode());
} }
// Now we can delete the locally saved image // now we can delete the locally saved image
Storage::disk('local')->delete('media/' . $this->filename); unlink(storage_path('app') . '/' . $this->filename);
} }
} }

View file

@ -4,42 +4,42 @@ declare(strict_types=1);
namespace App\Jobs; namespace App\Jobs;
use App\Exceptions\RemoteContentNotFoundException;
use App\Models\Note;
use App\Models\WebMention;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Jonnybarnes\WebmentionsParser\Exceptions\InvalidMentionException;
use Jonnybarnes\WebmentionsParser\Parser;
use Mf2; use Mf2;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use App\Models\{Note, WebMention};
use Jonnybarnes\WebmentionsParser\Parser;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Exceptions\RemoteContentNotFoundException;
use Illuminate\Queue\{InteractsWithQueue, SerializesModels};
class ProcessWebMention implements ShouldQueue class ProcessWebMention implements ShouldQueue
{ {
use InteractsWithQueue; use InteractsWithQueue, Queueable, SerializesModels;
use Queueable;
use SerializesModels; protected $note;
protected $source;
/** /**
* Create a new job instance. * Create a new job instance.
*
* @param \App\Note $note
* @param string $source
*/ */
public function __construct( public function __construct(Note $note, $source)
protected Note $note, {
protected string $source $this->note = $note;
) {} $this->source = $source;
}
/** /**
* Execute the job. * Execute the job.
* *
* @throws RemoteContentNotFoundException * @param \Jonnybarnes\WebmentionsParser\Parser $parser
* @throws GuzzleException * @param \GuzzleHttp\Client $guzzle
* @throws InvalidMentionException
*/ */
public function handle(Parser $parser, Client $guzzle): void public function handle(Parser $parser, Client $guzzle)
{ {
try { try {
$response = $guzzle->request('GET', $this->source); $response = $guzzle->request('GET', $this->source);
@ -52,30 +52,30 @@ class ProcessWebMention implements ShouldQueue
foreach ($webmentions as $webmention) { foreach ($webmentions as $webmention) {
// check webmention still references target // check webmention still references target
// we try each type of mention (reply/like/repost) // we try each type of mention (reply/like/repost)
if ($webmention->type === 'in-reply-to') { if ($webmention->type == 'in-reply-to') {
if ($parser->checkInReplyTo($microformats, $this->note->uri) === false) { if ($parser->checkInReplyTo($microformats, $this->note->longurl) == false) {
// it doesnt so delete // it doesnt so delete
$webmention->delete(); $webmention->delete();
return; return;
} }
// webmention is still a reply, so update content // webmenion is still a reply, so update content
dispatch(new SaveProfileImage($microformats)); dispatch(new SaveProfileImage($microformats));
$webmention->mf2 = json_encode($microformats); $webmention->mf2 = json_encode($microformats);
$webmention->save(); $webmention->save();
return; return;
} }
if ($webmention->type === 'like-of') { if ($webmention->type == 'like-of') {
if ($parser->checkLikeOf($microformats, $this->note->uri) === false) { if ($parser->checkLikeOf($microformats, $this->note->longurl) == false) {
// it doesnt so delete // it doesnt so delete
$webmention->delete(); $webmention->delete();
return; return;
} // note we dont need to do anything if it still is a like } // note we dont need to do anything if it still is a like
} }
if ($webmention->type === 'repost-of') { if ($webmention->type == 'repost-of') {
if ($parser->checkRepostOf($microformats, $this->note->uri) === false) { if ($parser->checkRepostOf($microformats, $this->note->longurl) == false) {
// it doesnt so delete // it doesnt so delete
$webmention->delete(); $webmention->delete();
@ -85,13 +85,13 @@ class ProcessWebMention implements ShouldQueue
}// foreach }// foreach
// no webmention in the db so create new one // no webmention in the db so create new one
$webmention = new WebMention; $webmention = new WebMention();
$type = $parser->getMentionType($microformats); // throw error here? $type = $parser->getMentionType($microformats); // throw error here?
dispatch(new SaveProfileImage($microformats)); dispatch(new SaveProfileImage($microformats));
$webmention->source = $this->source; $webmention->source = $this->source;
$webmention->target = $this->note->uri; $webmention->target = $this->note->longurl;
$webmention->commentable_id = $this->note->id; $webmention->commentable_id = $this->note->id;
$webmention->commentable_type = Note::class; $webmention->commentable_type = 'App\Note';
$webmention->type = $type; $webmention->type = $type;
$webmention->mf2 = json_encode($microformats); $webmention->mf2 = json_encode($microformats);
$webmention->save(); $webmention->save();
@ -99,23 +99,26 @@ class ProcessWebMention implements ShouldQueue
/** /**
* Save the HTML of a webmention for future use. * Save the HTML of a webmention for future use.
*
* @param string $html
* @param string $url
*/ */
private function saveRemoteContent(string $html, string $url): void private function saveRemoteContent($html, $url)
{ {
$filenameFromURL = str_replace( $filenameFromURL = str_replace(
['https://', 'http://'], ['https://', 'http://'],
['https/', 'http/'], ['https/', 'http/'],
$url $url
); );
if (str_ends_with($url, '/')) { if (substr($url, -1) == '/') {
$filenameFromURL .= 'index.html'; $filenameFromURL .= 'index.html';
} }
$path = storage_path() . '/HTML/' . $filenameFromURL; $path = storage_path() . '/HTML/' . $filenameFromURL;
$parts = explode('/', $path); $parts = explode('/', $path);
$name = array_pop($parts); $name = array_pop($parts);
$dir = implode('/', $parts); $dir = implode('/', $parts);
if (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir)) { if (! is_dir($dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir)); mkdir($dir, 0755, true);
} }
file_put_contents("$dir/$name", $html); file_put_contents("$dir/$name", $html);
} }

View file

@ -5,75 +5,64 @@ declare(strict_types=1);
namespace App\Jobs; namespace App\Jobs;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr; use Illuminate\Queue\InteractsWithQueue;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Jonnybarnes\WebmentionsParser\Authorship; use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException; use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
class SaveProfileImage implements ShouldQueue class SaveProfileImage implements ShouldQueue
{ {
use InteractsWithQueue; use InteractsWithQueue, Queueable, SerializesModels;
use Queueable;
use SerializesModels; protected $microformats;
/** /**
* Create a new job instance. * Create a new job instance.
*
* @param array $microformats
*/ */
public function __construct( public function __construct(array $microformats)
protected array $microformats {
) {} $this->microformats = $microformats;
}
/** /**
* Execute the job. * Execute the job.
*
* @param \Jonnybarnes\WebmentionsParser\Authorship $authorship
*/ */
public function handle(Authorship $authorship): void public function handle(Authorship $authorship)
{ {
try { try {
$author = $authorship->findAuthor($this->microformats); $author = $authorship->findAuthor($this->microformats);
} catch (AuthorshipParserException) { } catch (AuthorshipParserException $e) {
return; return;
} }
$photo = $author['properties']['photo'][0];
$photo = Arr::get($author, 'properties.photo.0'); $home = $author['properties']['url'][0];
$home = Arr::get($author, 'properties.url.0'); //dont save pbs.twimg.com links
if (parse_url($photo, PHP_URL_HOST) != 'pbs.twimg.com'
if (is_array($photo) && array_key_exists('value', $photo)) { && parse_url($photo, PHP_URL_HOST) != 'twitter.com') {
$photo = $photo['value'];
}
if (is_array($home)) {
$home = array_shift($home);
}
// dont save pbs.twimg.com links
if (
$photo
&& parse_url($photo, PHP_URL_HOST) !== 'pbs.twimg.com'
&& parse_url($photo, PHP_URL_HOST) !== 'twitter.com'
) {
$client = resolve(Client::class); $client = resolve(Client::class);
try { try {
$response = $client->get($photo); $response = $client->get($photo);
$image = $response->getBody(); $image = $response->getBody(true);
} catch (RequestException) { } catch (RequestException $e) {
// we are opening and reading the default image so that // we are openning and reading the default image so that
$default = public_path() . '/assets/profile-images/default-image'; $default = public_path() . '/assets/profile-images/default-image';
$handle = fopen($default, 'rb'); $handle = fopen($default, 'rb');
$image = fread($handle, filesize($default)); $image = fread($handle, filesize($default));
fclose($handle); fclose($handle);
} }
$path = public_path() . '/assets/profile-images/' . parse_url($home, PHP_URL_HOST) . '/image'; $path = public_path() . '/assets/profile-images/' . parse_url($home, PHP_URL_HOST) . '/image';
$parts = explode('/', $path); $parts = explode('/', $path);
$name = array_pop($parts); $name = array_pop($parts);
$dir = implode('/', $parts); $dir = implode('/', $parts);
if (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir)) { if (! is_dir($dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir)); mkdir($dir, 0755, true);
} }
file_put_contents("$dir/$name", $image); file_put_contents("$dir/$name", $image);
} }

View file

@ -1,103 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Bookmark;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use JsonException;
class SaveScreenshot implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
protected Bookmark $bookmark
) {}
/**
* Execute the job.
*
*
* @throws JsonException
*/
public function handle(): void
{
// A normal Guzzle client
$client = resolve(Client::class);
// A Guzzle client with a custom Middleware to retry the CloudConvert API requests
$retryClient = resolve('RetryGuzzle');
// First request that CloudConvert takes a screenshot of the URL
$takeScreenshotJobResponse = $client->request('POST', 'https://api.cloudconvert.com/v2/capture-website', [
'headers' => [
'Authorization' => 'Bearer ' . config('services.cloudconvert.token'),
],
'json' => [
'url' => $this->bookmark->url,
'output_format' => 'png',
'screen_width' => 1440,
'screen_height' => 900,
'wait_until' => 'networkidle0',
'wait_time' => 100,
],
]);
$taskId = json_decode($takeScreenshotJobResponse->getBody()->getContents(), false, 512, JSON_THROW_ON_ERROR)->data->id;
// Now wait till the status job is finished
$screenshotJobStatusResponse = $retryClient->request('GET', 'https://api.cloudconvert.com/v2/tasks/' . $taskId, [
'headers' => [
'Authorization' => 'Bearer ' . config('services.cloudconvert.token'),
],
'query' => [
'include' => 'payload',
],
]);
$finishedCaptureId = json_decode($screenshotJobStatusResponse->getBody()->getContents(), false, 512, JSON_THROW_ON_ERROR)->data->id;
// Now we can create a new job to request thst the screenshot is exported to a temporary URL we can download the screenshot from
$exportImageJob = $client->request('POST', 'https://api.cloudconvert.com/v2/export/url', [
'headers' => [
'Authorization' => 'Bearer ' . config('services.cloudconvert.token'),
],
'json' => [
'input' => $finishedCaptureId,
'archive_multiple_files' => false,
],
]);
$exportImageJobId = json_decode($exportImageJob->getBody()->getContents(), false, 512, JSON_THROW_ON_ERROR)->data->id;
// Again, wait till the status of this export job is finished
$finalImageUrlResponse = $retryClient->request('GET', 'https://api.cloudconvert.com/v2/tasks/' . $exportImageJobId, [
'headers' => [
'Authorization' => 'Bearer ' . config('services.cloudconvert.token'),
],
'query' => [
'include' => 'payload',
],
]);
// Now we can download the screenshot and save it to the storage
$finalImageUrl = json_decode($finalImageUrlResponse->getBody()->getContents(), false, 512, JSON_THROW_ON_ERROR)->data->result->files[0]->url;
$finalImageUrlContent = $client->request('GET', $finalImageUrl);
Storage::disk('public')->put('/assets/img/bookmarks/' . $taskId . '.png', $finalImageUrlContent->getBody()->getContents());
$this->bookmark->screenshot = $taskId;
$this->bookmark->save();
}
}

View file

@ -6,46 +6,48 @@ namespace App\Jobs;
use App\Models\Note; use App\Models\Note;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Header;
use GuzzleHttp\Psr7\UriResolver;
use GuzzleHttp\Psr7\Utils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendWebMentions implements ShouldQueue class SendWebMentions implements ShouldQueue
{ {
use InteractsWithQueue; use InteractsWithQueue, Queueable, SerializesModels;
use Queueable;
use SerializesModels; protected $note;
/** /**
* Create a new job instance. * Create the job instance, inject dependencies.
*
* @param Note $note
*/ */
public function __construct( public function __construct(Note $note)
protected Note $note {
) {} $this->note = $note;
}
/** /**
* Execute the job. * Execute the job.
* *
* @throws GuzzleException * @return void
*/ */
public function handle(): void public function handle()
{ {
$urlsInReplyTo = explode(' ', $this->note->in_reply_to ?? ''); //grab the URLs
$inReplyTo = $this->note->in_reply_to ?? '';
// above so explode doesnt complain about null being passed in
$urlsInReplyTo = explode(' ', $inReplyTo);
$urlsNote = $this->getLinks($this->note->note); $urlsNote = $this->getLinks($this->note->note);
$urls = array_filter(array_merge($urlsInReplyTo, $urlsNote)); $urls = array_filter(array_merge($urlsInReplyTo, $urlsNote)); //filter out none URLs
foreach ($urls as $url) { foreach ($urls as $url) {
$endpoint = $this->discoverWebmentionEndpoint($url); $endpoint = $this->discoverWebmentionEndpoint($url);
if ($endpoint !== null) { if ($endpoint !== null) {
$guzzle = resolve(Client::class); $guzzle = resolve(Client::class);
$guzzle->post($endpoint, [ $guzzle->post($endpoint, [
'form_params' => [ 'form_params' => [
'source' => $this->note->uri, 'source' => $this->note->longurl,
'target' => $url, 'target' => $url,
], ],
]); ]);
@ -56,31 +58,32 @@ class SendWebMentions implements ShouldQueue
/** /**
* Discover if a URL has a webmention endpoint. * Discover if a URL has a webmention endpoint.
* *
* @throws GuzzleException * @param string $url
* @return string|null
*/ */
public function discoverWebmentionEndpoint(string $url): ?string public function discoverWebmentionEndpoint(string $url)
{ {
// lets not send webmentions to myself //lets not send webmentions to myself
if (parse_url($url, PHP_URL_HOST) === parse_url(config('app.url'), PHP_URL_HOST)) { if (parse_url($url, PHP_URL_HOST) == config('app.longurl')) {
return null; return;
} }
if (Str::startsWith($url, '/notes/tagged/')) { if (Str::startsWith($url, '/notes/tagged/')) {
return null; return;
} }
$endpoint = null; $endpoint = null;
$guzzle = resolve(Client::class); $guzzle = resolve(Client::class);
$response = $guzzle->get($url); $response = $guzzle->get($url);
// check HTTP Headers for webmention endpoint //check HTTP Headers for webmention endpoint
$links = Header::parse($response->getHeader('Link')); $links = \GuzzleHttp\Psr7\parse_header($response->getHeader('Link'));
foreach ($links as $link) { foreach ($links as $link) {
if (array_key_exists('rel', $link) && mb_stristr($link['rel'], 'webmention')) { if (mb_stristr($link['rel'], 'webmention')) {
return $this->resolveUri(trim($link[0], '<>'), $url); return $this->resolveUri(trim($link[0], '<>'), $url);
} }
} }
// failed to find a header so parse HTML //failed to find a header so parse HTML
$html = (string) $response->getBody(); $html = (string) $response->getBody();
$mf2 = new \Mf2\Parser($html, $url); $mf2 = new \Mf2\Parser($html, $url);
@ -90,25 +93,24 @@ class SendWebMentions implements ShouldQueue
} elseif (array_key_exists('http://webmention.org/', $rels[0])) { } elseif (array_key_exists('http://webmention.org/', $rels[0])) {
$endpoint = $rels[0]['http://webmention.org/'][0]; $endpoint = $rels[0]['http://webmention.org/'][0];
} }
if ($endpoint) {
if ($endpoint === null) { return $this->resolveUri($endpoint, $url);
return null;
} }
return $this->resolveUri($endpoint, $url);
} }
/** /**
* Get the URLs from a note. * Get the URLs from a note.
*
* @param string $html
* @return array $urls
*/ */
public function getLinks(?string $html): array public function getLinks($html)
{ {
if ($html === '' || is_null($html)) { if ($html == '' || is_null($html)) {
return []; return [];
} }
$urls = []; $urls = [];
$dom = new \DOMDocument; $dom = new \DOMDocument();
$dom->loadHTML($html); $dom->loadHTML($html);
$anchors = $dom->getElementsByTagName('a'); $anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) { foreach ($anchors as $anchor) {
@ -120,16 +122,20 @@ class SendWebMentions implements ShouldQueue
/** /**
* Resolve a URI if necessary. * Resolve a URI if necessary.
*
* @param string $url
* @param string $base The base of the URL
* @return string
*/ */
public function resolveUri(string $url, string $base): string public function resolveUri(string $url, string $base): string
{ {
$endpoint = Utils::uriFor($url); $endpoint = \GuzzleHttp\Psr7\uri_for($url);
if ($endpoint->getScheme() !== '') { if ($endpoint->getScheme() != '') {
return (string) $endpoint; return (string) $endpoint;
} }
return (string) UriResolver::resolve( return (string) \GuzzleHttp\Psr7\Uri::resolve(
Utils::uriFor($base), \GuzzleHttp\Psr7\uri_for($base),
$endpoint $endpoint
); );
} }

View file

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use GuzzleHttp\Client;
use App\Models\Bookmark;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SyndicateBookmarkToTwitter implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $bookmark;
/**
* Create a new job instance.
*
* @param \App\Models\Bookmark $bookmark
*/
public function __construct(Bookmark $bookmark)
{
$this->bookmark = $bookmark;
}
/**
* Execute the job.
*
* @param \GuzzleHttp\Client $guzzle
*/
public function handle(Client $guzzle)
{
//send webmention
$response = $guzzle->request(
'POST',
'https://brid.gy/publish/webmention',
[
'form_params' => [
'source' => $this->bookmark->longurl,
'target' => 'https://brid.gy/publish/twitter',
'bridgy_omit_link' => 'maybe',
],
]
);
//parse for syndication URL
if ($response->getStatusCode() == 201) {
$json = json_decode((string) $response->getBody());
$syndicates = $this->bookmark->syndicates;
$syndicates['twitter'] = $json->url;
$this->bookmark->syndicates = $syndicates;
$this->bookmark->save();
}
}
}

View file

@ -1,62 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Note;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class SyndicateNoteToBluesky implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
protected Note $note
) {}
/**
* Execute the job.
*
* @throws GuzzleException
*/
public function handle(Client $guzzle): void
{
// We can only make the request if we have an access token
if (config('bridgy.bluesky_token') === null) {
return;
}
// Make micropub request
$response = $guzzle->request(
'POST',
'https://brid.gy/micropub',
[
'headers' => [
'Authorization' => 'Bearer ' . config('bridgy.bluesky_token'),
],
'json' => [
'type' => ['h-entry'],
'properties' => [
'content' => [$this->note->getRawOriginal('note')],
],
],
]
);
// Parse for syndication URL
if ($response->getStatusCode() === 201) {
$this->note->bluesky_url = $response->getHeader('Location')[0];
$this->note->save();
}
}
}

View file

@ -1,63 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Note;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class SyndicateNoteToMastodon implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
protected Note $note
) {}
/**
* Execute the job.
*
* @throws GuzzleException
*/
public function handle(Client $guzzle): void
{
// We can only make the request if we have an access token
if (config('bridgy.mastodon_token') === null) {
return;
}
// Make micropub request
$response = $guzzle->request(
'POST',
'https://brid.gy/micropub',
[
'headers' => [
'Authorization' => 'Bearer ' . config('bridgy.mastodon_token'),
],
'json' => [
'type' => ['h-entry'],
'properties' => [
'content' => [$this->note->getRawOriginal('note')],
],
],
]
);
// Parse for syndication URL
if ($response->getStatusCode() === 201) {
$mastodonUrl = $response->getHeader('Location')[0];
$this->note->mastodon_url = $mastodonUrl;
$this->note->save();
}
}
}

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Note;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SyndicateNoteToTwitter implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
protected $note;
/**
* Create a new job instance.
*
* @param \App\Models\Note $note
*/
public function __construct(Note $note)
{
$this->note = $note;
}
/**
* Execute the job.
*
* @param \GuzzleHttp\Client $guzzle
*/
public function handle(Client $guzzle)
{
//send webmention
$response = $guzzle->request(
'POST',
'https://brid.gy/publish/webmention',
[
'form_params' => [
'source' => $this->note->longurl,
'target' => 'https://brid.gy/publish/twitter',
'bridgy_omit_link' => 'maybe',
],
]
);
//parse for syndication URL
if ($response->getStatusCode() == 201) {
$json = json_decode((string) $response->getBody());
$tweet_id = basename(parse_url($json->url, PHP_URL_PATH));
$this->note->tweet_id = $tweet_id;
$this->note->save();
}
}
}

View file

@ -4,46 +4,40 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable; use League\CommonMark\Environment;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Cviebrock\EloquentSluggable\Sluggable;
use League\CommonMark\CommonMarkConverter;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use League\CommonMark\Environment\Environment; use League\CommonMark\Block\Element\FencedCode;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\Block\Element\IndentedCode;
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode;
use League\CommonMark\MarkdownConverter;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer; use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer; use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
class Article extends Model class Article extends Model
{ {
use HasFactory;
use Sluggable; use Sluggable;
use SoftDeletes; use SoftDeletes;
/** @var string */ /**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'articles'; protected $table = 'articles';
/** @var array<int, string> */
protected $fillable = [
'url',
'title',
'main',
'published',
];
/** @var array<string, string> */
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
];
/** /**
* Return the sluggable configuration array for this model. * Return the sluggable configuration array for this model.
*
* @return array
*/ */
public function sluggable(): array public function sluggable(): array
{ {
@ -54,62 +48,86 @@ class Article extends Model
]; ];
} }
protected function html(): Attribute /**
{ * We shall set a blacklist of non-modifiable model attributes.
return Attribute::get( *
get: function () { * @var array
$environment = new Environment; */
$environment->addExtension(new CommonMarkCoreExtension); protected $guarded = ['id'];
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer);
$environment->addRenderer(IndentedCode::class, new IndentedCodeRenderer);
$markdownConverter = new MarkdownConverter($environment);
return $markdownConverter->convert($this->main)->getContent(); /**
}, * Process the article for display.
); *
* @return string
*/
public function getHtmlAttribute(): string
{
$environment = Environment::createCommonMarkEnvironment();
$environment->addBlockRenderer(FencedCode::class, new FencedCodeRenderer());
$environment->addBlockRenderer(IndentedCode::class, new IndentedCodeRenderer());
$commonMarkConverter = new CommonMarkConverter([], $environment);
return $commonMarkConverter->convertToHtml($this->main);
} }
protected function w3cTime(): Attribute /**
* Convert updated_at to W3C time format.
*
* @return string
*/
public function getW3cTimeAttribute(): string
{ {
return Attribute::get( return $this->updated_at->toW3CString();
get: fn () => $this->updated_at->toW3CString(),
);
} }
protected function tooltipTime(): Attribute /**
* Convert updated_at to a tooltip appropriate format.
*
* @return string
*/
public function getTooltipTimeAttribute(): string
{ {
return Attribute::get( return $this->updated_at->toRFC850String();
get: fn () => $this->updated_at->toRFC850String(),
);
} }
protected function humanTime(): Attribute /**
* Convert updated_at to a human readable format.
*
* @return string
*/
public function getHumanTimeAttribute(): string
{ {
return Attribute::get( return $this->updated_at->diffForHumans();
get: fn () => $this->updated_at->diffForHumans(),
);
} }
protected function pubdate(): Attribute /**
* Get the pubdate value for RSS feeds.
*
* @return string
*/
public function getPubdateAttribute(): string
{ {
return Attribute::get( return $this->updated_at->toRSSString();
get: fn () => $this->updated_at->toRSSString(),
);
} }
protected function link(): Attribute /**
* A link to the article, i.e. `/blog/1999/12/25/merry-christmas`.
*
* @return string
*/
public function getLinkAttribute(): string
{ {
return Attribute::get( return '/blog/' . $this->updated_at->year . '/' . $this->updated_at->format('m') . '/' . $this->titleurl;
get: fn () => '/blog/' . $this->updated_at->year . '/' . $this->updated_at->format('m') . '/' . $this->titleurl,
);
} }
/** /**
* Scope a query to only include articles from a particular year/month. * Scope a query to only include articles from a particular year/month.
*
* @return \Illuminate\Database\Eloquent\Builder
*/ */
public function scopeDate(Builder $query, ?int $year = null, ?int $month = null): Builder public function scopeDate($query, int $year = null, int $month = null): Builder
{ {
if ($year === null) { if ($year == null) {
return $query; return $query;
} }
$start = $year . '-01-01 00:00:00'; $start = $year . '-01-01 00:00:00';

View file

@ -1,11 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Bio extends Model
{
use HasFactory;
}

View file

@ -4,32 +4,43 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Bookmark extends Model class Bookmark extends Model
{ {
use HasFactory; /**
* The attributes that are mass assignable.
/** @var array<int, string> */ *
* @var array
*/
protected $fillable = ['url', 'name', 'content']; protected $fillable = ['url', 'name', 'content'];
/** @var array<string, string> */ /**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [ protected $casts = [
'syndicates' => 'array', 'syndicates' => 'array',
]; ];
public function tags(): BelongsToMany /**
* The tags that belong to the bookmark.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags()
{ {
return $this->belongsToMany('App\Models\Tag'); return $this->belongsToMany('App\Models\Tag');
} }
protected function local_uri(): Attribute /**
* The full url of a bookmark.
*
* @return string
*/
public function getLongurlAttribute(): string
{ {
return Attribute::get( return config('app.url') . '/bookmarks/' . $this->id;
get: fn () => config('app.url') . '/bookmarks/' . $this->id,
);
} }
} }

View file

@ -4,33 +4,21 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
class Contact extends Model class Contact extends Model
{ {
use HasFactory; /**
* The database table used by the model.
/** @var string */ *
* @var string
*/
protected $table = 'contacts'; protected $table = 'contacts';
/** @var array<int, string> */ /**
* We shall guard against mass-migration.
*
* @var array
*/
protected $fillable = ['nick', 'name', 'homepage', 'twitter', 'facebook']; protected $fillable = ['nick', 'name', 'homepage', 'twitter', 'facebook'];
protected function photo(): Attribute
{
$photo = '/assets/profile-images/default-image';
if (array_key_exists('homepage', $this->attributes) && ! empty($this->attributes['homepage'])) {
$host = parse_url($this->attributes['homepage'], PHP_URL_HOST);
if (file_exists(public_path() . '/assets/profile-images/' . $host . '/image')) {
$photo = '/assets/profile-images/' . $host . '/image';
}
}
return Attribute::make(
get: fn () => $photo,
);
}
} }

View file

@ -4,53 +4,57 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use App\Traits\FilterHtml;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Mf2; use Mf2;
use App\Traits\FilterHtml;
use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Model;
class Like extends Model class Like extends Model
{ {
use FilterHtml; use FilterHtml;
use HasFactory;
/** @var array<int, string> */
protected $fillable = ['url']; protected $fillable = ['url'];
protected function url(): Attribute /**
* Normalize the URL of a Like.
*
* @param string $value The provided URL
*/
public function setUrlAttribute(string $value)
{ {
return Attribute::set( $this->attributes['url'] = normalize_url($value);
set: fn ($value) => normalize_url($value),
);
} }
protected function authorUrl(): Attribute /**
* Normalize the URL of the author of the like.
*
* @param string $value The authors url
*/
public function setAuthorUrlAttribute(?string $value)
{ {
return Attribute::set( $this->attributes['author_url'] = normalize_url($value);
set: fn ($value) => normalize_url($value),
);
} }
protected function content(): Attribute /**
* If the content contains HTML, filter it.
*
* @param string $value The content of the like
* @return string|null
*/
public function getContentAttribute(?string $value): ?string
{ {
return Attribute::get( if ($value === null) {
get: function ($value, $attributes) { return null;
if ($value === null) { }
return null;
}
$mf2 = Mf2\parse($value, $attributes['url']); $mf2 = Mf2\parse($value, $this->url);
if (Arr::get($mf2, 'items.0.properties.content.0.html')) { if (Arr::get($mf2, 'items.0.properties.content.0.html')) {
return $this->filterHtml( return $this->filterHtml(
$mf2['items'][0]['properties']['content'][0]['html'] $mf2['items'][0]['properties']['content'][0]['html']
); );
} }
return $value; return $value;
}
);
} }
} }

View file

@ -4,96 +4,102 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
class Media extends Model class Media extends Model
{ {
use HasFactory; /**
* The table associated with the model.
/** @var string */ *
* @var string
*/
protected $table = 'media_endpoint'; protected $table = 'media_endpoint';
/** @var array<int, string> */ /**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['token', 'path', 'type', 'image_widths']; protected $fillable = ['token', 'path', 'type', 'image_widths'];
/**
* Get the note that owns this media.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function note(): BelongsTo public function note(): BelongsTo
{ {
return $this->belongsTo(Note::class); return $this->belongsTo('App\Models\Note');
} }
protected function url(): Attribute /**
* Get the URL for an S3 media file.
*
* @return string
*/
public function getUrlAttribute(): string
{ {
return Attribute::get( if (Str::startsWith($this->path, 'https://')) {
get: function ($value, $attributes) { return $this->path;
if (Str::startsWith($attributes['path'], 'https://')) { }
return $attributes['path'];
}
return config('app.url') . '/storage/' . $attributes['path']; return config('filesystems.disks.s3.url') . '/' . $this->path;
}
);
} }
protected function mediumurl(): Attribute /**
* Get the URL for the medium size of an S3 image file.
*
* @return string
*/
public function getMediumurlAttribute(): string
{ {
return Attribute::get( $basename = $this->getBasename($this->path);
get: fn ($value, $attributes) => $this->getSizeUrl($attributes['path'], 'medium'), $extension = $this->getExtension($this->path);
);
return config('filesystems.disks.s3.url') . '/' . $basename . '-medium.' . $extension;
} }
protected function smallurl(): Attribute /**
* Get the URL for the small size of an S3 image file.
*
* @return string
*/
public function getSmallurlAttribute(): string
{ {
return Attribute::get( $basename = $this->getBasename($this->path);
get: fn ($value, $attributes) => $this->getSizeUrl($attributes['path'], 'small'), $extension = $this->getExtension($this->path);
);
return config('filesystems.disks.s3.url') . '/' . $basename . '-small.' . $extension;
} }
protected function mimetype(): Attribute /**
{ * Give the real part of a filename, i.e. strip the file extension.
return Attribute::get( *
get: function ($value, $attributes) { * @param string $path
$extension = $this->getExtension($attributes['path']); * @return string
*/
return match ($extension) { public function getBasename(string $path): string
'gif' => 'image/gif',
'jpeg', 'jpg' => 'image/jpeg',
'png' => 'image/png',
'svg' => 'image/svg+xml',
'tiff' => 'image/tiff',
'webp' => 'image/webp',
'mp4' => 'video/mp4',
'mkv' => 'video/mkv',
default => 'application/octet-stream',
};
},
);
}
private function getSizeUrl(string $path, string $size): string
{
$basename = $this->getBasename($path);
$extension = $this->getExtension($path);
return config('app.url') . '/storage/' . $basename . '-' . $size . '.' . $extension;
}
private function getBasename(string $path): string
{ {
// the following achieves this data flow // the following achieves this data flow
// foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar // foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar
$filenameParts = explode('.', $path); $filenameParts = explode('.', $path);
array_pop($filenameParts); array_pop($filenameParts);
$basename = ltrim(array_reduce($filenameParts, function ($carry, $item) {
return ltrim(array_reduce($filenameParts, static function ($carry, $item) {
return $carry . '.' . $item; return $carry . '.' . $item;
}, ''), '.'); }, ''), '.');
return $basename;
} }
private function getExtension(string $path): string /**
* Get the extension from a given filename.
*
* @param string $path
* @return string
*/
public function getExtension(string $path): string
{ {
$parts = explode('.', $path); $parts = explode('.', $path);

View file

@ -4,20 +4,30 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
class MicropubClient extends Model class MicropubClient extends Model
{ {
use HasFactory; /**
* The table associated with the model.
/** @var string */ *
* @var string
*/
protected $table = 'clients'; protected $table = 'clients';
/** @var array<int, string> */ /**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['client_url', 'client_name']; protected $fillable = ['client_url', 'client_name'];
/**
* Define the relationship with notes.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function notes(): HasMany public function notes(): HasMany
{ {
return $this->hasMany('App\Models\Note', 'client_id', 'client_url'); return $this->hasMany('App\Models\Note', 'client_id', 'client_url');

View file

@ -4,42 +4,32 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use App\CommonMark\Generators\MentionGenerator; use Cache;
use App\CommonMark\Renderers\MentionRenderer; use Twitter;
use Codebird\Codebird;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Jonnybarnes\IndieWeb\Numbers;
use Laravel\Scout\Searchable;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\Autolink\AutolinkExtension;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode;
use League\CommonMark\Extension\Mention\Mention;
use League\CommonMark\Extension\Mention\MentionExtension;
use League\CommonMark\MarkdownConverter;
use Normalizer; use Normalizer;
use GuzzleHttp\Client;
use Laravel\Scout\Searchable;
use Jonnybarnes\IndieWeb\Numbers;
use League\CommonMark\Environment;
use Illuminate\Database\Eloquent\Model;
use Jonnybarnes\EmojiA11y\EmojiModifier;
use Illuminate\Database\Eloquent\Builder;
use League\CommonMark\CommonMarkConverter;
use App\Exceptions\TwitterContentException;
use Illuminate\Database\Eloquent\SoftDeletes;
use League\CommonMark\Block\Element\FencedCode;
use League\CommonMark\Block\Element\IndentedCode;
use Jonnybarnes\CommonmarkLinkify\LinkifyExtension;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer; use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer; use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
class Note extends Model class Note extends Model
{ {
use HasFactory;
use Searchable; use Searchable;
use SoftDeletes; use SoftDeletes;
/** /**
* The regex for matching lone usernames. * The reges for matching lone usernames.
* *
* @var string * @var string
*/ */
@ -48,10 +38,12 @@ class Note extends Model
/** /**
* This variable is used to keep track of contacts in a note. * This variable is used to keep track of contacts in a note.
*/ */
protected ?array $contacts; protected $contacts;
/** /**
* Set our contacts variable to null. * Set our contacts variable to null.
*
* @param array $attributes
*/ */
public function __construct(array $attributes = []) public function __construct(array $attributes = [])
{ {
@ -59,46 +51,85 @@ class Note extends Model
$this->contacts = null; $this->contacts = null;
} }
/** @var string */ /**
* The database table used by the model.
*
* @var string
*/
protected $table = 'notes'; protected $table = 'notes';
/** @var array<int, string> */ /*
* Mass-assignment
*
* @var array
*/
protected $fillable = [ protected $fillable = [
'note', 'note',
'in_reply_to', 'in_reply_to',
'client_id', 'client_id',
]; ];
/** @var array<int, string> */ /**
* Hide the column used with Laravel Scout.
*
* @var array
*/
protected $hidden = ['searchable']; protected $hidden = ['searchable'];
public function tags(): BelongsToMany /**
* Define the relationship with tags.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags()
{ {
return $this->belongsToMany(Tag::class); return $this->belongsToMany('App\Models\Tag');
}
public function client(): BelongsTo
{
return $this->belongsTo(MicropubClient::class, 'client_id', 'client_url');
}
public function webmentions(): MorphMany
{
return $this->morphMany(WebMention::class, 'commentable');
}
public function place(): BelongsTo
{
return $this->belongsTo(Place::class);
}
public function media(): HasMany
{
return $this->hasMany(Media::class);
} }
/** /**
* @return array<string, mixed> * Define the relationship with clients.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function client()
{
return $this->belongsTo('App\Models\MicropubClient', 'client_id', 'client_url');
}
/**
* Define the relationship with webmentions.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function webmentions()
{
return $this->morphMany('App\Models\WebMention', 'commentable');
}
/**
* Define the relationship with places.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function place()
{
return $this->belongsTo('App\Models\Place');
}
/**
* Define the relationship with media.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function media()
{
return $this->hasMany('App\Models\Media');
}
/**
* Set the attributes to be indexed for searching with Scout.
*
* @return array
*/ */
public function toSearchableArray(): array public function toSearchableArray(): array
{ {
@ -107,11 +138,16 @@ class Note extends Model
]; ];
} }
public function setNoteAttribute(?string $value): void /**
* Normalize the note to Unicode FORM C.
*
* @param string|null $value
*/
public function setNoteAttribute(?string $value)
{ {
if ($value !== null) { if ($value !== null) {
$normalized = normalizer_normalize($value, Normalizer::FORM_C); $normalized = normalizer_normalize($value, Normalizer::FORM_C);
if ($normalized === '') { // we dont want to save empty strings to the db if ($normalized === '') { //we dont want to save empty strings to the db
$normalized = null; $normalized = null;
} }
$this->attributes['note'] = $normalized; $this->attributes['note'] = $normalized;
@ -120,11 +156,14 @@ class Note extends Model
/** /**
* Pre-process notes for web-view. * Pre-process notes for web-view.
*
* @param string|null $value
* @return string|null
*/ */
public function getNoteAttribute(?string $value): ?string public function getNoteAttribute(?string $value): ?string
{ {
if ($value === null && $this->place !== null) { if ($value === null && $this->place !== null) {
$value = '📍: <a href="' . $this->place->uri . '">' . $this->place->name . '</a>'; $value = '📍: <a href="' . $this->place->longurl . '">' . $this->place->name . '</a>';
} }
// if $value is still null, just return null // if $value is still null, just return null
@ -132,29 +171,34 @@ class Note extends Model
return null; return null;
} }
$hashtags = $this->autoLinkHashtag($value); $hcards = $this->makeHCards($value);
$hashtags = $this->autoLinkHashtag($hcards);
$html = $this->convertMarkdown($hashtags);
$modified = resolve(EmojiModifier::class)->makeEmojiAccessible($html);
return $this->convertMarkdown($hashtags); return $modified;
} }
/** /**
* Provide the content_html for JSON feed. * Provide the content_html for JSON feed.
* *
* In particular, we want to include media links such as images. * In particular we want to include media links such as images.
*
* @return string
*/ */
public function getContentAttribute(): string public function getContentAttribute(): string
{ {
$note = $this->getRawOriginal('note'); $note = $this->note;
foreach ($this->media as $media) { foreach ($this->media as $media) {
if ($media->type === 'image') { if ($media->type == 'image') {
$note .= PHP_EOL . '<img src="' . $media->url . '" alt="">'; $note .= '<img src="' . $media->url . '" alt="">';
} }
if ($media->type === 'audio') { if ($media->type == 'audio') {
$note .= PHP_EOL . '<audio src="' . $media->url . '">'; $note .= '<audio src="' . $media->url . '">';
} }
if ($media->type === 'video') { if ($media->type == 'video') {
$note .= PHP_EOL . '<video src="' . $media->url . '">'; $note .= '<video src="' . $media->url . '">';
} }
} }
@ -166,66 +210,112 @@ class Note extends Model
return $note; return $note;
} }
/**
* Generate the NewBase60 ID from primary ID.
*
* @return string
*/
public function getNb60idAttribute(): string public function getNb60idAttribute(): string
{ {
// we cast to string because sometimes the nb60id is an “int” // we cast to string because sometimes the nb60id is an “int”
return (string) resolve(Numbers::class)->numto60($this->id); return (string) resolve(Numbers::class)->numto60($this->id);
} }
public function getUriAttribute(): string /**
* The Long URL for a note.
*
* @return string
*/
public function getLongurlAttribute(): string
{ {
return config('app.url') . '/notes/' . $this->nb60id; return config('app.url') . '/notes/' . $this->nb60id;
} }
/**
* The Short URL for a note.
*
* @return string
*/
public function getShorturlAttribute(): string
{
return config('app.shorturl') . '/notes/' . $this->nb60id;
}
/**
* Get the ISO8601 value for mf2.
*
* @return string
*/
public function getIso8601Attribute(): string public function getIso8601Attribute(): string
{ {
return $this->updated_at->toISO8601String(); return $this->updated_at->toISO8601String();
} }
/**
* Get the ISO8601 value for mf2.
*
* @return string
*/
public function getHumandiffAttribute(): string public function getHumandiffAttribute(): string
{ {
return $this->updated_at->diffForHumans(); return $this->updated_at->diffForHumans();
} }
/**
* Get the pubdate value for RSS feeds.
*
* @return string
*/
public function getPubdateAttribute(): string public function getPubdateAttribute(): string
{ {
return $this->updated_at->toRSSString(); return $this->updated_at->toRSSString();
} }
/**
* Get the latitude value.
*
* @return float|null
*/
public function getLatitudeAttribute(): ?float public function getLatitudeAttribute(): ?float
{ {
if ($this->place !== null) { if ($this->place !== null) {
return $this->place->latitude; return $this->place->location->getLat();
} }
if ($this->location !== null) { if ($this->location !== null) {
$pieces = explode(':', $this->location); $pieces = explode(':', $this->location);
$latLng = explode(',', $pieces[0]); $latlng = explode(',', $pieces[0]);
return (float) trim($latLng[0]); return (float) trim($latlng[0]);
}
return null;
}
public function getLongitudeAttribute(): ?float
{
if ($this->place !== null) {
return $this->place->longitude;
}
if ($this->location !== null) {
$pieces = explode(':', $this->location);
$latLng = explode(',', $pieces[0]);
return (float) trim($latLng[1]);
} }
return null; return null;
} }
/** /**
* Get the address for a note. * Get the longitude value.
* *
* This is either a reverse geo-code from the location, or is derived from the associated place. * @return float|null
*/
public function getLongitudeAttribute(): ?float
{
if ($this->place !== null) {
return $this->place->location->getLng();
}
if ($this->location !== null) {
$pieces = explode(':', $this->location);
$latlng = explode(',', $pieces[0]);
return (float) trim($latlng[1]);
}
return null;
}
/**
* Get the address for a note. This is either a reverse geo-code from the
* location, or is derived from the associated place.
*
* @return string|null
*/ */
public function getAddressAttribute(): ?string public function getAddressAttribute(): ?string
{ {
@ -241,13 +331,12 @@ class Note extends Model
/** /**
* Get the OEmbed html for a tweet the note is a reply to. * Get the OEmbed html for a tweet the note is a reply to.
*
* @return object|null
*/ */
public function getTwitterAttribute(): ?object public function getTwitterAttribute(): ?object
{ {
if ( if ($this->in_reply_to == null || mb_substr($this->in_reply_to, 0, 20, 'UTF-8') !== 'https://twitter.com/') {
$this->in_reply_to === null ||
! $this->isTwitterLink($this->in_reply_to)
) {
return null; return null;
} }
@ -257,47 +346,84 @@ class Note extends Model
} }
try { try {
$codebird = resolve(Codebird::class); $oEmbed = Twitter::getOembed([
$oEmbed = $codebird->statuses_oembed([
'url' => $this->in_reply_to, 'url' => $this->in_reply_to,
'dnt' => true, 'dnt' => true,
'align' => 'center', 'align' => 'center',
'maxwidth' => 512, 'maxwidth' => 512,
]); ]);
} catch (\Exception $e) {
if ($oEmbed->httpstatus >= 400) {
throw new Exception;
}
} catch (Exception $e) {
return null; return null;
} }
Cache::put($tweetId, $oEmbed, ($oEmbed->cache_age)); Cache::put($tweetId, $oEmbed, ($oEmbed->cache_age / 60));
return $oEmbed; return $oEmbed;
} }
/**
* Show a specific form of the note for twitter.
*
* That is we swap the contacts names for their known Twitter handles.
*
* @return string
*/
public function getTwitterContentAttribute(): string
{
// check for contacts
if ($this->contacts === null || count($this->contacts) === 0) {
throw new TwitterContentException('There are no contacts for this note');
}
// here we check the matched contact from the note corresponds to a contact
// in the database
if (count(array_unique(array_values($this->contacts))) === 1
&& array_unique(array_values($this->contacts))[0] === null) {
throw new TwitterContentException('The matched contact is not in the database');
}
// swap in twitter usernames
$swapped = preg_replace_callback(
self::USERNAMES_REGEX,
function ($matches) {
if (is_null($this->contacts[$matches[1]])) {
return $matches[0];
}
$contact = $this->contacts[$matches[1]];
if ($contact->twitter) {
return '@' . $contact->twitter;
}
return $contact->name;
},
$this->getOriginal('note')
);
return $this->convertMarkdown($swapped);
}
/** /**
* Scope a query to select a note via a NewBase60 id. * Scope a query to select a note via a NewBase60 id.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $nb60id
* @return \Illuminate\Database\Eloquent\Builder
*/ */
public function scopeNb60(Builder $query, string $nb60id): Builder public function scopeNb60(Builder $query, string $nb60id): Builder
{ {
$realId = resolve(Numbers::class)->b60tonum($nb60id);
// Check nb60 does not translate to ID too big for database int4 column
if ($realId > 2_147_483_647) {
abort(404);
}
return $query->where('id', resolve(Numbers::class)->b60tonum($nb60id)); return $query->where('id', resolve(Numbers::class)->b60tonum($nb60id));
} }
/** /**
* Swap contacts nicks for a full mf2 h-card. * Swap contacts nicks for a full mf2 h-card.
* *
* Take note that this method does two things, given @username (NOT [@username](URL)!) * Take note that this method does two things, given @username (NOT [@username](URL)!)
* we try to create a fancy hcard from our contact info. If this is not possible * we try to create a fancy hcard from our contact info. If this is not possible
* due to lack of contact info, we assume @username is a twitter handle and link it * due to lack of contact info, we assume @username is a twitter handle and link it
* as such. * as such.
*
* @param string $text
* @return string
*/ */
private function makeHCards(string $text): string private function makeHCards(string $text): string
{ {
@ -307,7 +433,7 @@ class Note extends Model
return $text; return $text;
} }
return preg_replace_callback( $hcards = preg_replace_callback(
self::USERNAMES_REGEX, self::USERNAMES_REGEX,
function ($matches) { function ($matches) {
if (is_null($this->contacts[$matches[1]])) { if (is_null($this->contacts[$matches[1]])) {
@ -325,28 +451,28 @@ class Note extends Model
}, },
$text $text
); );
return $hcards;
} }
/** /**
* Get the value of the `contacts` property. * Get the value of the `contacts` property.
*/ */
public function getContacts(): array public function getContacts()
{ {
if ($this->contacts === null) { if ($this->contacts === null) {
$this->setContacts(); $this->setContacts();
} }
return $this->contacts;
} }
/** /**
* Process the note and save the contacts to the `contacts` property. * Process the note and save the contacts to the `contacts` property.
*/ */
public function setContacts(): void public function setContacts()
{ {
$contacts = []; $contacts = [];
if ($this->getRawOriginal('note')) { if ($this->getOriginal('note')) {
preg_match_all(self::USERNAMES_REGEX, $this->getRawOriginal('note'), $matches); preg_match_all(self::USERNAMES_REGEX, $this->getoriginal('note'), $matches);
foreach ($matches[1] as $match) { foreach ($matches[1] as $match) {
$contacts[$match] = Contact::where('nick', mb_strtolower($match))->first(); $contacts[$match] = Contact::where('nick', mb_strtolower($match))->first();
@ -362,11 +488,14 @@ class Note extends Model
* Given a string and section, finds all hashtags matching * Given a string and section, finds all hashtags matching
* `#[\-_a-zA-Z0-9]+` and wraps them in an `a` element with * `#[\-_a-zA-Z0-9]+` and wraps them in an `a` element with
* `rel=tag` set and a `href` of 'section/tagged/' + tagname without the #. * `rel=tag` set and a `href` of 'section/tagged/' + tagname without the #.
*
* @param string $note
* @return string
*/ */
public function autoLinkHashtag(string $note): string public function autoLinkHashtag(string $note): string
{ {
return preg_replace_callback( return preg_replace_callback(
'/#([^\s[:punct:]]+)/', '/#([^\s]*)\b/',
function ($matches) { function ($matches) {
return '<a rel="tag" class="p-category" href="/notes/tagged/' return '<a rel="tag" class="p-category" href="/notes/tagged/'
. Tag::normalize($matches[1]) . '">#' . Tag::normalize($matches[1]) . '">#'
@ -376,35 +505,35 @@ class Note extends Model
); );
} }
/**
* Pass a note through the commonmark library.
*
* @param string $note
* @return string
*/
private function convertMarkdown(string $note): string private function convertMarkdown(string $note): string
{ {
$config = [ $environment = Environment::createCommonMarkEnvironment();
'mentions' => [ $environment->addExtension(new LinkifyExtension());
'mentions_handle' => [ $environment->addBlockRenderer(FencedCode::class, new FencedCodeRenderer());
'prefix' => '@', $environment->addBlockRenderer(IndentedCode::class, new IndentedCodeRenderer());
'pattern' => '([\w@.])+(\b)', $converter = new CommonMarkConverter([], $environment);
'generator' => new MentionGenerator,
],
],
];
$environment = new Environment($config); return $converter->convertToHtml($note);
$environment->addExtension(new CommonMarkCoreExtension);
$environment->addExtension(new AutolinkExtension);
$environment->addExtension(new MentionExtension);
$environment->addRenderer(Mention::class, new MentionRenderer);
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer);
$environment->addRenderer(IndentedCode::class, new IndentedCodeRenderer);
$markdownConverter = new MarkdownConverter($environment);
return $markdownConverter->convert($note)->getContent();
} }
/**
* Do a reverse geocode lookup of a `lat,lng` value.
*
* @param float $latitude
* @param float $longitude
* @return string
*/
public function reverseGeoCode(float $latitude, float $longitude): string public function reverseGeoCode(float $latitude, float $longitude): string
{ {
$latLng = $latitude . ',' . $longitude; $latlng = $latitude . ',' . $longitude;
return Cache::get($latLng, function () use ($latLng, $latitude, $longitude) { return Cache::get($latlng, function () use ($latlng, $latitude, $longitude) {
$guzzle = resolve(Client::class); $guzzle = resolve(Client::class);
$response = $guzzle->request('GET', 'https://nominatim.openstreetmap.org/reverse', [ $response = $guzzle->request('GET', 'https://nominatim.openstreetmap.org/reverse', [
'query' => [ 'query' => [
@ -427,7 +556,7 @@ class Note extends Model
. '</span>, <span class="p-country-name">' . '</span>, <span class="p-country-name">'
. $json->address->country . $json->address->country
. '</span>'; . '</span>';
Cache::forever($latLng, $address); Cache::forever($latlng, $address);
return $address; return $address;
} }
@ -437,7 +566,7 @@ class Note extends Model
. '</span>, <span class="p-country-name">' . '</span>, <span class="p-country-name">'
. $json->address->country . $json->address->country
. '</span>'; . '</span>';
Cache::forever($latLng, $address); Cache::forever($latlng, $address);
return $address; return $address;
} }
@ -447,19 +576,14 @@ class Note extends Model
. '</span>, <span class="p-country-name">' . '</span>, <span class="p-country-name">'
. $json->address->country . $json->address->country
. '</span>'; . '</span>';
Cache::forever($latLng, $address); Cache::forever($latlng, $address);
return $address; return $address;
} }
$address = '<span class="p-country-name">' . $json->address->country . '</span>'; $address = '<span class="p-country-name">' . $json->address->country . '</span>';
Cache::forever($latLng, $address); Cache::forever($latlng, $address);
return $address; return $address;
}); });
} }
private function isTwitterLink(string $inReplyTo): bool
{
return str_starts_with($inReplyTo, 'https://twitter.com/');
}
} }

View file

@ -1,25 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Passkey extends Model
{
use HasFactory;
/** @inerhitDoc */
protected $fillable = [
'passkey_id',
'passkey',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

View file

@ -4,33 +4,41 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Cviebrock\EloquentSluggable\Sluggable;
use Phaza\LaravelPostgis\Geometries\Point;
use Phaza\LaravelPostgis\Eloquent\PostgisTrait;
class Place extends Model class Place extends Model
{ {
use HasFactory;
use Sluggable; use Sluggable;
use PostgisTrait;
public function getRouteKeyName(): string /**
{ * The attributes that are mass assignable.
return 'slug'; *
} * @var array
*/
/** @var array<int, string> */
protected $fillable = ['name', 'slug']; protected $fillable = ['name', 'slug'];
/** @var array<string, string> */ /**
protected $casts = [ * The attributes that are Postgis geometry objects.
'latitude' => 'float', *
'longitude' => 'float', * @var array
*/
protected $postgisFields = [
'location',
'polygon',
]; ];
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable(): array public function sluggable(): array
{ {
return [ return [
@ -41,31 +49,43 @@ class Place extends Model
]; ];
} }
public function notes(): HasMany /**
* Define the relationship with Notes.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function notes()
{ {
return $this->hasMany('App\Models\Note'); return $this->hasMany('App\Models\Note');
} }
/** /**
* Select places near a given location. * Select places near a given location.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Phaza\LaravelPostgis\Geometries\Point $point
* @param int $distance
* @return \Illuminate\Database\Eloquent\Builder
*/ */
public function scopeNear(Builder $query, object $location, int $distance = 1000): Builder public function scopeNear(Builder $query, Point $point, $distance = 1000): Builder
{ {
$haversine = "(6371 * acos(cos(radians($location->latitude)) $field = DB::raw(
* cos(radians(places.latitude)) sprintf(
* cos(radians(places.longitude) "ST_Distance(%s.location, ST_GeogFromText('%s'))",
- radians($location->longitude)) $this->getTable(),
+ sin(radians($location->latitude)) $point->toWKT()
* sin(radians(places.latitude))))"; )
);
return $query return $query->where($field, '<=', $distance)->orderBy($field);
->select() // pick the columns you want here.
->selectRaw("{$haversine} AS distance")
->whereRaw("{$haversine} < ?", [$distance]);
} }
/** /**
* Select places based on a URL. * Select places based on a URL.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $url
* @return \Illuminate\Database\Eloquent\Builder
*/ */
public function scopeWhereExternalURL(Builder $query, string $url): Builder public function scopeWhereExternalURL(Builder $query, string $url): Builder
{ {
@ -74,36 +94,80 @@ class Place extends Model
])); ]));
} }
protected function uri(): Attribute /**
* Get the latitude from the `location` property.
*
* @return float
*/
public function getLatitudeAttribute(): float
{ {
return Attribute::get( return $this->location->getLat();
get: static fn ($value, $attributes) => config('app.url') . '/places/' . $attributes['slug'],
);
} }
protected function externalUrls(): Attribute /**
* Get the longitude from the `location` property.
*
* @return float
*/
public function getLongitudeAttribute(): float
{ {
return Attribute::set( return $this->location->getLng();
set: function ($value, $attributes) { }
if ($value === null) {
return $attributes['external_urls'] ?? null;
}
$type = $this->getType($value); /**
$already = []; * The Long URL for a place.
*
* @return string
*/
public function getLongurlAttribute(): string
{
return config('app.url') . '/places/' . $this->slug;
}
if (array_key_exists('external_urls', $attributes)) { /**
$already = json_decode($attributes['external_urls'], true); * The Short URL for a place.
} *
$already[$type] = $value; * @return string
*/
public function getShorturlAttribute(): string
{
return config('app.shorturl') . '/places/' . $this->slug;
}
return json_encode($already); /**
} * This method is an alternative for `longurl`.
); *
* @return string
*/
public function getUriAttribute(): string
{
return $this->longurl;
}
/**
* Dealing with a jsonb column, so we check input first.
*
* @param string|null $url
*/
public function setExternalUrlsAttribute(?string $url)
{
if ($url === null) {
return;
}
$type = $this->getType($url);
$already = [];
if (array_key_exists('external_urls', $this->attributes)) {
$already = json_decode($this->attributes['external_urls'], true);
}
$already[$type] = $url;
$this->attributes['external_urls'] = json_encode($already);
} }
/** /**
* Given a URL, see if it is one of our known types. * Given a URL, see if it is one of our known types.
*
* @param string $url
* @return string
*/ */
private function getType(string $url): string private function getType(string $url): string
{ {

View file

@ -1,62 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class SyndicationTarget extends Model
{
use HasFactory;
/** @var array<int, string> */
protected $fillable = [
'uid',
'name',
'service_name',
'service_url',
'service_photo',
'user_name',
'user_url',
'user_photo',
];
/** @var array<int, string> */
protected $visible = [
'uid',
'name',
'service',
'user',
];
/** @var array<int, string> */
protected $appends = [
'service',
'user',
];
protected function service(): Attribute
{
return Attribute::get(
get: fn ($value, $attributes) => [
'name' => $attributes['service_name'],
'url' => $attributes['service_url'],
'photo' => $attributes['service_photo'],
],
);
}
protected function user(): Attribute
{
return Attribute::get(
get: fn ($value, $attributes) => [
'name' => $attributes['user_name'],
'url' => $attributes['user_url'],
'photo' => $attributes['user_photo'],
],
);
}
}

View file

@ -4,43 +4,63 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Str;
class Tag extends Model class Tag extends Model
{ {
use HasFactory; /**
* We shall set a blacklist of non-modifiable model attributes.
/** @var array<int, string> */ *
* @var array
*/
protected $guarded = ['id']; protected $guarded = ['id'];
public function notes(): BelongsToMany /**
* Define the relationship with notes.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function notes()
{ {
return $this->belongsToMany(Note::class); return $this->belongsToMany('App\Models\Note');
} }
public function bookmarks(): BelongsToMany /**
* The bookmarks that belong to the tag.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function bookmarks()
{ {
return $this->belongsToMany('App\Models\Bookmark'); return $this->belongsToMany('App\Models\Bookmark');
} }
protected function tag(): Attribute /**
* When creating a Tag model instance, invoke the nomralize method on the tag.
*
* @param string $value
*/
public function setTagAttribute(string $value)
{ {
return Attribute::set( $this->attributes['tag'] = $this->normalize($value);
set: fn ($value) => self::normalize($value),
);
} }
/** /**
* Normalizes a tag. * This method actually normalizes a tag. That means lowercase-ing and
* removing fancy diatric characters.
* *
* That means convert to lowercase and removing fancy diatric characters. * @param string $tag
* @return string
*/ */
public static function normalize(string $tag): string public static function normalize(string $tag): string
{ {
return Str::slug($tag); return mb_strtolower(
preg_replace(
'/&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml|caron);/i',
'$1',
htmlentities($tag)
),
'UTF-8'
);
} }
} }

View file

@ -4,30 +4,28 @@ declare(strict_types=1);
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable class User extends Authenticatable
{ {
use HasFactory;
use Notifiable; use Notifiable;
/** @var array<int, string> */ /**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [ protected $fillable = [
'name', 'password', 'name', 'email', 'password',
]; ];
/** @var array<int, string> */ /**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [ protected $hidden = [
'current_password', 'password', 'remember_token',
'password',
'remember_token',
]; ];
public function passkey(): HasMany
{
return $this->hasMany(Passkey::class);
}
} }

Some files were not shown because too many files have changed in this diff Show more