Compare commits

..

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

578 changed files with 13145 additions and 35091 deletions

View file

@ -1,21 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.{js,css}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

View file

@ -1,90 +1,52 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_KEY=SomeRandomString
APP_TIMEZONE=UTC
APP_URL=https://example.com
APP_LOCALE=en
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
APP_LANG=en
APP_LOG=daily
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
DB_CONNECTION=pgsql
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
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_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
MAILGUN_DOMAIN=null
MAILGUN_SECRET=null
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
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
VITE_APP_NAME="${APP_NAME}"
APP_URL=https://example.com
APP_LONGURL=example.com
APP_SHORTURL=examp.le
ADMIN_USER=admin# pick something better, this is used for `/admin`
ADMIN_USER=admin
ADMIN_PASS=password
DISPLAY_NAME='Joe Bloggs'# This is used for example in the header and titles
PIWIK_URL=
PIWIK_SITE_ID=
TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=
SCOUT_DRIVER=database
SCOUT_QUEUE=false
SESSION_SECURE_COOKIE=true
SESSION_SAME_SITE=strict
LOG_SLACK_WEBHOOK_URL=
FLARE_KEY=
IGNITION_OPEN_AI_KEY=
BRIDGY_MASTODON_TOKEN=

11
.env.travis Normal file
View file

@ -0,0 +1,11 @@
APP_ENV=testing
APP_KEY=
APP_URL=http://localhost:8000
APP_LONGURL=localhost
APP_SHORTURL=local
DB_CONNECTION=travis
CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync

10
.gitattributes vendored
View file

@ -1,7 +1,3 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
* text=auto
*.css linguist-vendored
*.scss linguist-vendored

31
.gitignore vendored
View file

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

7
.styleci.yml Normal file
View file

@ -0,0 +1,7 @@
preset: laravel
disabled:
- concat_without_spaces
finder:
path: app/

View file

@ -1,3 +0,0 @@
{
"extends": ["stylelint-config-standard"]
}

42
.travis.yml Normal file
View file

@ -0,0 +1,42 @@
language: php
sudo: false
addons:
postgresql: "9.4"
services:
- postgresql
env:
global:
- setup=basic
php:
- 7.0
- nightly
matrix:
allow_failures:
- php: nightly
before_install:
- phpenv config-rm xdebug.ini
- travis_retry composer self-update --preview
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
before_script:
- psql -U travis -c 'create database travis_ci_test'
- psql -U travis -d travis_ci_test -c 'create extension postgis'
- cp .env.travis .env
- php artisan key:generate
- php artisan migrate
- php artisan db:seed
- php artisan serve &
- sleep 5 # Give artisan some time to start serving
script:
- phpdbg -qrr vendor/bin/phpunit --coverage-text

148
app/Article.php Normal file
View file

@ -0,0 +1,148 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Jonnybarnes\UnicodeTools\UnicodeTools;
use League\CommonMark\CommonMarkConverter;
use MartinBean\Database\Eloquent\Sluggable;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
use SoftDeletes;
/*
* We want to turn the titles into slugs
*/
use Sluggable;
const DISPLAY_NAME = 'title';
const SLUG = 'titleurl';
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'articles';
/**
* Define the relationship with webmentions.
*
* @var array
*/
public function webmentions()
{
return $this->morphMany('App\WebMention', 'commentable');
}
/**
* We shall set a blacklist of non-modifiable model attributes.
*
* @var array
*/
protected $guarded = ['id'];
/**
* Process the article for display.
*
* @return string
*/
public function getMainAttribute($value)
{
$unicode = new UnicodeTools();
$markdown = new CommonMarkConverter();
$html = $markdown->convertToHtml($unicode->convertUnicodeCodepoints($value));
//change <pre><code>[lang] ~> <pre><code data-language="lang">
$match = '/<pre><code>\[(.*)\]\n/';
$replace = '<pre><code class="language-$1">';
$text = preg_replace($match, $replace, $html);
$default = preg_replace('/<pre><code>/', '<pre><code class="language-markdown">', $text);
return $default;
}
/**
* Convert updated_at to W3C time format.
*
* @return string
*/
public function getW3cTimeAttribute()
{
return $this->updated_at->toW3CString();
}
/**
* Convert updated_at to a tooltip appropriate format.
*
* @return string
*/
public function getTooltipTimeAttribute()
{
return $this->updated_at->toRFC850String();
}
/**
* Convert updated_at to a human readable format.
*
* @return string
*/
public function getHumanTimeAttribute()
{
return $this->updated_at->diffForHumans();
}
/**
* Get the pubdate value for RSS feeds.
*
* @return string
*/
public function getPubdateAttribute()
{
return $this->updated_at->toRSSString();
}
/**
* A link to the article, i.e. `/blog/1999/12/25/merry-christmas`.
*
* @return string
*/
public function getLinkAttribute()
{
return '/blog/' . $this->updated_at->year . '/' . $this->updated_at->format('m') . '/' . $this->titleurl;
}
/**
* Scope a query to only include articles from a particular year/month.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeDate($query, $year = null, $month = null)
{
if ($year == null) {
return $query;
}
$start = $year . '-01-01 00:00:00';
$end = ($year + 1) . '-01-01 00:00:00';
if (($month !== null) && ($month !== '12')) {
$start = $year . '-' . $month . '-01 00:00:00';
$end = $year . '-' . ($month + 1) . '-01 00:00:00';
}
if ($month === '12') {
$start = $year . '-12-01 00:00:00';
//$end as above
}
return $query->where([
['updated_at', '>=', $start],
['updated_at', '<', $end],
]);
}
}

22
app/Client.php Normal file
View file

@ -0,0 +1,22 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'clients';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['client_url', 'client_name'];
}

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

@ -0,0 +1,33 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
class Inspire extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'inspire';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Display an inspiring quote';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);
}
}

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

@ -1,64 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Models\WebMention;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\FileSystem\FileSystem;
class ParseCachedWebMentions extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'webmentions:parsecached';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Re-parse the webmentions cached HTML';
/**
* Execute the console command.
*
* @throws FileNotFoundException
*/
public function handle(FileSystem $filesystem): void
{
$htmlFiles = $filesystem->allFiles(storage_path() . '/HTML');
foreach ($htmlFiles as $file) {
if ($file->getExtension() !== 'backup') { // we dont want to parse `.backup` files
$filepath = $file->getPathname();
$this->info('Loading HTML from: ' . $filepath);
$html = $filesystem->get($filepath);
$url = $this->urlFromFilename($filepath);
$webmention = WebMention::where('source', $url)->firstOrFail();
$microformats = \Mf2\parse($html, $url);
$webmention->mf2 = json_encode($microformats);
$webmention->save();
$this->info('Saved the microformats to the database.');
}
}
}
/**
* Determine the source URL from a filename.
*/
private function urlFromFilename(string $filepath): string
{
$dir = mb_substr($filepath, mb_strlen(storage_path() . '/HTML/'));
$url = str_replace(['http/', 'https/'], ['http://', 'https://'], $dir);
if (mb_substr($url, -10) === 'index.html') {
$url = mb_substr($url, 0, -10);
}
return $url;
}
}

View file

@ -1,38 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Jobs\DownloadWebMention;
use App\Models\WebMention;
use Illuminate\Console\Command;
class ReDownloadWebMentions extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'webmentions:redownload';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Redownload the HTML content of webmentions';
/**
* Execute the console command.
*/
public function handle(): void
{
$webmentions = WebMention::all();
foreach ($webmentions as $webmention) {
$this->info('Initiation re-download of ' . $webmention->source);
dispatch(new DownloadWebMention($webmention->source));
}
}
}

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,21 +8,23 @@ use Illuminate\Foundation\Console\Kernel as 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
{
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->command('cache:prune-stale-tags')->hourly();
}
protected $commands = [
// Commands\Inspire::class,
];
/**
* Register the commands for the application.
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function commands(): void
protected function schedule(Schedule $schedule)
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
// $schedule->command('inspire')
// ->hourly();
}
}

22
app/Contact.php Normal file
View file

@ -0,0 +1,22 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'contacts';
/**
* We shall set a blacklist of non-modifiable model attributes.
*
* @var array
*/
protected $guarded = ['id'];
}

8
app/Events/Event.php Normal file
View file

@ -0,0 +1,8 @@
<?php
namespace App\Events;
abstract class Event
{
//
}

View file

@ -2,18 +2,86 @@
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* Register the exception handling callbacks for the application.
* A list of the exception types that should not be reported.
*
* @var array
*/
public function register(): void
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exc
* @return void
*/
public function report(Exception $exc)
{
$this->reportable(function (Throwable $_e) {
//
parent::report($exc);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exc
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exc)
{
if (config('app.debug')) {
return $this->renderExceptionWithWhoops($exc);
}
if ($exc instanceof ModelNotFoundException) {
$exc = new NotFoundHttpException($exc->getMessage(), $exc);
}
if ($exc instanceof TokenMismatchException) {
return redirect()->back()
->withInput($request->except('password', '_token'))
->withErrors('Validation Token has expired. Please try again', 'csrf');
}
return parent::render($request, $exc);
}
/**
* Render an exception using Whoops.
*
* @param \Exception $exc
* @return \Illuminate\Http\Response
*/
protected function renderExceptionWithWhoops(Exception $exc)
{
$whoops = new \Whoops\Run;
$handler = new \Whoops\Handler\PrettyPageHandler();
$handler->setEditor(function ($file, $line) {
return "atom://open?file=$file&line=$line";
});
$whoops->pushHandler($handler);
return new \Illuminate\Http\Response(
$whoops->handleException($exc),
$exc->getStatusCode(),
$exc->getHeaders()
);
}
}

View file

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

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

@ -0,0 +1,10 @@
<?php
namespace App\Exceptions;
use Exception;
class RemoteContentNotFound extends Exception
{
//used when guzzle cant find the remote content
}

View file

@ -1,10 +0,0 @@
<?php
namespace App\Exceptions;
use Exception;
class RemoteContentNotFoundException extends Exception
{
// used when guzzle cant find the remote content
}

View file

@ -1,69 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class ArticlesController extends Controller
{
public function index(): View
{
$posts = Article::select('id', 'title', 'published')->orderBy('id', 'desc')->get();
return view('admin.articles.index', ['posts' => $posts]);
}
public function create(): View
{
$message = session('message');
return view('admin.articles.create', ['message' => $message]);
}
public function store(): RedirectResponse
{
// if a `.md` is attached use that for the main content.
if (request()->hasFile('article')) {
$file = request()->file('article')->openFile();
$content = $file->fread($file->getSize());
}
$main = $content ?? request()->input('main');
Article::create([
'url' => request()->input('url'),
'title' => request()->input('title'),
'main' => $main,
'published' => request()->input('published') ?? 0,
]);
return redirect('/admin/blog');
}
public function edit(Article $article): View
{
return view('admin.articles.edit', ['article' => $article]);
}
public function update(int $articleId): RedirectResponse
{
$article = Article::find($articleId);
$article->title = request()->input('title');
$article->url = request()->input('url');
$article->main = request()->input('main');
$article->published = request()->input('published') ?? 0;
$article->save();
return redirect('/admin/blog');
}
public function destroy(int $articleId): RedirectResponse
{
Article::where('id', $articleId)->delete();
return redirect('/admin/blog');
}
}

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

@ -1,81 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\MicropubClient;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class ClientsController extends Controller
{
/**
* Show a list of known clients.
*/
public function index(): View
{
$clients = MicropubClient::all();
return view('admin.clients.index', compact('clients'));
}
/**
* Show form to add a client name.
*/
public function create(): View
{
return view('admin.clients.create');
}
/**
* Process the request to adda new client name.
*/
public function store(): RedirectResponse
{
MicropubClient::create([
'client_url' => request()->input('client_url'),
'client_name' => request()->input('client_name'),
]);
return redirect('/admin/clients');
}
/**
* Show a form to edit a client name.
*/
public function edit(int $clientId): View
{
$client = MicropubClient::findOrFail($clientId);
return view('admin.clients.edit', [
'id' => $clientId,
'client_url' => $client->client_url,
'client_name' => $client->client_name,
]);
}
/**
* Process the request to edit a client name.
*/
public function update(int $clientId): RedirectResponse
{
$client = MicropubClient::findOrFail($clientId);
$client->client_url = request()->input('client_url');
$client->client_name = request()->input('client_name');
$client->save();
return redirect('/admin/clients');
}
/**
* Process a request to delete a client.
*/
public function destroy(int $clientId): RedirectResponse
{
MicropubClient::where('id', $clientId)->delete();
return redirect('/admin/clients');
}
}

View file

@ -1,153 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use GuzzleHttp\Client;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Arr;
use Illuminate\View\View;
class ContactsController extends Controller
{
/**
* List the currect contacts that can be edited.
*/
public function index(): View
{
$contacts = Contact::all();
return view('admin.contacts.index', compact('contacts'));
}
/**
* Display the form to add a new contact.
*/
public function create(): View
{
return view('admin.contacts.create');
}
/**
* Process the request to add a new contact.
*/
public function store(): RedirectResponse
{
$contact = new Contact;
$contact->name = request()->input('name');
$contact->nick = request()->input('nick');
$contact->homepage = request()->input('homepage');
$contact->twitter = request()->input('twitter');
$contact->facebook = request()->input('facebook');
$contact->save();
return redirect('/admin/contacts');
}
/**
* Show the form to edit an existing contact.
*/
public function edit(int $contactId): View
{
$contact = Contact::findOrFail($contactId);
return view('admin.contacts.edit', compact('contact'));
}
/**
* Process the request to edit a contact.
*
* @todo Allow saving profile pictures for people without homepages
*/
public function update(int $contactId): RedirectResponse
{
$contact = Contact::findOrFail($contactId);
$contact->name = request()->input('name');
$contact->nick = request()->input('nick');
$contact->homepage = request()->input('homepage');
$contact->twitter = request()->input('twitter');
$contact->facebook = request()->input('facebook');
$contact->save();
if (request()->hasFile('avatar') && (request()->input('homepage') != '')) {
$dir = parse_url(request()->input('homepage'), PHP_URL_HOST);
$destination = public_path() . '/assets/profile-images/' . $dir;
$filesystem = new Filesystem;
if ($filesystem->isDirectory($destination) === false) {
$filesystem->makeDirectory($destination);
}
request()->file('avatar')->move($destination, 'image');
}
return redirect('/admin/contacts');
}
/**
* Process the request to delete a contact.
*/
public function destroy(int $contactId): RedirectResponse
{
$contact = Contact::findOrFail($contactId);
$contact->delete();
return redirect('/admin/contacts');
}
/**
* Download the avatar for a contact.
*
* This method attempts to find the microformat marked-up profile image
* from a given homepage and save it accordingly
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/
public function getAvatar(int $contactId)
{
// Initialising
$avatarURL = null;
$avatar = null;
$contact = Contact::findOrFail($contactId);
if ($contact->homepage !== null && mb_strlen($contact->homepage) !== 0) {
$client = resolve(Client::class);
try {
$response = $client->get($contact->homepage);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
return redirect('/admin/contacts/' . $contactId . '/edit')
->with('error', 'Bad resposne from contacts homepage');
}
$mf2 = \Mf2\parse((string) $response->getBody(), $contact->homepage);
foreach ($mf2['items'] as $microformat) {
if (Arr::get($microformat, 'type.0') === 'h-card') {
$avatarURL = Arr::get($microformat, 'properties.photo.0.value');
break;
}
}
if ($avatarURL !== null) {
try {
$avatar = $client->get($avatarURL);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
return redirect('/admin/contacts/' . $contactId . '/edit')
->with('error', 'Unable to download avatar');
}
}
if ($avatar !== null) {
$directory = public_path() . '/assets/profile-images/' . parse_url($contact->homepage, PHP_URL_HOST);
$filesystem = new Filesystem;
if ($filesystem->isDirectory($directory) === false) {
$filesystem->makeDirectory($directory);
}
$filesystem->put($directory . '/image', $avatar->getBody());
return view('admin.contacts.getavatarsuccess', [
'homepage' => parse_url($contact->homepage, PHP_URL_HOST),
]);
}
}
return redirect('/admin/contacts/' . $contactId . '/edit');
}
}

View file

@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\View\View;
class HomeController extends Controller
{
/**
* Show the homepage of the admin CP.
*/
public function welcome(): View
{
return view('admin.welcome', ['name' => config('admin.user')]);
}
}

View file

@ -1,81 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Jobs\ProcessLike;
use App\Models\Like;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class LikesController extends Controller
{
/**
* List the likes that can be edited.
*/
public function index(): View
{
$likes = Like::all();
return view('admin.likes.index', compact('likes'));
}
/**
* Show the form to make a new like.
*/
public function create(): View
{
return view('admin.likes.create');
}
/**
* Process a request to make a new like.
*/
public function store(): RedirectResponse
{
$like = Like::create([
'url' => normalize_url(request()->input('like_url')),
]);
ProcessLike::dispatch($like);
return redirect('/admin/likes');
}
/**
* Display the form to edit a specific like.
*/
public function edit(int $likeId): View
{
$like = Like::findOrFail($likeId);
return view('admin.likes.edit', [
'id' => $like->id,
'like_url' => $like->url,
]);
}
/**
* Process a request to edit a like.
*/
public function update(int $likeId): RedirectResponse
{
$like = Like::findOrFail($likeId);
$like->url = normalize_url(request()->input('like_url'));
$like->save();
ProcessLike::dispatch($like);
return redirect('/admin/likes');
}
/**
* Process the request to delete a like.
*/
public function destroy(int $likeId): RedirectResponse
{
Like::where('id', $likeId)->delete();
return redirect('/admin/likes');
}
}

View file

@ -1,90 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Jobs\SendWebMentions;
use App\Models\Note;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class NotesController extends Controller
{
/**
* List the notes that can be edited.
*/
public function index(): View
{
$notes = Note::select('id', 'note')->orderBy('id', 'desc')->get();
foreach ($notes as $note) {
$note->originalNote = $note->getOriginal('note');
}
return view('admin.notes.index', compact('notes'));
}
/**
* Show the form to make a new note.
*/
public function create(): View
{
return view('admin.notes.create');
}
/**
* Process a request to make a new note.
*/
public function store(Request $request): RedirectResponse
{
Note::create([
'in_reply_to' => $request->input('in-reply-to'),
'note' => $request->input('content'),
]);
return redirect('/admin/notes');
}
/**
* Display the form to edit a specific note.
*/
public function edit(int $noteId): View
{
$note = Note::find($noteId);
$note->originalNote = $note->getOriginal('note');
return view('admin.notes.edit', compact('note'));
}
/**
* Process a request to edit a note. Easy since this can only be done
* from the admin CP.
*/
public function update(int $noteId): RedirectResponse
{
// update note data
$note = Note::findOrFail($noteId);
$note->note = request()->input('content');
$note->in_reply_to = request()->input('in-reply-to');
$note->save();
if (request()->input('webmentions')) {
dispatch(new SendWebMentions($note));
}
return redirect('/admin/notes');
}
/**
* Delete the note.
*/
public function destroy(int $noteId): RedirectResponse
{
$note = Note::findOrFail($noteId);
$note->delete();
return redirect('/admin/notes');
}
}

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

@ -1,136 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Place;
use App\Services\PlaceService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class PlacesController extends Controller
{
protected PlaceService $placeService;
public function __construct(PlaceService $placeService)
{
$this->placeService = $placeService;
}
/**
* List the places that can be edited.
*/
public function index(): View
{
$places = Place::all();
return view('admin.places.index', compact('places'));
}
/**
* Show the form to make a new place.
*/
public function create(): View
{
return view('admin.places.create');
}
/**
* Process a request to make a new place.
*/
public function store(): RedirectResponse
{
$this->placeService->createPlace(
request()->only([
'name',
'description',
'latitude',
'longitude',
])
);
return redirect('/admin/places');
}
/**
* Display the form to edit a specific place.
*/
public function edit(int $placeId): View
{
$place = Place::findOrFail($placeId);
return view('admin.places.edit', compact('place'));
}
/**
* Process a request to edit a place.
*/
public function update(int $placeId): RedirectResponse
{
$place = Place::findOrFail($placeId);
$place->name = request()->input('name');
$place->description = request()->input('description');
$place->latitude = request()->input('latitude');
$place->longitude = request()->input('longitude');
$place->icon = request()->input('icon');
$place->save();
return redirect('/admin/places');
}
/**
* List the places we can merge with the current place.
*/
public function mergeIndex(int $placeId): View
{
$first = Place::find($placeId);
$results = Place::near((object) ['latitude' => $first->latitude, 'longitude' => $first->longitude])->get();
$places = [];
foreach ($results as $place) {
if ($place->slug !== $first->slug) {
$places[] = $place;
}
}
return view('admin.places.merge.index', compact('first', 'places'));
}
/**
* Show a form for merging two specific places.
*/
public function mergeEdit(int $placeId1, int $placeId2): View
{
$place1 = Place::find($placeId1);
$place2 = Place::find($placeId2);
return view('admin.places.merge.edit', compact('place1', 'place2'));
}
/**
* Process the request to merge two places.
*/
public function mergeStore(): RedirectResponse
{
$place1 = Place::find(request()->input('place1'));
$place2 = Place::find(request()->input('place2'));
if (request()->input('delete') === '1') {
foreach ($place1->notes as $note) {
$note->place()->dissociate();
$note->place()->associate($place2->id);
}
$place1->delete();
}
if (request()->input('delete') === '2') {
foreach ($place2->notes as $note) {
$note->place()->dissociate();
$note->place()->associate($place1->id);
}
$place2->delete();
}
return redirect('/admin/places');
}
}

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

@ -0,0 +1,35 @@
<?php
namespace App\Http\Controllers;
class AdminController extends Controller
{
/*
|--------------------------------------------------------------------------
| Admin Controller
|--------------------------------------------------------------------------
|
| Here we have the logic for the admin cp
|
*/
/**
* Set variables.
*
* @var string
*/
public function __construct()
{
$this->username = env('ADMIN_USER');
}
/**
* Show the main admin CP page.
*
* @return \Illuminate\View\Factory view
*/
public function showWelcome()
{
return view('admin.welcome', ['name' => $this->username]);
}
}

View file

@ -0,0 +1,140 @@
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticlesAdminController extends Controller
{
/**
* Show the new article form.
*
* @return \Illuminate\View\Factory view
*/
public function newArticle()
{
$message = session('message');
return view('admin.newarticle', ['message' => $message]);
}
/**
* List the articles that can be edited.
*
* @return \Illuminate\View\Factory view
*/
public function listArticles()
{
$posts = Article::select('id', 'title', 'published')->orderBy('id', 'desc')->get();
return view('admin.listarticles', ['posts' => $posts]);
}
/**
* Show the edit form for an existing article.
*
* @param string The article id
* @return \Illuminate\View\Factory view
*/
public function editArticle($articleId)
{
$post = Article::select(
'title',
'main',
'url',
'published'
)->where('id', $articleId)->get();
return view('admin.editarticle', ['id' => $articleId, 'post' => $post]);
}
/**
* Show the delete confirmation form for an article.
*
* @param string The article id
* @return \Illuminate\View\Factory view
*/
public function deleteArticle($articleId)
{
return view('admin.deletearticle', ['id' => $articleId]);
}
/**
* Process an incoming request for a new article and save it.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\Factory view
*/
public function postNewArticle(Request $request)
{
$published = $request->input('published');
if ($published == null) {
$published = '0';
}
//if a `.md` is attached use that for the main content.
$content = null; //set default value
if ($request->hasFile('article')) {
$file = $request->file('article')->openFile();
$content = $file->fread($file->getSize());
}
$main = $content ?? $request->input('main');
try {
$article = Article::create(
[
'url' => $request->input('url'),
'title' => $request->input('title'),
'main' => $main,
'published' => $published,
]
);
} catch (Exception $e) {
$msg = $e->getMessage();
$unique = strpos($msg, '1062');
if ($unique !== false) {
//We've checked for error 1062, i.e. duplicate titleurl
return redirect('admin/blog/new')->withInput()->with('message', 'Duplicate title, please change');
}
//this isn't the error you're looking for
throw $e;
}
return view('admin.newarticlesuccess', ['id' => $article->id, 'title' => $article->title]);
}
/**
* Process an incoming request to edit an article.
*
* @param string
* @param \Illuminate\Http\Request $request
* @return \Illuminate|View\Factory view
*/
public function postEditArticle($articleId, Request $request)
{
$published = $request->input('published');
if ($published == null) {
$published = '0';
}
$article = Article::find($articleId);
$article->title = $request->input('title');
$article->url = $request->input('url');
$article->main = $request->input('main');
$article->published = $published;
$article->save();
return view('admin.editarticlesuccess', ['id' => $articleId]);
}
/**
* Process a request to delete an aricle.
*
* @param string The article id
* @return \Illuminate\View\Factory view
*/
public function postDeleteArticle($articleId)
{
Article::where('id', $articleId)->delete();
return view('admin.deletearticlesuccess', ['id' => $articleId]);
}
}

View file

@ -1,60 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use App\Article;
use Illuminate\Http\Response;
use Jonnybarnes\IndieWeb\Numbers;
class ArticlesController extends Controller
{
/**
* Show all articles (with pagination).
*
* @return \Illuminate\View\Factory view
*/
public function index(?int $year = null, ?int $month = null): View
public function showAllArticles($year = null, $month = null)
{
$articles = Article::where('published', '1')
->date($year, $month)
->orderBy('updated_at', 'desc')
->simplePaginate(5);
->date($year, $month)
->orderBy('updated_at', 'desc')
->simplePaginate(5);
return view('articles.index', compact('articles'));
return view('multipost', ['data' => $articles]);
}
/**
* Show a single article.
*
* @return \Illuminate\View\Factory view
*/
public function show(int $year, int $month, string $slug): RedirectResponse|View
public function singleArticle($year, $month, $slug)
{
try {
$article = Article::where('titleurl', $slug)->firstOrFail();
} catch (ModelNotFoundException $exception) {
abort(404);
}
$article = Article::where('titleurl', $slug)->first();
if ($article->updated_at->year != $year || $article->updated_at->month != $month) {
return redirect('/blog/'
. $article->updated_at->year
. '/' . $article->updated_at->format('m')
. '/' . $slug);
throw new \Exception;
}
return view('articles.show', compact('article'));
return view('singlepost', ['article' => $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.
*
* @return \Illuminte\Routing\RedirectResponse redirect
*/
public function onlyIdInUrl(string $idFromUrl): RedirectResponse
public function onlyIdInUrl($inURLId)
{
$realId = resolve(Numbers::class)->b60tonum($idFromUrl);
$numbers = new Numbers();
$realId = $numbers->b60tonum($inURLId);
$article = Article::findOrFail($realId);
return redirect($article->link);
}
/**
* Returns the RSS feed.
*
* @return \Illuminate\Http\Response
*/
public function makeRSS()
{
$articles = Article::where('published', '1')->orderBy('updated_at', 'desc')->get();
$buildDate = $articles->first()->updated_at->toRssString();
$contents = (string) view('rss', ['articles' => $articles, 'buildDate' => $buildDate]);
return (new Response($contents, '200'))->header('Content-Type', 'application/rss+xml');
}
}

View file

@ -0,0 +1,72 @@
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}

View file

@ -1,62 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthController extends Controller
{
/**
* Show the login form.
* Log in a user, set a sesion variable, check credentials against
* the .env file.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function showLogin(): View|RedirectResponse
public function login(Request $request)
{
if (Auth::check()) {
return redirect('/');
}
if ($request->input('username') === env('ADMIN_USER')
&&
$request->input('password') === env('ADMIN_PASS')
) {
session(['loggedin' => true]);
return view('login');
}
/**
* Log in a user, set a session variable, check credentials against the `.env` file.
*/
public function login(Request $request): RedirectResponse
{
$credentials = $request->only('name', 'password');
if (Auth::attempt($credentials, true)) {
return redirect()->intended('/admin');
return redirect()->intended('admin');
}
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

@ -1,43 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Bookmark;
use Illuminate\View\View;
class BookmarksController extends Controller
{
/**
* Show the most recent bookmarks.
*/
public function index(): View
{
$bookmarks = Bookmark::latest()->with('tags')->withCount('tags')->paginate(10);
return view('bookmarks.index', compact('bookmarks'));
}
/**
* Show a single bookmark.
*/
public function show(Bookmark $bookmark): View
{
$bookmark->loadMissing('tags');
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

@ -0,0 +1,87 @@
<?php
namespace App\Http\Controllers;
use App\Client;
class ClientsAdminController extends Controller
{
/**
* Show a list of known clients.
*
* @return \Illuminate\View\Factory view
*/
public function listClients()
{
$clients = Client::all();
return view('admin.listclients', ['clients' => $clients]);
}
/**
* Show form to add a client name.
*
* @return \Illuminate\View\Factory view
*/
public function newClient()
{
return view('admin.newclient');
}
/**
* Process the request to adda new client name.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\Factory view
*/
public function postNewClient(Request $request)
{
Client::create([
'client_url' => $request->input('client_url'),
'client_name' => $request->input('client_name'),
]);
return view('admin.newclientsuccess');
}
/**
* Show a form to edit a client name.
*
* @param string The client id
* @return \Illuminate\View\Factory view
*/
public function editClient($clientId)
{
$client = Client::findOrFail($clientId);
return view('admin.editclient', [
'id' => $clientId,
'client_url' => $client->client_url,
'client_name' => $client->client_name,
]);
}
/**
* Process the request to edit a client name.
*
* @param string The client id
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\Factory view
*/
public function postEditClient($clientId, Request $request)
{
$client = Client::findOrFail($clientId);
if ($request->input('edit')) {
$client->client_url = $request->input('client_url');
$client->client_name = $request->input('client_name');
$client->save();
return view('admin.editclientsuccess');
}
if ($request->input('delete')) {
$client->delete();
return view('admin.deleteclientsuccess');
}
}
}

View file

@ -0,0 +1,166 @@
<?php
namespace App\Http\Controllers;
use App\Contact;
use GuzzleHttp\Client;
use Illuminate\Filesystem\Filesystem;
class ContactsAdminController extends Controller
{
/**
* Display the form to add a new contact.
*
* @return \Illuminate\View\Factory view
*/
public function newContact()
{
return view('admin.newcontact');
}
/**
* List the currect contacts that can be edited.
*
* @return \Illuminate\View\Factory view
*/
public function listContacts()
{
$contacts = Contact::all();
return view('admin.listcontacts', ['contacts' => $contacts]);
}
/**
* Show the form to edit an existing contact.
*
* @param string The contact id
* @return \Illuminate\View\Factory view
*/
public function editContact($contactId)
{
$contact = Contact::findOrFail($contactId);
return view('admin.editcontact', ['contact' => $contact]);
}
/**
* Show the form to confirm deleting a contact.
*
* @return \Illuminate\View\Factory view
*/
public function deleteContact($contactId)
{
return view('admin.deletecontact', ['id' => $contactId]);
}
/**
* Process the request to add a new contact.
*
* @param \Illuminate\Http|request $request
* @return \Illuminate\View\Factory view
*/
public function postNewContact(Request $request)
{
$contact = new Contact();
$contact->name = $request->input('name');
$contact->nick = $request->input('nick');
$contact->homepage = $request->input('homepage');
$contact->twitter = $request->input('twitter');
$contact->save();
$contactId = $contact->id;
return view('admin.newcontactsuccess', ['id' => $contactId]);
}
/**
* Process the request to edit a contact.
*
* @todo Allow saving profile pictures for people without homepages
*
* @param string The contact id
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\Factory view
*/
public function postEditContact($contactId, Request $request)
{
$contact = Contact::findOrFail($contactId);
$contact->name = $request->input('name');
$contact->nick = $request->input('nick');
$contact->homepage = $request->input('homepage');
$contact->twitter = $request->input('twitter');
$contact->save();
if ($request->hasFile('avatar')) {
if ($request->input('homepage') != '') {
$dir = parse_url($request->input('homepage'))['host'];
$destination = public_path() . '/assets/profile-images/' . $dir;
$filesystem = new Filesystem();
if ($filesystem->isDirectory($destination) === false) {
$filesystem->makeDirectory($destination);
}
$request->file('avatar')->move($destination, 'image');
}
}
return view('admin.editcontactsuccess');
}
/**
* Process the request to delete a contact.
*
* @param string The contact id
* @return \Illuminate\View\Factory view
*/
public function postDeleteContact($contactId)
{
$contact = Contact::findOrFail($contactId);
$contact->delete();
return view('admin.deletecontactsuccess');
}
/**
* Download the avatar for a contact.
*
* This method attempts to find the microformat marked-up profile image
* from a given homepage and save it accordingly
*
* @param string The contact id
* @return \Illuminate\View\Factory view
*/
public function getAvatar($contactId)
{
$contact = Contact::findOrFail($contactId);
$homepage = $contact->homepage;
if (($homepage !== null) && ($homepage !== '')) {
$client = new Client();
try {
$response = $client->get($homepage);
$html = (string) $response->getBody();
$mf2 = \Mf2\parse($html, $homepage);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
return "Bad Response from $homepage";
}
$avatarURL = null; // Initialising
foreach ($mf2['items'] as $microformat) {
if ($microformat['type'][0] == 'h-card') {
$avatarURL = $microformat['properties']['photo'][0];
break;
}
}
try {
$avatar = $client->get($avatarURL);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
return "Unable to get $avatarURL";
}
$directory = public_path() . '/assets/profile-images/' . parse_url($homepage)['host'];
$filesystem = new Filesystem();
if ($filesystem->isDirectory($directory) === false) {
$filesystem->makeDirectory($directory);
}
$filesystem->put($directory . '/image', $avatar->getBody());
return view('admin.getavatarsuccess', ['homepage' => parse_url($homepage)['host']]);
}
}
}

View file

@ -1,48 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Contact;
use App\Contact;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\View;
class ContactsController extends Controller
{
/**
* Show all the contacts.
*
* @return \Illuminate\View\Factory view
*/
public function index(): View
public function showAll()
{
$filesystem = new Filesystem;
$filesystem = new Filesystem();
$contacts = Contact::all();
foreach ($contacts as $contact) {
$contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST);
$file = public_path() . '/assets/profile-images/' . $contact->homepageHost . '/image';
$contact->homepagePretty = parse_url($contact->homepage)['host'];
$file = public_path() . '/assets/profile-images/' . $contact->homepagePretty . '/image';
$contact->image = ($filesystem->exists($file)) ?
'/assets/profile-images/' . $contact->homepageHost . '/image'
'/assets/profile-images/' . $contact->homepagePretty . '/image'
:
'/assets/profile-images/default-image';
}
return view('contacts.index', compact('contacts'));
return view('contacts', ['contacts' => $contacts]);
}
/**
* Show a single contact.
*
* @return \Illuminate\View\Factory view
*/
public function show(Contact $contact): View
public function showSingle($nick)
{
$contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST);
$file = public_path() . '/assets/profile-images/' . $contact->homepageHost . '/image';
$filesystem = new Filesystem;
$image = ($filesystem->exists($file)) ?
'/assets/profile-images/' . $contact->homepageHost . '/image'
$filesystem = new Filesystem();
$contact = Contact::where('nick', '=', $nick)->firstOrFail();
$contact->homepagePretty = parse_url($contact->homepage)['host'];
$file = public_path() . '/assets/profile-images/' . $contact->homepagePretty . '/image';
$contact->image = ($filesystem->exists($file)) ?
'/assets/profile-images/' . $contact->homepagePretty . '/image'
:
'/assets/profile-images/default-image';
return view('contacts.show', compact('contact', 'image'));
return view('contact', ['contact' => $contact]);
}
}

View file

@ -2,7 +2,13 @@
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;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
class Controller extends BaseController
{
//
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
}

View file

@ -1,207 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Note;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class FeedsController extends Controller
{
/**
* Returns the blog RSS feed.
*/
public function blogRss(): Response
{
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
$buildDate = $articles->first()->updated_at->toRssString();
return response()
->view('articles.rss', compact('articles', 'buildDate'))
->header('Content-Type', 'application/rss+xml; charset=utf-8');
}
/**
* Returns the blog Atom feed.
*/
public function blogAtom(): Response
{
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
return response()
->view('articles.atom', compact('articles'))
->header('Content-Type', 'application/atom+xml; charset=utf-8');
}
/**
* Returns the notes RSS feed.
*/
public function notesRss(): Response
{
$notes = Note::latest()->take(20)->get();
$buildDate = $notes->first()->updated_at->toRssString();
return response()
->view('notes.rss', compact('notes', 'buildDate'))
->header('Content-Type', 'application/rss+xml; charset=utf-8');
}
/**
* Returns the notes Atom feed.
*/
public function notesAtom(): Response
{
$notes = Note::latest()->take(20)->get();
return response()
->view('notes.atom', compact('notes'))
->header('Content-Type', 'application/atom+xml; charset=utf-8');
}
/** @todo sort out return type for json responses */
/**
* Returns the blog JSON feed.
*/
public function blogJson(): array
{
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
$data = [
'version' => 'https://jsonfeed.org/version/1.1',
'title' => 'The JSON Feed for ' . config('user.display_name') . 's blog',
'home_page_url' => config('app.url') . '/blog',
'feed_url' => config('app.url') . '/blog/feed.json',
'authors' => [
[
'name' => config('user.display_name'),
'url' => config('app.url'),
],
],
'items' => [],
];
foreach ($articles as $key => $article) {
$data['items'][$key] = [
'id' => config('app.url') . $article->link,
'title' => $article->title,
'url' => config('app.url') . $article->link,
'content_html' => $article->main,
'date_published' => $article->created_at->tz('UTC')->toRfc3339String(),
'date_modified' => $article->updated_at->tz('UTC')->toRfc3339String(),
];
}
return $data;
}
/**
* Returns the notes JSON feed.
*/
public function notesJson(): array
{
$notes = Note::latest()->with('media', 'place', 'tags')->take(20)->get();
$data = [
'version' => 'https://jsonfeed.org/version/1.1',
'title' => 'The JSON Feed for ' . config('user.display_name') . 's notes',
'home_page_url' => config('app.url') . '/notes',
'feed_url' => config('app.url') . '/notes/feed.json',
'authors' => [
[
'name' => config('user.display_name'),
'url' => config('app.url'),
],
],
'items' => [],
];
foreach ($notes as $key => $note) {
$data['items'][$key] = [
'id' => $note->uri,
'url' => $note->uri,
'content_text' => $note->content,
'date_published' => $note->created_at->tz('UTC')->toRfc3339String(),
'date_modified' => $note->updated_at->tz('UTC')->toRfc3339String(),
];
if ($note->tags->count() > 0) {
$data['items'][$key]['tags'] = implode(',', $note->tags->pluck('tag')->toArray());
}
}
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 +1,164 @@
<?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 IndieAuth\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;
use Random\RandomException;
use SodiumException;
use Illuminate\Http\Response;
use App\Services\TokenService;
use Illuminate\Cookie\CookieJar;
use App\Services\IndieAuthService;
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'],
]);
/**
* This service isolates the IndieAuth Client code.
*/
protected $indieAuthService;
/**
* The IndieAuth Client implementation.
*/
protected $client;
/**
* The Token handling service.
*/
protected $tokenService;
/**
* Inject the dependencies.
*
* @param \App\Services\IndieAuthService $indieAuthService
* @param \IndieAuth\Client $client
* @return void
*/
public function __construct(
IndieAuthService $indieAuthService = null,
Client $client = null,
TokenService $tokenService = null
) {
$this->indieAuthService = $indieAuthService ?? new IndieAuthService();
$this->client = $client ?? new Client();
$this->tokenService = $tokenService ?? new TokenService();
}
/**
* Process a GET request to the IndieAuth endpoint.
* Begin the indie auth process. This method ties in to the login page
* from our micropub client. Here we then query the users homepage
* for their authorisation endpoint, and redirect them there with a
* unique secure state value.
*
* This is the first step in the IndieAuth flow, where the client app sends the user to the IndieAuth endpoint.
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function start(Request $request): View
public function beginauth(Request $request)
{
// 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);
$authorizationEndpoint = $this->indieAuthService->getAuthorizationEndpoint(
$request->input('me'),
$this->client
);
if ($authorizationEndpoint) {
$authorizationURL = $this->indieAuthService->buildAuthorizationURL(
$authorizationEndpoint,
$request->input('me'),
$this->client
);
if ($authorizationURL) {
return redirect($authorizationURL);
}
}
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'),
]);
return redirect('/notes/new')->withErrors('Unable to determine authorisation endpoint', 'indieauth');
}
/**
* Confirm an IndieAuth approval request.
* Once they have verified themselves through the authorisation endpint
* the next step is retreiveing a token from the token endpoint.
*
* Generates an auth code and redirects the user back to the client app.
*
* @throws RandomException
* @param \Illuminate\Http\Rrequest $request
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function confirm(Request $request): RedirectResponse
public function indieauth(Request $request)
{
$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', '')),
if ($request->session()->get('state') != $request->input('state')) {
return redirect('/notes/new')->withErrors(
'Invalid <code>state</code> value returned from indieauth server',
'indieauth'
);
}
$tokenEndpoint = $this->indieAuthService->getTokenEndpoint($request->input('me'), $this->client);
$redirectURL = config('app.url') . '/indieauth';
$clientId = config('app.url') . '/notes/new';
$data = [
'endpoint' => $tokenEndpoint,
'code' => $request->input('code'),
'me' => $request->input('me'),
'redirect_url' => $redirectURL,
'client_id' => $clientId,
'state' => $request->input('state'),
];
$token = $this->indieAuthService->getAccessToken($data, $this->client);
Cache::put($cacheKey, $indieAuthRequestData, now()->addMinutes(10));
if (array_key_exists('access_token', $token)) {
$request->session()->put('me', $token['me']);
$request->session()->put('token', $token['access_token']);
$redirectUri = new Uri($request->get('redirect_uri'));
$redirectUri = Uri::withQueryValues($redirectUri, [
'code' => $authCode,
'state' => $request->get('state'),
'iss' => config('app.url'),
]);
return redirect('/notes/new');
}
return redirect()->away($redirectUri);
return redirect('/notes/new')->withErrors('Unable to get a token from the endpoint', 'indieauth');
}
/**
* Process a POST request to the IndieAuth auth endpoint.
* If the user has authd via IndieAuth, issue a valid token.
*
* 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.
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function processCodeExchange(Request $request): JsonResponse
public function tokenEndpoint(Request $request)
{
$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'],
$authData = [
'code' => $request->input('code'),
'me' => $request->input('me'),
'redirect_url' => $request->input('redirect_uri'),
'client_id' => $request->input('client_id'),
'state' => $request->input('state'),
];
$tokenService = resolve(TokenService::class);
$token = $tokenService->getNewToken($tokenData);
$auth = $this->indieAuthService->verifyIndieAuthCode($authData, $this->client);
if (array_key_exists('me', $auth)) {
$scope = $auth['scope'] ?? '';
$tokenData = [
'me' => $request->input('me'),
'client_id' => $request->input('client_id'),
'scope' => $auth['scope'],
];
$token = $this->tokenService->getNewToken($tokenData);
$content = http_build_query([
'me' => $request->input('me'),
'scope' => $scope,
'access_token' => $token,
]);
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;
return (new Response($content, 200))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
$content = 'There was an error verifying the authorisation code.';
// 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);
return new Response($content, 400);
}
/**
* @throws SodiumException
* Log out the user, flush an session data, and overwrite any cookie data.
*
* @param \Illuminate\Cookie\CookieJar $cookie
* @return \Illuminate\Routing\RedirectResponse redirect
*/
protected function validateAuthorizationCode(Request $request): JsonResponse|array
public function indieauthLogout(Request $request, CookieJar $cookie)
{
// 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',
]);
$request->session()->flush();
$cookie->queue('me', 'loggedout', 5);
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;
return redirect('/notes/new');
}
}

View file

@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Like;
use Illuminate\View\View;
class LikesController extends Controller
{
/**
* Show the latest likes.
*/
public function index(): View
{
$likes = Like::latest()->paginate(20);
return view('likes.index', compact('likes'));
}
/**
* Show a single like.
*/
public function show(Like $like): View
{
return view('likes.show', compact('like'));
}
}

View file

@ -0,0 +1,333 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Services\IndieAuthService;
use IndieAuth\Client as IndieClient;
use GuzzleHttp\Client as GuzzleClient;
class MicropubClientController extends Controller
{
/**
* The IndieAuth service container.
*/
protected $indieAuthService;
/**
* Inject the dependencies.
*/
public function __construct(
IndieAuthService $indieAuthService = null,
IndieClient $indieClient = null,
GuzzleClient $guzzleClient = null
) {
$this->indieAuthService = $indieAuthService ?? new IndieAuthService();
$this->guzzleClient = $guzzleClient ?? new GuzzleClient();
$this->indieClient = $indieClient ?? new IndieClient();
}
/**
* Display the new notes form.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\Factory view
*/
public function newNotePage(Request $request)
{
$url = $request->session()->get('me');
$syndication = $this->parseSyndicationTargets(
$request->session()->get('syndication')
);
return view('micropubnewnotepage', [
'url' => $url,
'syndication' => $syndication,
]);
}
/**
* Post the notes content to the relavent micropub API endpoint.
*
* @todo make sure this works with multiple syndication targets
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function postNewNote(Request $request)
{
$domain = $request->session()->get('me');
$token = $request->session()->get('token');
$micropubEndpoint = $this->indieAuthService->discoverMicropubEndpoint(
$domain,
$this->indieClient
);
if (! $micropubEndpoint) {
return redirect('notes/new')->withErrors('Unable to determine micropub API endpoint', 'endpoint');
}
$response = $this->postNoteRequest($request, $micropubEndpoint, $token);
if ($response->getStatusCode() == 201) {
$location = $response->getHeader('Location');
if (is_array($location)) {
return redirect($location[0]);
}
return redirect($location);
}
return redirect('notes/new')->withErrors('Endpoint didnt create the note.', 'endpoint');
}
/**
* We make a request to the micropub endpoint requesting syndication targets
* and store them in the session.
*
* @todo better handling of response regarding mp-syndicate-to
* and syndicate-to
*
* @param \Illuminate\Http\Request $request
* @param \IndieAuth\Client $indieClient
* @param \GuzzleHttp\Client $guzzleClient
* @return \Illuminate\Routing\Redirector redirect
*/
public function refreshSyndicationTargets(Request $request)
{
$domain = $request->session()->get('me');
$token = $request->session()->get('token');
$micropubEndpoint = $this->indieAuthService->discoverMicropubEndpoint($domain, $this->indieClient);
if (! $micropubEndpoint) {
return redirect('notes/new')->withErrors('Unable to determine micropub API endpoint', 'endpoint');
}
try {
$response = $this->guzzleClient->get($micropubEndpoint, [
'headers' => ['Authorization' => 'Bearer ' . $token],
'query' => ['q' => 'syndicate-to'],
]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
return redirect('notes/new')->withErrors('Bad response when refreshing syndication targets', 'endpoint');
}
$body = (string) $response->getBody();
$syndication = str_replace(['&', '[]'], [';', ''], $body);
$request->session()->put('syndication', $syndication);
return redirect('notes/new');
}
/**
* This method performs the actual POST request.
*
* @param \Illuminate\Http\Request $request
* @param string The Micropub endpoint to post to
* @param string The token to authenticate the request with
* @return \GuzzleHttp\Response $response | \Illuminate\RedirectFactory redirect
*/
private function postNoteRequest(
Request $request,
$micropubEndpoint,
$token
) {
$multipart = [
[
'name' => 'h',
'contents' => 'entry',
],
[
'name' => 'content',
'contents' => $request->input('content'),
],
];
if ($request->hasFile('photo')) {
$photos = $request->file('photo');
foreach ($photos as $photo) {
$filename = $photo->getClientOriginalName();
$photo->move(storage_path() . '/media-tmp', $filename);
$multipart[] = [
'name' => 'photo[]',
'contents' => fopen(storage_path() . '/media-tmp/' . $filename, 'r'),
];
}
}
if ($request->input('in-reply-to') != '') {
$multipart[] = [
'name' => 'in-reply-to',
'contents' => $request->input('reply-to'),
];
}
if ($request->input('mp-syndicate-to')) {
foreach ($request->input('mp-syndicate-to') as $syn) {
$multipart[] = [
'name' => 'mp-syndicate-to',
'contents' => $syn,
];
}
}
if ($request->input('confirmlocation')) {
$latLng = $request->input('location');
$geoURL = 'geo:' . str_replace(' ', '', $latLng);
$multipart[] = [
'name' => 'location',
'contents' => $geoURL,
];
if ($request->input('address') != '') {
$multipart[] = [
'name' => 'place_name',
'contents' => $request->input('address'),
];
}
}
$headers = [
'Authorization' => 'Bearer ' . $token,
];
try {
$response = $this->guzzleClient->post($micropubEndpoint, [
'multipart' => $multipart,
'headers' => $headers,
]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
return redirect('notes/new')
->withErrors('There was a bad response from the micropub endpoint.', 'endpoint');
}
return $response;
}
/**
* Create a new place.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function postNewPlace(Request $request)
{
$domain = $request->session()->get('me');
$token = $request->session()->get('token');
$micropubEndpoint = $this->indieAuthService->discoverMicropubEndpoint($domain, $this->indieClient);
if (! $micropubEndpoint) {
return (new Response(json_encode([
'error' => true,
'message' => 'Could not determine the micropub endpoint.',
]), 400))
->header('Content-Type', 'application/json');
}
$place = $this->postPlaceRequest($request, $micropubEndpoint, $token);
if ($place === false) {
return (new Response(json_encode([
'error' => true,
'message' => 'Unable to create the new place',
]), 400))
->header('Content-Type', 'application/json');
}
return (new Response(json_encode([
'url' => $place,
'name' => $request->input('place-name'),
'latitude' => $request->input('place-latitude'),
'longitude' => $request->input('place-longitude'),
]), 200))
->header('Content-Type', 'application/json');
}
/**
* Actually make a micropub request to make a new place.
*
* @param \Illuminate\Http\Request $request
* @param string The Micropub endpoint to post to
* @param string The token to authenticate the request with
* @param \GuzzleHttp\Client $client
* @return \GuzzleHttp\Response $response | \Illuminate\RedirectFactory redirect
*/
private function postPlaceRequest(
Request $request,
$micropubEndpoint,
$token
) {
$formParams = [
'h' => 'card',
'name' => $request->input('place-name'),
'description' => $request->input('place-description'),
'geo' => 'geo:' . $request->input('place-latitude') . ',' . $request->input('place-longitude'),
];
$headers = [
'Authorization' => 'Bearer ' . $token,
];
try {
$response = $this->guzzleClient->request('POST', $micropubEndpoint, [
'form_params' => $formParams,
'headers' => $headers,
]);
} catch (ClientException $e) {
//not sure yet...
}
if ($response->getStatusCode() == 201) {
return $response->getHeader('Location')[0];
}
return false;
}
/**
* Make a request to the micropub endpoint requesting any nearby places.
*
* @param \Illuminate\Http\Request $request
* @param string $latitude
* @param string $longitude
* @return \Illuminate\Http\Response
*/
public function nearbyPlaces(
Request $request,
$latitude,
$longitude
) {
$domain = $request->session()->get('me');
$token = $request->session()->get('token');
$micropubEndpoint = $this->indieAuthService->discoverMicropubEndpoint($domain, $this->indieClient);
if (! $micropubEndpoint) {
return;
}
try {
$response = $this->guzzleClient->get($micropubEndpoint, [
'headers' => ['Authorization' => 'Bearer ' . $token],
'query' => ['q' => 'geo:' . $latitude . ',' . $longitude],
]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
return;
}
return (new Response($response->getBody(), 200))
->header('Content-Type', 'application/json');
}
/**
* Parse the syndication targets retreived from a cookie, to a form that can
* be used in a view.
*
* @param string $syndicationTargets
* @return array|null
*/
private function parseSyndicationTargets($syndicationTargets = null)
{
if ($syndicationTargets === null) {
return;
}
$mpSyndicateTo = [];
$parts = explode(';', $syndicationTargets);
foreach ($parts as $part) {
$target = explode('=', $part);
$mpSyndicateTo[] = urldecode($target[1]);
}
if (count($mpSyndicateTo) > 0) {
return $mpSyndicateTo;
}
}
}

View file

@ -1,130 +1,143 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exceptions\InvalidTokenScopeException;
use App\Exceptions\MicropubHandlerException;
use App\Http\Requests\MicropubRequest;
use App\Models\Place;
use App\Models\SyndicationTarget;
use App\Services\Micropub\MicropubHandlerRegistry;
use Illuminate\Http\JsonResponse;
use App\Place;
use Illuminate\Http\Request;
use Lcobucci\JWT\Token;
use Illuminate\Http\Response;
use App\Services\NoteService;
use App\Services\TokenService;
use App\Services\PlaceService;
class MicropubController extends Controller
{
protected MicropubHandlerRegistry $handlerRegistry;
public function __construct(MicropubHandlerRegistry $handlerRegistry)
{
$this->handlerRegistry = $handlerRegistry;
}
/**
* Respond to a POST request to the micropub endpoint.
*
* The request is initially processed by the MicropubRequest form request
* 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.
* The Token service container.
*/
public function post(MicropubRequest $request): JsonResponse
{
$type = $request->getType();
protected $tokenService;
if (! $type) {
return response()->json([
'error' => 'invalid_request',
'error_description' => 'Microformat object type is missing, for example: h-entry or h-card',
], 400);
}
/**
* The Note service container.
*/
protected $noteService;
try {
$handler = $this->handlerRegistry->getHandler($type);
$result = $handler->handle($request->getMicropubData());
/**
* The Place service container.
*/
protected $placeService;
// 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);
}
/**
* Injest the dependency.
*/
public function __construct(
TokenService $tokenService = null,
NoteService $noteService = null,
PlaceService $placeService = null
) {
$this->tokenService = $tokenService ?? new TokenService();
$this->noteService = $noteService ?? new NoteService();
$this->placeService = $placeService ?? new PlaceService();
}
/**
* Respond to a GET request to the micropub endpoint.
* This function receives an API request, verifies the authenticity
* then passes over the info to the relavent Service class.
*
* @param \Illuminate\Http\Request request
* @return \Illuminate\Http\Response
*/
public function post(Request $request)
{
$httpAuth = $request->header('Authorization');
if (preg_match('/Bearer (.+)/', $httpAuth, $match)) {
$token = $match[1];
$tokenData = $this->tokenService->validateToken($token);
if ($tokenData->hasClaim('scope')) {
$scopes = explode(' ', $tokenData->getClaim('scope'));
if (array_search('post', $scopes) !== false) {
$clientId = $tokenData->getClaim('client_id');
$type = $request->input('h');
if ($type == 'entry') {
$note = $this->noteService->createNote($request, $clientId);
$content = 'Note created at ' . $note->longurl;
return (new Response($content, 201))
->header('Location', $note->longurl);
}
if ($type == 'card') {
$place = $this->placeService->createPlace($request);
$content = 'Place created at ' . $place->longurl;
return (new Response($content, 201))
->header('Location', $place->longurl);
}
}
}
$content = http_build_query([
'error' => 'invalid_token',
'error_description' => 'The token provided is not valid or does not have the necessary scope',
]);
return (new Response($content, 400))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
$content = 'No OAuth token sent with request.';
return new Response($content, 400);
}
/**
* 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
* syndicate-to we respond with the known syndication endpoints.
* synidicate-to we respond with the known syndication endpoints.
*
* @todo Move the syndication endpoints into a .env variable
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function get(Request $request): JsonResponse
public function getEndpoint(Request $request)
{
if ($request->input('q') === 'syndicate-to') {
return response()->json([
'syndicate-to' => SyndicationTarget::all(),
$httpAuth = $request->header('Authorization');
if (preg_match('/Bearer (.+)/', $httpAuth, $match)) {
$token = $match[1];
$valid = $this->tokenService->validateToken($token);
if ($valid === null) {
return new Response('Invalid token', 400);
}
//we have a valid token, is `syndicate-to` set?
if ($request->input('q') === 'syndicate-to') {
$content = http_build_query([
'mp-syndicate-to' => 'twitter.com/jonnybarnes',
]);
return (new Response($content, 200))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
//nope, how about a geo URL?
if (substr($request->input('q'), 0, 4) === 'geo:') {
$geo = explode(':', $request->input('q'));
$latlng = explode(',', $geo[1]);
$latitude = $latlng[0];
$longitude = $latlng[1];
$places = Place::near($latitude, $longitude, 1000);
return (new Response(json_encode($places), 200))
->header('Content-Type', 'application/json');
}
//nope, just return the token
$content = http_build_query([
'me' => $valid->getClaim('me'),
'scope' => $valid->getClaim('scope'),
'client_id' => $valid->getClaim('client_id'),
]);
return (new Response($content, 200))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
$content = 'No OAuth token sent with request.';
if ($request->input('q') === 'config') {
return response()->json([
'syndicate-to' => SyndicationTarget::all(),
'media-endpoint' => route('media-endpoint'),
]);
}
if ($request->has('q') && str_starts_with($request->input('q'), 'geo:')) {
preg_match_all(
'/([0-9.\-]+)/',
$request->input('q'),
$matches
);
$distance = (count($matches[0]) === 3) ? 100 * $matches[0][2] : 1000;
$places = Place::near(
(object) ['latitude' => $matches[0][0], 'longitude' => $matches[0][1]],
$distance
)->get();
return response()->json([
'response' => 'places',
'places' => $places,
]);
}
// the default response is just to return the token data
/** @var Token $tokenData */
$tokenData = $request->input('token_data');
return response()->json([
'response' => 'token',
'token' => [
'me' => $tokenData['me'],
'scope' => $tokenData['scope'],
'client_id' => $tokenData['client_id'],
],
]);
return new Response($content, 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

@ -0,0 +1,100 @@
<?php
namespace App\Http\Controllers;
use App\Note;
use Validator;
use Illuminate\Http\Request;
use App\Services\NoteService;
class NotesAdminController extends Controller
{
/**
* Show the form to make a new note.
*
* @return \Illuminate\View\Factory view
*/
public function newNotePage()
{
return view('admin.newnote');
}
/**
* List the notes that can be edited.
*
* @return \Illuminate\View\Factory view
*/
public function listNotesPage()
{
$notes = Note::select('id', 'note')->orderBy('id', 'desc')->get();
foreach ($notes as $note) {
$note->originalNote = $note->getOriginal('note');
}
return view('admin.listnotes', ['notes' => $notes]);
}
/**
* Display the form to edit a specific note.
*
* @param string The note id
* @return \Illuminate\View\Factory view
*/
public function editNotePage($noteId)
{
$note = Note::find($noteId);
$note->originalNote = $note->getOriginal('note');
return view('admin.editnote', ['id' => $noteId, 'note' => $note]);
}
/**
* Process a request to make a new note.
*
* @param Illuminate\Http\Request $request
* @todo Sort this mess out
*/
public function createNote(Request $request)
{
$validator = Validator::make(
$request->all(),
['photo' => 'photosize'],
['photosize' => 'At least one uploaded file exceeds size limit of 5MB']
);
if ($validator->fails()) {
return redirect('/admin/note/new')
->withErrors($validator)
->withInput();
}
$note = $this->noteService->createNote($request);
return view('admin.newnotesuccess', [
'id' => $note->id,
'shorturl' => $note->shorturl,
]);
}
/**
* Process a request to edit a note. Easy since this can only be done
* from the admin CP.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\Factory view
*/
public function editNote($noteId, Request $request)
{
//update note data
$note = Note::find($noteId);
$note->note = $request->input('content');
$note->in_reply_to = $request->input('in-reply-to');
$note->save();
if ($request->input('webmentions')) {
$wmc = new WebMentionsController();
$wmc->send($note);
}
return view('admin.editnotesuccess', ['id' => $noteId]);
}
}

View file

@ -1,92 +1,240 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
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 Cache;
use Twitter;
use App\Tag;
use App\Note;
use Jonnybarnes\IndieWeb\Numbers;
/**
* @todo Need to sort out Twitter and webmentions!
*/
// Need to sort out Twitter and webmentions!
class NotesController extends Controller
{
/**
* Show all the notes. This is also the homepage.
* Show all the notes.
*
* @return \Illuminte\View\Factory view
*/
public function index(): View|Response
public function showNotes()
{
$notes = Note::latest()
->with('place', 'media', 'client')
->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');
}])->paginate(10);
$notes = Note::orderBy('id', 'desc')->with('webmentions', 'place')->simplePaginate(10);
foreach ($notes as $note) {
$replies = 0;
foreach ($note->webmentions as $webmention) {
if ($webmention->type == 'reply') {
$replies = $replies + 1;
}
}
$note->replies = $replies;
$note->twitter = $this->checkTwitterReply($note->in_reply_to);
$note->iso8601_time = $note->updated_at->toISO8601String();
$note->human_time = $note->updated_at->diffForHumans();
if ($note->location && ($note->place === null)) {
$pieces = explode(':', $note->location);
$latlng = explode(',', $pieces[0]);
$note->latitude = trim($latlng[0]);
$note->longitude = trim($latlng[1]);
if (count($pieces) == 2) {
$note->address = $pieces[1];
}
}
if ($note->place !== null) {
preg_match('/\((.*)\)/', $note->place->location, $matches);
$lnglat = explode(' ', $matches[1]);
$note->latitude = $lnglat[1];
$note->longitude = $lnglat[0];
$note->address = $note->place->name;
$note->placeLink = '/places/' . $note->place->slug;
}
$photoURLs = [];
$photos = $note->getMedia();
foreach ($photos as $photo) {
$photoURLs[] = $photo->getUrl();
}
$note->photoURLs = $photoURLs;
}
return view('notes.index', compact('notes'));
return view('allnotes', ['notes' => $notes]);
}
/**
* Show a single note.
*
* @param string The id of the note
* @return \Illuminate\View\Factory view
*/
public function show(string $urlId): View|JsonResponse|Response
public function singleNote($urlId)
{
try {
$note = Note::nb60($urlId)->with('place', 'media', 'client')
->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');
}])->firstOrFail();
} catch (ModelNotFoundException $exception) {
abort(404);
$numbers = new Numbers();
$realId = $numbers->b60tonum($urlId);
$note = Note::find($realId);
$replies = [];
$reposts = [];
$likes = [];
foreach ($note->webmentions as $webmention) {
switch ($webmention->type) {
case 'reply':
$content = unserialize($webmention->content);
$content['source'] = $this->bridgyReply($webmention->source);
$content['photo'] = $this->createPhotoLink($content['photo']);
$content['date'] = $carbon->parse($content['date'])->toDayDateTimeString();
$replies[] = $content;
break;
case 'repost':
$content = unserialize($webmention->content);
$content['photo'] = $this->createPhotoLink($content['photo']);
$content['date'] = $carbon->parse($content['date'])->toDayDateTimeString();
$reposts[] = $content;
break;
case 'like':
$content = unserialize($webmention->content);
$content['photo'] = $this->createPhotoLink($content['photo']);
$likes[] = $content;
break;
}
}
$note->twitter = $this->checkTwitterReply($note->in_reply_to);
$note->iso8601_time = $note->updated_at->toISO8601String();
$note->human_time = $note->updated_at->diffForHumans();
if ($note->location && ($note->place === null)) {
$pieces = explode(':', $note->location);
$latlng = explode(',', $pieces[0]);
$note->latitude = trim($latlng[0]);
$note->longitude = trim($latlng[1]);
if (count($pieces) == 2) {
$note->address = $pieces[1];
}
}
if ($note->place !== null) {
preg_match('/\((.*)\)/', $note->place->location, $matches);
$lnglat = explode(' ', $matches[1]);
$note->latitude = $lnglat[1];
$note->longitude = $lnglat[0];
$note->address = $note->place->name;
$note->placeLink = '/places/' . $note->place->slug;
}
return view('notes.show', compact('note'));
$note->photoURLs = [];
foreach ($note->getMedia() as $photo) {
$note->photoURLs[] = $photo->getUrl();
}
return view('singlenote', [
'note' => $note,
'replies' => $replies,
'reposts' => $reposts,
'likes' => $likes,
]);
}
/**
* Redirect /note/{decID} to /notes/{nb60id}.
*
* @param string The decimal id of he note
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function redirect(int $decId): RedirectResponse
public function singleNoteRedirect($decId)
{
return redirect(config('app.url') . '/notes/' . (new Numbers)->numto60($decId));
$numbers = new Numbers();
$realId = $numbers->numto60($decId);
$url = config('app.url') . '/notes/' . $realId;
return redirect($url);
}
/**
* Show all notes tagged with {tag}.
*
* @param string The tag
* @return \Illuminate\View\Factory view
*/
public function tagged(string $tag): View
public function taggedNotes($tag)
{
$notes = Note::whereHas('tags', function ($query) use ($tag) {
$query->where('tag', $tag);
})->get();
$tagId = Tag::where('tag', $tag)->pluck('id');
$notes = Tag::find($tagId)->notes()->orderBy('updated_at', 'desc')->get();
foreach ($notes as $note) {
$note->iso8601_time = $note->updated_at->toISO8601String();
$note->human_time = $note->updated_at->diffForHumans();
}
return view('notes.tagged', compact('notes', 'tag'));
return view('taggednotes', ['notes' => $notes, 'tag' => $tag]);
}
/**
* Page to create a new note.
* Swap a brid.gy URL shim-ing a twitter reply to a real twitter link.
*
* Dummy page for now.
* @param string
* @return string
*/
public function create(): View
public function bridgyReply($source)
{
return view('notes.create');
$url = $source;
if (mb_substr($source, 0, 28, 'UTF-8') == 'https://brid-gy.appspot.com/') {
$parts = explode('/', $source);
$tweetId = array_pop($parts);
if ($tweetId) {
$url = 'https://twitter.com/_/status/' . $tweetId;
}
}
return $url;
}
/**
* Create the photo link.
*
* @param string
* @return string
*/
public function createPhotoLink($url)
{
$host = parse_url($url)['host'];
if ($host != 'twitter.com' && $host != 'pbs.twimg.com') {
return '/assets/profile-images/' . $host . '/image';
}
if (mb_substr($url, 0, 20) == 'http://pbs.twimg.com') {
return str_replace('http://', 'https://', $url);
}
}
/**
* Twitter!!!
*
* @param string The reply to URL
* @return string | null
*/
private function checkTwitterReply($url)
{
if ($url == null) {
return;
}
if (mb_substr($url, 0, 20, 'UTF-8') !== 'https://twitter.com/') {
return;
}
$arr = explode('/', $url);
$tweetId = end($arr);
if (Cache::has($tweetId)) {
return Cache::get($tweetId);
}
try {
$oEmbed = Twitter::getOembed([
'id' => $tweetId,
'align' => 'center',
'omit_script' => true,
'maxwidth' => 550,
]);
} catch (\Exception $e) {
return;
}
Cache::put($tweetId, $oEmbed, ($oEmbed->cache_age / 60));
return $oEmbed;
}
}

View file

@ -0,0 +1,94 @@
<?php
namespace App\Http\Controllers;
use App\Note;
use Imagine\Image\Box;
use Imagine\Gd\Imagine;
use Illuminate\Http\Request;
use Illuminate\Filesystem\Filesystem;
class PhotosController extends Controller
{
/**
* Image box size limit for resizing photos.
*/
public function __construct()
{
$this->imageResizeLimit = 800;
}
/**
* Save an uploaded photo to the image folder.
*
* @param \Illuminate\Http\Request $request
* @param string The associated notes nb60 ID
* @return bool
*/
public function saveImage(Request $request, $nb60id)
{
if ($request->hasFile('photo') !== true) {
return false;
}
$photoFilename = 'note-' . $nb60id;
$path = public_path() . '/assets/img/notes/';
$ext = $request->file('photo')->getClientOriginalExtension();
$photoFilename .= '.' . $ext;
$request->file('photo')->move($path, $photoFilename);
return true;
}
/**
* Prepare a photo for posting to twitter.
*
* @param string photo fileanme
* @return string small photo filename, or null
*/
public function makeSmallPhotoForTwitter($photoFilename)
{
$imagine = new Imagine();
$orig = $imagine->open(public_path() . '/assets/img/notes/' . $photoFilename);
$size = [$orig->getSize()->getWidth(), $orig->getSize()->getHeight()];
if ($size[0] > $this->imageResizeLimit || $size[1] > $this->imageResizeLimit) {
$filenameParts = explode('.', $photoFilename);
$preExt = count($filenameParts) - 2;
$filenameParts[$preExt] .= '-small';
$photoFilenameSmall = implode('.', $filenameParts);
$aspectRatio = $size[0] / $size[1];
$box = ($aspectRatio >= 1) ?
[$this->imageResizeLimit, (int) round($this->imageResizeLimit / $aspectRatio)]
:
[(int) round($this->imageResizeLimit * $aspectRatio), $this->imageResizeLimit];
$orig->resize(new Box($box[0], $box[1]))
->save(public_path() . '/assets/img/notes/' . $photoFilenameSmall);
return $photoFilenameSmall;
}
}
/**
* Get the image path for a note.
*
* @param string $nb60id
* @return string | null
*/
public function getPhotoPath($nb60id)
{
$filesystem = new Filesystem();
$photoDir = public_path() . '/assets/img/notes';
$files = $filesystem->files($photoDir);
foreach ($files as $file) {
$parts = explode('.', $file);
$name = $parts[0];
$dirs = explode('/', $name);
$actualname = last($dirs);
if ($actualname == 'note-' . $nb60id) {
$ext = $parts[1];
}
}
if (isset($ext)) {
return '/assets/img/notes/note-' . $nb60id . '.' . $ext;
}
}
}

View file

@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Place;
use Illuminate\Http\Request;
use Phaza\LaravelPostgis\Geometries\Point;
class PlacesAdminController extends Controller
{
/**
* List the places that can be edited.
*
* @return \Illuminate\View\Factory view
*/
public function listPlacesPage()
{
$places = Place::all();
return view('admin.listplaces', ['places' => $places]);
}
/**
* Show the form to make a new place.
*
* @return \Illuminate\View\Factory view
*/
public function newPlacePage()
{
return view('admin.newplace');
}
/**
* Display the form to edit a specific place.
*
* @param string The place id
* @return \Illuminate\View\Factory view
*/
public function editPlacePage($placeId)
{
$place = Place::findOrFail($placeId);
$latitude = $place->getLatitude();
$longitude = $place->getLongitude();
return view('admin.editplace', [
'id' => $placeId,
'name' => $place->name,
'description' => $place->description,
'latitude' => $latitude,
'longitude' => $longitude,
]);
}
/**
* Process a request to make a new place.
*
* @param Illuminate\Http\Request $request
* @return Illuminate\View\Factory view
*/
public function createPlace(Request $request)
{
$this->placeService->createPlace($request);
return view('admin.newplacesuccess');
}
/**
* Process a request to edit a place.
*
* @param string The place id
* @param Illuminate\Http\Request $request
* @return Illuminate\View\Factory view
*/
public function editPlace($placeId, Request $request)
{
$place = Place::findOrFail($placeId);
$place->name = $request->name;
$place->description = $request->description;
$place->location = new Point((float) $request->latitude, (float) $request->longitude);
$place->save();
return view('admin.editplacesuccess');
}
}

View file

@ -1,18 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Place;
use Illuminate\View\View;
use App\Place;
use Illuminate\Http\Request;
class PlacesController extends Controller
{
/**
* Show all the places.
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
public function index()
{
$places = Place::all();
@ -20,10 +20,70 @@ class PlacesController extends Controller
}
/**
* Show a specific place.
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function show(Place $place): View
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param string $slug
* @return \Illuminate\Http\Response
*/
public function show($slug)
{
$place = Place::where('slug', '=', $slug)->first();
return view('singleplace', ['place' => $place]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

View file

@ -1,34 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\Note;
use Illuminate\Http\Request;
use Illuminate\View\View;
class SearchController extends Controller
{
public function search(Request $request): View
{
$search = $request->input('q');
$notes = Note::search($search)
->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,120 @@
<?php
namespace App\Http\Controllers;
use App\ShortURL;
use Jonnybanres\IndieWeb\Numbers;
class ShortURLsController extends Controller
{
/*
|--------------------------------------------------------------------------
| Short URL Controller
|--------------------------------------------------------------------------
|
| This redirects the short urls to long ones
|
*/
/**
* Redirect from '/' to the long url.
*
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function baseURL()
{
return redirect(config('app.url'));
}
/**
* Redirect from '/@' to a twitter profile.
*
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function twitter()
{
return redirect('https://twitter.com/jonnybarnes');
}
/**
* Redirect from '/+' to a Google+ profile.
*
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function googlePLus()
{
return redirect('https://plus.google.com/u/0/117317270900655269082/about');
}
/**
* Redirect from '/α' to an App.net profile.
*
* @return \Illuminate\Routing\Redirector redirect
*/
public function appNet()
{
return redirect('https://alpha.app.net/jonnybarnes');
}
/**
* 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\Routing\Redirector redirect
*/
public function expandType($type, $postId)
{
if ($type == 't') {
$type = 'notes';
}
if ($type == 'b') {
$type = 'blog/s';
}
return redirect(config('app.url') . '/' . $type . '/' . $postId);
}
/**
* Redirect a saved short URL, this is generic.
*
* @param string The short URL id
* @return \Illuminate\Routing\Redirector redirect
*/
public function redirect($shortURLId)
{
$numbers = new Numbers();
$num = $numbers->b60tonum($shortURLId);
$shorturl = ShortURL::find($num);
$redirect = $shorturl->redirect;
return redirect($redirect);
}
/**
* I had an old redirect systme breifly, but cool URLs should still work.
*
* @param string URL ID
* @return \Illuminate\Routing\Redirector redirect
*/
public function oldRedirect($shortURLId)
{
$filename = base_path() . '/public/assets/old-shorturls.json';
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
$object = json_decode($contents);
foreach ($object as $key => $val) {
if ($shortURLId == $key) {
return redirect($val);
}
}
return 'This id was never used.
Old redirects are located at
<code>
<a href="https://jonnybarnes.net/assets/old-shorturls.json">old-shorturls.json</a>
</code>.';
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers;
use App\Services\TokenService;
class TokensController extends Controller
{
/**
* The token service container.
*
* @var string
*/
protected $tokenService;
/**
* Inject the service dependency.
*
* @return void
*/
public function __construct(TokenService $tokenService = null)
{
$this->tokenService = $tokenService ?? new TokenService();
}
/**
* Show all the saved tokens.
*
* @return \Illuminate\View\Factory view
*/
public function showTokens()
{
$tokens = $$his->tokenService->getAll();
return view('admin.listtokens', ['tokens' => $tokens]);
}
/**
* Show the form to delete a certain token.
*
* @param string The token id
* @return \Illuminate\View\Factory view
*/
public function deleteToken($tokenId)
{
return view('admin.deletetoken', ['id' => $tokenId]);
}
/**
* Process the request to delete a token.
*
* @param string The token id
* @return \Illuminate\View\Factory view
*/
public function postDeleteToken($tokenId)
{
$this->tokenService->deleteToken($tokenId);
return view('admin.deletetokensuccess', ['id' => $tokenId]);
}
}

View file

@ -1,72 +1,100 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Jobs\ProcessWebMention;
use App\Models\Note;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Note;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
use App\Jobs\SendWebMentions;
use App\Jobs\ProcessWebMention;
use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class WebMentionsController extends Controller
{
/**
* Response to a GET request to the webmention endpoint.
*
* This is probably someone looking for information about what
* webmentions are, or about my particular implementation.
*/
public function get(): View
{
return view('webmention-endpoint');
}
/**
* Receive and process a webmention.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Respone
*/
public function receive(Request $request): Response
public function receive(Request $request)
{
// 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)) {
return response(
return new Response(
'You need both the target and source parameters',
400
);
}
// next check the $target is valid
$path = parse_url($request->input('target'), PHP_URL_PATH);
//next check the $target is valid
$path = parse_url($request->input('target'))['path'];
$pathParts = explode('/', $path);
if ($pathParts[1] === 'notes') {
// we have a note
$noteId = $pathParts[2];
try {
$note = Note::findOrFail(resolve(Numbers::class)->b60tonum($noteId));
dispatch(new ProcessWebMention($note, $request->input('source')));
} catch (ModelNotFoundException $e) {
return response('This note doesnt exist.', 400);
}
switch ($pathParts[1]) {
case 'notes':
//we have a note
$noteId = $pathParts[2];
$numbers = new Numbers();
$realId = $numbers->b60tonum($noteId);
try {
$note = Note::findOrFail($realId);
$this->dispatch(new ProcessWebMention($note, $request->input('source')));
} catch (ModelNotFoundException $e) {
return new Response('This note doesnt exist.', 400);
}
return response(
'Webmention received, it will be processed shortly',
202
);
return new Response(
'Webmention received, it will be processed shortly',
202
);
break;
case 'blog':
return new Response(
'I dont accept webmentions for blog posts yet.',
501
);
break;
default:
return new Response(
'Invalid request',
400
);
break;
}
if ($pathParts[1] === 'blog') {
return response(
'I dont accept webmentions for blog posts yet.',
501
);
}
/**
* Send a webmention.
*
* @param \App\Note $note
* @return array An array of successful then failed URLs
*/
public function send(Note $note)
{
//grab the URLs
$urlsInReplyTo = explode(' ', $note->in_reply_to);
$urlsNote = $this->getLinks($note->note);
$urls = array_filter(array_merge($urlsInReplyTo, $urlsNote)); //filter out none URLs
foreach ($urls as $url) {
$this->dispatch(new SendWebMentions($url, $note->longurl));
}
}
/**
* Get the URLs from a note.
*/
private function getLinks($html)
{
$urls = [];
$dom = new \DOMDocument();
$dom->loadHTML($html);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$urls[] = ($anchor->hasAttribute('href')) ? $anchor->getAttribute('href') : false;
}
return response(
'Invalid request',
400
);
return $urls;
}
}

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

@ -0,0 +1,55 @@
<?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 = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::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\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\LinkHeadersMiddleware::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* 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,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'myauth' => \App\Http\Middleware\MyAuthMiddleware::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

View file

@ -2,19 +2,29 @@
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Closure;
use Illuminate\Support\Facades\Auth;
/**
* @codeCoverageIgnore
*/
class Authenticate extends Middleware
class Authenticate
{
/**
* Get the path the user should be redirected to when they are not authenticated.
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
protected function redirectTo(Request $request): ?string
public function handle($request, Closure $next, $guard = null)
{
return $request->expectsJson() ? null : route('login');
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}

View file

@ -1,29 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CorsHeaders
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
if ($request->path() === 'api/media') {
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Methods', 'OPTIONS, POST');
$response->header(
'Access-Control-Allow-Headers',
'Authorization, Content-Type, DNT, X-CSRF-TOKEN, X-REQUESTED-WITH'
);
$response->header('Access-Control-Allow-Credentials', 'true');
}
return $response;
}
}

View file

@ -2,14 +2,14 @@
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends Middleware
class EncryptCookies extends BaseEncrypter
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
* @var array
*/
protected $except = [
//

View file

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

View file

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class LocalhostSessionMiddleware
{
/**
* Whilst we are developing locally, automatically log in as
* `['me' => config('app.url')]` as I cant manually log in as
* a .localhost domain.
*/
public function handle(Request $request, Closure $next): Response
{
if (config('app.env') !== 'production') {
session(['me' => config('app.url')]);
}
return $next($request);
}
}

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

@ -1,25 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class MyAuthMiddleware
{
/**
* 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, Closure $next)
{
if (Auth::check() === false) {
// theyre not logged in, so send them to login form
redirect()->setIntendedUrl($request->fullUrl());
if ($request->session()->has('loggedin') !== true) {
//theyre not logged in, so send them to login form
return redirect()->route('login');
}

View file

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

View file

@ -2,30 +2,23 @@
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
/**
* @codeCoverageIgnore
*/
class RedirectIfAuthenticated
{
/**
* 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;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);

View file

@ -1,19 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'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

@ -1,28 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The header that should be used to detect proxies.
*
* @var int
*/
protected $headers =
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

@ -2,20 +2,19 @@
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends Middleware
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
* @var array
*/
protected $except = [
'api/media',
'api/post',
'api/token',
'micropub/places',
'api/post',
'webmention',
'places/new',
];
}

View file

@ -1,81 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Http\Responses\MicropubResponses;
use Closure;
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
{
/**
* Handle an incoming request.
*
* @param Closure(Request): (Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$rawToken = null;
if ($request->input('access_token')) {
$rawToken = $request->input('access_token');
} elseif ($request->bearerToken()) {
$rawToken = $request->bearerToken();
}
if (! $rawToken) {
return response()->json([
'response' => 'error',
'error' => 'unauthorized',
'error_description' => 'No access token was provided in the request',
], 401);
}
try {
$tokenData = $this->validateToken($rawToken);
} catch (RequiredConstraintsViolated|InvalidTokenStructure|CannotDecodeContent) {
$micropubResponses = new MicropubResponses;
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

@ -0,0 +1,10 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
//
}

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);
}
}

150
app/Http/routes.php Normal file
View file

@ -0,0 +1,150 @@
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['domain' => config('url.longurl')], function () {
//Static homepage
Route::get('/', function () {
return view('homepage');
});
//Static project page
Route::get('projects', function () {
return view('projects');
});
//The login routes to get authe'd for admin
Route::get('login', ['as' => 'login', function () {
return view('login');
}]);
Route::post('login', 'AuthController@login');
//Admin pages grouped for filter
Route::group(['middleware' => 'myauth'], function () {
Route::get('admin', 'AdminController@showWelcome');
//Articles
Route::get('admin/blog/new', 'ArticlesAdminController@newArticle');
Route::get('admin/blog/edit', 'ArticlesAdminController@listArticles');
Route::get('admin/blog/edit/{id}', 'ArticlesAdminController@editArticle');
Route::get('admin/blog/delete/{id}', 'ArticlesAdminController@deleteArticle');
Route::post('admin/blog/new', 'ArticlesAdminController@postNewArticle');
Route::post('admin/blog/edit/{id}', 'ArticlesAdminController@postEditArticle');
Route::post('admin/blog/delete/{id}', 'ArticlesAdminController@postDeleteArticle');
//Notes
Route::get('admin/note/new', 'NotesAdminController@newNotePage');
Route::get('admin/note/edit', 'NotesAdminController@listNotesPage');
Route::get('admin/note/edit/{id}', 'NotesAdminController@editNotePage');
Route::post('admin/note/new', 'NotesAdminController@createNote');
Route::post('admin/note/edit/{id}', 'NotesAdminController@editNote');
//Tokens
Route::get('admin/tokens', 'TokensController@showTokens');
Route::get('admin/tokens/delete/{id}', 'TokensController@deleteToken');
Route::post('admin/tokens/delete/{id}', 'TokensController@postDeleteToken');
//Micropub Clients
Route::get('admin/clients', 'ClientsAdminController@listClients');
Route::get('admin/clients/new', 'ClientsAdminController@newClient');
Route::get('admin/clients/edit/{id}', 'ClientsAdminController@editClient');
Route::post('admin/clients/new', 'ClientsAdminController@postNewClient');
Route::post('admin/clients/edit/{id}', 'ClientsAdminController@postEditClient');
//Contacts
Route::get('admin/contacts/new', 'ContactsAdminController@newContact');
Route::get('admin/contacts/edit', 'ContactsAdminController@listContacts');
Route::get('admin/contacts/edit/{id}', 'ContactsAdminController@editContact');
Route::get('admin/contacts/edit/{id}/getavatar', 'ContactsAdminController@getAvatar');
Route::get('admin/contacts/delete/{id}', 'ContactsAdminController@deleteContact');
Route::post('admin/contacts/new', 'ContactsAdminController@postNewContact');
Route::post('admin/contacts/edit/{id}', 'ContactsAdminController@postEditContact');
Route::post('admin/contacts/delete/{id}', 'ContactsAdminController@postDeleteContact');
//Places
Route::get('admin/places/new', 'PlacesAdminController@newPlacePage');
Route::get('admin/places/edit', 'PlacesAdminController@listPlacesPage');
Route::get('admin/places/edit/{id}', 'PlacesAdminController@editPlacePage');
Route::post('admin/places/new', 'PlacesAdminController@createPlace');
Route::post('admin/places/edit/{id}', 'PlacesAdminController@editPlace');
});
//Blog pages using ArticlesController
Route::get('blog/s/{id}', 'ArticlesController@onlyIdInURL');
Route::get('blog/{year?}/{month?}', 'ArticlesController@showAllArticles');
Route::get('blog/{year}/{month}/{slug}', 'ArticlesController@singleArticle');
//micropub new notes page
//this needs to be first so `notes/new` doesn't match `notes/{id}`
Route::get('notes/new', 'MicropubClientController@newNotePage');
Route::post('notes/new', 'MicropubClientController@postNewNote');
//Notes pages using NotesController
Route::get('notes', 'NotesController@showNotes');
Route::get('note/{id}', 'NotesController@singleNoteRedirect');
Route::get('notes/{id}', 'NotesController@singleNote');
Route::get('notes/tagged/{tag}', 'NotesController@taggedNotes');
//indieauth
Route::any('beginauth', 'IndieAuthController@beginauth');
Route::get('indieauth', 'IndieAuthController@indieauth');
Route::post('api/token', 'IndieAuthController@tokenEndpoint');
Route::get('logout', 'IndieAuthController@indieauthLogout');
//micropub endoints
Route::post('api/post', 'MicropubController@post');
Route::get('api/post', 'MicropubController@getEndpoint');
//micropub refresh syndication targets
Route::get('refresh-syndication-targets', 'MicropubClientController@refreshSyndicationTargets');
//webmention
Route::get('webmention', function () {
return view('webmention-endpoint');
});
Route::post('webmention', 'WebMentionsController@receive');
//Contacts
Route::get('contacts', 'ContactsController@showAll');
Route::get('contacts/{nick}', 'ContactsController@showSingle');
//Places
Route::get('places', 'PlacesController@index');
Route::get('places/{slug}', 'PlacesController@show');
//Places micropub
Route::get('places/near/{lat}/{lng}', 'MicropubClientController@nearbyPlaces');
Route::post('places/new', 'MicropubClientController@postNewPlace');
Route::get('feed', 'ArticlesController@makeRSS');
});
//Short URL
Route::group(['domain' => config('url.shorturl')], function () {
Route::get('/', 'ShortURLsController@baseURL');
Route::get('@', 'ShortURLsController@twitter');
Route::get('+', 'ShortURLsController@googlePlus');
Route::get('α', 'ShortURLsController@appNet');
Route::get('{type}/{id}', 'ShortURLsController@expandType')->where(
[
'type' => '[bt]',
'id' => '[0-9A-HJ-NP-Z_a-km-z]+',
]
);
Route::get('h/{id}', 'ShortURLsController@redirect');
Route::get('{id}', 'ShortURLsController@oldRedirect')->where(
[
'id' => '[0-9A-HJ-NP-Z_a-km-z]{4}',
]
);
});

View file

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

View file

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

21
app/Jobs/Job.php Normal file
View file

@ -0,0 +1,21 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
abstract class Job
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "onQueue" and "delay" queue helper methods.
|
*/
use Queueable;
}

View file

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

View file

@ -1,105 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Like;
use Codebird\Codebird;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
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\Arr;
use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
class ProcessLike implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
protected Like $like
) {}
/**
* Execute the job.
*
* @throws GuzzleException
*/
public function handle(Client $client, Authorship $authorship): int
{
if ($this->isTweet($this->like->url)) {
$codebird = resolve(Codebird::class);
$tweet = $codebird->statuses_oembed(['url' => $this->like->url]);
$this->like->author_name = $tweet->author_name;
$this->like->author_url = $tweet->author_url;
$this->like->content = $tweet->html;
$this->like->save();
// POSSE like
try {
$client->request(
'POST',
'https://brid.gy/publish/webmention',
[
'form_params' => [
'source' => $this->like->url,
'target' => 'https://brid.gy/publish/twitter',
],
]
);
} catch (RequestException) {
return 0;
}
return 0;
}
$response = $client->request('GET', $this->like->url);
$mf2 = \Mf2\parse((string) $response->getBody(), $this->like->url);
if (Arr::has($mf2, 'items.0.properties.content')) {
$this->like->content = $mf2['items'][0]['properties']['content'][0]['html'];
}
try {
$author = $authorship->findAuthor($mf2);
if (is_array($author)) {
$this->like->author_name = Arr::get($author, 'properties.name.0');
$this->like->author_url = Arr::get($author, 'properties.url.0');
}
if (is_string($author) && $author !== '') {
$this->like->author_name = $author;
}
} catch (AuthorshipParserException $exception) {
return 1;
}
$this->like->save();
return 0;
}
/**
* Determine if a given URL is that of a Tweet.
*/
private function isTweet(string $url): bool
{
$host = parse_url($url, PHP_URL_HOST);
$parts = array_reverse(explode('.', $host));
return $parts[0] === 'com' && $parts[1] === 'twitter';
}
}

View file

@ -1,69 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
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 Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\ImageManager;
class ProcessMedia implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
protected string $filename
) {}
/**
* Execute the job.
*/
public function handle(ImageManager $manager): void
{
// Load file
$file = Storage::disk('local')->get('media/' . $this->filename);
// Open file
try {
$image = $manager->read($file);
} catch (DecoderException) {
// not an image; delete file and end job
Storage::disk('local')->delete('media/' . $this->filename);
return;
}
// Save the file publicly
Storage::disk('public')->put('media/' . $this->filename, $file);
// Create smaller versions if necessary
if ($image->width() > 1000) {
$filenameParts = explode('.', $this->filename);
$extension = array_pop($filenameParts);
// the following achieves this data flow
// foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar
$basename = trim(implode('.', $filenameParts), '.');
$medium = $image->resize(width: 1000);
Storage::disk('public')->put('media/' . $basename . '-medium.' . $extension, (string) $medium->encode());
$small = $image->resize(width: 500);
Storage::disk('public')->put('media/' . $basename . '-small.' . $extension, (string) $small->encode());
}
// Now we can delete the locally saved image
Storage::disk('local')->delete('media/' . $this->filename);
}
}

View file

@ -1,122 +1,256 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Exceptions\RemoteContentNotFoundException;
use App\Models\Note;
use App\Models\WebMention;
use App\Note;
use Mf2\parse;
use HTMLPurifier;
use App\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 HTMLPurifier_Config;
use Illuminate\Queue\SerializesModels;
use Jonnybarnes\WebmentionsParser\Exceptions\InvalidMentionException;
use Illuminate\Queue\InteractsWithQueue;
use Jonnybarnes\WebmentionsParser\Parser;
use Mf2;
use Illuminate\Contracts\Queue\ShouldQueue;
class ProcessWebMention implements ShouldQueue
class ProcessWebMention extends Job implements ShouldQueue
{
use InteractsWithQueue;
use Queueable;
use SerializesModels;
use InteractsWithQueue, SerializesModels;
protected $note;
protected $source;
/**
* Create a new job instance.
*
* @param \App\Note $note
* @param string $source
* @return void
*/
public function __construct(
protected Note $note,
protected string $source
) {}
public function __construct(Note $note, $source)
{
$this->note = $note;
$this->source = $source;
}
/**
* Execute the job.
*
* @throws RemoteContentNotFoundException
* @throws GuzzleException
* @throws InvalidMentionException
* @param \Jonnybarnes\WebmentionsParser\Parser $parser
* @return void
*/
public function handle(Parser $parser, Client $guzzle): void
public function handle(Parser $parser)
{
try {
$response = $guzzle->request('GET', $this->source);
} catch (RequestException $e) {
throw new RemoteContentNotFoundException;
$sourceURL = parse_url($this->source);
$baseURL = $sourceURL['scheme'] . '://' . $sourceURL['host'];
$remoteContent = $this->getRemoteContent($this->source);
$microformats = $this->parseHTML($remoteContent, $baseURL);
$count = WebMention::where('source', '=', $this->source)->count();
if ($count > 0) {
//we already have a webmention from this source
$webmentions = WebMention::where('source', '=', $this->source)->get();
foreach ($webmentions as $webmention) {
//now check it still 'mentions' this target
//we switch for each type of mention (reply/like/repost)
switch ($webmention->type) {
case 'reply':
if ($parser->checkInReplyTo($microformats, $note->longurl) == false) {
//it doesn't so delete
$webmention->delete();
return true;
}
//webmenion is still a reply, so update content
$content = $parser->replyContent($microformats);
$this->saveImage($content);
$content['reply'] = $this->filterHTML($content['reply']);
$content = serialize($content);
$webmention->content = $content;
$webmention->save();
return true;
break;
case 'like':
if ($parser->checkLikeOf($microformats, $note->longurl) == false) {
//it doesn't so delete
$webmention->delete();
return true;
} //note we don't need to do anything if it still is a like
break;
case 'repost':
if ($parser->checkRepostOf($microformats, $note->longurl) == false) {
//it doesn't so delete
$webmention->delete();
return true;
} //again, we don't need to do anything if it still is a repost
break;
}//switch
}//foreach
}//if
//no wemention in db so create new one
$webmention = new WebMention();
//check it is in fact a reply
if ($parser->checkInReplyTo($microformats, $note->longurl)) {
$content = $parser->replyContent($microformats);
$this->saveImage($content);
$content['reply'] = $this->filterHTML($content['reply']);
$content = serialize($content);
$webmention->source = $this->source;
$webmention->target = $note->longurl;
$webmention->commentable_id = $this->note->id;
$webmention->commentable_type = 'App\Note';
$webmention->type = 'reply';
$webmention->content = $content;
$webmention->save();
return true;
} elseif ($parser->checkLikeOf($microformats, $note->longurl)) {
//it is a like
$content = $parser->likeContent($microformats);
$this->saveImage($content);
$content = serialize($content);
$webmention->source = $this->source;
$webmention->target = $note->longurl;
$webmention->commentable_id = $this->note->id;
$webmention->commentable_type = 'App\Note';
$webmention->type = 'like';
$webmention->content = $content;
$webmention->save();
return true;
} elseif ($parser->checkRepostOf($microformats, $note->longurl)) {
//it is a repost
$content = $parser->repostContent($microformats);
$this->saveImage($content);
$content = serialize($content);
$webmention->source = $this->source;
$webmention->target = $note->longurl;
$webmention->commentable_id = $this->note->id;
$webmention->commentable_type = 'App\Note';
$webmention->type = 'repost';
$webmention->content = $content;
$webmention->save();
return true;
}
$this->saveRemoteContent((string) $response->getBody(), $this->source);
$microformats = Mf2\parse((string) $response->getBody(), $this->source);
$webmentions = WebMention::where('source', $this->source)->get();
foreach ($webmentions as $webmention) {
// check webmention still references target
// we try each type of mention (reply/like/repost)
if ($webmention->type === 'in-reply-to') {
if ($parser->checkInReplyTo($microformats, $this->note->uri) === false) {
// it doesnt so delete
$webmention->delete();
return;
}
// webmention is still a reply, so update content
dispatch(new SaveProfileImage($microformats));
$webmention->mf2 = json_encode($microformats);
$webmention->save();
return;
}
if ($webmention->type === 'like-of') {
if ($parser->checkLikeOf($microformats, $this->note->uri) === false) {
// it doesnt so delete
$webmention->delete();
return;
} // note we dont need to do anything if it still is a like
}
if ($webmention->type === 'repost-of') {
if ($parser->checkRepostOf($microformats, $this->note->uri) === false) {
// it doesnt so delete
$webmention->delete();
return;
} // again, we dont need to do anything if it still is a repost
}
}// foreach
// no webmention in the db so create new one
$webmention = new WebMention;
$type = $parser->getMentionType($microformats); // throw error here?
dispatch(new SaveProfileImage($microformats));
$webmention->source = $this->source;
$webmention->target = $this->note->uri;
$webmention->commentable_id = $this->note->id;
$webmention->commentable_type = Note::class;
$webmention->type = $type;
$webmention->mf2 = json_encode($microformats);
$webmention->save();
}
/**
* Save the HTML of a webmention for future use.
* Retreive the remote content from a URL, and caches the result.
*
* @param string The URL to retreive content from
* @return string The HTML from the URL
*/
private function saveRemoteContent(string $html, string $url): void
private function getRemoteContent($url)
{
$filenameFromURL = str_replace(
['https://', 'http://'],
['https/', 'http/'],
$url
);
if (str_ends_with($url, '/')) {
$filenameFromURL .= 'index.html';
$client = new Client();
$response = $client->get($url);
$html = (string) $response->getBody();
$path = storage_path() . '/HTML/' . $this->createFilenameFromURL($url);
$this->fileForceContents($path, $html);
return $html;
}
/**
* 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($url)
{
$url = str_replace(['https://', 'http://'], ['', ''], $url);
if (substr($url, -1) == '/') {
$url = $url . 'index.html';
}
$path = storage_path() . '/HTML/' . $filenameFromURL;
$parts = explode('/', $path);
return $url;
}
/**
* Save a file, and create any necessary folders.
*
* @param string The directory to save to
* @param binary The file to save
*/
private function fileForceContents($dir, $contents)
{
$parts = explode('/', $dir);
$name = array_pop($parts);
$dir = implode('/', $parts);
if (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir));
if (! is_dir($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents("$dir/$name", $html);
file_put_contents("$dir/$name", $contents);
}
/**
* A wrapper function for php-mf2s parse method.
*
* @param string The HTML to parse
* @param string The base URL to resolve relative URLs in the HTML against
* @return array The porcessed microformats
*/
private function parseHTML($html, $baseurl)
{
$microformats = \Mf2\parse((string) $html, $baseurl);
return $microformats;
}
/**
* Save a profile image to the local cache.
*
* @param array source content
* @return bool wether image was saved or not (we dont save twitter profiles)
*/
public function saveImage(array $content)
{
$photo = $content['photo'];
$home = $content['url'];
//dont save pbs.twimg.com links
if (parse_url($photo)['host'] != 'pbs.twimg.com'
&& parse_url($photo)['host'] != 'twitter.com') {
$client = new Client();
try {
$response = $client->get($photo);
$image = $response->getBody(true);
$path = public_path() . '/assets/profile-images/' . parse_url($home)['host'] . '/image';
$this->fileForceContents($path, $image);
} catch (Exception $e) {
// we are openning and reading the default image so that
// fileForceContent work
$default = public_path() . '/assets/profile-images/default-image';
$handle = fopen($default, 'rb');
$image = fread($handle, filesize($default));
fclose($handle);
$path = public_path() . '/assets/profile-images/' . parse_url($home)['host'] . '/image';
$this->fileForceContents($path, $image);
}
return true;
}
return false;
}
/**
* Purify HTML received from a webmention.
*
* @param string The HTML to be processed
* @return string The processed HTML
*/
public function filterHTML($html)
{
$config = HTMLPurifier_Config::createDefault();
$config->set('Cache.SerializerPath', storage_path() . '/HTMLPurifier');
$purifier = new HTMLPurifier($config);
return $purifier->purify($html);
}
}

View file

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

@ -1,86 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Note;
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\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendWebMentions implements ShouldQueue
class SendWebMentions extends Job implements ShouldQueue
{
use InteractsWithQueue;
use Queueable;
use SerializesModels;
use InteractsWithQueue, SerializesModels;
protected $url;
protected $source;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(
protected Note $note
) {}
public function __construct($url, $source)
{
$this->url = $url;
$this->source = $source;
}
/**
* Execute the job.
*
* @throws GuzzleException
* @return void
*/
public function handle(): void
public function handle(Client $client)
{
$urlsInReplyTo = explode(' ', $this->note->in_reply_to ?? '');
$urlsNote = $this->getLinks($this->note->note);
$urls = array_filter(array_merge($urlsInReplyTo, $urlsNote));
foreach ($urls as $url) {
$endpoint = $this->discoverWebmentionEndpoint($url);
if ($endpoint !== null) {
$guzzle = resolve(Client::class);
$guzzle->post($endpoint, [
'form_params' => [
'source' => $this->note->uri,
'target' => $url,
],
]);
}
$endpoint = $this->discoverWebmentionEndpoint($this->url, $client);
if ($endpoint) {
$client->post($endpoint, [
'form_params' => [
'source' => $this->source,
'target' => $this->url,
],
]);
}
}
/**
* Discover if a URL has a webmention endpoint.
*
* @throws GuzzleException
* @param string The URL
* @param \GuzzleHttp\Client $client
* @return string The webmention endpoint URL
*/
public function discoverWebmentionEndpoint(string $url): ?string
private function discoverWebmentionEndpoint($url, $client)
{
// lets not send webmentions to myself
if (parse_url($url, PHP_URL_HOST) === parse_url(config('app.url'), PHP_URL_HOST)) {
return null;
}
if (Str::startsWith($url, '/notes/tagged/')) {
return null;
}
$endpoint = null;
$guzzle = resolve(Client::class);
$response = $guzzle->get($url);
// check HTTP Headers for webmention endpoint
$links = Header::parse($response->getHeader('Link'));
$response = $client->get($url);
//check HTTP Headers for webmention endpoint
$links = \GuzzleHttp\Psr7\parse_header($response->getHeader('Link'));
foreach ($links as $link) {
if (array_key_exists('rel', $link) && mb_stristr($link['rel'], 'webmention')) {
return $this->resolveUri(trim($link[0], '<>'), $url);
if ($link['rel'] == 'webmention') {
return trim($link[0], '<>');
}
}
// failed to find a header so parse HTML
//failed to find a header so parse HTML
$html = (string) $response->getBody();
$mf2 = new \Mf2\Parser($html, $url);
@ -90,47 +73,14 @@ class SendWebMentions implements ShouldQueue
} elseif (array_key_exists('http://webmention.org/', $rels[0])) {
$endpoint = $rels[0]['http://webmention.org/'][0];
}
if ($endpoint === null) {
return null;
if ($endpoint) {
if (filter_var($endpoint, FILTER_VALIDATE_URL)) {
return $endpoint;
}
//it must be a relative url, so resolve with php-mf2
return $mf2->resolveUrl($endpoint);
}
return $this->resolveUri($endpoint, $url);
}
/**
* Get the URLs from a note.
*/
public function getLinks(?string $html): array
{
if ($html === '' || is_null($html)) {
return [];
}
$urls = [];
$dom = new \DOMDocument;
$dom->loadHTML($html);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$urls[] = ($anchor->hasAttribute('href')) ? $anchor->getAttribute('href') : false;
}
return $urls;
}
/**
* Resolve a URI if necessary.
*/
public function resolveUri(string $url, string $base): string
{
$endpoint = Utils::uriFor($url);
if ($endpoint->getScheme() !== '') {
return (string) $endpoint;
}
return (string) UriResolver::resolve(
Utils::uriFor($base),
$endpoint
);
return false;
}
}

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,108 @@
<?php
namespace App\Jobs;
use Twitter;
use App\Note;
use App\Contact;
use Jonnybarnes\IndieWeb\Numbers;
use Jonnybarnes\IndieWeb\NotePrep;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SyndicateToTwitter extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $note;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Note $note)
{
$this->note = $note;
}
/**
* Execute the job.
*
* @param \Jonnybarnes\IndieWeb\Numbers $numbers
* @param \Jonnybarnes\IndieWeb\NotePrep $noteprep
* @return void
*/
public function handle(Numbers $numbers, NotePrep $noteprep)
{
$noteSwappedNames = $this->swapNames($this->note->getOriginal('note'));
$shorturl = 'https://' . config('url.shorturl') . '/t/' . $numbers->numto60($this->note->id);
$tweet = $noteprep->createNote($noteSwappedNames, $shorturl, 140, true);
$tweetOpts = ['status' => $tweet, 'format' => 'json'];
if ($this->note->in_reply_to) {
$tweetOpts['in_reply_to_status_id'] = $noteprep->replyTweetId($this->note->in_reply_to);
}
/*if ($this->note->location) {
$explode = explode(':', $this->note->location);
$location = (count($explode) == 2) ? explode(',', $explode[0]) : explode(',', $explode);
$lat = trim($location[0]);
$long = trim($location[1]);
$jsonPlaceId = Twitter::getGeoReverse(array('lat' => $lat, 'long' => $long, 'format' => 'json'));
$parsePlaceId = json_decode($jsonPlaceId);
$placeId = $parsePlaceId->result->places[0]->id ?: null;
$tweetOpts['lat'] = $lat;
$tweetOpts['long'] = $long;
if ($placeId) {
$tweetOpts['place_id'] = $placeId;
}
}*/
$mediaItems = $this->note->getMedia();
if (count($mediaItems) > 0) {
foreach ($mediaItems as $item) {
$uploadedMedia = Twitter::uploadMedia(['media' => file_get_contents($item->getUrl())]);
$mediaIds[] = $uploadedMedia->media_id_string;
}
$tweetOpts['media_ids'] = implode(',', $mediaIds);
}
$responseJson = Twitter::postTweet($tweetOpts);
$response = json_decode($responseJson);
$tweetId = $response->id;
$this->note->tweet_id = $tweetId;
$this->note->save();
}
/**
* Swap @names in a note.
*
* When a note is being saved and we are posting it to twitter, we want
* to swap our @local_name to Twitters @twitter_name so the user gets
* mentioned on Twitter.
*
* @param string $note
* @return string $noteSwappedNames
*/
private function swapNames($note)
{
$regex = '/\[.*?\](*SKIP)(*F)|@(\w+)/'; //match @alice but not [@bob](...)
$noteSwappedNames = preg_replace_callback(
$regex,
function ($matches) {
try {
$contact = Contact::where('nick', '=', mb_strtolower($matches[1]))->firstOrFail();
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return '@' . $matches[1];
}
$twitterHandle = $contact->twitter;
return '@' . $twitterHandle;
},
$note
);
return $noteSwappedNames;
}
}

1
app/Listeners/.gitkeep Normal file
View file

@ -0,0 +1 @@

View file

@ -1,131 +0,0 @@
<?php
declare(strict_types=1);
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\SoftDeletes;
use League\CommonMark\Environment\Environment;
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\MarkdownConverter;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
class Article extends Model
{
use HasFactory;
use Sluggable;
use SoftDeletes;
/** @var string */
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.
*/
public function sluggable(): array
{
return [
'titleurl' => [
'source' => 'title',
],
];
}
protected function html(): Attribute
{
return Attribute::get(
get: function () {
$environment = new Environment;
$environment->addExtension(new CommonMarkCoreExtension);
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer);
$environment->addRenderer(IndentedCode::class, new IndentedCodeRenderer);
$markdownConverter = new MarkdownConverter($environment);
return $markdownConverter->convert($this->main)->getContent();
},
);
}
protected function w3cTime(): Attribute
{
return Attribute::get(
get: fn () => $this->updated_at->toW3CString(),
);
}
protected function tooltipTime(): Attribute
{
return Attribute::get(
get: fn () => $this->updated_at->toRFC850String(),
);
}
protected function humanTime(): Attribute
{
return Attribute::get(
get: fn () => $this->updated_at->diffForHumans(),
);
}
protected function pubdate(): Attribute
{
return Attribute::get(
get: fn () => $this->updated_at->toRSSString(),
);
}
protected function link(): Attribute
{
return Attribute::get(
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.
*/
public function scopeDate(Builder $query, ?int $year = null, ?int $month = null): Builder
{
if ($year === null) {
return $query;
}
$start = $year . '-01-01 00:00:00';
$end = ($year + 1) . '-01-01 00:00:00';
if (($month !== null) && ($month !== 12)) {
$start = $year . '-' . $month . '-01 00:00:00';
$end = $year . '-' . ($month + 1) . '-01 00:00:00';
}
if ($month === 12) {
$start = $year . '-12-01 00:00:00';
$end = ($year + 1) . '-01-01 00:00:00';
}
return $query->where([
['updated_at', '>=', $start],
['updated_at', '<', $end],
]);
}
}

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;
}

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