Compare commits
29 commits
Author | SHA1 | Date | |
---|---|---|---|
054bba1da9 | |||
22e3eaab23 | |||
e0efd19ef9 | |||
0cd6f81a09 | |||
30c9b2e248 | |||
52ac67ba7a | |||
272a5ea2fd | |||
0bea4a1e95 | |||
8ec738a765 | |||
2f548725db | |||
f6546e2335 | |||
d52b8a3e83 | |||
46133be181 | |||
0faf896e8f | |||
374e231a6b | |||
729c52df2f | |||
ac19c02e76 | |||
0289f9f0b0 | |||
14a10472a6 | |||
b74bdd01ef | |||
9c059f822f | |||
75e369992d | |||
a18f7b2d03 | |||
7d1738964a | |||
77004ec7d4 | |||
3f891b580c | |||
38f3244e31 | |||
650d54292e | |||
c40548be73 |
407 changed files with 22631 additions and 13967 deletions
|
@ -1,21 +1,21 @@
|
|||
# EditorConfig is awesome: http://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
# Unix-style newlines with a newline ending every file
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 4
|
||||
indent_style = space
|
||||
charset = utf-8
|
||||
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_style = space
|
||||
indent_size = 4
|
||||
|
||||
# Tab indentation
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
tab_width = 4
|
||||
|
||||
[yml]
|
||||
indent_size = 2
|
||||
|
|
14
.env.dusk.testing
Normal file
14
.env.dusk.testing
Normal file
|
@ -0,0 +1,14 @@
|
|||
APP_ENV=testing
|
||||
APP_DEBUG=true
|
||||
APP_KEY=base64:6DJhvZLVjE6dD4Cqrteh+6Z5vZlG+v/soCKcDHLOAH0=
|
||||
APP_URL=http://localhost:8000
|
||||
APP_LONGURL=localhost
|
||||
APP_SHORTURL=local
|
||||
|
||||
DB_CONNECTION=travis
|
||||
|
||||
CACHE_DRIVER=array
|
||||
SESSION_DRIVER=file
|
||||
QUEUE_DRIVER=sync
|
||||
|
||||
SCOUT_DRIVER=pgsql
|
72
.env.example
72
.env.example
|
@ -2,22 +2,11 @@ APP_NAME=Laravel
|
|||
APP_ENV=local
|
||||
APP_KEY=
|
||||
APP_DEBUG=true
|
||||
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
|
||||
APP_LONGURL=example.com
|
||||
APP_SHORTURL=examp.le
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_STACK=single
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
|
||||
|
@ -28,30 +17,22 @@ DB_DATABASE=laravel
|
|||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
|
||||
SESSION_DRIVER=database
|
||||
SESSION_LIFETIME=120
|
||||
SESSION_ENCRYPT=false
|
||||
SESSION_PATH=/
|
||||
SESSION_DOMAIN=null
|
||||
|
||||
BROADCAST_CONNECTION=log
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_DRIVER=file
|
||||
FILESYSTEM_DISK=local
|
||||
QUEUE_CONNECTION=database
|
||||
|
||||
CACHE_STORE=database
|
||||
# CACHE_PREFIX=
|
||||
QUEUE_CONNECTION=sync
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
|
||||
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_PORT=2525
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=mailhog
|
||||
MAIL_PORT=1025
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=null
|
||||
|
@ -64,7 +45,19 @@ AWS_DEFAULT_REGION=us-east-1
|
|||
AWS_BUCKET=
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||
|
||||
VITE_APP_NAME="${APP_NAME}"
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
PUSHER_HOST=
|
||||
PUSHER_PORT=443
|
||||
PUSHER_SCHEME=https
|
||||
PUSHER_APP_CLUSTER=mt1
|
||||
|
||||
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
||||
VITE_PUSHER_HOST="${PUSHER_HOST}"
|
||||
VITE_PUSHER_PORT="${PUSHER_PORT}"
|
||||
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
|
||||
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
||||
|
||||
ADMIN_USER=admin# pick something better, this is used for `/admin`
|
||||
ADMIN_PASS=password
|
||||
|
@ -75,16 +68,21 @@ TWITTER_CONSUMER_SECRET=
|
|||
TWITTER_ACCESS_TOKEN=
|
||||
TWITTER_ACCESS_TOKEN_SECRET=
|
||||
|
||||
SCOUT_DRIVER=database
|
||||
SCOUT_QUEUE=false
|
||||
SCOUT_DRIVER=pgsql
|
||||
|
||||
SESSION_SECURE_COOKIE=true
|
||||
SESSION_SAME_SITE=strict
|
||||
PIWIK=false
|
||||
PIWIK_ID=1
|
||||
PIWIK_URL=https://analytics.jmb.lv/piwik.php
|
||||
|
||||
FATHOM_ID=
|
||||
|
||||
APP_TIMEZONE=UTC
|
||||
APP_LANG=en
|
||||
APP_LOG=daily
|
||||
SECURE_SESSION_COOKIE=true
|
||||
|
||||
LOG_SLACK_WEBHOOK_URL=
|
||||
|
||||
FLARE_KEY=
|
||||
|
||||
IGNITION_OPEN_AI_KEY=
|
||||
FONT_LINK=
|
||||
|
||||
BRIDGY_MASTODON_TOKEN=
|
||||
|
|
66
.env.github
Normal file
66
.env.github
Normal file
|
@ -0,0 +1,66 @@
|
|||
APP_NAME=Laravel
|
||||
APP_ENV=testing
|
||||
APP_KEY=SomeRandomString # Leave this
|
||||
APP_DEBUG=false
|
||||
APP_LOG_LEVEL=warning
|
||||
|
||||
DB_CONNECTION=pgsql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=5432
|
||||
DB_DATABASE=jbukdev_testing
|
||||
DB_USERNAME=postgres
|
||||
DB_PASSWORD=postgres
|
||||
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_DRIVER=file
|
||||
SESSION_DRIVER=file
|
||||
QUEUE_DRIVER=sync
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_DRIVER=smtp
|
||||
MAIL_HOST=smtp.mailtrap.io
|
||||
MAIL_PORT=2525
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=null
|
||||
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
|
||||
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
|
||||
|
||||
APP_URL=https://example.com # This one is necessary
|
||||
APP_LONGURL=example.com
|
||||
APP_SHORTURL=examp.le
|
||||
|
||||
ADMIN_USER=admin # pick something better, this is used for `/admin`
|
||||
ADMIN_PASS=password
|
||||
DISPLAY_NAME="Joe Bloggs" # This is used for example in the header and titles
|
||||
|
||||
TWITTER_CONSUMER_KEY=
|
||||
TWITTER_CONSUMER_SECRET=
|
||||
TWITTER_ACCESS_TOKEN=
|
||||
TWITTER_ACCESS_TOKEN_SECRET=
|
||||
|
||||
SCOUT_DRIVER=pgsql
|
||||
|
||||
PIWIK=false
|
||||
|
||||
FATHOM_ID=
|
||||
|
||||
APP_TIMEZONE=UTC
|
||||
APP_LANG=en
|
||||
APP_LOG=daily
|
||||
SECURE_SESSION_COOKIE=true
|
||||
|
||||
LOG_SLACK_WEBHOOK_URL=
|
||||
|
||||
FONT_LINK=
|
24
.eslintrc.yml
Normal file
24
.eslintrc.yml
Normal file
|
@ -0,0 +1,24 @@
|
|||
parserOptions:
|
||||
sourceType: 'module'
|
||||
extends: 'eslint:recommended'
|
||||
env:
|
||||
browser: true
|
||||
es6: true
|
||||
rules:
|
||||
indent:
|
||||
- error
|
||||
- 4
|
||||
linebreak-style:
|
||||
- error
|
||||
- unix
|
||||
quotes:
|
||||
- error
|
||||
- single
|
||||
semi:
|
||||
- error
|
||||
- always
|
||||
no-console:
|
||||
- error
|
||||
- allow:
|
||||
- warn
|
||||
- error
|
12
.gitattributes
vendored
12
.gitattributes
vendored
|
@ -1,7 +1,5 @@
|
|||
* 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
|
||||
*.js linguist-vendored
|
||||
CHANGELOG.md export-ignore
|
||||
|
|
12
.github/dependabot.yml
vendored
Normal file
12
.github/dependabot.yml
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
version: 2
|
||||
|
||||
updates:
|
||||
- package-ecosystem: "composer"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
142
.github/workflows/deploy.yml
vendored
Normal file
142
.github/workflows/deploy.yml
vendored
Normal file
|
@ -0,0 +1,142 @@
|
|||
name: Deploy
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy
|
||||
runs-on: ubuntu-latest
|
||||
environment: Hetzner
|
||||
env:
|
||||
repository: 'jonnybarnes/jonnybarnes.uk'
|
||||
newReleaseName: '${{ github.run_id }}'
|
||||
|
||||
steps:
|
||||
- name: 🌍 Set Environment Variables
|
||||
run: |
|
||||
echo "releasesDir=${{ secrets.DEPLOYMENT_BASE_DIR }}/releases" >> $GITHUB_ENV
|
||||
echo "persistentDir=${{ secrets.DEPLOYMENT_BASE_DIR }}/persistent" >> $GITHUB_ENV
|
||||
echo "currentDir=${{ secrets.DEPLOYMENT_BASE_DIR }}/current" >> $GITHUB_ENV
|
||||
- name: 🌎 Set Environment Variables Part 2
|
||||
run: |
|
||||
echo "newReleaseDir=${{ env.releasesDir }}/${{ env.newReleaseName }}" >> $GITHUB_ENV
|
||||
- name: 🔄 Clone Repository
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.DEPLOYMENT_HOST }}
|
||||
port: ${{ secrets.DEPLOYMENT_PORT }}
|
||||
username: ${{ secrets.DEPLOYMENT_USER }}
|
||||
key: ${{ secrets.DEPLOYMENT_KEY }}
|
||||
script: |
|
||||
[ -d ${{ env.releasesDir }} ] || mkdir ${{ env.releasesDir }}
|
||||
[ -d ${{ env.persistentDir }} ] || mkdir ${{ env.persistentDir }}
|
||||
[ -d ${{ env.persistentDir }}/storage ] || mkdir ${{ env.persistentDir }}/storage
|
||||
|
||||
cd ${{ env.releasesDir }}
|
||||
|
||||
# Create new release directory
|
||||
mkdir ${{ env.newReleaseDir }}
|
||||
|
||||
# Clone app
|
||||
git clone --depth 1 --branch ${{ github.ref_name }} https://github.com/${{ env.repository }} ${{ env.newReleaseName }}
|
||||
|
||||
# Mark release
|
||||
cd ${{ env.newReleaseDir }}
|
||||
echo "${{ env.newReleaseName }}" > public/release-name.txt
|
||||
|
||||
# Fix cache directory permissions
|
||||
sudo chown -R ${{ secrets.HTTP_USER }}:${{ secrets.HTTP_USER }} bootstrap/cache
|
||||
|
||||
- name: 🎵 Run Composer
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.DEPLOYMENT_HOST }}
|
||||
port: ${{ secrets.DEPLOYMENT_PORT }}
|
||||
username: ${{ secrets.DEPLOYMENT_USER }}
|
||||
key: ${{ secrets.DEPLOYMENT_KEY }}
|
||||
script: |
|
||||
cd ${{ env.newReleaseDir }}
|
||||
composer install --prefer-dist --no-scripts --no-dev --no-progress --optimize-autoloader --quiet --no-interaction
|
||||
|
||||
- name: 🔗 Update Symlinks
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.DEPLOYMENT_HOST }}
|
||||
port: ${{ secrets.DEPLOYMENT_PORT }}
|
||||
username: ${{ secrets.DEPLOYMENT_USER }}
|
||||
key: ${{ secrets.DEPLOYMENT_KEY }}
|
||||
script: |
|
||||
# Import the environment config
|
||||
cd ${{ env.newReleaseDir }};
|
||||
ln -nfs ${{ secrets.DEPLOYMENT_BASE_DIR }}/.env .env;
|
||||
|
||||
# Remove the storage directory and replace with persistent data
|
||||
rm -rf ${{ env.newReleaseDir }}/storage;
|
||||
cd ${{ env.newReleaseDir }};
|
||||
ln -nfs ${{ secrets.DEPLOYMENT_BASE_DIR }}/persistent/storage storage;
|
||||
|
||||
# Remove the public/profile-images directory and replace with persistent data
|
||||
rm -rf ${{ env.newReleaseDir }}/public/assets/profile-images;
|
||||
cd ${{ env.newReleaseDir }};
|
||||
ln -nfs ${{ secrets.DEPLOYMENT_BASE_DIR }}/persistent/profile-images public/assets/profile-images;
|
||||
|
||||
# Add the persistent files data
|
||||
cd ${{ env.newReleaseDir }};
|
||||
ln -nfs ${{ secrets.DEPLOYMENT_BASE_DIR }}/persistent/files public/files;
|
||||
|
||||
# Add the persistent fonts data
|
||||
cd ${{ env.newReleaseDir }};
|
||||
ln -nfs ${{ secrets.DEPLOYMENT_BASE_DIR }}/persistent/fonts public/fonts;
|
||||
|
||||
- name: ✨ Optimize Installation
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.DEPLOYMENT_HOST }}
|
||||
port: ${{ secrets.DEPLOYMENT_PORT }}
|
||||
username: ${{ secrets.DEPLOYMENT_USER }}
|
||||
key: ${{ secrets.DEPLOYMENT_KEY }}
|
||||
script: |
|
||||
cd ${{ env.newReleaseDir }};
|
||||
sudo runuser -u ${{ secrets.HTTP_USER }} -- php artisan clear-compiled;
|
||||
|
||||
- name: 🙈 Migrate database
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.DEPLOYMENT_HOST }}
|
||||
port: ${{ secrets.DEPLOYMENT_PORT }}
|
||||
username: ${{ secrets.DEPLOYMENT_USER }}
|
||||
key: ${{ secrets.DEPLOYMENT_KEY }}
|
||||
script: |
|
||||
cd ${{ env.newReleaseDir }}
|
||||
sudo runuser -u ${{ secrets.HTTP_USER }} -- php artisan migrate --force
|
||||
|
||||
- name: 🙏 Bless release
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.DEPLOYMENT_HOST }}
|
||||
port: ${{ secrets.DEPLOYMENT_PORT }}
|
||||
username: ${{ secrets.DEPLOYMENT_USER }}
|
||||
key: ${{ secrets.DEPLOYMENT_KEY }}
|
||||
script: |
|
||||
ln -nfs ${{ env.newReleaseDir }} ${{ env.currentDir }};
|
||||
cd ${{ env.newReleaseDir }}
|
||||
sudo runuser -u ${{ secrets.HTTP_USER }} -- php artisan horizon:terminate
|
||||
sudo runuser -u ${{ secrets.HTTP_USER }} -- php artisan config:cache
|
||||
sudo runuser -u ${{ secrets.HTTP_USER }} -- php artisan event:cache
|
||||
sudo runuser -u ${{ secrets.HTTP_USER }} -- php artisan route:cache
|
||||
sudo runuser -u ${{ secrets.HTTP_USER }} -- php artisan view:cache
|
||||
|
||||
sudo systemctl restart php-fpm.service
|
||||
sudo systemctl restart jbuk-horizon.service
|
||||
|
||||
- name: 🚾 Clean up old releases
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.DEPLOYMENT_HOST }}
|
||||
port: ${{ secrets.DEPLOYMENT_PORT }}
|
||||
username: ${{ secrets.DEPLOYMENT_USER }}
|
||||
key: ${{ secrets.DEPLOYMENT_KEY }}
|
||||
script: |
|
||||
fd '.+' ${{ env.releasesDir }} -d 1 | head -n -3 | xargs -d "\n" -I'{}' sudo chown -R ${{ secrets.DEPLOYMENT_USER }}:${{ secrets.DEPLOYMENT_USER }} {}/bootstrap/cache;
|
||||
fd '.+' ${{ env.releasesDir }} -d 1 | head -n -3 | xargs -d "\n" -I'{}' rm -rf {};
|
68
.github/workflows/phpunit.yml
vendored
Normal file
68
.github/workflows/phpunit.yml
vendored
Normal file
|
@ -0,0 +1,68 @@
|
|||
name: PHP Unit
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
phpunit:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
name: PHPUnit test suite
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:latest
|
||||
env:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: jbukdev_testing
|
||||
ports:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install Node and dependencies
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
|
||||
- name: Setup PHP with pecl extensions
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.1'
|
||||
extensions: phpredis,imagick
|
||||
|
||||
- name: Copy .env
|
||||
run: php -r "file_exists('.env') || copy('.env.github', '.env');"
|
||||
|
||||
- name: Get Composer Cache Directory
|
||||
id: composer-cache
|
||||
run: |
|
||||
echo "::set-output name=dir::$(composer config cache-files-dir)"
|
||||
|
||||
- name: Cache composer dependencies
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ${{ steps.composer-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-composer-
|
||||
|
||||
- name: Install Composer Dependencies
|
||||
run: composer install --quiet --no-ansi --no-interaction --no-progress
|
||||
|
||||
- name: Generate Key
|
||||
run: php artisan key:generate
|
||||
|
||||
- name: Setup Directory Permissions
|
||||
run: chmod -R 777 storage bootstrap/cache
|
||||
|
||||
- name: Setup Database
|
||||
run: php artisan migrate
|
||||
|
||||
- name: Execute PHPUnit Tests
|
||||
run: vendor/bin/phpunit
|
38
.github/workflows/pint.yml
vendored
Normal file
38
.github/workflows/pint.yml
vendored
Normal file
|
@ -0,0 +1,38 @@
|
|||
name: Laravel Pint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
pint:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
name: Laravel Pint
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup PHP with pecl extensions
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.1'
|
||||
|
||||
- name: Get Composer Cache Directory
|
||||
id: composer-cache
|
||||
run: |
|
||||
echo "::set-output name=dir::$(composer config cache-files-dir)"
|
||||
|
||||
- name: Cache composer dependencies
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ${{ steps.composer-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-composer-
|
||||
|
||||
- name: Install Composer Dependencies
|
||||
run: composer install --quiet --no-ansi --no-interaction --no-progress
|
||||
|
||||
- name: Check Files with Laravel Pint
|
||||
run: vendor/bin/pint --test
|
24
.gitignore
vendored
24
.gitignore
vendored
|
@ -1,24 +1,22 @@
|
|||
/.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
|
||||
Homestead.yaml
|
||||
auth.json
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
/.fleet
|
||||
/.idea
|
||||
/.vscode
|
||||
/lsp
|
||||
.phpstorm.meta.php
|
||||
_ide_helper.php
|
||||
ray.php
|
||||
/public/gpg.key
|
||||
/public/assets/img/favicon.png
|
||||
# Custom paths in /public
|
||||
/public/coverage
|
||||
/public/hot
|
||||
/public/storage
|
||||
/public/fonts
|
||||
/public/files
|
||||
/public/keybase.txt
|
||||
/public/assets/*.map
|
||||
|
|
8
.styleci.yml
Normal file
8
.styleci.yml
Normal file
|
@ -0,0 +1,8 @@
|
|||
preset: laravel
|
||||
|
||||
disabled:
|
||||
- concat_without_spaces
|
||||
- single_import_per_statement
|
||||
|
||||
finder:
|
||||
path: app/
|
|
@ -1,3 +1,7 @@
|
|||
{
|
||||
"extends": ["stylelint-config-standard"]
|
||||
"extends": ["stylelint-config-standard"],
|
||||
"rules": {
|
||||
"indentation": 4,
|
||||
"import-notation": "string"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface;
|
|||
use League\CommonMark\Extension\Mention\Mention;
|
||||
use League\CommonMark\Node\Inline\AbstractInline;
|
||||
|
||||
class MentionGenerator implements MentionGeneratorInterface
|
||||
class ContactMentionGenerator implements MentionGeneratorInterface
|
||||
{
|
||||
public function generateMention(Mention $mention): ?AbstractInline
|
||||
{
|
24
app/CommonMark/Renderers/ContactMentionRenderer.php
Normal file
24
app/CommonMark/Renderers/ContactMentionRenderer.php
Normal file
|
@ -0,0 +1,24 @@
|
|||
<?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;
|
||||
|
||||
class ContactMentionRenderer implements NodeRendererInterface
|
||||
{
|
||||
public function render(Node $node, ChildNodeRendererInterface $childRenderer): string
|
||||
{
|
||||
$contact = Contact::where('nick', $node->getIdentifier())->first();
|
||||
|
||||
if ($contact === null) {
|
||||
return '<a href="https://twitter.com/' . $node->getIdentifier() . '">@' . $node->getIdentifier() . '</a>';
|
||||
}
|
||||
|
||||
return trim(view('templates.mini-hcard', ['contact' => $contact])->render());
|
||||
}
|
||||
}
|
|
@ -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 can’t 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);
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -26,9 +26,21 @@ class MigratePlaceDataFromPostgis extends Command
|
|||
protected $description = 'Copy Postgis data to normal latitude longitude fields';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle(): int
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$locationColumn = DB::selectOne(DB::raw("
|
||||
SELECT EXISTS (
|
||||
|
|
|
@ -6,7 +6,6 @@ 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
|
||||
|
@ -28,9 +27,9 @@ class ParseCachedWebMentions extends Command
|
|||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @throws FileNotFoundException
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(FileSystem $filesystem): void
|
||||
public function handle(FileSystem $filesystem)
|
||||
{
|
||||
$htmlFiles = $filesystem->allFiles(storage_path() . '/HTML');
|
||||
foreach ($htmlFiles as $file) {
|
||||
|
@ -50,6 +49,9 @@ class ParseCachedWebMentions extends Command
|
|||
|
||||
/**
|
||||
* Determine the source URL from a filename.
|
||||
*
|
||||
* @param string
|
||||
* @return string
|
||||
*/
|
||||
private function urlFromFilename(string $filepath): string
|
||||
{
|
||||
|
|
|
@ -25,9 +25,21 @@ class ReDownloadWebMentions extends Command
|
|||
protected $description = 'Redownload the HTML content of webmentions';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle(): void
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$webmentions = WebMention::all();
|
||||
foreach ($webmentions as $webmention) {
|
||||
|
|
|
@ -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');
|
||||
}
|
||||
}
|
|
@ -8,18 +8,34 @@ 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
|
||||
protected $commands = [
|
||||
Commands\ParseCachedWebMentions::class,
|
||||
Commands\ReDownloadWebMentions::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Define the application's command schedule.
|
||||
*
|
||||
* @param \Illuminate\Console\Scheduling\Schedule $schedule
|
||||
* @return void
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
protected function schedule(Schedule $schedule)
|
||||
{
|
||||
$schedule->command('horizon:snapshot')->everyFiveMinutes();
|
||||
$schedule->command('cache:prune-stale-tags')->hourly();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the commands for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function commands(): void
|
||||
protected function commands()
|
||||
{
|
||||
$this->load(__DIR__ . '/Commands');
|
||||
|
||||
|
|
|
@ -2,18 +2,104 @@
|
|||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Exception;
|
||||
use GuzzleHttp\Client;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Session\TokenMismatchException;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* Register the exception handling callbacks for the application.
|
||||
* A list of the exception types that are not reported.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public function register(): void
|
||||
protected $dontReport = [
|
||||
NotFoundHttpException::class,
|
||||
ModelNotFoundException::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* A list of the inputs that are never flashed for validation exceptions.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
||||
/**
|
||||
* Report or log an exception.
|
||||
*
|
||||
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
|
||||
*
|
||||
* @param Throwable $throwable
|
||||
* @return void
|
||||
*
|
||||
* @throws Exception
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function report(Throwable $throwable)
|
||||
{
|
||||
$this->reportable(function (Throwable $_e) {
|
||||
//
|
||||
});
|
||||
parent::report($throwable);
|
||||
|
||||
if (config('logging.slack') && $this->shouldReport($throwable)) {
|
||||
$guzzle = new Client([
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
]);
|
||||
|
||||
$exceptionName = get_class($throwable) ?? 'Unknown Exception';
|
||||
$title = $exceptionName . ': ' . $throwable->getMessage();
|
||||
|
||||
$guzzle->post(
|
||||
config('logging.slack'),
|
||||
[
|
||||
'body' => json_encode([
|
||||
'attachments' => [[
|
||||
'fallback' => 'There was an exception.',
|
||||
'pretext' => 'There was an exception.',
|
||||
'color' => '#d00000',
|
||||
'author_name' => app()->environment(),
|
||||
'author_link' => config('app.url'),
|
||||
'fields' => [[
|
||||
'title' => $title,
|
||||
'value' => request()->method() . ' ' . request()->fullUrl(),
|
||||
]],
|
||||
'ts' => time(),
|
||||
]],
|
||||
]),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an exception into an HTTP response.
|
||||
*
|
||||
* @param Request $request
|
||||
* @param Throwable $throwable
|
||||
* @return Response
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function render($request, Throwable $throwable)
|
||||
{
|
||||
if ($throwable instanceof TokenMismatchException) {
|
||||
Route::getRoutes()->match($request);
|
||||
}
|
||||
|
||||
return parent::render($request, $throwable);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,4 +2,6 @@
|
|||
|
||||
namespace App\Exceptions;
|
||||
|
||||
class InternetArchiveException extends \Exception {}
|
||||
class InternetArchiveException extends \Exception
|
||||
{
|
||||
}
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
class InvalidTokenScopeException extends \Exception {}
|
|
@ -1,7 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
class MicropubHandlerException extends \Exception {}
|
7
app/Exceptions/TwitterContentException.php
Normal file
7
app/Exceptions/TwitterContentException.php
Normal file
|
@ -0,0 +1,7 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
class TwitterContentException extends \Exception
|
||||
{
|
||||
}
|
|
@ -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');
|
||||
}
|
||||
}
|
|
@ -7,12 +7,15 @@ namespace App\Http\Controllers\Admin;
|
|||
use App\Http\Controllers\Controller;
|
||||
use App\Models\MicropubClient;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ClientsController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show a list of known clients.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -23,6 +26,8 @@ class ClientsController extends Controller
|
|||
|
||||
/**
|
||||
* Show form to add a client name.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
|
@ -31,6 +36,8 @@ class ClientsController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to adda new client name.
|
||||
*
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function store(): RedirectResponse
|
||||
{
|
||||
|
@ -44,6 +51,9 @@ class ClientsController extends Controller
|
|||
|
||||
/**
|
||||
* Show a form to edit a client name.
|
||||
*
|
||||
* @param int $clientId
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function edit(int $clientId): View
|
||||
{
|
||||
|
@ -58,6 +68,9 @@ class ClientsController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to edit a client name.
|
||||
*
|
||||
* @param int $clientId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function update(int $clientId): RedirectResponse
|
||||
{
|
||||
|
@ -71,6 +84,9 @@ class ClientsController extends Controller
|
|||
|
||||
/**
|
||||
* Process a request to delete a client.
|
||||
*
|
||||
* @param int $clientId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function destroy(int $clientId): RedirectResponse
|
||||
{
|
||||
|
|
|
@ -9,6 +9,7 @@ use App\Models\Contact;
|
|||
use GuzzleHttp\Client;
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\View\View;
|
||||
|
||||
|
@ -16,6 +17,8 @@ class ContactsController extends Controller
|
|||
{
|
||||
/**
|
||||
* List the currect contacts that can be edited.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -26,6 +29,8 @@ class ContactsController extends Controller
|
|||
|
||||
/**
|
||||
* Display the form to add a new contact.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
|
@ -34,10 +39,12 @@ class ContactsController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to add a new contact.
|
||||
*
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function store(): RedirectResponse
|
||||
{
|
||||
$contact = new Contact;
|
||||
$contact = new Contact();
|
||||
$contact->name = request()->input('name');
|
||||
$contact->nick = request()->input('nick');
|
||||
$contact->homepage = request()->input('homepage');
|
||||
|
@ -50,6 +57,9 @@ class ContactsController extends Controller
|
|||
|
||||
/**
|
||||
* Show the form to edit an existing contact.
|
||||
*
|
||||
* @param int $contactId
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function edit(int $contactId): View
|
||||
{
|
||||
|
@ -62,6 +72,9 @@ class ContactsController extends Controller
|
|||
* Process the request to edit a contact.
|
||||
*
|
||||
* @todo Allow saving profile pictures for people without homepages
|
||||
*
|
||||
* @param int $contactId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function update(int $contactId): RedirectResponse
|
||||
{
|
||||
|
@ -76,7 +89,7 @@ class ContactsController extends Controller
|
|||
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;
|
||||
$filesystem = new Filesystem();
|
||||
if ($filesystem->isDirectory($destination) === false) {
|
||||
$filesystem->makeDirectory($destination);
|
||||
}
|
||||
|
@ -88,6 +101,9 @@ class ContactsController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to delete a contact.
|
||||
*
|
||||
* @param int $contactId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function destroy(int $contactId): RedirectResponse
|
||||
{
|
||||
|
@ -103,6 +119,7 @@ class ContactsController extends Controller
|
|||
* This method attempts to find the microformat marked-up profile image
|
||||
* from a given homepage and save it accordingly
|
||||
*
|
||||
* @param int $contactId
|
||||
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
|
||||
*/
|
||||
public function getAvatar(int $contactId)
|
||||
|
@ -136,7 +153,7 @@ class ContactsController extends Controller
|
|||
}
|
||||
if ($avatar !== null) {
|
||||
$directory = public_path() . '/assets/profile-images/' . parse_url($contact->homepage, PHP_URL_HOST);
|
||||
$filesystem = new Filesystem;
|
||||
$filesystem = new Filesystem();
|
||||
if ($filesystem->isDirectory($directory) === false) {
|
||||
$filesystem->makeDirectory($directory);
|
||||
}
|
||||
|
|
|
@ -11,6 +11,8 @@ class HomeController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show the homepage of the admin CP.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function welcome(): View
|
||||
{
|
||||
|
|
|
@ -14,6 +14,8 @@ class LikesController extends Controller
|
|||
{
|
||||
/**
|
||||
* List the likes that can be edited.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -24,6 +26,8 @@ class LikesController extends Controller
|
|||
|
||||
/**
|
||||
* Show the form to make a new like.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
|
@ -32,6 +36,8 @@ class LikesController extends Controller
|
|||
|
||||
/**
|
||||
* Process a request to make a new like.
|
||||
*
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function store(): RedirectResponse
|
||||
{
|
||||
|
@ -45,6 +51,9 @@ class LikesController extends Controller
|
|||
|
||||
/**
|
||||
* Display the form to edit a specific like.
|
||||
*
|
||||
* @param int $likeId
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function edit(int $likeId): View
|
||||
{
|
||||
|
@ -58,6 +67,9 @@ class LikesController extends Controller
|
|||
|
||||
/**
|
||||
* Process a request to edit a like.
|
||||
*
|
||||
* @param int $likeId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function update(int $likeId): RedirectResponse
|
||||
{
|
||||
|
@ -71,6 +83,9 @@ class LikesController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to delete a like.
|
||||
*
|
||||
* @param int $likeId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function destroy(int $likeId): RedirectResponse
|
||||
{
|
||||
|
|
|
@ -15,6 +15,8 @@ class NotesController extends Controller
|
|||
{
|
||||
/**
|
||||
* List the notes that can be edited.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -28,6 +30,8 @@ class NotesController extends Controller
|
|||
|
||||
/**
|
||||
* Show the form to make a new note.
|
||||
*
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
|
@ -36,6 +40,9 @@ class NotesController extends Controller
|
|||
|
||||
/**
|
||||
* Process a request to make a new note.
|
||||
*
|
||||
* @param Request $request
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
|
@ -49,6 +56,9 @@ class NotesController extends Controller
|
|||
|
||||
/**
|
||||
* Display the form to edit a specific note.
|
||||
*
|
||||
* @param int $noteId
|
||||
* @return \Illuminate\View\View
|
||||
*/
|
||||
public function edit(int $noteId): View
|
||||
{
|
||||
|
@ -61,6 +71,9 @@ class NotesController extends Controller
|
|||
/**
|
||||
* Process a request to edit a note. Easy since this can only be done
|
||||
* from the admin CP.
|
||||
*
|
||||
* @param int $noteId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function update(int $noteId): RedirectResponse
|
||||
{
|
||||
|
@ -79,6 +92,9 @@ class NotesController extends Controller
|
|||
|
||||
/**
|
||||
* Delete the note.
|
||||
*
|
||||
* @param int $noteId
|
||||
* @return \Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function destroy(int $noteId): RedirectResponse
|
||||
{
|
||||
|
|
|
@ -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',
|
||||
]);
|
||||
}
|
||||
}
|
|
@ -21,6 +21,8 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* List the places that can be edited.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -31,6 +33,8 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* Show the form to make a new place.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
|
@ -39,6 +43,8 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* Process a request to make a new place.
|
||||
*
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function store(): RedirectResponse
|
||||
{
|
||||
|
@ -56,6 +62,9 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* Display the form to edit a specific place.
|
||||
*
|
||||
* @param int $placeId
|
||||
* @return View
|
||||
*/
|
||||
public function edit(int $placeId): View
|
||||
{
|
||||
|
@ -66,6 +75,9 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* Process a request to edit a place.
|
||||
*
|
||||
* @param int $placeId
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function update(int $placeId): RedirectResponse
|
||||
{
|
||||
|
@ -82,6 +94,9 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* List the places we can merge with the current place.
|
||||
*
|
||||
* @param int $placeId
|
||||
* @return View
|
||||
*/
|
||||
public function mergeIndex(int $placeId): View
|
||||
{
|
||||
|
@ -99,6 +114,10 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* Show a form for merging two specific places.
|
||||
*
|
||||
* @param int $placeId1
|
||||
* @param int $placeId2
|
||||
* @return View
|
||||
*/
|
||||
public function mergeEdit(int $placeId1, int $placeId2): View
|
||||
{
|
||||
|
@ -110,6 +129,8 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to merge two places.
|
||||
*
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function mergeStore(): RedirectResponse
|
||||
{
|
||||
|
|
|
@ -14,6 +14,8 @@ class SyndicationTargetsController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show a list of known syndication targets.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -24,6 +26,8 @@ class SyndicationTargetsController extends Controller
|
|||
|
||||
/**
|
||||
* Show form to add a syndication target.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
|
@ -32,6 +36,9 @@ class SyndicationTargetsController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to adda new syndication target.
|
||||
*
|
||||
* @param Request $request
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
|
@ -53,6 +60,9 @@ class SyndicationTargetsController extends Controller
|
|||
|
||||
/**
|
||||
* Show a form to edit a syndication target.
|
||||
*
|
||||
* @param SyndicationTarget $syndicationTarget
|
||||
* @return View
|
||||
*/
|
||||
public function edit(SyndicationTarget $syndicationTarget): View
|
||||
{
|
||||
|
@ -63,6 +73,10 @@ class SyndicationTargetsController extends Controller
|
|||
|
||||
/**
|
||||
* Process the request to edit a client name.
|
||||
*
|
||||
* @param Request $request
|
||||
* @param SyndicationTarget $syndicationTarget
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function update(Request $request, SyndicationTarget $syndicationTarget): RedirectResponse
|
||||
{
|
||||
|
@ -84,6 +98,9 @@ class SyndicationTargetsController extends Controller
|
|||
|
||||
/**
|
||||
* Process a request to delete a client.
|
||||
*
|
||||
* @param SyndicationTarget $syndicationTarget
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function destroy(SyndicationTarget $syndicationTarget): RedirectResponse
|
||||
{
|
||||
|
|
|
@ -14,8 +14,12 @@ class ArticlesController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show all articles (with pagination).
|
||||
*
|
||||
* @param int|null $year
|
||||
* @param int|null $month
|
||||
* @return View
|
||||
*/
|
||||
public function index(?int $year = null, ?int $month = null): View
|
||||
public function index(int $year = null, int $month = null): View
|
||||
{
|
||||
$articles = Article::where('published', '1')
|
||||
->date($year, $month)
|
||||
|
@ -27,8 +31,13 @@ class ArticlesController extends Controller
|
|||
|
||||
/**
|
||||
* Show a single article.
|
||||
*
|
||||
* @param int $year
|
||||
* @param int $month
|
||||
* @param string $slug
|
||||
* @return RedirectResponse|View
|
||||
*/
|
||||
public function show(int $year, int $month, string $slug): RedirectResponse|View
|
||||
public function show(int $year, int $month, string $slug)
|
||||
{
|
||||
try {
|
||||
$article = Article::where('titleurl', $slug)->firstOrFail();
|
||||
|
@ -47,7 +56,11 @@ class ArticlesController extends Controller
|
|||
}
|
||||
|
||||
/**
|
||||
* We only have the ID, work out post title, year and month and redirect to it.
|
||||
* We only have the ID, work out post title, year and month
|
||||
* and redirect to it.
|
||||
*
|
||||
* @param string $idFromUrl
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function onlyIdInUrl(string $idFromUrl): RedirectResponse
|
||||
{
|
||||
|
|
|
@ -5,7 +5,6 @@ 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;
|
||||
|
||||
|
@ -13,8 +12,10 @@ class AuthController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show the login form.
|
||||
*
|
||||
* @return View|RedirectResponse
|
||||
*/
|
||||
public function showLogin(): View|RedirectResponse
|
||||
public function showLogin()
|
||||
{
|
||||
if (Auth::check()) {
|
||||
return redirect('/');
|
||||
|
@ -24,23 +25,28 @@ class AuthController extends Controller
|
|||
}
|
||||
|
||||
/**
|
||||
* Log in a user, set a session variable, check credentials against the `.env` file.
|
||||
* Log in a user, set a session variable, check credentials against
|
||||
* the .env file.
|
||||
*
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function login(Request $request): RedirectResponse
|
||||
public function login(): RedirectResponse
|
||||
{
|
||||
$credentials = $request->only('name', 'password');
|
||||
$credentials = request()->only('name', 'password');
|
||||
|
||||
if (Auth::attempt($credentials, true)) {
|
||||
return redirect()->intended('/admin');
|
||||
return redirect()->intended('/');
|
||||
}
|
||||
|
||||
return redirect()->route('login');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the form to allow a user to log-out.
|
||||
* Show the form to logout a user.
|
||||
*
|
||||
* @return View|RedirectResponse
|
||||
*/
|
||||
public function showLogout(): View|RedirectResponse
|
||||
public function showLogout()
|
||||
{
|
||||
if (Auth::check() === false) {
|
||||
// The user is not logged in, just redirect them home
|
||||
|
@ -52,6 +58,8 @@ class AuthController extends Controller
|
|||
|
||||
/**
|
||||
* Log the user out from their current session.
|
||||
*
|
||||
* @return RedirectResponse;
|
||||
*/
|
||||
public function logout(): RedirectResponse
|
||||
{
|
||||
|
|
|
@ -11,6 +11,8 @@ class BookmarksController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show the most recent bookmarks.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -21,6 +23,9 @@ class BookmarksController extends Controller
|
|||
|
||||
/**
|
||||
* Show a single bookmark.
|
||||
*
|
||||
* @param Bookmark $bookmark
|
||||
* @return View
|
||||
*/
|
||||
public function show(Bookmark $bookmark): View
|
||||
{
|
||||
|
@ -31,6 +36,9 @@ class BookmarksController extends Controller
|
|||
|
||||
/**
|
||||
* Show bookmarks tagged with a specific tag.
|
||||
*
|
||||
* @param string $tag
|
||||
* @return View
|
||||
*/
|
||||
public function tagged(string $tag): View
|
||||
{
|
||||
|
|
|
@ -12,10 +12,12 @@ class ContactsController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show all the contacts.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
$filesystem = new Filesystem;
|
||||
$filesystem = new Filesystem();
|
||||
$contacts = Contact::all();
|
||||
foreach ($contacts as $contact) {
|
||||
$contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST);
|
||||
|
@ -31,13 +33,16 @@ class ContactsController extends Controller
|
|||
|
||||
/**
|
||||
* Show a single contact.
|
||||
*
|
||||
* @param Contact $contact
|
||||
* @return View
|
||||
*/
|
||||
public function show(Contact $contact): View
|
||||
{
|
||||
$contact->homepageHost = parse_url($contact->homepage, PHP_URL_HOST);
|
||||
$file = public_path() . '/assets/profile-images/' . $contact->homepageHost . '/image';
|
||||
|
||||
$filesystem = new Filesystem;
|
||||
$filesystem = new Filesystem();
|
||||
$image = ($filesystem->exists($file)) ?
|
||||
'/assets/profile-images/' . $contact->homepageHost . '/image'
|
||||
:
|
||||
|
|
|
@ -2,7 +2,14 @@
|
|||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
abstract class Controller
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Bus\DispatchesJobs;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
//
|
||||
use AuthorizesRequests;
|
||||
use DispatchesJobs;
|
||||
use ValidatesRequests;
|
||||
}
|
||||
|
|
|
@ -13,6 +13,8 @@ class FeedsController extends Controller
|
|||
{
|
||||
/**
|
||||
* Returns the blog RSS feed.
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
public function blogRss(): Response
|
||||
{
|
||||
|
@ -26,6 +28,8 @@ class FeedsController extends Controller
|
|||
|
||||
/**
|
||||
* Returns the blog Atom feed.
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
public function blogAtom(): Response
|
||||
{
|
||||
|
@ -38,6 +42,8 @@ class FeedsController extends Controller
|
|||
|
||||
/**
|
||||
* Returns the notes RSS feed.
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
public function notesRss(): Response
|
||||
{
|
||||
|
@ -51,6 +57,8 @@ class FeedsController extends Controller
|
|||
|
||||
/**
|
||||
* Returns the notes Atom feed.
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
public function notesAtom(): Response
|
||||
{
|
||||
|
@ -65,21 +73,17 @@ class FeedsController extends Controller
|
|||
|
||||
/**
|
||||
* Returns the blog JSON feed.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
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',
|
||||
'version' => 'https://jsonfeed.org/version/1',
|
||||
'title' => 'The JSON Feed for ' . config('app.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' => [],
|
||||
];
|
||||
|
||||
|
@ -91,6 +95,9 @@ class FeedsController extends Controller
|
|||
'content_html' => $article->main,
|
||||
'date_published' => $article->created_at->tz('UTC')->toRfc3339String(),
|
||||
'date_modified' => $article->updated_at->tz('UTC')->toRfc3339String(),
|
||||
'author' => [
|
||||
'name' => config('app.display_name'),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
|
@ -99,35 +106,31 @@ class FeedsController extends Controller
|
|||
|
||||
/**
|
||||
* Returns the notes JSON feed.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function notesJson(): array
|
||||
public function notesJson()
|
||||
{
|
||||
$notes = Note::latest()->with('media', 'place', 'tags')->take(20)->get();
|
||||
$notes = Note::latest()->with('media')->take(20)->get();
|
||||
$data = [
|
||||
'version' => 'https://jsonfeed.org/version/1.1',
|
||||
'title' => 'The JSON Feed for ' . config('user.display_name') . '’s notes',
|
||||
'version' => 'https://jsonfeed.org/version/1',
|
||||
'title' => 'The JSON Feed for ' . config('app.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,
|
||||
'id' => $note->longurl,
|
||||
'url' => $note->longurl,
|
||||
'content_html' => $note->content,
|
||||
'date_published' => $note->created_at->tz('UTC')->toRfc3339String(),
|
||||
'date_modified' => $note->updated_at->tz('UTC')->toRfc3339String(),
|
||||
'author' => [
|
||||
'name' => config('app.display_name'),
|
||||
],
|
||||
];
|
||||
if ($note->tags->count() > 0) {
|
||||
$data['items'][$key]['tags'] = implode(',', $note->tags->pluck('tag')->toArray());
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
@ -135,6 +138,8 @@ class FeedsController extends Controller
|
|||
|
||||
/**
|
||||
* Returns the blog JF2 feed.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function blogJf2(): JsonResponse
|
||||
{
|
||||
|
@ -160,8 +165,8 @@ class FeedsController extends Controller
|
|||
'url' => url('/blog'),
|
||||
'author' => [
|
||||
'type' => 'card',
|
||||
'name' => config('user.display_name'),
|
||||
'url' => config('app.url'),
|
||||
'name' => config('user.displayname'),
|
||||
'url' => config('app.longurl'),
|
||||
],
|
||||
'children' => $items,
|
||||
], 200, [
|
||||
|
@ -171,6 +176,8 @@ class FeedsController extends Controller
|
|||
|
||||
/**
|
||||
* Returns the notes JF2 feed.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function notesJf2(): JsonResponse
|
||||
{
|
||||
|
@ -180,8 +187,8 @@ class FeedsController extends Controller
|
|||
$items[] = [
|
||||
'type' => 'entry',
|
||||
'published' => $note->created_at,
|
||||
'uid' => $note->uri,
|
||||
'url' => $note->uri,
|
||||
'uid' => $note->longurl,
|
||||
'url' => $note->longurl,
|
||||
'content' => [
|
||||
'text' => $note->getRawOriginal('note'),
|
||||
'html' => $note->note,
|
||||
|
@ -196,8 +203,8 @@ class FeedsController extends Controller
|
|||
'url' => url('/notes'),
|
||||
'author' => [
|
||||
'type' => 'card',
|
||||
'name' => config('user.display_name'),
|
||||
'url' => config('app.url'),
|
||||
'name' => config('user.displayname'),
|
||||
'url' => config('app.longurl'),
|
||||
],
|
||||
'children' => $items,
|
||||
], 200, [
|
||||
|
|
|
@ -3,10 +3,10 @@
|
|||
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 App\Services\ActivityStreamsService;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\View\View;
|
||||
|
||||
|
@ -14,20 +14,18 @@ class FrontPageController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show all the recent activity.
|
||||
*
|
||||
* @return Response|View
|
||||
*/
|
||||
public function index(): Response|View
|
||||
public function index()
|
||||
{
|
||||
$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();
|
||||
if (request()->wantsActivityStream()) {
|
||||
return (new ActivityStreamsService())->siteOwnerResponse();
|
||||
}
|
||||
|
||||
$notes = Note::latest()->with(['media', 'client', 'place'])->get();
|
||||
$articles = Article::latest()->get();
|
||||
$bookmarks = Bookmark::latest()->with('tags')->get();
|
||||
$bookmarks = Bookmark::latest()->get();
|
||||
$likes = Like::latest()->get();
|
||||
|
||||
$items = collect($notes)
|
||||
|
@ -37,11 +35,8 @@ class FrontPageController extends Controller
|
|||
->sortByDesc('updated_at')
|
||||
->paginate(10);
|
||||
|
||||
$bio = Bio::first()?->content;
|
||||
|
||||
return view('front-page', [
|
||||
'items' => $items,
|
||||
'bio' => $bio,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,327 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\TokenService;
|
||||
use Exception;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Psr7\Uri;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\View\View;
|
||||
use Random\RandomException;
|
||||
use SodiumException;
|
||||
|
||||
class IndieAuthController extends Controller
|
||||
{
|
||||
public function indieAuthMetadataEndpoint(): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'issuer' => config('app.url'),
|
||||
'authorization_endpoint' => route('indieauth.start'),
|
||||
'token_endpoint' => route('indieauth.token'),
|
||||
'code_challenge_methods_supported' => ['S256'],
|
||||
// 'introspection_endpoint' => route('indieauth.introspection'),
|
||||
// 'introspection_endpoint_auth_methods_supported' => ['none'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a GET request to the IndieAuth endpoint.
|
||||
*
|
||||
* This is the first step in the IndieAuth flow, where the client app sends the user to the IndieAuth endpoint.
|
||||
*/
|
||||
public function start(Request $request): View
|
||||
{
|
||||
// First check all required params are present
|
||||
$validator = Validator::make($request->all(), [
|
||||
'response_type' => 'required:string',
|
||||
'client_id' => 'required',
|
||||
'redirect_uri' => 'required',
|
||||
'state' => 'required',
|
||||
'code_challenge' => 'required:string',
|
||||
'code_challenge_method' => 'required:string',
|
||||
], [
|
||||
'response_type' => 'response_type is required',
|
||||
'client_id.required' => 'client_id is required to display which app is asking for authentication',
|
||||
'redirect_uri.required' => 'redirect_uri is required so we can progress successful requests',
|
||||
'state.required' => 'state is required',
|
||||
'code_challenge.required' => 'code_challenge is required',
|
||||
'code_challenge_method.required' => 'code_challenge_method is required',
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return view('indieauth.error')->withErrors($validator);
|
||||
}
|
||||
|
||||
if ($request->get('response_type') !== 'code') {
|
||||
return view('indieauth.error')->withErrors(['response_type' => 'only a response_type of "code" is supported']);
|
||||
}
|
||||
|
||||
if (mb_strtoupper($request->get('code_challenge_method')) !== 'S256') {
|
||||
return view('indieauth.error')->withErrors(['code_challenge_method' => 'only a code_challenge_method of "S256" is supported']);
|
||||
}
|
||||
|
||||
if (! $this->isValidRedirectUri($request->get('client_id'), $request->get('redirect_uri'))) {
|
||||
return view('indieauth.error')->withErrors(['redirect_uri' => 'redirect_uri is not valid for this client_id']);
|
||||
}
|
||||
|
||||
$scopes = $request->get('scope', '');
|
||||
$scopes = explode(' ', $scopes);
|
||||
|
||||
return view('indieauth.start', [
|
||||
'me' => $request->get('me'),
|
||||
'client_id' => $request->get('client_id'),
|
||||
'redirect_uri' => $request->get('redirect_uri'),
|
||||
'state' => $request->get('state'),
|
||||
'scopes' => $scopes,
|
||||
'code_challenge' => $request->get('code_challenge'),
|
||||
'code_challenge_method' => $request->get('code_challenge_method'),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm an IndieAuth approval request.
|
||||
*
|
||||
* Generates an auth code and redirects the user back to the client app.
|
||||
*
|
||||
* @throws RandomException
|
||||
*/
|
||||
public function confirm(Request $request): RedirectResponse
|
||||
{
|
||||
$authCode = bin2hex(random_bytes(16));
|
||||
|
||||
$cacheKey = hash('xxh3', $request->get('client_id'));
|
||||
|
||||
$indieAuthRequestData = [
|
||||
'code_challenge' => $request->get('code_challenge'),
|
||||
'code_challenge_method' => $request->get('code_challenge_method'),
|
||||
'client_id' => $request->get('client_id'),
|
||||
'redirect_uri' => $request->get('redirect_uri'),
|
||||
'auth_code' => $authCode,
|
||||
'scope' => implode(' ', $request->get('scope', '')),
|
||||
];
|
||||
|
||||
Cache::put($cacheKey, $indieAuthRequestData, now()->addMinutes(10));
|
||||
|
||||
$redirectUri = new Uri($request->get('redirect_uri'));
|
||||
$redirectUri = Uri::withQueryValues($redirectUri, [
|
||||
'code' => $authCode,
|
||||
'state' => $request->get('state'),
|
||||
'iss' => config('app.url'),
|
||||
]);
|
||||
|
||||
return redirect()->away($redirectUri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a POST request to the IndieAuth auth endpoint.
|
||||
*
|
||||
* This is one possible second step in the IndieAuth flow, where the client app sends the auth code to the IndieAuth
|
||||
* endpoint. As it is to the auth endpoint we return profile information. A similar request can be made to the token
|
||||
* endpoint to get an access token.
|
||||
*/
|
||||
public function processCodeExchange(Request $request): JsonResponse
|
||||
{
|
||||
$invalidCodeResponse = $this->validateAuthorizationCode($request);
|
||||
|
||||
if ($invalidCodeResponse instanceof JsonResponse) {
|
||||
return $invalidCodeResponse;
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'me' => config('app.url'),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a POST request to the IndieAuth token endpoint.
|
||||
*
|
||||
* This is another possible second step in the IndieAuth flow, where the client app sends the auth code to the
|
||||
* IndieAuth token endpoint. As it is to the token endpoint we return an access token.
|
||||
*
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public function processTokenRequest(Request $request): JsonResponse
|
||||
{
|
||||
$indieAuthData = $this->validateAuthorizationCode($request);
|
||||
|
||||
if ($indieAuthData instanceof JsonResponse) {
|
||||
return $indieAuthData;
|
||||
}
|
||||
|
||||
if ($indieAuthData['scope'] === '') {
|
||||
return response()->json(['errors' => [
|
||||
'scope' => [
|
||||
'The scope property must be non-empty for an access token to be issued.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
|
||||
$tokenData = [
|
||||
'me' => config('app.url'),
|
||||
'client_id' => $request->get('client_id'),
|
||||
'scope' => $indieAuthData['scope'],
|
||||
];
|
||||
$tokenService = resolve(TokenService::class);
|
||||
$token = $tokenService->getNewToken($tokenData);
|
||||
|
||||
return response()->json([
|
||||
'access_token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
'scope' => $indieAuthData['scope'],
|
||||
'me' => config('app.url'),
|
||||
]);
|
||||
}
|
||||
|
||||
protected function isValidRedirectUri(string $clientId, string $redirectUri): bool
|
||||
{
|
||||
// If client_id is not a valid URL, then it's not valid
|
||||
$clientIdParsed = \Mf2\parseUriToComponents($clientId);
|
||||
if (! isset($clientIdParsed['authority'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If redirect_uri is not a valid URL, then it's not valid
|
||||
$redirectUriParsed = \Mf2\parseUriToComponents($redirectUri);
|
||||
if (! isset($redirectUriParsed['authority'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If client_id and redirect_uri are the same host, then it's valid
|
||||
if ($clientIdParsed['authority'] === $redirectUriParsed['authority']) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Otherwise we need to check the redirect_uri is in the client_id's redirect_uris
|
||||
$guzzle = resolve(Client::class);
|
||||
|
||||
try {
|
||||
$clientInfo = $guzzle->get($clientId);
|
||||
} catch (Exception) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$clientInfoParsed = \Mf2\parse($clientInfo->getBody()->getContents(), $clientId);
|
||||
|
||||
$redirectUris = $clientInfoParsed['rels']['redirect_uri'] ?? [];
|
||||
|
||||
return in_array($redirectUri, $redirectUris, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws SodiumException
|
||||
*/
|
||||
protected function validateAuthorizationCode(Request $request): JsonResponse|array
|
||||
{
|
||||
// First check all the data is present
|
||||
$validator = Validator::make($request->all(), [
|
||||
'grant_type' => 'required:string',
|
||||
'code' => 'required:string',
|
||||
'client_id' => 'required',
|
||||
'redirect_uri' => 'required',
|
||||
'code_verifier' => 'required',
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return response()->json(['errors' => $validator->errors()], 400);
|
||||
}
|
||||
|
||||
if ($request->get('grant_type') !== 'authorization_code') {
|
||||
return response()->json(['errors' => [
|
||||
'grant_type' => [
|
||||
'Only a grant type of "authorization_code" is supported.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
|
||||
// Check cache for auth code
|
||||
$cacheKey = hash('xxh3', $request->get('client_id'));
|
||||
$indieAuthRequestData = Cache::pull($cacheKey);
|
||||
|
||||
if ($indieAuthRequestData === null) {
|
||||
return response()->json(['errors' => [
|
||||
'code' => [
|
||||
'The code is invalid.',
|
||||
],
|
||||
]], 404);
|
||||
}
|
||||
|
||||
// Check the IndieAuth code
|
||||
if (! array_key_exists('auth_code', $indieAuthRequestData)) {
|
||||
return response()->json(['errors' => [
|
||||
'code' => [
|
||||
'The code is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
if ($indieAuthRequestData['auth_code'] !== $request->get('code')) {
|
||||
return response()->json(['errors' => [
|
||||
'code' => [
|
||||
'The code is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
|
||||
// Check code verifier
|
||||
if (! array_key_exists('code_challenge', $indieAuthRequestData)) {
|
||||
return response()->json(['errors' => [
|
||||
'code_verifier' => [
|
||||
'The code verifier is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
if (! hash_equals(
|
||||
$indieAuthRequestData['code_challenge'],
|
||||
sodium_bin2base64(
|
||||
hash('sha256', $request->get('code_verifier'), true),
|
||||
SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING
|
||||
)
|
||||
)) {
|
||||
return response()->json(['errors' => [
|
||||
'code_verifier' => [
|
||||
'The code verifier is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
|
||||
// Check redirect_uri
|
||||
if (! array_key_exists('redirect_uri', $indieAuthRequestData)) {
|
||||
return response()->json(['errors' => [
|
||||
'redirect_uri' => [
|
||||
'The redirect uri is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
if ($indieAuthRequestData['redirect_uri'] !== $request->get('redirect_uri')) {
|
||||
return response()->json(['errors' => [
|
||||
'redirect_uri' => [
|
||||
'The redirect uri is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
|
||||
// Check client_id
|
||||
if (! array_key_exists('client_id', $indieAuthRequestData)) {
|
||||
return response()->json(['errors' => [
|
||||
'client_id' => [
|
||||
'The client id is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
if ($indieAuthRequestData['client_id'] !== $request->get('client_id')) {
|
||||
return response()->json(['errors' => [
|
||||
'client_id' => [
|
||||
'The client id is invalid.',
|
||||
],
|
||||
]], 400);
|
||||
}
|
||||
|
||||
return $indieAuthRequestData;
|
||||
}
|
||||
}
|
|
@ -11,6 +11,8 @@ class LikesController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show the latest likes.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -21,6 +23,9 @@ class LikesController extends Controller
|
|||
|
||||
/**
|
||||
* Show a single like.
|
||||
*
|
||||
* @param Like $like
|
||||
* @return View
|
||||
*/
|
||||
public function show(Like $like): View
|
||||
{
|
||||
|
|
|
@ -4,73 +4,110 @@ declare(strict_types=1);
|
|||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Exceptions\InvalidTokenScopeException;
|
||||
use App\Exceptions\MicropubHandlerException;
|
||||
use App\Http\Requests\MicropubRequest;
|
||||
use App\Http\Responses\MicropubResponses;
|
||||
use App\Models\Place;
|
||||
use App\Models\SyndicationTarget;
|
||||
use App\Services\Micropub\MicropubHandlerRegistry;
|
||||
use App\Services\Micropub\HCardService;
|
||||
use App\Services\Micropub\HEntryService;
|
||||
use App\Services\Micropub\UpdateService;
|
||||
use App\Services\TokenService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Lcobucci\JWT\Token;
|
||||
use Lcobucci\JWT\Encoding\CannotDecodeContent;
|
||||
use Lcobucci\JWT\Token\InvalidTokenStructure;
|
||||
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
|
||||
use Monolog\Handler\StreamHandler;
|
||||
use Monolog\Logger;
|
||||
|
||||
class MicropubController extends Controller
|
||||
{
|
||||
protected MicropubHandlerRegistry $handlerRegistry;
|
||||
protected TokenService $tokenService;
|
||||
|
||||
public function __construct(MicropubHandlerRegistry $handlerRegistry)
|
||||
{
|
||||
$this->handlerRegistry = $handlerRegistry;
|
||||
protected HEntryService $hentryService;
|
||||
|
||||
protected HCardService $hcardService;
|
||||
|
||||
protected UpdateService $updateService;
|
||||
|
||||
public function __construct(
|
||||
TokenService $tokenService,
|
||||
HEntryService $hentryService,
|
||||
HCardService $hcardService,
|
||||
UpdateService $updateService
|
||||
) {
|
||||
$this->tokenService = $tokenService;
|
||||
$this->hentryService = $hentryService;
|
||||
$this->hcardService = $hcardService;
|
||||
$this->updateService = $updateService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Respond to a POST request to the micropub endpoint.
|
||||
* This function receives an API request, verifies the authenticity
|
||||
* then passes over the info to the relevant Service class.
|
||||
*
|
||||
* 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.
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function post(MicropubRequest $request): JsonResponse
|
||||
public function post(Request $request): JsonResponse
|
||||
{
|
||||
$type = $request->getType();
|
||||
|
||||
if (! $type) {
|
||||
return response()->json([
|
||||
'error' => 'invalid_request',
|
||||
'error_description' => 'Microformat object type is missing, for example: h-entry or h-card',
|
||||
], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$handler = $this->handlerRegistry->getHandler($type);
|
||||
$result = $handler->handle($request->getMicropubData());
|
||||
$tokenData = $this->tokenService->validateToken($request->input('access_token'));
|
||||
} catch (RequiredConstraintsViolated|InvalidTokenStructure|CannotDecodeContent) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
// 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);
|
||||
return $micropubResponses->invalidTokenResponse();
|
||||
}
|
||||
|
||||
if ($tokenData->claims()->has('scope') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->tokenHasNoScopeResponse();
|
||||
}
|
||||
|
||||
$this->logMicropubRequest($request->all());
|
||||
|
||||
if (($request->input('h') === 'entry') || ($request->input('type.0') === 'h-entry')) {
|
||||
if (stripos($tokenData->claims()->get('scope'), 'create') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->insufficientScopeResponse();
|
||||
}
|
||||
$location = $this->hentryService->process($request->all(), $this->getCLientId());
|
||||
|
||||
return response()->json([
|
||||
'response' => 'created',
|
||||
'location' => $location,
|
||||
], 201)->header('Location', $location);
|
||||
}
|
||||
|
||||
if ($request->input('h') === 'card' || $request->input('type.0') === 'h-card') {
|
||||
if (stripos($tokenData->claims()->get('scope'), 'create') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->insufficientScopeResponse();
|
||||
}
|
||||
$location = $this->hcardService->process($request->all());
|
||||
|
||||
return response()->json([
|
||||
'response' => 'created',
|
||||
'location' => $location,
|
||||
], 201)->header('Location', $location);
|
||||
}
|
||||
|
||||
if ($request->input('action') === 'update') {
|
||||
if (stripos($tokenData->claims()->get('scope'), 'update') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->insufficientScopeResponse();
|
||||
}
|
||||
|
||||
return $this->updateService->process($request->all());
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'response' => 'error',
|
||||
'error_description' => 'unsupported_request_type',
|
||||
], 500);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -80,29 +117,37 @@ class MicropubController extends Controller
|
|||
* token, here we check whether the token is valid and respond
|
||||
* appropriately. Further if the request has the query parameter
|
||||
* syndicate-to we respond with the known syndication endpoints.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function get(Request $request): JsonResponse
|
||||
public function get(): JsonResponse
|
||||
{
|
||||
if ($request->input('q') === 'syndicate-to') {
|
||||
try {
|
||||
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
|
||||
} catch (RequiredConstraintsViolated|InvalidTokenStructure) {
|
||||
return (new MicropubResponses())->invalidTokenResponse();
|
||||
}
|
||||
|
||||
if (request()->input('q') === 'syndicate-to') {
|
||||
return response()->json([
|
||||
'syndicate-to' => SyndicationTarget::all(),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($request->input('q') === 'config') {
|
||||
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:')) {
|
||||
if (request()->has('q') && substr(request()->input('q'), 0, 4) === 'geo:') {
|
||||
preg_match_all(
|
||||
'/([0-9.\-]+)/',
|
||||
$request->input('q'),
|
||||
request()->input('q'),
|
||||
$matches
|
||||
);
|
||||
$distance = (count($matches[0]) === 3) ? 100 * $matches[0][2] : 1000;
|
||||
$distance = (count($matches[0]) == 3) ? 100 * $matches[0][2] : 1000;
|
||||
$places = Place::near(
|
||||
(object) ['latitude' => $matches[0][0], 'longitude' => $matches[0][1]],
|
||||
$distance
|
||||
|
@ -114,17 +159,40 @@ class MicropubController extends Controller
|
|||
]);
|
||||
}
|
||||
|
||||
// the default response is just to return the token data
|
||||
/** @var Token $tokenData */
|
||||
$tokenData = $request->input('token_data');
|
||||
|
||||
// default response is just to return the token data
|
||||
return response()->json([
|
||||
'response' => 'token',
|
||||
'token' => [
|
||||
'me' => $tokenData['me'],
|
||||
'scope' => $tokenData['scope'],
|
||||
'client_id' => $tokenData['client_id'],
|
||||
'me' => $tokenData->claims()->get('me'),
|
||||
'scope' => $tokenData->claims()->get('scope'),
|
||||
'client_id' => $tokenData->claims()->get('client_id'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the client id from the access token sent with the request.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws RequiredConstraintsViolated
|
||||
*/
|
||||
private function getClientId(): string
|
||||
{
|
||||
return resolve(TokenService::class)
|
||||
->validateToken(request()->input('access_token'))
|
||||
->claims()->get('client_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the details of the micropub request to a log file.
|
||||
*
|
||||
* @param array $request This is the info from request()->all()
|
||||
*/
|
||||
private function logMicropubRequest(array $request)
|
||||
{
|
||||
$logger = new Logger('micropub');
|
||||
$logger->pushHandler(new StreamHandler(storage_path('logs/micropub.log')));
|
||||
$logger->debug('MicropubLog', $request);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,29 +7,52 @@ namespace App\Http\Controllers;
|
|||
use App\Http\Responses\MicropubResponses;
|
||||
use App\Jobs\ProcessMedia;
|
||||
use App\Models\Media;
|
||||
use App\Services\TokenService;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
use Illuminate\Http\File;
|
||||
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 Illuminate\Support\Str;
|
||||
use Intervention\Image\Exception\NotReadableException;
|
||||
use Intervention\Image\ImageManager;
|
||||
use Lcobucci\JWT\Token\InvalidTokenStructure;
|
||||
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
class MicropubMediaController extends Controller
|
||||
{
|
||||
protected TokenService $tokenService;
|
||||
|
||||
public function __construct(TokenService $tokenService)
|
||||
{
|
||||
$this->tokenService = $tokenService;
|
||||
}
|
||||
|
||||
public function getHandler(Request $request): JsonResponse
|
||||
{
|
||||
$tokenData = $request->input('token_data');
|
||||
try {
|
||||
$tokenData = $this->tokenService->validateToken($request->input('access_token'));
|
||||
} catch (RequiredConstraintsViolated|InvalidTokenStructure) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
$scopes = $tokenData['scope'];
|
||||
if (is_string($scopes)) {
|
||||
$scopes = explode(' ', $scopes);
|
||||
return $micropubResponses->invalidTokenResponse();
|
||||
}
|
||||
if (! in_array('create', $scopes, true)) {
|
||||
return (new MicropubResponses)->insufficientScopeResponse();
|
||||
|
||||
if ($tokenData->claims()->has('scope') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->tokenHasNoScopeResponse();
|
||||
}
|
||||
|
||||
if (Str::contains($tokenData->claims()->get('scope'), 'create') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->insufficientScopeResponse();
|
||||
}
|
||||
|
||||
if ($request->input('q') === 'last') {
|
||||
|
@ -75,22 +98,34 @@ class MicropubMediaController extends Controller
|
|||
/**
|
||||
* Process a media item posted to the media endpoint.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*
|
||||
* @throws BindingResolutionException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function media(Request $request): JsonResponse
|
||||
public function media(): JsonResponse
|
||||
{
|
||||
$tokenData = $request->input('token_data');
|
||||
try {
|
||||
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
|
||||
} catch (RequiredConstraintsViolated|InvalidTokenStructure $exception) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
$scopes = $tokenData['scope'];
|
||||
if (is_string($scopes)) {
|
||||
$scopes = explode(' ', $scopes);
|
||||
}
|
||||
if (! in_array('create', $scopes, true)) {
|
||||
return (new MicropubResponses)->insufficientScopeResponse();
|
||||
return $micropubResponses->invalidTokenResponse();
|
||||
}
|
||||
|
||||
if ($request->hasFile('file') === false) {
|
||||
if ($tokenData->claims()->has('scope') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->tokenHasNoScopeResponse();
|
||||
}
|
||||
|
||||
if (Str::contains($tokenData->claims()->get('scope'), 'create') === false) {
|
||||
$micropubResponses = new MicropubResponses();
|
||||
|
||||
return $micropubResponses->insufficientScopeResponse();
|
||||
}
|
||||
|
||||
if (request()->hasFile('file') === false) {
|
||||
return response()->json([
|
||||
'response' => 'error',
|
||||
'error' => 'invalid_request',
|
||||
|
@ -98,10 +133,7 @@ class MicropubMediaController extends Controller
|
|||
], 400);
|
||||
}
|
||||
|
||||
/** @var UploadedFile $file */
|
||||
$file = $request->file('file');
|
||||
|
||||
if ($file->isValid() === false) {
|
||||
if (request()->file('file')->isValid() === false) {
|
||||
return response()->json([
|
||||
'response' => 'error',
|
||||
'error' => 'invalid_request',
|
||||
|
@ -109,25 +141,31 @@ class MicropubMediaController extends Controller
|
|||
], 400);
|
||||
}
|
||||
|
||||
$filename = Storage::disk('local')->putFile('media', $file);
|
||||
$filename = $this->saveFile(request()->file('file'));
|
||||
|
||||
/** @var ImageManager $manager */
|
||||
$manager = resolve(ImageManager::class);
|
||||
try {
|
||||
$image = $manager->read($request->file('file'));
|
||||
$image = $manager->make(request()->file('file'));
|
||||
$width = $image->width();
|
||||
} catch (Exception) {
|
||||
} catch (NotReadableException $exception) {
|
||||
// not an image
|
||||
$width = null;
|
||||
}
|
||||
|
||||
$media = Media::create([
|
||||
'token' => $request->input('access_token'),
|
||||
'path' => $filename,
|
||||
'type' => $this->getFileTypeFromMimeType($request->file('file')->getMimeType()),
|
||||
'token' => request()->bearerToken(),
|
||||
'path' => 'media/' . $filename,
|
||||
'type' => $this->getFileTypeFromMimeType(request()->file('file')->getMimeType()),
|
||||
'image_widths' => $width,
|
||||
]);
|
||||
|
||||
// put the file on S3 initially, the ProcessMedia job may edit this
|
||||
Storage::disk('s3')->putFileAs(
|
||||
'media',
|
||||
new File(storage_path('app') . '/' . $filename),
|
||||
$filename
|
||||
);
|
||||
|
||||
ProcessMedia::dispatch($filename);
|
||||
|
||||
return response()->json([
|
||||
|
@ -138,6 +176,8 @@ class MicropubMediaController extends Controller
|
|||
|
||||
/**
|
||||
* Return the relevant CORS headers to a pre-flight OPTIONS request.
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
public function mediaOptionsResponse(): Response
|
||||
{
|
||||
|
@ -146,6 +186,9 @@ class MicropubMediaController extends Controller
|
|||
|
||||
/**
|
||||
* Get the file type from the mime-type of the uploaded file.
|
||||
*
|
||||
* @param string $mimeType
|
||||
* @return string
|
||||
*/
|
||||
private function getFileTypeFromMimeType(string $mimeType): string
|
||||
{
|
||||
|
@ -189,9 +232,12 @@ class MicropubMediaController extends Controller
|
|||
/**
|
||||
* Save an uploaded file to the local disk.
|
||||
*
|
||||
* @param UploadedFile $file
|
||||
* @return string
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
private function saveFileToLocal(UploadedFile $file): string
|
||||
private function saveFile(UploadedFile $file): string
|
||||
{
|
||||
$filename = Uuid::uuid4()->toString() . '.' . $file->extension();
|
||||
Storage::disk('local')->putFileAs('', $file, $filename);
|
||||
|
|
|
@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Note;
|
||||
use App\Services\ActivityStreamsService;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
@ -12,26 +13,25 @@ use Illuminate\Http\Response;
|
|||
use Illuminate\View\View;
|
||||
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.
|
||||
*
|
||||
* @return View|Response
|
||||
*/
|
||||
public function index(): View|Response
|
||||
public function index()
|
||||
{
|
||||
if (request()->wantsActivityStream()) {
|
||||
return (new ActivityStreamsService())->siteOwnerResponse();
|
||||
}
|
||||
|
||||
$notes = Note::latest()
|
||||
->with('place', 'media', 'client')
|
||||
->withCount(['webmentions AS replies' => function ($query) {
|
||||
->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);
|
||||
|
||||
return view('notes.index', compact('notes'));
|
||||
|
@ -39,37 +39,41 @@ class NotesController extends Controller
|
|||
|
||||
/**
|
||||
* Show a single note.
|
||||
*
|
||||
* @param string $urlId The id of the note
|
||||
* @return View|JsonResponse|Response
|
||||
*/
|
||||
public function show(string $urlId): View|JsonResponse|Response
|
||||
public function show(string $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();
|
||||
$note = Note::nb60($urlId)->with('webmentions')->firstOrFail();
|
||||
} catch (ModelNotFoundException $exception) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if (request()->wantsActivityStream()) {
|
||||
return (new ActivityStreamsService())->singleNoteResponse($note);
|
||||
}
|
||||
|
||||
return view('notes.show', compact('note'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect /note/{decID} to /notes/{nb60id}.
|
||||
*
|
||||
* @param int $decId The decimal id of the note
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function redirect(int $decId): RedirectResponse
|
||||
{
|
||||
return redirect(config('app.url') . '/notes/' . (new Numbers)->numto60($decId));
|
||||
return redirect(config('app.url') . '/notes/' . (new Numbers())->numto60($decId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Show all notes tagged with {tag}.
|
||||
*
|
||||
* @param string $tag
|
||||
* @return View
|
||||
*/
|
||||
public function tagged(string $tag): View
|
||||
{
|
||||
|
@ -84,6 +88,8 @@ class NotesController extends Controller
|
|||
* Page to create a new note.
|
||||
*
|
||||
* Dummy page for now.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
|
|
|
@ -11,6 +11,8 @@ class PlacesController extends Controller
|
|||
{
|
||||
/**
|
||||
* Show all the places.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
|
@ -21,6 +23,9 @@ class PlacesController extends Controller
|
|||
|
||||
/**
|
||||
* Show a specific place.
|
||||
*
|
||||
* @param Place $place
|
||||
* @return View
|
||||
*/
|
||||
public function show(Place $place): View
|
||||
{
|
||||
|
|
|
@ -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'));
|
||||
}
|
||||
}
|
59
app/Http/Controllers/ShortURLsController.php
Normal file
59
app/Http/Controllers/ShortURLsController.php
Normal file
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class ShortURLsController extends Controller
|
||||
{
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Short URL Controller
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This redirects the short urls to long ones
|
||||
|
|
||||
*/
|
||||
|
||||
/**
|
||||
* Redirect from '/' to the long url.
|
||||
*
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function baseURL(): RedirectResponse
|
||||
{
|
||||
return redirect(config('app.url'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect from '/@' to a twitter profile.
|
||||
*
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public function twitter(): RedirectResponse
|
||||
{
|
||||
return redirect('https://twitter.com/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 RedirectResponse
|
||||
*/
|
||||
public function expandType(string $type, string $postId): RedirectResponse
|
||||
{
|
||||
if ($type == 't') {
|
||||
$type = 'notes';
|
||||
}
|
||||
if ($type == 'b') {
|
||||
$type = 'blog/s';
|
||||
}
|
||||
|
||||
return redirect(config('app.url') . '/' . $type . '/' . $postId);
|
||||
}
|
||||
}
|
116
app/Http/Controllers/TokenEndpointController.php
Normal file
116
app/Http/Controllers/TokenEndpointController.php
Normal file
|
@ -0,0 +1,116 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\TokenService;
|
||||
use GuzzleHttp\Client as GuzzleClient;
|
||||
use GuzzleHttp\Exception\BadResponseException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use IndieAuth\Client;
|
||||
use JsonException;
|
||||
|
||||
class TokenEndpointController extends Controller
|
||||
{
|
||||
/**
|
||||
* @var Client The IndieAuth Client.
|
||||
*/
|
||||
protected Client $client;
|
||||
|
||||
/**
|
||||
* @var GuzzleClient The GuzzleHttp client.
|
||||
*/
|
||||
protected GuzzleClient $guzzle;
|
||||
|
||||
/**
|
||||
* @var TokenService The Token handling service.
|
||||
*/
|
||||
protected TokenService $tokenService;
|
||||
|
||||
/**
|
||||
* Inject the dependencies.
|
||||
*
|
||||
* @param Client $client
|
||||
* @param GuzzleClient $guzzle
|
||||
* @param TokenService $tokenService
|
||||
*/
|
||||
public function __construct(
|
||||
Client $client,
|
||||
GuzzleClient $guzzle,
|
||||
TokenService $tokenService
|
||||
) {
|
||||
$this->client = $client;
|
||||
$this->guzzle = $guzzle;
|
||||
$this->tokenService = $tokenService;
|
||||
}
|
||||
|
||||
/**
|
||||
* If the user has auth’d via the IndieAuth protocol, issue a valid token.
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function create(Request $request): JsonResponse
|
||||
{
|
||||
$auth = $this->verifyIndieAuthCode(
|
||||
config('app.authorization_endpoint'),
|
||||
$request->input('code'),
|
||||
$request->input('redirect_uri'),
|
||||
$request->input('client_id'),
|
||||
);
|
||||
|
||||
if ($auth === null || ! array_key_exists('me', $auth)) {
|
||||
return response()->json([
|
||||
'error' => 'There was an error verifying the IndieAuth code',
|
||||
], 401);
|
||||
}
|
||||
|
||||
$scope = $auth['scope'] ?? '';
|
||||
$tokenData = [
|
||||
'me' => config('app.url'),
|
||||
'client_id' => $request->input('client_id'),
|
||||
'scope' => $scope,
|
||||
];
|
||||
$token = $this->tokenService->getNewToken($tokenData);
|
||||
$content = [
|
||||
'me' => config('app.url'),
|
||||
'scope' => $scope,
|
||||
'access_token' => $token,
|
||||
];
|
||||
|
||||
return response()->json($content);
|
||||
}
|
||||
|
||||
protected function verifyIndieAuthCode(
|
||||
string $authorizationEndpoint,
|
||||
string $code,
|
||||
string $redirectUri,
|
||||
string $clientId
|
||||
): ?array {
|
||||
try {
|
||||
$response = $this->guzzle->request('POST', $authorizationEndpoint, [
|
||||
'headers' => [
|
||||
'Accept' => 'application/json',
|
||||
],
|
||||
'form_params' => [
|
||||
'code' => $code,
|
||||
'me' => config('app.url'),
|
||||
'redirect_uri' => $redirectUri,
|
||||
'client_id' => $clientId,
|
||||
],
|
||||
]);
|
||||
} catch (BadResponseException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$authData = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (JsonException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $authData;
|
||||
}
|
||||
}
|
|
@ -7,7 +7,6 @@ namespace App\Http\Controllers;
|
|||
use App\Jobs\ProcessWebMention;
|
||||
use App\Models\Note;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\View\View;
|
||||
use Jonnybarnes\IndieWeb\Numbers;
|
||||
|
@ -19,6 +18,8 @@ class WebMentionsController extends Controller
|
|||
*
|
||||
* This is probably someone looking for information about what
|
||||
* webmentions are, or about my particular implementation.
|
||||
*
|
||||
* @return View
|
||||
*/
|
||||
public function get(): View
|
||||
{
|
||||
|
@ -27,11 +28,13 @@ class WebMentionsController extends Controller
|
|||
|
||||
/**
|
||||
* Receive and process a webmention.
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
public function receive(Request $request): Response
|
||||
public function receive(): Response
|
||||
{
|
||||
//first we trivially reject requests that lack all required inputs
|
||||
if (($request->has('target') !== true) || ($request->has('source') !== true)) {
|
||||
if ((request()->has('target') !== true) || (request()->has('source') !== true)) {
|
||||
return response(
|
||||
'You need both the target and source parameters',
|
||||
400
|
||||
|
@ -39,15 +42,15 @@ class WebMentionsController extends Controller
|
|||
}
|
||||
|
||||
//next check the $target is valid
|
||||
$path = parse_url($request->input('target'), PHP_URL_PATH);
|
||||
$path = parse_url(request()->input('target'), PHP_URL_PATH);
|
||||
$pathParts = explode('/', $path);
|
||||
|
||||
if ($pathParts[1] === 'notes') {
|
||||
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')));
|
||||
dispatch(new ProcessWebMention($note, request()->input('source')));
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return response('This note doesn’t exist.', 400);
|
||||
}
|
||||
|
@ -57,7 +60,7 @@ class WebMentionsController extends Controller
|
|||
202
|
||||
);
|
||||
}
|
||||
if ($pathParts[1] === 'blog') {
|
||||
if ($pathParts[1] == 'blog') {
|
||||
return response(
|
||||
'I don’t accept webmentions for blog posts yet.',
|
||||
501
|
||||
|
|
73
app/Http/Kernel.php
Normal file
73
app/Http/Kernel.php
Normal file
|
@ -0,0 +1,73 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
|
||||
class Kernel extends HttpKernel
|
||||
{
|
||||
/**
|
||||
* The application's global HTTP middleware stack.
|
||||
*
|
||||
* These middleware are run during every request to your application.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $middleware = [
|
||||
// \App\Http\Middleware\TrustHosts::class,
|
||||
\App\Http\Middleware\TrustProxies::class,
|
||||
\Illuminate\Http\Middleware\HandleCors::class,
|
||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||
\App\Http\Middleware\TrimStrings::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware groups.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $middlewareGroups = [
|
||||
'web' => [
|
||||
\App\Http\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
// \Illuminate\Session\Middleware\AuthenticateSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
\App\Http\Middleware\LinkHeadersMiddleware::class,
|
||||
\App\Http\Middleware\LocalhostSessionMiddleware::class,
|
||||
\App\Http\Middleware\ActivityStreamLinks::class,
|
||||
\App\Http\Middleware\CSPHeader::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
'throttle:api',
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* 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,
|
||||
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
||||
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
||||
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
||||
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
||||
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
'micropub.token' => \App\Http\Middleware\VerifyMicropubToken::class,
|
||||
'myauth' => \App\Http\Middleware\MyAuthMiddleware::class,
|
||||
'cors' => \App\Http\Middleware\CorsHeaders::class,
|
||||
];
|
||||
}
|
31
app/Http/Middleware/ActivityStreamLinks.php
Normal file
31
app/Http/Middleware/ActivityStreamLinks.php
Normal file
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ActivityStreamLinks
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
$response = $next($request);
|
||||
if ($request->path() === '/') {
|
||||
$response->header('Link', '<' . config('app.url') . '>; rel="application/activity+json"', false);
|
||||
}
|
||||
if ($request->is('notes/*')) {
|
||||
$response->header('Link', '<' . $request->url() . '>; rel="application/activity+json"', false);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
|
@ -3,7 +3,6 @@
|
|||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
|
@ -12,9 +11,14 @@ class Authenticate extends Middleware
|
|||
{
|
||||
/**
|
||||
* Get the path the user should be redirected to when they are not authenticated.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return string
|
||||
*/
|
||||
protected function redirectTo(Request $request): ?string
|
||||
protected function redirectTo($request)
|
||||
{
|
||||
return $request->expectsJson() ? null : route('login');
|
||||
if (! $request->expectsJson()) {
|
||||
return route('login');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
49
app/Http/Middleware/CSPHeader.php
Normal file
49
app/Http/Middleware/CSPHeader.php
Normal file
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\App;
|
||||
|
||||
class CSPHeader
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param Request $request
|
||||
* @param Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($request, Closure $next)
|
||||
{
|
||||
if (App::environment('local', 'development')) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// headers have to be single-line strings,
|
||||
// so we concat multiple lines
|
||||
// phpcs:disable Generic.Files.LineLength.TooLong
|
||||
return $next($request)
|
||||
->header(
|
||||
'Content-Security-Policy',
|
||||
"default-src 'self'; " .
|
||||
"style-src 'self' cloud.typography.com jonnybarnes.uk; " .
|
||||
"img-src 'self' data: blob: https://pbs.twimg.com https://jbuk-media.s3-eu-west-1.amazonaws.com https://jbuk-media-dev.s3-eu-west-1.amazonaws.com https://secure.gravatar.com https://graph.facebook.com *.fbcdn.net https://*.cdninstagram.com https://*.4sqi.net https://upload.wikimedia.org; " .
|
||||
"font-src 'self' data:; " .
|
||||
"frame-src 'self' https://www.youtube.com blob:; " .
|
||||
'upgrade-insecure-requests; ' .
|
||||
'block-all-mixed-content; ' .
|
||||
'report-to csp-endpoint; ' .
|
||||
'report-uri https://jonnybarnes.report-uri.io/r/default/csp/enforce;'
|
||||
)->header(
|
||||
'Report-To',
|
||||
'{' .
|
||||
"'url': 'https://jonnybarnes.report-uri.io/r/default/csp/enforce', " .
|
||||
"'group': 'csp-endpoint', " .
|
||||
"'max-age': 10886400" .
|
||||
'}'
|
||||
);
|
||||
// phpcs:enable Generic.Files.LineLength.TooLong
|
||||
}
|
||||
}
|
17
app/Http/Middleware/CheckForMaintenanceMode.php
Normal file
17
app/Http/Middleware/CheckForMaintenanceMode.php
Normal file
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
|
||||
|
||||
class CheckForMaintenanceMode extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
|
@ -3,15 +3,17 @@
|
|||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CorsHeaders
|
||||
{
|
||||
/**
|
||||
* 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);
|
||||
if ($request->path() === 'api/media') {
|
||||
|
|
|
@ -9,7 +9,7 @@ class EncryptCookies extends Middleware
|
|||
/**
|
||||
* The names of the cookies that should not be encrypted.
|
||||
*
|
||||
* @var array<int, string>
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -6,7 +6,6 @@ namespace App\Http\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class LocalhostSessionMiddleware
|
||||
{
|
||||
|
@ -14,8 +13,12 @@ class LocalhostSessionMiddleware
|
|||
* Whilst we are developing locally, automatically log in as
|
||||
* `['me' => config('app.url')]` as I can’t manually log in as
|
||||
* a .localhost domain.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if (config('app.env') !== 'production') {
|
||||
session(['me' => config('app.url')]);
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -7,19 +7,20 @@ 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 $request, Closure $next)
|
||||
{
|
||||
if (Auth::check() === false) {
|
||||
if (Auth::check($request->user()) == false) {
|
||||
//they’re not logged in, so send them to login form
|
||||
redirect()->setIntendedUrl($request->fullUrl());
|
||||
|
||||
return redirect()->route('login');
|
||||
}
|
||||
|
||||
|
|
|
@ -9,7 +9,7 @@ class PreventRequestsDuringMaintenance extends Middleware
|
|||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array<int, string>
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
|
|
|
@ -6,7 +6,6 @@ use App\Providers\RouteServiceProvider;
|
|||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
|
@ -16,9 +15,12 @@ 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 ...$guards
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string ...$guards): Response
|
||||
public function handle(Request $request, Closure $next, ...$guards)
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
|
|
|
@ -9,10 +9,9 @@ class TrimStrings extends Middleware
|
|||
/**
|
||||
* The names of the attributes that should not be trimmed.
|
||||
*
|
||||
* @var array<int, string>
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
|
|
@ -12,9 +12,9 @@ class TrustHosts extends Middleware
|
|||
/**
|
||||
* Get the host patterns that should be trusted.
|
||||
*
|
||||
* @return array<int, string|null>
|
||||
* @return array
|
||||
*/
|
||||
public function hosts(): array
|
||||
public function hosts()
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
|
|
|
@ -10,7 +10,7 @@ class TrustProxies extends Middleware
|
|||
/**
|
||||
* The trusted proxies for this application.
|
||||
*
|
||||
* @var array<int, string>|string|null
|
||||
* @var array|string
|
||||
*/
|
||||
protected $proxies;
|
||||
|
||||
|
|
|
@ -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',
|
||||
];
|
||||
}
|
|
@ -9,7 +9,7 @@ class VerifyCsrfToken extends Middleware
|
|||
/**
|
||||
* The URIs that should be excluded from CSRF verification.
|
||||
*
|
||||
* @var array<int, string>
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
'api/media',
|
||||
|
|
|
@ -4,78 +4,34 @@ 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
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
$rawToken = null;
|
||||
|
||||
if ($request->input('access_token')) {
|
||||
$rawToken = $request->input('access_token');
|
||||
} elseif ($request->bearerToken()) {
|
||||
$rawToken = $request->bearerToken();
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if ($request->bearerToken()) {
|
||||
return $next($request->merge([
|
||||
'access_token' => $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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -10,6 +10,8 @@ class MicropubResponses
|
|||
{
|
||||
/**
|
||||
* Generate a response to be returned when the token has insufficient scope.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function insufficientScopeResponse(): JsonResponse
|
||||
{
|
||||
|
@ -22,6 +24,8 @@ class MicropubResponses
|
|||
|
||||
/**
|
||||
* Generate a response to be returned when the token is invalid.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function invalidTokenResponse(): JsonResponse
|
||||
{
|
||||
|
@ -34,6 +38,8 @@ class MicropubResponses
|
|||
|
||||
/**
|
||||
* Generate a response to be returned when the token has no scope.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function tokenHasNoScopeResponse(): JsonResponse
|
||||
{
|
||||
|
|
|
@ -18,22 +18,26 @@ class AddClientToDatabase implements ShouldQueue
|
|||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
protected string $client_id;
|
||||
protected $client_id;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param string $client_id
|
||||
*/
|
||||
public function __construct(string $clientId)
|
||||
public function __construct(string $client_id)
|
||||
{
|
||||
$this->client_id = $clientId;
|
||||
$this->client_id = $client_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle(): void
|
||||
public function handle()
|
||||
{
|
||||
if (MicropubClient::where('client_url', $this->client_id)->count() === 0) {
|
||||
if (MicropubClient::where('client_url', $this->client_id)->count() == 0) {
|
||||
MicropubClient::create([
|
||||
'client_url' => $this->client_id,
|
||||
'client_name' => $this->client_id, // default client name is the URL
|
||||
|
|
|
@ -20,25 +20,37 @@ class DownloadWebMention implements ShouldQueue
|
|||
use SerializesModels;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
* The webmention source URL.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public function __construct(
|
||||
protected string $source
|
||||
) {}
|
||||
protected $source;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param string $source
|
||||
*/
|
||||
public function __construct(string $source)
|
||||
{
|
||||
$this->source = $source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param Client $guzzle
|
||||
*
|
||||
* @throws GuzzleException
|
||||
* @throws FileNotFoundException
|
||||
*/
|
||||
public function handle(Client $guzzle): void
|
||||
public function handle(Client $guzzle)
|
||||
{
|
||||
$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;
|
||||
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';
|
||||
|
@ -60,7 +72,7 @@ class DownloadWebMention implements ShouldQueue
|
|||
);
|
||||
//remove backup if the same
|
||||
if ($filesystem->exists($filenameBackup)) {
|
||||
if ($filesystem->get($filename) === $filesystem->get($filenameBackup)) {
|
||||
if ($filesystem->get($filename) == $filesystem->get($filenameBackup)) {
|
||||
$filesystem->delete($filenameBackup);
|
||||
}
|
||||
}
|
||||
|
@ -69,11 +81,14 @@ class DownloadWebMention implements ShouldQueue
|
|||
|
||||
/**
|
||||
* Create a file path from a URL. This is used when caching the HTML response.
|
||||
*
|
||||
* @param string $url
|
||||
* @return string The path name
|
||||
*/
|
||||
private function createFilenameFromURL(string $url): string
|
||||
private function createFilenameFromURL(string $url)
|
||||
{
|
||||
$filepath = str_replace(['https://', 'http://'], ['https/', 'http/'], $url);
|
||||
if (str_ends_with($filepath, '/')) {
|
||||
if (substr($filepath, -1) == '/') {
|
||||
$filepath .= 'index.html';
|
||||
}
|
||||
|
||||
|
|
|
@ -20,15 +20,22 @@ class ProcessBookmark implements ShouldQueue
|
|||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
protected Bookmark $bookmark;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param Bookmark $bookmark
|
||||
*/
|
||||
public function __construct(
|
||||
protected Bookmark $bookmark
|
||||
) {}
|
||||
public function __construct(Bookmark $bookmark)
|
||||
{
|
||||
$this->bookmark = $bookmark;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle(): void
|
||||
{
|
||||
|
|
|
@ -25,16 +25,26 @@ class ProcessLike implements ShouldQueue
|
|||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
/** @var Like */
|
||||
protected $like;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param Like $like
|
||||
*/
|
||||
public function __construct(
|
||||
protected Like $like
|
||||
) {}
|
||||
public function __construct(Like $like)
|
||||
{
|
||||
$this->like = $like;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param Client $client
|
||||
* @param Authorship $authorship
|
||||
* @return int
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function handle(Client $client, Authorship $authorship): int
|
||||
|
@ -94,6 +104,9 @@ class ProcessLike implements ShouldQueue
|
|||
|
||||
/**
|
||||
* Determine if a given URL is that of a Tweet.
|
||||
*
|
||||
* @param string $url
|
||||
* @return bool
|
||||
*/
|
||||
private function isTweet(string $url): bool
|
||||
{
|
||||
|
|
|
@ -10,7 +10,7 @@ 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\Exception\NotReadableException;
|
||||
use Intervention\Image\ImageManager;
|
||||
|
||||
class ProcessMedia implements ShouldQueue
|
||||
|
@ -20,50 +20,55 @@ class ProcessMedia implements ShouldQueue
|
|||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
/** @var string */
|
||||
protected $filename;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param string $filename
|
||||
*/
|
||||
public function __construct(
|
||||
protected string $filename
|
||||
) {}
|
||||
public function __construct(string $filename)
|
||||
{
|
||||
$this->filename = $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param ImageManager $manager
|
||||
*/
|
||||
public function handle(ImageManager $manager): void
|
||||
public function handle(ImageManager $manager)
|
||||
{
|
||||
// Load file
|
||||
$file = Storage::disk('local')->get('media/' . $this->filename);
|
||||
|
||||
// Open file
|
||||
//open file
|
||||
try {
|
||||
$image = $manager->read($file);
|
||||
} catch (DecoderException) {
|
||||
$image = $manager->make(storage_path('app') . '/' . $this->filename);
|
||||
} catch (NotReadableException $exception) {
|
||||
// not an image; delete file and end job
|
||||
Storage::disk('local')->delete('media/' . $this->filename);
|
||||
unlink(storage_path('app') . '/' . $this->filename);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Save the file publicly
|
||||
Storage::disk('public')->put('media/' . $this->filename, $file);
|
||||
|
||||
// Create smaller versions if necessary
|
||||
//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());
|
||||
$basename = ltrim(array_reduce($filenameParts, function ($carry, $item) {
|
||||
return $carry . '.' . $item;
|
||||
}, ''), '.');
|
||||
$medium = $image->resize(1000, null, function ($constraint) {
|
||||
$constraint->aspectRatio();
|
||||
});
|
||||
Storage::disk('s3')->put('media/' . $basename . '-medium.' . $extension, (string) $medium->encode());
|
||||
$small = $image->resize(500, null, function ($constraint) {
|
||||
$constraint->aspectRatio();
|
||||
});
|
||||
Storage::disk('s3')->put('media/' . $basename . '-small.' . $extension, (string) $small->encode());
|
||||
}
|
||||
|
||||
// Now we can delete the locally saved image
|
||||
Storage::disk('local')->delete('media/' . $this->filename);
|
||||
// now we can delete the locally saved image
|
||||
unlink(storage_path('app') . '/' . $this->filename);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -24,27 +24,40 @@ class ProcessWebMention implements ShouldQueue
|
|||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
/** @var Note */
|
||||
protected $note;
|
||||
|
||||
/** @var string */
|
||||
protected $source;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param Note $note
|
||||
* @param string $source
|
||||
*/
|
||||
public function __construct(
|
||||
protected Note $note,
|
||||
protected string $source
|
||||
) {}
|
||||
public function __construct(Note $note, string $source)
|
||||
{
|
||||
$this->note = $note;
|
||||
$this->source = $source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param Parser $parser
|
||||
* @param Client $guzzle
|
||||
*
|
||||
* @throws RemoteContentNotFoundException
|
||||
* @throws GuzzleException
|
||||
* @throws InvalidMentionException
|
||||
*/
|
||||
public function handle(Parser $parser, Client $guzzle): void
|
||||
public function handle(Parser $parser, Client $guzzle)
|
||||
{
|
||||
try {
|
||||
$response = $guzzle->request('GET', $this->source);
|
||||
} catch (RequestException $e) {
|
||||
throw new RemoteContentNotFoundException;
|
||||
throw new RemoteContentNotFoundException();
|
||||
}
|
||||
$this->saveRemoteContent((string) $response->getBody(), $this->source);
|
||||
$microformats = Mf2\parse((string) $response->getBody(), $this->source);
|
||||
|
@ -52,8 +65,8 @@ class ProcessWebMention implements ShouldQueue
|
|||
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) {
|
||||
if ($webmention->type == 'in-reply-to') {
|
||||
if ($parser->checkInReplyTo($microformats, $this->note->longurl) == false) {
|
||||
// it doesn’t so delete
|
||||
$webmention->delete();
|
||||
|
||||
|
@ -66,16 +79,16 @@ class ProcessWebMention implements ShouldQueue
|
|||
|
||||
return;
|
||||
}
|
||||
if ($webmention->type === 'like-of') {
|
||||
if ($parser->checkLikeOf($microformats, $this->note->uri) === false) {
|
||||
if ($webmention->type == 'like-of') {
|
||||
if ($parser->checkLikeOf($microformats, $this->note->longurl) == false) {
|
||||
// it doesn’t so delete
|
||||
$webmention->delete();
|
||||
|
||||
return;
|
||||
} // note we don’t need to do anything if it still is a like
|
||||
}
|
||||
if ($webmention->type === 'repost-of') {
|
||||
if ($parser->checkRepostOf($microformats, $this->note->uri) === false) {
|
||||
if ($webmention->type == 'repost-of') {
|
||||
if ($parser->checkRepostOf($microformats, $this->note->longurl) == false) {
|
||||
// it doesn’t so delete
|
||||
$webmention->delete();
|
||||
|
||||
|
@ -85,13 +98,13 @@ class ProcessWebMention implements ShouldQueue
|
|||
}// foreach
|
||||
|
||||
// no webmention in the db so create new one
|
||||
$webmention = new WebMention;
|
||||
$webmention = new WebMention();
|
||||
$type = $parser->getMentionType($microformats); // throw error here?
|
||||
dispatch(new SaveProfileImage($microformats));
|
||||
$webmention->source = $this->source;
|
||||
$webmention->target = $this->note->uri;
|
||||
$webmention->target = $this->note->longurl;
|
||||
$webmention->commentable_id = $this->note->id;
|
||||
$webmention->commentable_type = Note::class;
|
||||
$webmention->commentable_type = 'App\Model\Note';
|
||||
$webmention->type = $type;
|
||||
$webmention->mf2 = json_encode($microformats);
|
||||
$webmention->save();
|
||||
|
@ -99,23 +112,26 @@ class ProcessWebMention implements ShouldQueue
|
|||
|
||||
/**
|
||||
* Save the HTML of a webmention for future use.
|
||||
*
|
||||
* @param string $html
|
||||
* @param string $url
|
||||
*/
|
||||
private function saveRemoteContent(string $html, string $url): void
|
||||
private function saveRemoteContent($html, $url)
|
||||
{
|
||||
$filenameFromURL = str_replace(
|
||||
['https://', 'http://'],
|
||||
['https/', 'http/'],
|
||||
$url
|
||||
);
|
||||
if (str_ends_with($url, '/')) {
|
||||
if (substr($url, -1) == '/') {
|
||||
$filenameFromURL .= 'index.html';
|
||||
}
|
||||
$path = storage_path() . '/HTML/' . $filenameFromURL;
|
||||
$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));
|
||||
if (! is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
file_put_contents("$dir/$name", $html);
|
||||
}
|
||||
|
|
|
@ -20,40 +20,39 @@ class SaveProfileImage implements ShouldQueue
|
|||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
protected array $microformats;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param array $microformats
|
||||
*/
|
||||
public function __construct(
|
||||
protected array $microformats
|
||||
) {}
|
||||
public function __construct(array $microformats)
|
||||
{
|
||||
$this->microformats = $microformats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param Authorship $authorship
|
||||
*/
|
||||
public function handle(Authorship $authorship): void
|
||||
public function handle(Authorship $authorship)
|
||||
{
|
||||
try {
|
||||
$author = $authorship->findAuthor($this->microformats);
|
||||
} catch (AuthorshipParserException) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
$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'
|
||||
&& parse_url($photo, PHP_URL_HOST) != 'pbs.twimg.com'
|
||||
&& parse_url($photo, PHP_URL_HOST) != 'twitter.com'
|
||||
) {
|
||||
$client = resolve(Client::class);
|
||||
|
||||
|
@ -72,8 +71,8 @@ class SaveProfileImage implements ShouldQueue
|
|||
$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));
|
||||
if (! is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
file_put_contents("$dir/$name", $image);
|
||||
}
|
||||
|
|
|
@ -18,16 +18,22 @@ class SaveScreenshot implements ShouldQueue
|
|||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
private Bookmark $bookmark;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct(
|
||||
protected Bookmark $bookmark
|
||||
) {}
|
||||
public function __construct(Bookmark $bookmark)
|
||||
{
|
||||
$this->bookmark = $bookmark;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @throws JsonException
|
||||
*/
|
||||
|
|
|
@ -22,16 +22,23 @@ class SendWebMentions implements ShouldQueue
|
|||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
protected Note $note;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
* Create the job instance, inject dependencies.
|
||||
*
|
||||
* @param Note $note
|
||||
*/
|
||||
public function __construct(
|
||||
protected Note $note
|
||||
) {}
|
||||
public function __construct(Note $note)
|
||||
{
|
||||
$this->note = $note;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function handle(): void
|
||||
|
@ -45,7 +52,7 @@ class SendWebMentions implements ShouldQueue
|
|||
$guzzle = resolve(Client::class);
|
||||
$guzzle->post($endpoint, [
|
||||
'form_params' => [
|
||||
'source' => $this->note->uri,
|
||||
'source' => $this->note->longurl,
|
||||
'target' => $url,
|
||||
],
|
||||
]);
|
||||
|
@ -56,12 +63,15 @@ class SendWebMentions implements ShouldQueue
|
|||
/**
|
||||
* Discover if a URL has a webmention endpoint.
|
||||
*
|
||||
* @param string $url
|
||||
* @return string|null
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function discoverWebmentionEndpoint(string $url): ?string
|
||||
{
|
||||
// let’s not send webmentions to myself
|
||||
if (parse_url($url, PHP_URL_HOST) === parse_url(config('app.url'), PHP_URL_HOST)) {
|
||||
if (parse_url($url, PHP_URL_HOST) === config('app.longurl')) {
|
||||
return null;
|
||||
}
|
||||
if (Str::startsWith($url, '/notes/tagged/')) {
|
||||
|
@ -70,12 +80,13 @@ class SendWebMentions implements ShouldQueue
|
|||
|
||||
$endpoint = null;
|
||||
|
||||
/** @var Client $guzzle */
|
||||
$guzzle = resolve(Client::class);
|
||||
$response = $guzzle->get($url);
|
||||
//check HTTP Headers for webmention endpoint
|
||||
$links = Header::parse($response->getHeader('Link'));
|
||||
foreach ($links as $link) {
|
||||
if (array_key_exists('rel', $link) && mb_stristr($link['rel'], 'webmention')) {
|
||||
if (mb_stristr($link['rel'], 'webmention')) {
|
||||
return $this->resolveUri(trim($link[0], '<>'), $url);
|
||||
}
|
||||
}
|
||||
|
@ -100,6 +111,9 @@ class SendWebMentions implements ShouldQueue
|
|||
|
||||
/**
|
||||
* Get the URLs from a note.
|
||||
*
|
||||
* @param string|null $html
|
||||
* @return array
|
||||
*/
|
||||
public function getLinks(?string $html): array
|
||||
{
|
||||
|
@ -108,7 +122,7 @@ class SendWebMentions implements ShouldQueue
|
|||
}
|
||||
|
||||
$urls = [];
|
||||
$dom = new \DOMDocument;
|
||||
$dom = new \DOMDocument();
|
||||
$dom->loadHTML($html);
|
||||
$anchors = $dom->getElementsByTagName('a');
|
||||
foreach ($anchors as $anchor) {
|
||||
|
@ -120,6 +134,10 @@ class SendWebMentions implements ShouldQueue
|
|||
|
||||
/**
|
||||
* Resolve a URI if necessary.
|
||||
*
|
||||
* @param string $url
|
||||
* @param string $base The base of the URL
|
||||
* @return string
|
||||
*/
|
||||
public function resolveUri(string $url, string $base): string
|
||||
{
|
||||
|
|
66
app/Jobs/SyndicateBookmarkToTwitter.php
Normal file
66
app/Jobs/SyndicateBookmarkToTwitter.php
Normal file
|
@ -0,0 +1,66 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Bookmark;
|
||||
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 SyndicateBookmarkToTwitter implements ShouldQueue
|
||||
{
|
||||
use Dispatchable;
|
||||
use InteractsWithQueue;
|
||||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
/** @var Bookmark */
|
||||
protected $bookmark;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param Bookmark $bookmark
|
||||
*/
|
||||
public function __construct(Bookmark $bookmark)
|
||||
{
|
||||
$this->bookmark = $bookmark;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param Client $guzzle
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function handle(Client $guzzle)
|
||||
{
|
||||
//send webmention
|
||||
$response = $guzzle->request(
|
||||
'POST',
|
||||
'https://brid.gy/publish/webmention',
|
||||
[
|
||||
'form_params' => [
|
||||
'source' => $this->bookmark->longurl,
|
||||
'target' => 'https://brid.gy/publish/twitter',
|
||||
'bridgy_omit_link' => 'maybe',
|
||||
],
|
||||
]
|
||||
);
|
||||
//parse for syndication URL
|
||||
if ($response->getStatusCode() == 201) {
|
||||
$json = json_decode((string) $response->getBody());
|
||||
$syndicates = $this->bookmark->syndicates;
|
||||
$syndicates['twitter'] = $json->url;
|
||||
$this->bookmark->syndicates = $syndicates;
|
||||
$this->bookmark->save();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -19,14 +19,21 @@ class SyndicateNoteToMastodon implements ShouldQueue
|
|||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param Note $note
|
||||
* @return void
|
||||
*/
|
||||
public function __construct(
|
||||
protected Note $note
|
||||
) {}
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param Client $guzzle
|
||||
* @return void
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function handle(Client $guzzle): void
|
||||
|
|
63
app/Jobs/SyndicateNoteToTwitter.php
Normal file
63
app/Jobs/SyndicateNoteToTwitter.php
Normal file
|
@ -0,0 +1,63 @@
|
|||
<?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\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class SyndicateNoteToTwitter implements ShouldQueue
|
||||
{
|
||||
use InteractsWithQueue;
|
||||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
/** @var Note */
|
||||
protected $note;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param Note $note
|
||||
*/
|
||||
public function __construct(Note $note)
|
||||
{
|
||||
$this->note = $note;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param Client $guzzle
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function handle(Client $guzzle)
|
||||
{
|
||||
//send webmention
|
||||
$response = $guzzle->request(
|
||||
'POST',
|
||||
'https://brid.gy/publish/webmention',
|
||||
[
|
||||
'form_params' => [
|
||||
'source' => $this->note->longurl,
|
||||
'target' => 'https://brid.gy/publish/twitter',
|
||||
'bridgy_omit_link' => 'maybe',
|
||||
],
|
||||
]
|
||||
);
|
||||
//parse for syndication URL
|
||||
if ($response->getStatusCode() == 201) {
|
||||
$json = json_decode((string) $response->getBody());
|
||||
$tweet_id = basename(parse_url($json->url, PHP_URL_PATH));
|
||||
$this->note->tweet_id = $tweet_id;
|
||||
$this->note->save();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -24,26 +24,24 @@ class Article extends Model
|
|||
use Sluggable;
|
||||
use SoftDeletes;
|
||||
|
||||
/** @var string */
|
||||
/**
|
||||
* The attributes that should be mutated to dates.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
|
||||
|
||||
/**
|
||||
* The database table used by the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'articles';
|
||||
|
||||
/** @var array<int, string> */
|
||||
protected $fillable = [
|
||||
'url',
|
||||
'title',
|
||||
'main',
|
||||
'published',
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
protected $casts = [
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
'deleted_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Return the sluggable configuration array for this model.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function sluggable(): array
|
||||
{
|
||||
|
@ -54,14 +52,26 @@ class Article extends Model
|
|||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'url',
|
||||
'title',
|
||||
'main',
|
||||
'published',
|
||||
];
|
||||
|
||||
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);
|
||||
$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();
|
||||
|
@ -106,8 +116,13 @@ class Article extends Model
|
|||
|
||||
/**
|
||||
* Scope a query to only include articles from a particular year/month.
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param int|null $year
|
||||
* @param int|null $month
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeDate(Builder $query, ?int $year = null, ?int $month = null): Builder
|
||||
public function scopeDate(Builder $query, int $year = null, int $month = null): Builder
|
||||
{
|
||||
if ($year === null) {
|
||||
return $query;
|
||||
|
|
|
@ -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;
|
||||
}
|
|
@ -13,20 +13,33 @@ class Bookmark extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = ['url', 'name', 'content'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
/**
|
||||
* The attributes that should be cast to native types.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $casts = [
|
||||
'syndicates' => 'array',
|
||||
];
|
||||
|
||||
public function tags(): BelongsToMany
|
||||
/**
|
||||
* The tags that belong to the bookmark.
|
||||
*
|
||||
* @return BelongsToMany
|
||||
*/
|
||||
public function tags()
|
||||
{
|
||||
return $this->belongsToMany('App\Models\Tag');
|
||||
}
|
||||
|
||||
protected function local_uri(): Attribute
|
||||
protected function longurl(): Attribute
|
||||
{
|
||||
return Attribute::get(
|
||||
get: fn () => config('app.url') . '/bookmarks/' . $this->id,
|
||||
|
|
|
@ -12,10 +12,18 @@ class Contact extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
/** @var string */
|
||||
/**
|
||||
* The database table used by the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'contacts';
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* We shall guard against mass-migration.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = ['nick', 'name', 'homepage', 'twitter', 'facebook'];
|
||||
|
||||
protected function photo(): Attribute
|
||||
|
|
|
@ -16,7 +16,6 @@ class Like extends Model
|
|||
use FilterHtml;
|
||||
use HasFactory;
|
||||
|
||||
/** @var array<int, string> */
|
||||
protected $fillable = ['url'];
|
||||
|
||||
protected function url(): Attribute
|
||||
|
|
|
@ -14,12 +14,25 @@ class Media extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
/** @var string */
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'media_endpoint';
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = ['token', 'path', 'type', 'image_widths'];
|
||||
|
||||
/**
|
||||
* Get the note that owns this media.
|
||||
*
|
||||
* @return BelongsTo
|
||||
*/
|
||||
public function note(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Note::class);
|
||||
|
@ -33,7 +46,7 @@ class Media extends Model
|
|||
return $attributes['path'];
|
||||
}
|
||||
|
||||
return config('app.url') . '/storage/' . $attributes['path'];
|
||||
return config('filesystems.disks.s3.url') . '/' . $attributes['path'];
|
||||
}
|
||||
);
|
||||
}
|
||||
|
@ -78,7 +91,7 @@ class Media extends Model
|
|||
$basename = $this->getBasename($path);
|
||||
$extension = $this->getExtension($path);
|
||||
|
||||
return config('app.url') . '/storage/' . $basename . '-' . $size . '.' . $extension;
|
||||
return config('filesystems.disks.s3.url') . '/' . $basename . '-' . $size . '.' . $extension;
|
||||
}
|
||||
|
||||
private function getBasename(string $path): string
|
||||
|
|
|
@ -12,12 +12,25 @@ class MicropubClient extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
/** @var string */
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'clients';
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = ['client_url', 'client_name'];
|
||||
|
||||
/**
|
||||
* Define the relationship with notes.
|
||||
*
|
||||
* @return HasMany
|
||||
*/
|
||||
public function notes(): HasMany
|
||||
{
|
||||
return $this->hasMany('App\Models\Note', 'client_id', 'client_url');
|
||||
|
|
|
@ -4,8 +4,9 @@ declare(strict_types=1);
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\CommonMark\Generators\MentionGenerator;
|
||||
use App\CommonMark\Renderers\MentionRenderer;
|
||||
use App\CommonMark\Generators\ContactMentionGenerator;
|
||||
use App\CommonMark\Renderers\ContactMentionRenderer;
|
||||
use App\Exceptions\TwitterContentException;
|
||||
use Codebird\Codebird;
|
||||
use Exception;
|
||||
use GuzzleHttp\Client;
|
||||
|
@ -19,7 +20,6 @@ use Illuminate\Database\Eloquent\Relations\MorphMany;
|
|||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Jonnybarnes\IndieWeb\Numbers;
|
||||
use Laravel\Scout\Searchable;
|
||||
use League\CommonMark\Environment\Environment;
|
||||
use League\CommonMark\Extension\Autolink\AutolinkExtension;
|
||||
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
|
||||
|
@ -35,7 +35,6 @@ use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
|
|||
class Note extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use Searchable;
|
||||
use SoftDeletes;
|
||||
|
||||
/**
|
||||
|
@ -52,6 +51,8 @@ class Note extends Model
|
|||
|
||||
/**
|
||||
* Set our contacts variable to null.
|
||||
*
|
||||
* @param array $attributes
|
||||
*/
|
||||
public function __construct(array $attributes = [])
|
||||
{
|
||||
|
@ -59,46 +60,85 @@ class Note extends Model
|
|||
$this->contacts = null;
|
||||
}
|
||||
|
||||
/** @var string */
|
||||
/**
|
||||
* The database table used by the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'notes';
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* Mass-assignment.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = [
|
||||
'note',
|
||||
'in_reply_to',
|
||||
'client_id',
|
||||
];
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* Hide the column used with Laravel Scout.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $hidden = ['searchable'];
|
||||
|
||||
/**
|
||||
* Define the relationship with tags.
|
||||
*
|
||||
* @return BelongsToMany
|
||||
*/
|
||||
public function tags(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Tag::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the relationship with clients.
|
||||
*
|
||||
* @return BelongsTo
|
||||
*/
|
||||
public function client(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(MicropubClient::class, 'client_id', 'client_url');
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the relationship with webmentions.
|
||||
*
|
||||
* @return MorphMany
|
||||
*/
|
||||
public function webmentions(): MorphMany
|
||||
{
|
||||
return $this->morphMany(WebMention::class, 'commentable');
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the relationship with places.
|
||||
*
|
||||
* @return BelongsTo
|
||||
*/
|
||||
public function place(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Place::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the relationship with media.
|
||||
*
|
||||
* @return HasMany
|
||||
*/
|
||||
public function media(): HasMany
|
||||
{
|
||||
return $this->hasMany(Media::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
* Set the attributes to be indexed for searching with Scout.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toSearchableArray(): array
|
||||
{
|
||||
|
@ -107,6 +147,11 @@ class Note extends Model
|
|||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the note to Unicode FORM C.
|
||||
*
|
||||
* @param string|null $value
|
||||
*/
|
||||
public function setNoteAttribute(?string $value): void
|
||||
{
|
||||
if ($value !== null) {
|
||||
|
@ -120,11 +165,14 @@ class Note extends Model
|
|||
|
||||
/**
|
||||
* Pre-process notes for web-view.
|
||||
*
|
||||
* @param string|null $value
|
||||
* @return string|null
|
||||
*/
|
||||
public function getNoteAttribute(?string $value): ?string
|
||||
{
|
||||
if ($value === null && $this->place !== null) {
|
||||
$value = '📍: <a href="' . $this->place->uri . '">' . $this->place->name . '</a>';
|
||||
$value = '📍: <a href="' . $this->place->longurl . '">' . $this->place->name . '</a>';
|
||||
}
|
||||
|
||||
// if $value is still null, just return null
|
||||
|
@ -141,20 +189,22 @@ class Note extends Model
|
|||
* Provide the content_html for JSON feed.
|
||||
*
|
||||
* In particular, we want to include media links such as images.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getContentAttribute(): string
|
||||
{
|
||||
$note = $this->getRawOriginal('note');
|
||||
$note = $this->note;
|
||||
|
||||
foreach ($this->media as $media) {
|
||||
if ($media->type === 'image') {
|
||||
$note .= PHP_EOL . '<img src="' . $media->url . '" alt="">';
|
||||
$note .= '<img src="' . $media->url . '" alt="">';
|
||||
}
|
||||
if ($media->type === 'audio') {
|
||||
$note .= PHP_EOL . '<audio src="' . $media->url . '">';
|
||||
$note .= '<audio src="' . $media->url . '">';
|
||||
}
|
||||
if ($media->type === 'video') {
|
||||
$note .= PHP_EOL . '<video src="' . $media->url . '">';
|
||||
$note .= '<video src="' . $media->url . '">';
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -166,32 +216,72 @@ class Note extends Model
|
|||
return $note;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the NewBase60 ID from primary ID.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getNb60idAttribute(): string
|
||||
{
|
||||
// we cast to string because sometimes the nb60id is an “int”
|
||||
return (string) resolve(Numbers::class)->numto60($this->id);
|
||||
}
|
||||
|
||||
public function getUriAttribute(): string
|
||||
/**
|
||||
* The Long URL for a note.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getLongurlAttribute(): string
|
||||
{
|
||||
return config('app.url') . '/notes/' . $this->nb60id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Short URL for a note.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getShorturlAttribute(): string
|
||||
{
|
||||
return config('app.shorturl') . '/notes/' . $this->nb60id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the ISO8601 value for mf2.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getIso8601Attribute(): string
|
||||
{
|
||||
return $this->updated_at->toISO8601String();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the ISO8601 value for mf2.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getHumandiffAttribute(): string
|
||||
{
|
||||
return $this->updated_at->diffForHumans();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the publish date value for RSS feeds.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPubdateAttribute(): string
|
||||
{
|
||||
return $this->updated_at->toRSSString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latitude value.
|
||||
*
|
||||
* @return float|null
|
||||
*/
|
||||
public function getLatitudeAttribute(): ?float
|
||||
{
|
||||
if ($this->place !== null) {
|
||||
|
@ -207,6 +297,11 @@ class Note extends Model
|
|||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the longitude value.
|
||||
*
|
||||
* @return float|null
|
||||
*/
|
||||
public function getLongitudeAttribute(): ?float
|
||||
{
|
||||
if ($this->place !== null) {
|
||||
|
@ -223,9 +318,10 @@ class Note extends Model
|
|||
}
|
||||
|
||||
/**
|
||||
* Get the address for a note.
|
||||
* Get the address for a note. This is either a reverse geo-code from the
|
||||
* location, or is derived from the associated place.
|
||||
*
|
||||
* This is either a reverse geo-code from the location, or is derived from the associated place.
|
||||
* @return string|null
|
||||
*/
|
||||
public function getAddressAttribute(): ?string
|
||||
{
|
||||
|
@ -241,6 +337,8 @@ class Note extends Model
|
|||
|
||||
/**
|
||||
* Get the OEmbed html for a tweet the note is a reply to.
|
||||
*
|
||||
* @return object|null
|
||||
*/
|
||||
public function getTwitterAttribute(): ?object
|
||||
{
|
||||
|
@ -266,7 +364,7 @@ class Note extends Model
|
|||
]);
|
||||
|
||||
if ($oEmbed->httpstatus >= 400) {
|
||||
throw new Exception;
|
||||
throw new Exception();
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
return null;
|
||||
|
@ -276,18 +374,63 @@ class Note extends Model
|
|||
return $oEmbed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a specific form of the note for twitter.
|
||||
*
|
||||
* That is we swap the contacts names for their known Twitter handles.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws TwitterContentException
|
||||
*/
|
||||
public function getTwitterContentAttribute(): string
|
||||
{
|
||||
$this->getContacts();
|
||||
|
||||
// check for contacts
|
||||
if ($this->contacts === null || count($this->contacts) === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// here we check the matched contact from the note corresponds to a contact
|
||||
// in the database
|
||||
if (
|
||||
count(array_unique(array_values($this->contacts))) === 1
|
||||
&& array_unique(array_values($this->contacts))[0] === null
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// swap in Twitter usernames
|
||||
$swapped = preg_replace_callback(
|
||||
self::USERNAMES_REGEX,
|
||||
function ($matches) {
|
||||
if (is_null($this->contacts[$matches[1]])) {
|
||||
return $matches[0];
|
||||
}
|
||||
|
||||
$contact = $this->contacts[$matches[1]];
|
||||
if ($contact->twitter) {
|
||||
return '@' . $contact->twitter;
|
||||
}
|
||||
|
||||
return $contact->name;
|
||||
},
|
||||
$this->getRawOriginal('note')
|
||||
);
|
||||
|
||||
return $this->convertMarkdown($swapped);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope a query to select a note via a NewBase60 id.
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param string $nb60id
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeNb60(Builder $query, string $nb60id): Builder
|
||||
{
|
||||
$realId = resolve(Numbers::class)->b60tonum($nb60id);
|
||||
|
||||
// Check nb60 does not translate to ID too big for database int4 column
|
||||
if ($realId > 2_147_483_647) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return $query->where('id', resolve(Numbers::class)->b60tonum($nb60id));
|
||||
}
|
||||
|
||||
|
@ -298,6 +441,9 @@ class Note extends Model
|
|||
* we try to create a fancy hcard from our contact info. If this is not possible
|
||||
* due to lack of contact info, we assume @username is a twitter handle and link it
|
||||
* as such.
|
||||
*
|
||||
* @param string $text
|
||||
* @return string
|
||||
*/
|
||||
private function makeHCards(string $text): string
|
||||
{
|
||||
|
@ -329,6 +475,8 @@ class Note extends Model
|
|||
|
||||
/**
|
||||
* Get the value of the `contacts` property.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getContacts(): array
|
||||
{
|
||||
|
@ -341,6 +489,8 @@ class Note extends Model
|
|||
|
||||
/**
|
||||
* Process the note and save the contacts to the `contacts` property.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setContacts(): void
|
||||
{
|
||||
|
@ -362,6 +512,9 @@ class Note extends Model
|
|||
* Given a string and section, finds all hashtags matching
|
||||
* `#[\-_a-zA-Z0-9]+` and wraps them in an `a` element with
|
||||
* `rel=tag` set and a `href` of 'section/tagged/' + tagname without the #.
|
||||
*
|
||||
* @param string $note
|
||||
* @return string
|
||||
*/
|
||||
public function autoLinkHashtag(string $note): string
|
||||
{
|
||||
|
@ -376,30 +529,43 @@ class Note extends Model
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pass a note through the commonmark library.
|
||||
*
|
||||
* @param string $note
|
||||
* @return string
|
||||
*/
|
||||
private function convertMarkdown(string $note): string
|
||||
{
|
||||
$config = [
|
||||
'mentions' => [
|
||||
'mentions_handle' => [
|
||||
'contacts_handle' => [
|
||||
'prefix' => '@',
|
||||
'pattern' => '([\w@.])+(\b)',
|
||||
'generator' => new MentionGenerator,
|
||||
'pattern' => '[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}(?!\w)',
|
||||
'generator' => new ContactMentionGenerator(),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$environment = new Environment($config);
|
||||
$environment->addExtension(new CommonMarkCoreExtension);
|
||||
$environment->addExtension(new AutolinkExtension);
|
||||
$environment->addExtension(new MentionExtension);
|
||||
$environment->addRenderer(Mention::class, new MentionRenderer);
|
||||
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer);
|
||||
$environment->addRenderer(IndentedCode::class, new IndentedCodeRenderer);
|
||||
$environment->addExtension(new CommonMarkCoreExtension());
|
||||
$environment->addExtension(new AutolinkExtension());
|
||||
$environment->addExtension(new MentionExtension());
|
||||
$environment->addRenderer(Mention::class, new ContactMentionRenderer());
|
||||
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer());
|
||||
$environment->addRenderer(IndentedCode::class, new IndentedCodeRenderer());
|
||||
$markdownConverter = new MarkdownConverter($environment);
|
||||
|
||||
return $markdownConverter->convert($note)->getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Do a reverse geocode lookup of a `lat,lng` value.
|
||||
*
|
||||
* @param float $latitude
|
||||
* @param float $longitude
|
||||
* @return string
|
||||
*/
|
||||
public function reverseGeoCode(float $latitude, float $longitude): string
|
||||
{
|
||||
$latLng = $latitude . ',' . $longitude;
|
||||
|
|
|
@ -1,25 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Passkey extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
/** @inerhitDoc */
|
||||
protected $fillable = [
|
||||
'passkey_id',
|
||||
'passkey',
|
||||
];
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
|
@ -17,20 +17,38 @@ class Place extends Model
|
|||
use HasFactory;
|
||||
use Sluggable;
|
||||
|
||||
public function getRouteKeyName(): string
|
||||
/**
|
||||
* Get the route key for the model.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRouteKeyName()
|
||||
{
|
||||
return 'slug';
|
||||
}
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = ['name', 'slug'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $casts = [
|
||||
'latitude' => 'float',
|
||||
'longitude' => 'float',
|
||||
];
|
||||
|
||||
/**
|
||||
* Return the sluggable configuration array for this model.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function sluggable(): array
|
||||
{
|
||||
return [
|
||||
|
@ -41,13 +59,23 @@ class Place extends Model
|
|||
];
|
||||
}
|
||||
|
||||
public function notes(): HasMany
|
||||
/**
|
||||
* Define the relationship with Notes.
|
||||
*
|
||||
* @return HasMany
|
||||
*/
|
||||
public function notes()
|
||||
{
|
||||
return $this->hasMany('App\Models\Note');
|
||||
}
|
||||
|
||||
/**
|
||||
* Select places near a given location.
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param object $location
|
||||
* @param int $distance
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeNear(Builder $query, object $location, int $distance = 1000): Builder
|
||||
{
|
||||
|
@ -66,6 +94,10 @@ class Place extends Model
|
|||
|
||||
/**
|
||||
* Select places based on a URL.
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param string $url
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeWhereExternalURL(Builder $query, string $url): Builder
|
||||
{
|
||||
|
@ -74,10 +106,24 @@ class Place extends Model
|
|||
]));
|
||||
}
|
||||
|
||||
protected function longurl(): Attribute
|
||||
{
|
||||
return Attribute::get(
|
||||
get: fn ($value, $attributes) => config('app.url') . '/places/' . $attributes['slug'],
|
||||
);
|
||||
}
|
||||
|
||||
protected function shorturl(): Attribute
|
||||
{
|
||||
return Attribute::get(
|
||||
get: fn ($value, $attributes) => config('app.shorturl') . '/places/' . $attributes['slug'],
|
||||
);
|
||||
}
|
||||
|
||||
protected function uri(): Attribute
|
||||
{
|
||||
return Attribute::get(
|
||||
get: static fn ($value, $attributes) => config('app.url') . '/places/' . $attributes['slug'],
|
||||
get: fn () => $this->longurl,
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -104,6 +150,9 @@ class Place extends Model
|
|||
|
||||
/**
|
||||
* Given a URL, see if it is one of our known types.
|
||||
*
|
||||
* @param string $url
|
||||
* @return string
|
||||
*/
|
||||
private function getType(string $url): string
|
||||
{
|
||||
|
|
|
@ -12,7 +12,11 @@ class SyndicationTarget extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = [
|
||||
'uid',
|
||||
'name',
|
||||
|
@ -24,7 +28,11 @@ class SyndicationTarget extends Model
|
|||
'user_photo',
|
||||
];
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that are visible when serializing the model.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected $visible = [
|
||||
'uid',
|
||||
'name',
|
||||
|
@ -32,12 +40,21 @@ class SyndicationTarget extends Model
|
|||
'user',
|
||||
];
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The accessors to append to the model's array form.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $appends = [
|
||||
'service',
|
||||
'user',
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the service data as a single attribute.
|
||||
*
|
||||
* @vreturn Attribute
|
||||
*/
|
||||
protected function service(): Attribute
|
||||
{
|
||||
return Attribute::get(
|
||||
|
@ -49,6 +66,11 @@ class SyndicationTarget extends Model
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the user data as a single attribute.
|
||||
*
|
||||
* @vreturn Attribute
|
||||
*/
|
||||
protected function user(): Attribute
|
||||
{
|
||||
return Attribute::get(
|
||||
|
|
|
@ -14,15 +14,29 @@ class Tag extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* We shall set a blacklist of non-modifiable model attributes.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $guarded = ['id'];
|
||||
|
||||
public function notes(): BelongsToMany
|
||||
/**
|
||||
* Define the relationship with notes.
|
||||
*
|
||||
* @return BelongsToMany
|
||||
*/
|
||||
public function notes()
|
||||
{
|
||||
return $this->belongsToMany(Note::class);
|
||||
}
|
||||
|
||||
public function bookmarks(): BelongsToMany
|
||||
/**
|
||||
* The bookmarks that belong to the tag.
|
||||
*
|
||||
* @return BelongsToMany
|
||||
*/
|
||||
public function bookmarks()
|
||||
{
|
||||
return $this->belongsToMany('App\Models\Bookmark');
|
||||
}
|
||||
|
@ -35,9 +49,11 @@ class Tag extends Model
|
|||
}
|
||||
|
||||
/**
|
||||
* Normalizes a tag.
|
||||
* This method actually normalizes a tag. That means lowercase-ing and
|
||||
* removing fancy diatric characters.
|
||||
*
|
||||
* That means convert to lowercase and removing fancy diatric characters.
|
||||
* @param string $tag
|
||||
* @return string
|
||||
*/
|
||||
public static function normalize(string $tag): string
|
||||
{
|
||||
|
|
|
@ -5,7 +5,6 @@ declare(strict_types=1);
|
|||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
|
@ -14,20 +13,21 @@ class User extends Authenticatable
|
|||
use HasFactory;
|
||||
use Notifiable;
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = [
|
||||
'name', 'password',
|
||||
];
|
||||
|
||||
/** @var array<int, string> */
|
||||
/**
|
||||
* The attributes that should be hidden for arrays.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $hidden = [
|
||||
'current_password',
|
||||
'password',
|
||||
'remember_token',
|
||||
'password', 'remember_token',
|
||||
];
|
||||
|
||||
public function passkey(): HasMany
|
||||
{
|
||||
return $this->hasMany(Passkey::class);
|
||||
}
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue