Merge pull request #215 from jonnybarnes/develop

MTM: Get main branch up to date
This commit is contained in:
Jonny Barnes 2020-11-08 11:14:29 +00:00 committed by GitHub
commit 650d54292e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
551 changed files with 19876 additions and 21183 deletions

View file

@ -56,9 +56,13 @@ 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
SLACK_WEBHOOK_URL=
LOG_SLACK_WEBHOOK_URL=
FONT_LINK=

66
.env.github Normal file
View 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=jbuktest
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=

View file

@ -1,7 +1,7 @@
APP_ENV=testing
APP_DEBUG=true
APP_KEY=base64:6DJhvZLVjE6dD4Cqrteh+6Z5vZlG+v/soCKcDHLOAH0=
APP_URL=http://jonnybarnes.localhost:8000
APP_URL=http://jonnybarnes.localhost
APP_LONGURL=jonnybarnes.localhost
APP_SHORTURL=jmb.localhost

56
.github/workflows/run-tests.yml vendored Normal file
View file

@ -0,0 +1,56 @@
name: Run Tests
on:
pull_request:
jobs:
phpunit:
runs-on: ubuntu-20.04
name: PHPUnit test suite
services:
postgres:
image: postgres:12
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: jbuktest
ports:
- 5432:5432
steps:
- uses: actions/checkout@v2
- name: Cache node modules
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-${{ hashFiles('**/package.json') }}
- name: Install npm dependencies
run: npm install
- name: Install ImageMagick
run: sudo apt install imagemagick
- name: Setup PHP with pecl extension
uses: shivammathur/setup-php@v2
with:
php-version: '7.4'
tools: pecl, phpcs
extensions: imagick
- name: Copy .env
run: php -r "file_exists('.env') || copy('.env.github', '.env');"
- name: Install dependencies
run: composer install -q --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 test database
run: |
php artisan migrate
php artisan db:seed
- name: Execute tests (Unit and Feature tests) via PHPUnit
run: vendor/bin/phpunit
- name: Run phpcs
run: phpcs
- name: Check for security vulnerabilities
run: php vendor/bin/security-checker security:check

8
.gitignore vendored
View file

@ -1,6 +1,4 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.env
@ -10,7 +8,13 @@ Homestead.yaml
npm-debug.log
yarn-error.log
/.idea
/lsp
.phpstorm.meta.php
_ide_helper.php
# Custom paths in /public
/public/coverage
/public/hot
/public/storage
/public/fonts
/public/files
/public/keybase.txt

View file

@ -2,7 +2,6 @@ preset: laravel
disabled:
- concat_without_spaces
- simplified_null_return
- single_import_per_statement
finder:

View file

@ -1,5 +1,5 @@
{
"extends": "stylelint-config-standard",
"extends": ["stylelint-config-standard", "stylelint-a11y/recommended"],
"rules": {
"indentation": 4
}

View file

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

View file

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

View file

@ -4,9 +4,9 @@ declare(strict_types=1);
namespace App\Console\Commands;
use App\Jobs\DownloadWebMention;
use App\Models\WebMention;
use Illuminate\Console\Command;
use App\Jobs\DownloadWebMention;
class ReDownloadWebMentions extends Command
{

View file

@ -27,6 +27,7 @@ class Kernel extends ConsoleKernel
protected function schedule(Schedule $schedule)
{
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->command('telescope:prune --hours=48')->daily();
}
/**
@ -36,7 +37,7 @@ class Kernel extends ConsoleKernel
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}

View file

@ -2,11 +2,16 @@
namespace App\Exceptions;
use App;
use Exception;
use Illuminate\Support\Facades\Route;
use Illuminate\Session\TokenMismatchException;
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
@ -19,7 +24,8 @@ class Handler extends ExceptionHandler
* @var array
*/
protected $dontReport = [
\Symfony\Component\HttpKernel\Exception\HttpException::class,
NotFoundHttpException::class,
ModelNotFoundException::class,
];
/**
@ -37,53 +43,61 @@ class Handler extends ExceptionHandler
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @param Throwable $throwable
* @return void
* @throws Exception
* @throws Throwable
*/
public function report(Exception $exception)
public function report(Throwable $throwable)
{
$guzzle = new \GuzzleHttp\Client([
'headers' => [
'Content-Type' => 'application/json',
],
]);
parent::report($throwable);
$guzzle->post(
env('SLACK_WEBHOOK_URL'),
[
'body' => json_encode([
'attachments' => [[
'fallback' => 'There was an exception.',
'pretext' => 'There was an exception.',
'color' => '#d00000',
'author_name' => App::environment(),
'author_link' => config('app.url'),
'fields' => [[
'title' => get_class($exception) ?? 'Unkown Exception',
'value' => $exception->getMessage() ?? '',
if ($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(),
]],
'ts' => time(),
]],
]),
]
);
parent::report($exception);
]),
]
);
}
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
* @param Request $request
* @param Throwable $throwable
* @return Response
* @throws Throwable
*/
public function render($request, Exception $exception)
public function render($request, Throwable $throwable)
{
if ($exception instanceof TokenMismatchException) {
if ($throwable instanceof TokenMismatchException) {
Route::getRoutes()->match($request);
}
return parent::render($request, $exception);
return parent::render($request, $throwable);
}
}

View file

@ -4,11 +4,11 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Models\Article;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class ArticlesController extends Controller
{

View file

@ -4,11 +4,11 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Models\MicropubClient;
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
{

View file

@ -4,14 +4,14 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use GuzzleHttp\Client;
use App\Models\Contact;
use Illuminate\View\View;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use 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;
class ContactsController extends Controller
{

View file

@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use Illuminate\View\View;
use App\Http\Controllers\Controller;
use Illuminate\View\View;
class HomeController extends Controller
{

View file

@ -4,11 +4,11 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Models\Like;
use App\Jobs\ProcessLike;
use Illuminate\View\View;
use App\Http\Controllers\Controller;
use App\Jobs\ProcessLike;
use App\Models\Like;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class LikesController extends Controller
{

View file

@ -4,12 +4,12 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Models\Note;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Jobs\SendWebMentions;
use App\Http\Controllers\Controller;
use App\Jobs\SendWebMentions;
use App\Models\Note;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class NotesController extends Controller
{

View file

@ -4,17 +4,15 @@ declare(strict_types=1);
namespace App\Http\Controllers\Admin;
use App\Models\Place;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Services\PlaceService;
use App\Http\Controllers\Controller;
use App\Models\Place;
use App\Services\PlaceService;
use Illuminate\Http\RedirectResponse;
use Phaza\LaravelPostgis\Geometries\Point;
use Illuminate\View\View;
class PlacesController extends Controller
{
protected $placeService;
protected PlaceService $placeService;
public function __construct(PlaceService $placeService)
{
@ -24,7 +22,7 @@ class PlacesController extends Controller
/**
* List the places that can be edited.
*
* @return \Illuminate\View\View
* @return View
*/
public function index(): View
{
@ -36,7 +34,7 @@ class PlacesController extends Controller
/**
* Show the form to make a new place.
*
* @return \Illuminate\View\View
* @return View
*/
public function create(): View
{
@ -46,12 +44,18 @@ class PlacesController extends Controller
/**
* Process a request to make a new place.
*
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
*/
public function store(): RedirectResponse
{
$data = request()->only(['name', 'description', 'latitude', 'longitude']);
$place = $this->placeService->createPlace($data);
$this->placeService->createPlace(
request()->only([
'name',
'description',
'latitude',
'longitude',
])
);
return redirect('/admin/places');
}
@ -60,7 +64,7 @@ class PlacesController extends Controller
* Display the form to edit a specific place.
*
* @param int $placeId
* @return \Illuminate\View\View
* @return View
*/
public function edit(int $placeId): View
{
@ -73,17 +77,15 @@ class PlacesController extends Controller
* Process a request to edit a place.
*
* @param int $placeId
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
*/
public function update(int $placeId): RedirectResponse
{
$place = Place::findOrFail($placeId);
$place->name = request()->input('name');
$place->description = request()->input('description');
$place->location = new Point(
(float) request()->input('latitude'),
(float) request()->input('longitude')
);
$place->latitude = request()->input('latitude');
$place->longitude = request()->input('longitude');
$place->icon = request()->input('icon');
$place->save();
@ -94,12 +96,12 @@ class PlacesController extends Controller
* List the places we can merge with the current place.
*
* @param int $placeId
* @return \Illuminate\View\View
* @return View
*/
public function mergeIndex(int $placeId): View
{
$first = Place::find($placeId);
$results = Place::near(new Point($first->latitude, $first->longitude))->get();
$results = Place::near((object) ['latitude' => $first->latitude, 'longitude' => $first->longitude])->get();
$places = [];
foreach ($results as $place) {
if ($place->slug !== $first->slug) {
@ -115,7 +117,7 @@ class PlacesController extends Controller
*
* @param int $placeId1
* @param int $placeId2
* @return \Illuminate\View\View
* @return View
*/
public function mergeEdit(int $placeId1, int $placeId2): View
{
@ -128,7 +130,7 @@ class PlacesController extends Controller
/**
* Process the request to merge two places.
*
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
*/
public function mergeStore(): RedirectResponse
{

View file

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

View file

@ -4,15 +4,16 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthController extends Controller
{
/**
* Show the login form.
*
* @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
* @return View|RedirectResponse
*/
public function showLogin()
{
@ -27,7 +28,7 @@ class AuthController extends Controller
* Log in a user, set a session variable, check credentials against
* the .env file.
*
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
*/
public function login(): RedirectResponse
{
@ -43,7 +44,7 @@ class AuthController extends Controller
/**
* Show the form to logout a user.
*
* @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
* @return View|RedirectResponse
*/
public function showLogout()
{
@ -58,7 +59,7 @@ class AuthController extends Controller
/**
* Log the user out from their current session.
*
* @return \Illuminate\Http\RedirectResponse;
* @return RedirectResponse;
*/
public function logout(): RedirectResponse
{

View file

@ -12,7 +12,7 @@ class BookmarksController extends Controller
/**
* Show the most recent bookmarks.
*
* @return \Illuminate\View\View
* @return View
*/
public function index(): View
{
@ -24,8 +24,8 @@ class BookmarksController extends Controller
/**
* Show a single bookmark.
*
* @param \App\Models\Bookmark $bookmark
* @return \Illuminate\View\View
* @param Bookmark $bookmark
* @return View
*/
public function show(Bookmark $bookmark): View
{

View file

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

View file

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

View file

@ -4,15 +4,16 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use App\Models\{Article, Note};
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class FeedsController extends Controller
{
/**
* Returns the blog RSS feed.
*
* @return \Illuminate\Http\Response
* @return Response
*/
public function blogRss(): Response
{
@ -27,7 +28,7 @@ class FeedsController extends Controller
/**
* Returns the blog Atom feed.
*
* @return \Illuminate\Http\Response
* @return Response
*/
public function blogAtom(): Response
{
@ -41,7 +42,7 @@ class FeedsController extends Controller
/**
* Returns the notes RSS feed.
*
* @return \Illuminate\Http\Response
* @return Response
*/
public function notesRss(): Response
{
@ -56,7 +57,7 @@ class FeedsController extends Controller
/**
* Returns the notes Atom feed.
*
* @return \Illuminate\Http\Response
* @return Response
*/
public function notesAtom(): Response
{
@ -72,9 +73,9 @@ class FeedsController extends Controller
/**
* Returns the blog JSON feed.
*
* @return \Illuminate\Http\JsonResponse
* @return array
*/
public function blogJson()
public function blogJson(): array
{
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
$data = [
@ -105,7 +106,7 @@ class FeedsController extends Controller
/**
* Returns the notes JSON feed.
*
* @return \Illuminate\Http\JsonResponse
* @return array
*/
public function notesJson()
{
@ -133,4 +134,80 @@ class FeedsController extends Controller
return $data;
}
/**
* Returns the blog JF2 feed.
*
* @return JsonResponse
*/
public function blogJf2(): JsonResponse
{
$articles = Article::where('published', '1')->latest('updated_at')->take(20)->get();
$items = [];
foreach ($articles as $article) {
$items[] = [
'type' => 'entry',
'published' => $article->created_at,
'uid' => config('app.url') . $article->link,
'url' => config('app.url') . $article->link,
'content' => [
'text' => $article->main,
'html' => $article->html,
],
'post-type' => 'article',
];
}
return response()->json([
'type' => 'feed',
'name' => 'Blog feed for ' . config('app.name'),
'url' => url('/blog'),
'author' => [
'type' => 'card',
'name' => config('user.displayname'),
'url' => config('app.longurl'),
],
'children' => $items,
], 200, [
'Content-Type' => 'application/jf2feed+json',
]);
}
/**
* Returns the notes JF2 feed.
*
* @return JsonResponse
*/
public function notesJf2(): JsonResponse
{
$notes = Note::latest()->take(20)->get();
$items = [];
foreach ($notes as $note) {
$items[] = [
'type' => 'entry',
'published' => $note->created_at,
'uid' => $note->longurl,
'url' => $note->longurl,
'content' => [
'text' => $note->getRawOriginal('note'),
'html' => $note->note,
],
'post-type' => 'note',
];
}
return response()->json([
'type' => 'feed',
'name' => 'Notes feed for ' . config('app.name'),
'url' => url('/notes'),
'author' => [
'type' => 'card',
'name' => config('user.displayname'),
'url' => config('app.longurl'),
],
'children' => $items,
], 200, [
'Content-Type' => 'application/jf2feed+json',
]);
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Bookmark;
use App\Models\Like;
use App\Models\Note;
use App\Services\ActivityStreamsService;
use Illuminate\Http\Response;
use Illuminate\View\View;
class FrontPageController extends Controller
{
/**
* Show all the recent activity.
*
* @return Response|View
*/
public function index()
{
if (request()->wantsActivityStream()) {
return (new ActivityStreamsService())->siteOwnerResponse();
}
$notes = Note::latest()->get();
$articles = Article::latest()->get();
$bookmarks = Bookmark::latest()->get();
$likes = Like::latest()->get();
$items = collect($notes)
->merge($articles)
->merge($bookmarks)
->merge($likes)
->sortByDesc('updated_at')
->paginate(10);
return view('front-page', [
'items' => $items,
]);
}
}

View file

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

View file

@ -4,29 +4,21 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use Monolog\Logger;
use Ramsey\Uuid\Uuid;
use Illuminate\Http\File;
use App\Jobs\ProcessMedia;
use App\Exceptions\InvalidTokenException;
use App\Http\Responses\MicropubResponses;
use App\Models\Place;
use App\Services\Micropub\{HCardService, HEntryService, UpdateService};
use App\Services\TokenService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\UploadedFile;
use Monolog\Handler\StreamHandler;
use Intervention\Image\ImageManager;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\{Request, Response};
use App\Exceptions\InvalidTokenException;
use App\Models\{Like, Media, Note, Place};
use Phaza\LaravelPostgis\Geometries\Point;
use Intervention\Image\Exception\NotReadableException;
use App\Services\Micropub\{HCardService, HEntryService, UpdateService};
use Monolog\Logger;
class MicropubController extends Controller
{
protected $tokenService;
protected $hentryService;
protected $hcardService;
protected $updateService;
protected TokenService $tokenService;
protected HEntryService $hentryService;
protected HCardService $hcardService;
protected UpdateService $updateService;
public function __construct(
TokenService $tokenService,
@ -42,27 +34,34 @@ class MicropubController extends Controller
/**
* This function receives an API request, verifies the authenticity
* then passes over the info to the relavent Service class.
* then passes over the info to the relevant Service class.
*
* @return \Illuminate\Http\JsonResponse
* @return JsonResponse
* @throws InvalidTokenException
*/
public function post(): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
} catch (InvalidTokenException $e) {
return $this->invalidTokenResponse();
$micropubResponses = new MicropubResponses();
return $micropubResponses->invalidTokenResponse();
}
if ($tokenData->hasClaim('scope') === false) {
return $this->tokenHasNoScopeResponse();
$micropubResponses = new MicropubResponses();
return $micropubResponses->tokenHasNoScopeResponse();
}
$this->logMicropubRequest(request()->all());
if ((request()->input('h') == 'entry') || (request()->input('type.0') == 'h-entry')) {
if (stristr($tokenData->getClaim('scope'), 'create') === false) {
return $this->insufficientScopeResponse();
$micropubResponses = new MicropubResponses();
return $micropubResponses->insufficientScopeResponse();
}
$location = $this->hentryService->process(request()->all(), $this->getCLientId());
@ -72,9 +71,11 @@ class MicropubController extends Controller
], 201)->header('Location', $location);
}
if (request()->input('h') == 'card' || request()->input('type')[0] == 'h-card') {
if (request()->input('h') == 'card' || request()->input('type.0') == 'h-card') {
if (stristr($tokenData->getClaim('scope'), 'create') === false) {
return $this->insufficientScopeResponse();
$micropubResponses = new MicropubResponses();
return $micropubResponses->insufficientScopeResponse();
}
$location = $this->hcardService->process(request()->all());
@ -86,7 +87,9 @@ class MicropubController extends Controller
if (request()->input('action') == 'update') {
if (stristr($tokenData->getClaim('scope'), 'update') === false) {
return $this->insufficientScopeResponse();
$micropubResponses = new MicropubResponses();
return $micropubResponses->insufficientScopeResponse();
}
return $this->updateService->process(request()->all());
@ -102,18 +105,20 @@ class MicropubController extends Controller
* Respond to a GET request to the micropub endpoint.
*
* A GET request has been made to `api/post` with an accompanying
* token, here we check wether the token is valid and respond
* token, here we check whether the token is valid and respond
* appropriately. Further if the request has the query parameter
* synidicate-to we respond with the known syndication endpoints.
* syndicate-to we respond with the known syndication endpoints.
*
* @return \Illuminate\Http\JsonResponse
* @return JsonResponse
*/
public function get(): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
} catch (InvalidTokenException $e) {
return $this->invalidTokenResponse();
$micropubResponses = new MicropubResponses();
return $micropubResponses->invalidTokenResponse();
}
if (request()->input('q') === 'syndicate-to') {
@ -131,12 +136,15 @@ class MicropubController extends Controller
if (request()->has('q') && substr(request()->input('q'), 0, 4) === 'geo:') {
preg_match_all(
'/([0-9\.\-]+)/',
'/([0-9.\-]+)/',
request()->input('q'),
$matches
);
$distance = (count($matches[0]) == 3) ? 100 * $matches[0][2] : 1000;
$places = Place::near(new Point($matches[0][0], $matches[0][1]))->get();
$places = Place::near(
(object) ['latitude' => $matches[0][0], 'longitude' => $matches[0][1]],
$distance
)->get();
return response()->json([
'response' => 'places',
@ -155,129 +163,11 @@ class MicropubController extends Controller
]);
}
/**
* Process a media item posted to the media endpoint.
*
* @return Illuminate\Http\JsonResponse
*/
public function media(): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
} catch (InvalidTokenException $e) {
return $this->invalidTokenResponse();
}
if ($tokenData->hasClaim('scope') === false) {
return $this->tokenHasNoScopeResponse();
}
if (stristr($tokenData->getClaim('scope'), 'create') === false) {
return $this->insufficientScopeResponse();
}
if ((request()->hasFile('file') && request()->file('file')->isValid()) === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'The uploaded file failed validation',
], 400);
}
$this->logMicropubRequest(request()->all());
$filename = $this->saveFile(request()->file('file'));
$manager = resolve(ImageManager::class);
try {
$image = $manager->make(request()->file('file'));
$width = $image->width();
} catch (NotReadableException $exception) {
// not an image
$width = null;
}
$media = Media::create([
'token' => request()->bearerToken(),
'path' => 'media/' . $filename,
'type' => $this->getFileTypeFromMimeType(request()->file('file')->getMimeType()),
'image_widths' => $width,
]);
// put the file on S3 initially, the ProcessMedia job may edit this
Storage::disk('s3')->putFileAs(
'media',
new File(storage_path('app') . '/' . $filename),
$filename
);
ProcessMedia::dispatch($filename);
return response()->json([
'response' => 'created',
'location' => $media->url,
], 201)->header('Location', $media->url);
}
/**
* Return the relavent CORS headers to a pre-flight OPTIONS request.
*
* @return \Illuminate\Http\Response
*/
public function mediaOptionsResponse(): Response
{
return response('OK', 200);
}
/**
* Get the file type from the mimetype of the uploaded file.
*
* @param string $mimetype
* @return string
*/
private function getFileTypeFromMimeType(string $mimetype): string
{
//try known images
$imageMimeTypes = [
'image/gif',
'image/jpeg',
'image/png',
'image/svg+xml',
'image/tiff',
'image/webp',
];
if (in_array($mimetype, $imageMimeTypes)) {
return 'image';
}
//try known video
$videoMimeTypes = [
'video/mp4',
'video/mpeg',
'video/ogg',
'video/quicktime',
'video/webm',
];
if (in_array($mimetype, $videoMimeTypes)) {
return 'video';
}
//try known audio types
$audioMimeTypes = [
'audio/midi',
'audio/mpeg',
'audio/ogg',
'audio/x-m4a',
];
if (in_array($mimetype, $audioMimeTypes)) {
return 'audio';
}
return 'download';
}
/**
* Determine the client id from the access token sent with the request.
*
* @return string
* @throws InvalidTokenException
*/
private function getClientId(): string
{
@ -289,68 +179,12 @@ class MicropubController extends Controller
/**
* Save the details of the micropub request to a log file.
*
* @param array $request This is the info from request()->all()
* @param array $request This is the info from request()->all()
*/
private function logMicropubRequest(array $request)
{
$logger = new Logger('micropub');
$logger->pushHandler(new StreamHandler(storage_path('logs/micropub.log')), Logger::DEBUG);
$logger->pushHandler(new StreamHandler(storage_path('logs/micropub.log')));
$logger->debug('MicropubLog', $request);
}
/**
* Save an uploaded file to the local disk.
*
* @param \Illuminate\Http\UploadedFele $file
* @return string $filename
*/
private function saveFile(UploadedFile $file): string
{
$filename = Uuid::uuid4() . '.' . $file->extension();
Storage::disk('local')->putFileAs('', $file, $filename);
return $filename;
}
/**
* Generate a response to be returned when the token has insufficient scope.
*
* @return \Illuminate\Http\JsonRepsonse
*/
private function insufficientScopeResponse()
{
return response()->json([
'response' => 'error',
'error' => 'insufficient_scope',
'error_description' => 'The tokens scope does not have the necessary requirements.',
], 401);
}
/**
* Generate a response to be returned when the token is invalid.
*
* @return \Illuminate\Http\JsonRepsonse
*/
private function invalidTokenResponse()
{
return response()->json([
'response' => 'error',
'error' => 'invalid_token',
'error_description' => 'The provided token did not pass validation',
], 400);
}
/**
* Generate a response to be returned when the token has no scope.
*
* @return \Illuminate\Http\JsonRepsonse
*/
private function tokenHasNoScopeResponse()
{
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'The provided token has no scopes',
], 400);
}
}

View file

@ -0,0 +1,242 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exceptions\InvalidTokenException;
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\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\File;
use Illuminate\Http\JsonResponse;
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 Ramsey\Uuid\Uuid;
class MicropubMediaController extends Controller
{
protected TokenService $tokenService;
public function __construct(TokenService $tokenService)
{
$this->tokenService = $tokenService;
}
public function getHandler(): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
} catch (InvalidTokenException $e) {
$micropubResponses = new MicropubResponses();
return $micropubResponses->invalidTokenResponse();
}
if ($tokenData->hasClaim('scope') === false) {
$micropubResponses = new MicropubResponses();
return $micropubResponses->tokenHasNoScopeResponse();
}
if (Str::contains($tokenData->getClaim('scope'), 'create') === false) {
$micropubResponses = new MicropubResponses();
return $micropubResponses->insufficientScopeResponse();
}
if (request()->input('q') === 'last') {
try {
$media = Media::latest()->whereDate('created_at', '>=', Carbon::now()->subMinutes(30))->firstOrFail();
} catch (ModelNotFoundException $exception) {
return response()->json(['url' => null]);
}
return response()->json(['url' => $media->url]);
}
if (request()->input('q') === 'source') {
$limit = request()->input('limit', 10);
$offset = request()->input('offset', 0);
$media = Media::latest()->offset($offset)->limit($limit)->get();
$media->transform(function ($mediaItem) {
return [
'url' => $mediaItem->url,
];
});
return response()->json(['items' => $media]);
}
if (request()->has('q')) {
return response()->json([
'error' => 'invalid_request',
'error_description' => sprintf(
'This server does not know how to handle this q parameter (%s)',
request()->input('q')
),
], 400);
}
return response()->json(['status' => 'OK']);
}
/**
* Process a media item posted to the media endpoint.
*
* @return JsonResponse
* @throws BindingResolutionException
* @throws Exception
*/
public function media(): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
} catch (InvalidTokenException $e) {
$micropubResponses = new MicropubResponses();
return $micropubResponses->invalidTokenResponse();
}
if ($tokenData->hasClaim('scope') === false) {
$micropubResponses = new MicropubResponses();
return $micropubResponses->tokenHasNoScopeResponse();
}
if (Str::contains($tokenData->getClaim('scope'), 'create') === false) {
$micropubResponses = new MicropubResponses();
return $micropubResponses->insufficientScopeResponse();
}
if (request()->hasFile('file') === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'No file was sent with the request',
], 400);
}
if (request()->file('file')->isValid() === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
'error_description' => 'The uploaded file failed validation',
], 400);
}
$filename = $this->saveFile(request()->file('file'));
$manager = resolve(ImageManager::class);
try {
$image = $manager->make(request()->file('file'));
$width = $image->width();
} catch (NotReadableException $exception) {
// not an image
$width = null;
}
$media = Media::create([
'token' => request()->bearerToken(),
'path' => 'media/' . $filename,
'type' => $this->getFileTypeFromMimeType(request()->file('file')->getMimeType()),
'image_widths' => $width,
]);
// put the file on S3 initially, the ProcessMedia job may edit this
Storage::disk('s3')->putFileAs(
'media',
new File(storage_path('app') . '/' . $filename),
$filename
);
ProcessMedia::dispatch($filename);
return response()->json([
'response' => 'created',
'location' => $media->url,
], 201)->header('Location', $media->url);
}
/**
* Return the relevant CORS headers to a pre-flight OPTIONS request.
*
* @return Response
*/
public function mediaOptionsResponse(): Response
{
return response('OK', 200);
}
/**
* Get the file type from the mime-type of the uploaded file.
*
* @param string $mimeType
* @return string
*/
private function getFileTypeFromMimeType(string $mimeType): string
{
//try known images
$imageMimeTypes = [
'image/gif',
'image/jpeg',
'image/png',
'image/svg+xml',
'image/tiff',
'image/webp',
];
if (in_array($mimeType, $imageMimeTypes)) {
return 'image';
}
//try known video
$videoMimeTypes = [
'video/mp4',
'video/mpeg',
'video/ogg',
'video/quicktime',
'video/webm',
];
if (in_array($mimeType, $videoMimeTypes)) {
return 'video';
}
//try known audio types
$audioMimeTypes = [
'audio/midi',
'audio/mpeg',
'audio/ogg',
'audio/x-m4a',
];
if (in_array($mimeType, $audioMimeTypes)) {
return 'audio';
}
return 'download';
}
/**
* Save an uploaded file to the local disk.
*
* @param UploadedFile $file
* @return string
* @throws Exception
*/
private function saveFile(UploadedFile $file): string
{
$filename = Uuid::uuid4()->toString() . '.' . $file->extension();
Storage::disk('local')->putFileAs('', $file, $filename);
return $filename;
}
}

View file

@ -5,11 +5,13 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Note;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Http\RedirectResponse;
use App\Services\ActivityStreamsService;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\View\View;
use Jonnybarnes\IndieWeb\Numbers;
// Need to sort out Twitter and webmentions!
@ -18,12 +20,12 @@ class NotesController extends Controller
/**
* Show all the notes. This is also the homepage.
*
* @return \Illuminate\View\View|\Illuminate\Http\JsonResponse
* @return View|Response
*/
public function index()
{
if (request()->wantsActivityStream()) {
return (new ActivityStreamsService)->siteOwnerResponse();
return (new ActivityStreamsService())->siteOwnerResponse();
}
$notes = Note::latest()
@ -38,15 +40,19 @@ class NotesController extends Controller
/**
* Show a single note.
*
* @param string $urlId The id of the note
* @return \Illuminate\View\View|\Illuminate\Http\JsonResponse
* @param string $urlId The id of the note
* @return View|JsonResponse|Response
*/
public function show(string $urlId)
{
$note = Note::nb60($urlId)->with('webmentions')->firstOrFail();
try {
$note = Note::nb60($urlId)->with('webmentions')->firstOrFail();
} catch (ModelNotFoundException $exception) {
abort(404);
}
if (request()->wantsActivityStream()) {
return (new ActivityStreamsService)->singleNoteResponse($note);
return (new ActivityStreamsService())->singleNoteResponse($note);
}
return view('notes.show', compact('note'));
@ -55,8 +61,8 @@ class NotesController extends Controller
/**
* Redirect /note/{decID} to /notes/{nb60id}.
*
* @param int $decId The decimal id of the note
* @return \Illuminate\Http\RedirectResponse
* @param int $decId The decimal id of the note
* @return RedirectResponse
*/
public function redirect(int $decId): RedirectResponse
{
@ -66,8 +72,8 @@ class NotesController extends Controller
/**
* Show all notes tagged with {tag}.
*
* @param string $tag
* @return \Illuminate\View\View
* @param string $tag
* @return View
*/
public function tagged(string $tag): View
{

View file

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

View file

@ -12,7 +12,7 @@ class SearchController extends Controller
/**
* Display search results.
*
* @return \Illuminate\View\View
* @return View
*/
public function search(): View
{

View file

@ -9,9 +9,9 @@ class SessionStoreController extends Controller
/**
* Save the selected colour scheme in the session.
*
* @return \Illuminate\Http\JsonResponse
* @return string[]
*/
public function saveColour()
public function saveColour(): array
{
$css = request()->input('css');

View file

@ -20,7 +20,7 @@ class ShortURLsController extends Controller
/**
* Redirect from '/' to the long url.
*
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
*/
public function baseURL(): RedirectResponse
{
@ -30,30 +30,20 @@ class ShortURLsController extends Controller
/**
* Redirect from '/@' to a twitter profile.
*
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
*/
public function twitter(): RedirectResponse
{
return redirect('https://twitter.com/jonnybarnes');
}
/**
* Redirect from '/+' to a Google+ profile.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function googlePlus(): RedirectResponse
{
return redirect('https://plus.google.com/u/0/117317270900655269082/about');
}
/**
* Redirect a short url of this site out to a long one based on post type.
* Further redirects may happen.
*
* @param string Post type
* @param string Post ID
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
*/
public function expandType(string $type, string $postId): RedirectResponse
{

View file

@ -4,27 +4,27 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use IndieAuth\Client;
use App\Services\TokenService;
use Illuminate\Http\JsonResponse;
use IndieAuth\Client;
class TokenEndpointController extends Controller
{
/**
* The IndieAuth Client.
*/
protected $client;
protected Client $client;
/**
* The Token handling service.
*/
protected $tokenService;
protected TokenService $tokenService;
/**
* Inject the dependencies.
*
* @param \IndieAuth\Client $client
* @param \App\Services\TokenService $tokenService
* @param Client $client
* @param TokenService $tokenService
*/
public function __construct(
Client $client,
@ -37,7 +37,7 @@ class TokenEndpointController extends Controller
/**
* If the user has authd via the IndieAuth protocol, issue a valid token.
*
* @return \Illuminate\Http\JsonResponse
* @return JsonResponse
*/
public function create(): JsonResponse
{

View file

@ -4,12 +4,12 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Note;
use Illuminate\View\View;
use Illuminate\Http\Response;
use App\Jobs\ProcessWebMention;
use Jonnybarnes\IndieWeb\Numbers;
use App\Models\Note;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Response;
use Illuminate\View\View;
use Jonnybarnes\IndieWeb\Numbers;
class WebMentionsController extends Controller
{
@ -19,7 +19,7 @@ class WebMentionsController extends Controller
* This is probably someone looking for information about what
* webmentions are, or about my particular implementation.
*
* @return \Illuminate\View\View
* @return View
*/
public function get(): View
{
@ -29,11 +29,11 @@ class WebMentionsController extends Controller
/**
* Receive and process a webmention.
*
* @return \Illuminate\Http\Respone
* @return Response
*/
public function receive(): Response
{
//first we trivially reject requets that lack all required inputs
//first we trivially reject requests that lack all required inputs
if ((request()->has('target') !== true) || (request()->has('source') !== true)) {
return response(
'You need both the target and source parameters',

View file

@ -14,11 +14,13 @@ class Kernel extends HttpKernel
* @var array
*/
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
@ -42,8 +44,8 @@ class Kernel extends HttpKernel
],
'api' => [
'throttle:60,1',
'bindings',
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
@ -57,10 +59,10 @@ class Kernel extends HttpKernel
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'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,
@ -68,20 +70,4 @@ class Kernel extends HttpKernel
'myauth' => \App\Http\Middleware\MyAuthMiddleware::class,
'cors' => \App\Http\Middleware\CorsHeaders::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,27 +5,31 @@ declare(strict_types=1);
namespace App\Jobs;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\FileSystem\FileSystem;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\FileSystem\FileSystem;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class DownloadWebMention implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* The webmention source URL.
*
* @var
* @var string
*/
protected $source;
/**
* Create a new job instance.
*
* @param string $source
* @param string $source
*/
public function __construct(string $source)
{
@ -35,7 +39,9 @@ class DownloadWebMention implements ShouldQueue
/**
* Execute the job.
*
* @param \GuzzleHttp\Client $guzzle
* @param Client $guzzle
* @throws GuzzleException
* @throws FileNotFoundException
*/
public function handle(Client $guzzle)
{
@ -73,13 +79,12 @@ class DownloadWebMention implements ShouldQueue
}
/**
* Create a file path from a URL. This is used when caching the HTML
* response.
* Create a file path from a URL. This is used when caching the HTML response.
*
* @param string The URL
* @return string The path name
* @param string $url
* @return string The path name
*/
private function createFilenameFromURL($url)
private function createFilenameFromURL(string $url)
{
$filepath = str_replace(['https://', 'http://'], ['https/', 'http/'], $url);
if (substr($filepath, -1) == '/') {

View file

@ -4,25 +4,29 @@ declare(strict_types=1);
namespace App\Jobs;
use App\Exceptions\InternetArchiveException;
use App\Models\Bookmark;
use Illuminate\Bus\Queueable;
use App\Services\BookmarkService;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Exceptions\InternetArchiveException;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessBookmark implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var Bookmark */
protected $bookmark;
/**
* Create a new job instance.
*
* @param \App\Models\Bookmark $bookmark
* @param Bookmark $bookmark
*/
public function __construct(Bookmark $bookmark)
{

View file

@ -5,28 +5,33 @@ declare(strict_types=1);
namespace App\Jobs;
use App\Models\Like;
use Codebird\Codebird;
use GuzzleHttp\Client;
use Illuminate\Support\Arr;
use Illuminate\Bus\Queueable;
use Thujohn\Twitter\Facades\Twitter;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
class ProcessLike implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var Like */
protected $like;
/**
* Create a new job instance.
*
* @param \App\Models\Like $like
* @param Like $like
*/
public function __construct(Like $like)
{
@ -36,14 +41,18 @@ class ProcessLike implements ShouldQueue
/**
* Execute the job.
*
* @param \GuzzleHttp\Client $client
* @param \Jonnybarnes\WebmentionsParser\Authorship $authorship
* @param Client $client
* @param Authorship $authorship
* @return int
* @throws GuzzleException
*/
public function handle(Client $client, Authorship $authorship): int
{
if ($this->isTweet($this->like->url)) {
$tweet = Twitter::getOembed(['url' => $this->like->url]);
$codebird = resolve(Codebird::class);
$tweet = $codebird->statuses_oembed(['url' => $this->like->url]);
$this->like->author_name = $tweet->author_name;
$this->like->author_url = $tweet->author_url;
$this->like->content = $tweet->html;

View file

@ -5,24 +5,28 @@ declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Intervention\Image\ImageManager;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Exception\NotReadableException;
use Intervention\Image\ImageManager;
class ProcessMedia implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var string */
protected $filename;
/**
* Create a new job instance.
*
* @param string $filename
* @param string $filename
*/
public function __construct(string $filename)
{
@ -32,7 +36,7 @@ class ProcessMedia implements ShouldQueue
/**
* Execute the job.
*
* @param \Intervention\Image\ImageManager $manager
* @param ImageManager $manager
*/
public function handle(ImageManager $manager)
{
@ -49,7 +53,7 @@ class ProcessMedia implements ShouldQueue
if ($image->width() > 1000) {
$filenameParts = explode('.', $this->filename);
$extension = array_pop($filenameParts);
// the following acheives this data flow
// the following achieves this data flow
// foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar
$basename = ltrim(array_reduce($filenameParts, function ($carry, $item) {
return $carry . '.' . $item;
@ -57,7 +61,7 @@ class ProcessMedia implements ShouldQueue
$medium = $image->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
});
Storage::disk('s3')->put('media/'. $basename . '-medium.' . $extension, (string) $medium->encode());
Storage::disk('s3')->put('media/' . $basename . '-medium.' . $extension, (string) $medium->encode());
$small = $image->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
});

View file

@ -4,30 +4,37 @@ declare(strict_types=1);
namespace App\Jobs;
use Mf2;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use App\Models\{Note, WebMention};
use Jonnybarnes\WebmentionsParser\Parser;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Exceptions\RemoteContentNotFoundException;
use App\Models\{Note, WebMention};
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\{InteractsWithQueue, SerializesModels};
use Jonnybarnes\WebmentionsParser\Exceptions\InvalidMentionException;
use Jonnybarnes\WebmentionsParser\Parser;
use Mf2;
class ProcessWebMention implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var Note */
protected $note;
/** @var string */
protected $source;
/**
* Create a new job instance.
*
* @param \App\Note $note
* @param string $source
* @param Note $note
* @param string $source
*/
public function __construct(Note $note, $source)
public function __construct(Note $note, string $source)
{
$this->note = $note;
$this->source = $source;
@ -36,15 +43,18 @@ class ProcessWebMention implements ShouldQueue
/**
* Execute the job.
*
* @param \Jonnybarnes\WebmentionsParser\Parser $parser
* @param \GuzzleHttp\Client $guzzle
* @param Parser $parser
* @param Client $guzzle
* @throws RemoteContentNotFoundException
* @throws GuzzleException
* @throws InvalidMentionException
*/
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);
@ -59,7 +69,7 @@ class ProcessWebMention implements ShouldQueue
return;
}
// webmenion is still a reply, so update content
// webmention is still a reply, so update content
dispatch(new SaveProfileImage($microformats));
$webmention->mf2 = json_encode($microformats);
$webmention->save();
@ -91,7 +101,7 @@ class ProcessWebMention implements ShouldQueue
$webmention->source = $this->source;
$webmention->target = $this->note->longurl;
$webmention->commentable_id = $this->note->id;
$webmention->commentable_type = 'App\Note';
$webmention->commentable_type = 'App\Model\Note';
$webmention->type = $type;
$webmention->mf2 = json_encode($microformats);
$webmention->save();

View file

@ -5,24 +5,27 @@ declare(strict_types=1);
namespace App\Jobs;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
class SaveProfileImage implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
protected $microformats;
protected array $microformats;
/**
* Create a new job instance.
*
* @param array $microformats
* @param array $microformats
*/
public function __construct(array $microformats)
{
@ -32,7 +35,7 @@ class SaveProfileImage implements ShouldQueue
/**
* Execute the job.
*
* @param \Jonnybarnes\WebmentionsParser\Authorship $authorship
* @param Authorship $authorship
*/
public function handle(Authorship $authorship)
{
@ -41,17 +44,20 @@ class SaveProfileImage implements ShouldQueue
} catch (AuthorshipParserException $e) {
return;
}
$photo = $author['properties']['photo'][0];
$home = $author['properties']['url'][0];
$photo = Arr::get($author, 'properties.photo.0');
$home = Arr::get($author, 'properties.url.0');
//dont save pbs.twimg.com links
if (parse_url($photo, PHP_URL_HOST) != 'pbs.twimg.com'
&& parse_url($photo, PHP_URL_HOST) != 'twitter.com') {
if (
$photo
&& parse_url($photo, PHP_URL_HOST) != 'pbs.twimg.com'
&& parse_url($photo, PHP_URL_HOST) != 'twitter.com'
) {
$client = resolve(Client::class);
try {
$response = $client->get($photo);
$image = $response->getBody(true);
$image = $response->getBody();
} catch (RequestException $e) {
// we are openning and reading the default image so that
// we are opening and reading the default image so that
$default = public_path() . '/assets/profile-images/default-image';
$handle = fopen($default, 'rb');
$image = fread($handle, filesize($default));

View file

@ -6,22 +6,26 @@ namespace App\Jobs;
use App\Models\Note;
use GuzzleHttp\Client;
use Illuminate\Support\Str;
use GuzzleHttp\Psr7\Uri;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;
class SendWebMentions implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var Note */
protected $note;
/**
* Create the job instance, inject dependencies.
*
* @param Note $note
* @param Note $note
*/
public function __construct(Note $note)
{
@ -58,7 +62,7 @@ class SendWebMentions implements ShouldQueue
/**
* Discover if a URL has a webmention endpoint.
*
* @param string $url
* @param string $url
* @return string|null
*/
public function discoverWebmentionEndpoint(string $url)
@ -101,14 +105,15 @@ class SendWebMentions implements ShouldQueue
/**
* Get the URLs from a note.
*
* @param string $html
* @return array $urls
* @param string|null $html
* @return array
*/
public function getLinks($html)
public function getLinks(?string $html): array
{
if ($html == '' || is_null($html)) {
return [];
}
$urls = [];
$dom = new \DOMDocument();
$dom->loadHTML($html);
@ -123,8 +128,10 @@ class SendWebMentions implements ShouldQueue
/**
* Resolve a URI if necessary.
*
* @param string $url
* @param string $base The base of the URL
* @todo Update deprecated resolve method
*
* @param string $url
* @param string $base The base of the URL
* @return string
*/
public function resolveUri(string $url, string $base): string
@ -134,7 +141,7 @@ class SendWebMentions implements ShouldQueue
return (string) $endpoint;
}
return (string) \GuzzleHttp\Psr7\Uri::resolve(
return (string) Uri::resolve(
\GuzzleHttp\Psr7\uri_for($base),
$endpoint
);

View file

@ -4,24 +4,29 @@ declare(strict_types=1);
namespace App\Jobs;
use GuzzleHttp\Client;
use App\Models\Bookmark;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class SyndicateBookmarkToTwitter implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var Bookmark */
protected $bookmark;
/**
* Create a new job instance.
*
* @param \App\Models\Bookmark $bookmark
* @param Bookmark $bookmark
*/
public function __construct(Bookmark $bookmark)
{
@ -31,7 +36,8 @@ class SyndicateBookmarkToTwitter implements ShouldQueue
/**
* Execute the job.
*
* @param \GuzzleHttp\Client $guzzle
* @param Client $guzzle
* @throws GuzzleException
*/
public function handle(Client $guzzle)
{

View file

@ -6,21 +6,25 @@ namespace App\Jobs;
use App\Models\Note;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class SyndicateNoteToTwitter implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var Note */
protected $note;
/**
* Create a new job instance.
*
* @param \App\Models\Note $note
* @param Note $note
*/
public function __construct(Note $note)
{
@ -30,7 +34,8 @@ class SyndicateNoteToTwitter implements ShouldQueue
/**
* Execute the job.
*
* @param \GuzzleHttp\Client $guzzle
* @param Client $guzzle
* @throws GuzzleException
*/
public function handle(Client $guzzle)
{

View file

@ -4,17 +4,58 @@ declare(strict_types=1);
namespace App\Models;
use League\CommonMark\Environment;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Cviebrock\EloquentSluggable\Sluggable;
use League\CommonMark\CommonMarkConverter;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use League\CommonMark\Block\Element\FencedCode;
use League\CommonMark\Block\Element\IndentedCode;
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\Environment;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
/**
* App\Models\Article.
*
* @property int $id
* @property string $titleurl
* @property string|null $url
* @property string $title
* @property string $main
* @property int $published
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property Carbon|null $deleted_at
* @property-read string $html
* @property-read string $human_time
* @property-read string $link
* @property-read string $pubdate
* @property-read string $tooltip_time
* @property-read string $w3c_time
* @method static Builder|Article date($year = null, $month = null)
* @method static Builder|Article findSimilarSlugs($attribute, $config, $slug)
* @method static bool|null forceDelete()
* @method static Builder|Article newModelQuery()
* @method static Builder|Article newQuery()
* @method static \Illuminate\Database\Query\Builder|Article onlyTrashed()
* @method static Builder|Article query()
* @method static bool|null restore()
* @method static Builder|Article whereCreatedAt($value)
* @method static Builder|Article whereDeletedAt($value)
* @method static Builder|Article whereId($value)
* @method static Builder|Article whereMain($value)
* @method static Builder|Article wherePublished($value)
* @method static Builder|Article whereTitle($value)
* @method static Builder|Article whereTitleurl($value)
* @method static Builder|Article whereUpdatedAt($value)
* @method static Builder|Article whereUrl($value)
* @method static \Illuminate\Database\Query\Builder|Article withTrashed()
* @method static \Illuminate\Database\Query\Builder|Article withoutTrashed()
* @mixin Eloquent
*/
class Article extends Model
{
use Sluggable;
@ -123,9 +164,12 @@ class Article extends Model
/**
* Scope a query to only include articles from a particular year/month.
*
* @return \Illuminate\Database\Eloquent\Builder
* @param Builder $query
* @param int|null $year
* @param int|null $month
* @return Builder
*/
public function scopeDate($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;

View file

@ -4,10 +4,47 @@ declare(strict_types=1);
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Carbon;
/**
* App\Models\Bookmark.
*
* @property int $id
* @property string $url
* @property string|null $name
* @property string|null $content
* @property string|null $screenshot
* @property string|null $archive
* @property array|null $syndicates
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read string $longurl
* @property-read Collection|Tag[] $tags
* @property-read int|null $tags_count
* @method static Builder|Bookmark newModelQuery()
* @method static Builder|Bookmark newQuery()
* @method static Builder|Bookmark query()
* @method static Builder|Bookmark whereArchive($value)
* @method static Builder|Bookmark whereContent($value)
* @method static Builder|Bookmark whereCreatedAt($value)
* @method static Builder|Bookmark whereId($value)
* @method static Builder|Bookmark whereName($value)
* @method static Builder|Bookmark whereScreenshot($value)
* @method static Builder|Bookmark whereSyndicates($value)
* @method static Builder|Bookmark whereUpdatedAt($value)
* @method static Builder|Bookmark whereUrl($value)
* @mixin Eloquent
*/
class Bookmark extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
@ -27,7 +64,7 @@ class Bookmark extends Model
/**
* The tags that belong to the bookmark.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @return BelongsToMany
*/
public function tags()
{

View file

@ -4,8 +4,35 @@ declare(strict_types=1);
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* App\Models\Contact.
*
* @property int $id
* @property string $nick
* @property string $name
* @property string|null $homepage
* @property string|null $twitter
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property string|null $facebook
* @method static Builder|Contact newModelQuery()
* @method static Builder|Contact newQuery()
* @method static Builder|Contact query()
* @method static Builder|Contact whereCreatedAt($value)
* @method static Builder|Contact whereFacebook($value)
* @method static Builder|Contact whereHomepage($value)
* @method static Builder|Contact whereId($value)
* @method static Builder|Contact whereName($value)
* @method static Builder|Contact whereNick($value)
* @method static Builder|Contact whereTwitter($value)
* @method static Builder|Contact whereUpdatedAt($value)
* @mixin Eloquent
*/
class Contact extends Model
{
/**

View file

@ -4,14 +4,41 @@ declare(strict_types=1);
namespace App\Models;
use Mf2;
use App\Traits\FilterHtml;
use Illuminate\Support\Arr;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Mf2;
/**
* App\Models\Like.
*
* @property int $id
* @property string $url
* @property string|null $author_name
* @property string|null $author_url
* @property string|null $content
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @method static Builder|Like newModelQuery()
* @method static Builder|Like newQuery()
* @method static Builder|Like query()
* @method static Builder|Like whereAuthorName($value)
* @method static Builder|Like whereAuthorUrl($value)
* @method static Builder|Like whereContent($value)
* @method static Builder|Like whereCreatedAt($value)
* @method static Builder|Like whereId($value)
* @method static Builder|Like whereUpdatedAt($value)
* @method static Builder|Like whereUrl($value)
* @mixin Eloquent
*/
class Like extends Model
{
use FilterHtml;
use HasFactory;
protected $fillable = ['url'];
@ -28,7 +55,7 @@ class Like extends Model
/**
* Normalize the URL of the author of the like.
*
* @param string $value The authors url
* @param string|null $value The authors url
*/
public function setAuthorUrlAttribute(?string $value)
{
@ -38,7 +65,7 @@ class Like extends Model
/**
* If the content contains HTML, filter it.
*
* @param string $value The content of the like
* @param string|null $value The content of the like
* @return string|null
*/
public function getContentAttribute(?string $value): ?string

View file

@ -4,10 +4,41 @@ declare(strict_types=1);
namespace App\Models;
use Illuminate\Support\Str;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
/**
* App\Models\Media.
*
* @property int $id
* @property string|null $token
* @property string $path
* @property string $type
* @property int|null $note_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property string|null $image_widths
* @property-read string $mediumurl
* @property-read string $smallurl
* @property-read string $url
* @property-read Note|null $note
* @method static Builder|Media newModelQuery()
* @method static Builder|Media newQuery()
* @method static Builder|Media query()
* @method static Builder|Media whereCreatedAt($value)
* @method static Builder|Media whereId($value)
* @method static Builder|Media whereImageWidths($value)
* @method static Builder|Media whereNoteId($value)
* @method static Builder|Media wherePath($value)
* @method static Builder|Media whereToken($value)
* @method static Builder|Media whereType($value)
* @method static Builder|Media whereUpdatedAt($value)
* @mixin Eloquent
*/
class Media extends Model
{
/**
@ -27,7 +58,7 @@ class Media extends Model
/**
* Get the note that owns this media.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return BelongsTo
*/
public function note(): BelongsTo
{
@ -77,7 +108,7 @@ class Media extends Model
/**
* Give the real part of a filename, i.e. strip the file extension.
*
* @param string $path
* @param string $path
* @return string
*/
public function getBasename(string $path): string
@ -86,17 +117,16 @@ class Media extends Model
// foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar
$filenameParts = explode('.', $path);
array_pop($filenameParts);
$basename = ltrim(array_reduce($filenameParts, function ($carry, $item) {
return ltrim(array_reduce($filenameParts, function ($carry, $item) {
return $carry . '.' . $item;
}, ''), '.');
return $basename;
}
/**
* Get the extension from a given filename.
*
* @param string $path
* @param string $path
* @return string
*/
public function getExtension(string $path): string

View file

@ -4,11 +4,38 @@ declare(strict_types=1);
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
/**
* App\Models\MicropubClient.
*
* @property int $id
* @property string $client_url
* @property string $client_name
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Collection|\App\Models\Note[] $notes
* @property-read int|null $notes_count
* @method static Builder|MicropubClient newModelQuery()
* @method static Builder|MicropubClient newQuery()
* @method static Builder|MicropubClient query()
* @method static Builder|MicropubClient whereClientName($value)
* @method static Builder|MicropubClient whereClientUrl($value)
* @method static Builder|MicropubClient whereCreatedAt($value)
* @method static Builder|MicropubClient whereId($value)
* @method static Builder|MicropubClient whereUpdatedAt($value)
* @mixin Eloquent
*/
class MicropubClient extends Model
{
use HasFactory;
/**
* The table associated with the model.
*
@ -26,7 +53,7 @@ class MicropubClient extends Model
/**
* Define the relationship with notes.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return HasMany
*/
public function notes(): HasMany
{

View file

@ -4,32 +4,96 @@ declare(strict_types=1);
namespace App\Models;
use Cache;
use Twitter;
use Normalizer;
use GuzzleHttp\Client;
use Laravel\Scout\Searchable;
use Jonnybarnes\IndieWeb\Numbers;
use League\CommonMark\Environment;
use Illuminate\Database\Eloquent\Model;
use Jonnybarnes\EmojiA11y\EmojiModifier;
use Illuminate\Database\Eloquent\Builder;
use League\CommonMark\CommonMarkConverter;
use App\Exceptions\TwitterContentException;
use Illuminate\Database\Eloquent\SoftDeletes;
use League\CommonMark\Block\Element\FencedCode;
use League\CommonMark\Block\Element\IndentedCode;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use League\CommonMark\Ext\Autolink\AutolinkExtension;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
use Codebird\Codebird;
use Eloquent;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Relations\{BelongsTo, BelongsToMany, HasMany, MorphMany};
use Illuminate\Database\Eloquent\{Builder, Collection, Factories\HasFactory, Model, SoftDeletes};
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Jonnybarnes\IndieWeb\Numbers;
use Laravel\Scout\Searchable;
use League\CommonMark\Block\Element\{FencedCode, IndentedCode};
use League\CommonMark\Extension\Autolink\AutolinkExtension;
use League\CommonMark\{CommonMarkConverter, Environment};
use Normalizer;
use Spatie\CommonMarkHighlighter\{FencedCodeRenderer, IndentedCodeRenderer};
/**
* App\Models\Note.
*
* @property int $id
* @property string|null $note
* @property string|null $in_reply_to
* @property string $shorturl
* @property string|null $location
* @property int|null $photo
* @property string|null $tweet_id
* @property string|null $client_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property Carbon|null $deleted_at
* @property int|null $place_id
* @property string|null $facebook_url
* @property string|null $searchable
* @property string|null $swarm_url
* @property string|null $instagram_url
* @property-read MicropubClient|null $client
* @property-read string|null $address
* @property-read string $content
* @property-read string $humandiff
* @property-read string $iso8601
* @property-read float|null $latitude
* @property-read float|null $longitude
* @property-read string $longurl
* @property-read string $nb60id
* @property-read string $pubdate
* @property-read object|null $twitter
* @property-read string $twitter_content
* @property-read Collection|Media[] $media
* @property-read int|null $media_count
* @property-read Place|null $place
* @property-read Collection|Tag[] $tags
* @property-read int|null $tags_count
* @property-read Collection|WebMention[] $webmentions
* @property-read int|null $webmentions_count
* @method static bool|null forceDelete()
* @method static Builder|Note nb60($nb60id)
* @method static Builder|Note newModelQuery()
* @method static Builder|Note newQuery()
* @method static \Illuminate\Database\Query\Builder|Note onlyTrashed()
* @method static Builder|Note query()
* @method static bool|null restore()
* @method static Builder|Note whereClientId($value)
* @method static Builder|Note whereCreatedAt($value)
* @method static Builder|Note whereDeletedAt($value)
* @method static Builder|Note whereFacebookUrl($value)
* @method static Builder|Note whereId($value)
* @method static Builder|Note whereInReplyTo($value)
* @method static Builder|Note whereInstagramUrl($value)
* @method static Builder|Note whereLocation($value)
* @method static Builder|Note whereNote($value)
* @method static Builder|Note wherePhoto($value)
* @method static Builder|Note wherePlaceId($value)
* @method static Builder|Note whereSearchable($value)
* @method static Builder|Note whereShorturl($value)
* @method static Builder|Note whereSwarmUrl($value)
* @method static Builder|Note whereTweetId($value)
* @method static Builder|Note whereUpdatedAt($value)
* @method static \Illuminate\Database\Query\Builder|Note withTrashed()
* @method static \Illuminate\Database\Query\Builder|Note withoutTrashed()
* @mixin Eloquent
*/
class Note extends Model
{
use HasFactory;
use Searchable;
use SoftDeletes;
/**
* The reges for matching lone usernames.
* The regex for matching lone usernames.
*
* @var string
*/
@ -58,8 +122,8 @@ class Note extends Model
*/
protected $table = 'notes';
/*
* Mass-assignment
/**
* Mass-assignment.
*
* @var array
*/
@ -79,7 +143,7 @@ class Note extends Model
/**
* Define the relationship with tags.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @return BelongsToMany
*/
public function tags()
{
@ -89,7 +153,7 @@ class Note extends Model
/**
* Define the relationship with clients.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return BelongsTo
*/
public function client()
{
@ -99,7 +163,7 @@ class Note extends Model
/**
* Define the relationship with webmentions.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
* @return MorphMany
*/
public function webmentions()
{
@ -109,7 +173,7 @@ class Note extends Model
/**
* Define the relationship with places.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return BelongsTo
*/
public function place()
{
@ -119,7 +183,7 @@ class Note extends Model
/**
* Define the relationship with media.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return HasMany
*/
public function media()
{
@ -141,7 +205,7 @@ class Note extends Model
/**
* Normalize the note to Unicode FORM C.
*
* @param string|null $value
* @param string|null $value
*/
public function setNoteAttribute(?string $value)
{
@ -157,7 +221,7 @@ class Note extends Model
/**
* Pre-process notes for web-view.
*
* @param string|null $value
* @param string|null $value
* @return string|null
*/
public function getNoteAttribute(?string $value): ?string
@ -173,10 +237,8 @@ class Note extends Model
$hcards = $this->makeHCards($value);
$hashtags = $this->autoLinkHashtag($hcards);
$html = $this->convertMarkdown($hashtags);
$modified = resolve(EmojiModifier::class)->makeEmojiAccessible($html);
return $modified;
return $this->convertMarkdown($hashtags);
}
/**
@ -262,7 +324,7 @@ class Note extends Model
}
/**
* Get the pubdate value for RSS feeds.
* Get the publish date value for RSS feeds.
*
* @return string
*/
@ -279,13 +341,13 @@ class Note extends Model
public function getLatitudeAttribute(): ?float
{
if ($this->place !== null) {
return $this->place->location->getLat();
return $this->place->latitude;
}
if ($this->location !== null) {
$pieces = explode(':', $this->location);
$latlng = explode(',', $pieces[0]);
$latLng = explode(',', $pieces[0]);
return (float) trim($latlng[0]);
return (float) trim($latLng[0]);
}
return null;
@ -299,13 +361,13 @@ class Note extends Model
public function getLongitudeAttribute(): ?float
{
if ($this->place !== null) {
return $this->place->location->getLng();
return $this->place->longitude;
}
if ($this->location !== null) {
$pieces = explode(':', $this->location);
$latlng = explode(',', $pieces[0]);
$latLng = explode(',', $pieces[0]);
return (float) trim($latlng[1]);
return (float) trim($latLng[1]);
}
return null;
@ -346,13 +408,18 @@ class Note extends Model
}
try {
$oEmbed = Twitter::getOembed([
$codebird = resolve(Codebird::class);
$oEmbed = $codebird->statuses_oembed([
'url' => $this->in_reply_to,
'dnt' => true,
'align' => 'center',
'maxwidth' => 512,
]);
} catch (\Exception $e) {
if ($oEmbed->httpstatus >= 400) {
throw new Exception();
}
} catch (Exception $e) {
return null;
}
Cache::put($tweetId, $oEmbed, ($oEmbed->cache_age));
@ -366,6 +433,7 @@ class Note extends Model
* That is we swap the contacts names for their known Twitter handles.
*
* @return string
* @throws TwitterContentException
*/
public function getTwitterContentAttribute(): string
{
@ -376,8 +444,10 @@ class Note extends Model
// 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) {
if (
count(array_unique(array_values($this->contacts))) === 1
&& array_unique(array_values($this->contacts))[0] === null
) {
throw new TwitterContentException('The matched contact is not in the database');
}
@ -405,9 +475,9 @@ class Note extends Model
/**
* Scope a query to select a note via a NewBase60 id.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $nb60id
* @return \Illuminate\Database\Eloquent\Builder
* @param Builder $query
* @param string $nb60id
* @return Builder
*/
public function scopeNb60(Builder $query, string $nb60id): Builder
{
@ -422,7 +492,7 @@ class Note extends Model
* due to lack of contact info, we assume @username is a twitter handle and link it
* as such.
*
* @param string $text
* @param string $text
* @return string
*/
private function makeHCards(string $text): string
@ -433,7 +503,7 @@ class Note extends Model
return $text;
}
$hcards = preg_replace_callback(
return preg_replace_callback(
self::USERNAMES_REGEX,
function ($matches) {
if (is_null($this->contacts[$matches[1]])) {
@ -451,28 +521,32 @@ class Note extends Model
},
$text
);
return $hcards;
}
/**
* Get the value of the `contacts` property.
*
* @return array
*/
public function getContacts()
public function getContacts(): array
{
if ($this->contacts === null) {
$this->setContacts();
}
return $this->contacts;
}
/**
* Process the note and save the contacts to the `contacts` property.
*
* @return void
*/
public function setContacts()
public function setContacts(): void
{
$contacts = [];
if ($this->getOriginal('note')) {
preg_match_all(self::USERNAMES_REGEX, $this->getoriginal('note'), $matches);
if ($this->getRawOriginal('note')) {
preg_match_all(self::USERNAMES_REGEX, $this->getRawOriginal('note'), $matches);
foreach ($matches[1] as $match) {
$contacts[$match] = Contact::where('nick', mb_strtolower($match))->first();
@ -489,7 +563,7 @@ class Note extends Model
* `#[\-_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
* @param string $note
* @return string
*/
public function autoLinkHashtag(string $note): string
@ -508,7 +582,7 @@ class Note extends Model
/**
* Pass a note through the commonmark library.
*
* @param string $note
* @param string $note
* @return string
*/
private function convertMarkdown(string $note): string
@ -525,15 +599,15 @@ class Note extends Model
/**
* Do a reverse geocode lookup of a `lat,lng` value.
*
* @param float $latitude
* @param float $longitude
* @param float $latitude
* @param float $longitude
* @return string
*/
public function reverseGeoCode(float $latitude, float $longitude): string
{
$latlng = $latitude . ',' . $longitude;
$latLng = $latitude . ',' . $longitude;
return Cache::get($latlng, function () use ($latlng, $latitude, $longitude) {
return Cache::get($latLng, function () use ($latLng, $latitude, $longitude) {
$guzzle = resolve(Client::class);
$response = $guzzle->request('GET', 'https://nominatim.openstreetmap.org/reverse', [
'query' => [
@ -556,7 +630,7 @@ class Note extends Model
. '</span>, <span class="p-country-name">'
. $json->address->country
. '</span>';
Cache::forever($latlng, $address);
Cache::forever($latLng, $address);
return $address;
}
@ -566,7 +640,7 @@ class Note extends Model
. '</span>, <span class="p-country-name">'
. $json->address->country
. '</span>';
Cache::forever($latlng, $address);
Cache::forever($latLng, $address);
return $address;
}
@ -576,12 +650,12 @@ class Note extends Model
. '</span>, <span class="p-country-name">'
. $json->address->country
. '</span>';
Cache::forever($latlng, $address);
Cache::forever($latLng, $address);
return $address;
}
$address = '<span class="p-country-name">' . $json->address->country . '</span>';
Cache::forever($latlng, $address);
Cache::forever($latLng, $address);
return $address;
});

View file

@ -4,18 +4,65 @@ declare(strict_types=1);
namespace App\Models;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Cviebrock\EloquentSluggable\Sluggable;
use Phaza\LaravelPostgis\Geometries\Point;
use Phaza\LaravelPostgis\Eloquent\PostgisTrait;
use Eloquent;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\{Builder, Collection, Factories\HasFactory, Model};
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
/**
* App\Models\Place.
*
* @property int $id
* @property string $name
* @property string $slug
* @property string|null $description
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property string|null $icon
* @property string|null $foursquare
* @property mixed|null $external_urls
* @property float|null $latitude
* @property float|null $longitude
* @property-read string $longurl
* @property-read string $shorturl
* @property-read string $uri
* @property-read Collection|\App\Models\Note[] $notes
* @property-read int|null $notes_count
* @method static Builder|Place findSimilarSlugs($attribute, $config, $slug)
* @method static Builder|Place near($location, $distance = 1000)
* @method static Builder|Place newModelQuery()
* @method static Builder|Place newQuery()
* @method static Builder|Place query()
* @method static Builder|Place whereCreatedAt($value)
* @method static Builder|Place whereDescription($value)
* @method static Builder|Place whereExternalURL($url)
* @method static Builder|Place whereExternalUrls($value)
* @method static Builder|Place whereFoursquare($value)
* @method static Builder|Place whereIcon($value)
* @method static Builder|Place whereId($value)
* @method static Builder|Place whereLatitude($value)
* @method static Builder|Place whereLongitude($value)
* @method static Builder|Place whereName($value)
* @method static Builder|Place whereSlug($value)
* @method static Builder|Place whereUpdatedAt($value)
* @mixin Eloquent
*/
class Place extends Model
{
use HasFactory;
use Sluggable;
use PostgisTrait;
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
/**
* The attributes that are mass assignable.
@ -25,13 +72,13 @@ class Place extends Model
protected $fillable = ['name', 'slug'];
/**
* The attributes that are Postgis geometry objects.
* The attributes that should be cast.
*
* @var array
*/
protected $postgisFields = [
'location',
'polygon',
protected $casts = [
'latitude' => 'float',
'longitude' => 'float',
];
/**
@ -52,7 +99,7 @@ class Place extends Model
/**
* Define the relationship with Notes.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return HasMany
*/
public function notes()
{
@ -62,30 +109,32 @@ class Place extends Model
/**
* Select places near a given location.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Phaza\LaravelPostgis\Geometries\Point $point
* @param int $distance
* @return \Illuminate\Database\Eloquent\Builder
* @param Builder $query
* @param object $location
* @param int $distance
* @return Builder
*/
public function scopeNear(Builder $query, Point $point, $distance = 1000): Builder
public function scopeNear(Builder $query, object $location, int $distance = 1000): Builder
{
$field = DB::raw(
sprintf(
"ST_Distance(%s.location, ST_GeogFromText('%s'))",
$this->getTable(),
$point->toWKT()
)
);
$haversine = "(6371 * acos(cos(radians($location->latitude))
* cos(radians(places.latitude))
* cos(radians(places.longitude)
- radians($location->longitude))
+ sin(radians($location->latitude))
* sin(radians(places.latitude))))";
return $query->where($field, '<=', $distance)->orderBy($field);
return $query
->select() //pick the columns you want here.
->selectRaw("{$haversine} AS distance")
->whereRaw("{$haversine} < ?", [$distance]);
}
/**
* Select places based on a URL.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $url
* @return \Illuminate\Database\Eloquent\Builder
* @param Builder $query
* @param string $url
* @return Builder
*/
public function scopeWhereExternalURL(Builder $query, string $url): Builder
{
@ -94,26 +143,6 @@ class Place extends Model
]));
}
/**
* Get the latitude from the `location` property.
*
* @return float
*/
public function getLatitudeAttribute(): float
{
return $this->location->getLat();
}
/**
* Get the longitude from the `location` property.
*
* @return float
*/
public function getLongitudeAttribute(): float
{
return $this->location->getLng();
}
/**
* The Long URL for a place.
*

View file

@ -4,10 +4,38 @@ declare(strict_types=1);
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Carbon;
/**
* App\Models\Tag.
*
* @property int $id
* @property string $tag
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Collection|Bookmark[] $bookmarks
* @property-read int|null $bookmarks_count
* @property-read Collection|Note[] $notes
* @property-read int|null $notes_count
* @method static Builder|Tag newModelQuery()
* @method static Builder|Tag newQuery()
* @method static Builder|Tag query()
* @method static Builder|Tag whereCreatedAt($value)
* @method static Builder|Tag whereId($value)
* @method static Builder|Tag whereTag($value)
* @method static Builder|Tag whereUpdatedAt($value)
* @mixin Eloquent
*/
class Tag extends Model
{
use HasFactory;
/**
* We shall set a blacklist of non-modifiable model attributes.
*
@ -18,7 +46,7 @@ class Tag extends Model
/**
* Define the relationship with notes.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @return BelongsToMany
*/
public function notes()
{
@ -28,7 +56,7 @@ class Tag extends Model
/**
* The bookmarks that belong to the tag.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @return BelongsToMany
*/
public function bookmarks()
{
@ -38,7 +66,7 @@ class Tag extends Model
/**
* When creating a Tag model instance, invoke the nomralize method on the tag.
*
* @param string $value
* @param string $value
*/
public function setTagAttribute(string $value)
{
@ -49,7 +77,7 @@ class Tag extends Model
* This method actually normalizes a tag. That means lowercase-ing and
* removing fancy diatric characters.
*
* @param string $tag
* @param string $tag
* @return string
*/
public static function normalize(string $tag): string

View file

@ -4,11 +4,40 @@ declare(strict_types=1);
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Notifications\DatabaseNotificationCollection;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
/**
* App\Models\User.
*
* @property int $id
* @property string $name
* @property string $password
* @property string|null $remember_token
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read DatabaseNotificationCollection|DatabaseNotification[] $notifications
* @property-read int|null $notifications_count
* @method static Builder|User newModelQuery()
* @method static Builder|User newQuery()
* @method static Builder|User query()
* @method static Builder|User whereCreatedAt($value)
* @method static Builder|User whereId($value)
* @method static Builder|User whereName($value)
* @method static Builder|User wherePassword($value)
* @method static Builder|User whereRememberToken($value)
* @method static Builder|User whereUpdatedAt($value)
* @mixin Eloquent
*/
class User extends Authenticatable
{
use HasFactory;
use Notifiable;
/**

View file

@ -4,13 +4,54 @@ declare(strict_types=1);
namespace App\Models;
use Cache;
use Twitter;
use App\Traits\FilterHtml;
use Illuminate\Filesystem\Filesystem;
use Codebird\Codebird;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
/**
* App\Models\WebMention.
*
* @property int $id
* @property string $source
* @property string $target
* @property int|null $commentable_id
* @property string|null $commentable_type
* @property string|null $type
* @property string|null $content
* @property int $verified
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property string|null $deleted_at
* @property mixed|null $mf2
* @property-read WebMention|null $commentable
* @property-read array $author
* @property-read string|null $published
* @property-read string|null $reply
* @method static Builder|WebMention newModelQuery()
* @method static Builder|WebMention newQuery()
* @method static Builder|WebMention query()
* @method static Builder|WebMention whereCommentableId($value)
* @method static Builder|WebMention whereCommentableType($value)
* @method static Builder|WebMention whereContent($value)
* @method static Builder|WebMention whereCreatedAt($value)
* @method static Builder|WebMention whereDeletedAt($value)
* @method static Builder|WebMention whereId($value)
* @method static Builder|WebMention whereMf2($value)
* @method static Builder|WebMention whereSource($value)
* @method static Builder|WebMention whereTarget($value)
* @method static Builder|WebMention whereType($value)
* @method static Builder|WebMention whereUpdatedAt($value)
* @method static Builder|WebMention whereVerified($value)
* @mixin Eloquent
*/
class WebMention extends Model
{
use FilterHtml;
@ -32,7 +73,7 @@ class WebMention extends Model
/**
* Define the relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
* @return MorphTo
*/
public function commentable()
{
@ -43,12 +84,19 @@ class WebMention extends Model
* Get the author of the webmention.
*
* @return array
* @throws AuthorshipParserException
*/
public function getAuthorAttribute(): array
{
$authorship = new Authorship();
$hCard = $authorship->findAuthor(json_decode($this->mf2, true));
if (array_key_exists('properties', $hCard) &&
if ($hCard === false) {
return [];
}
if (
array_key_exists('properties', $hCard) &&
array_key_exists('photo', $hCard['properties'])
) {
$hCard['properties']['photo'][0] = $this->createPhotoLink($hCard['properties']['photo'][0]);
@ -102,7 +150,7 @@ class WebMention extends Model
/**
* Create the photo link.
*
* @param string
* @param string $url
* @return string
*/
public function createPhotoLink(string $url): string
@ -118,7 +166,8 @@ class WebMention extends Model
return Cache::get($url);
}
$username = ltrim(parse_url($url, PHP_URL_PATH), '/');
$info = Twitter::getUsers(['screen_name' => $username]);
$codebird = resolve(Codebird::class);
$info = $codebird->users_show(['screen_name' => $username]);
$profile_image = $info->profile_image_url_https;
Cache::put($url, $profile_image, 10080); //1 week

View file

@ -12,11 +12,11 @@ class NoteObserver
/**
* Listen to the Note created event.
*
* @param \App\Note $note
* @param Note $note
*/
public function created(Note $note)
{
$text = array_get($note->getAttributes(), 'note');
$text = Arr::get($note->getAttributes(), 'note');
if ($text === null) {
return;
}
@ -36,7 +36,7 @@ class NoteObserver
/**
* Listen to the Note updated event.
*
* @param \App\Note $Note
* @param Note $note
*/
public function updated(Note $note)
{
@ -62,7 +62,7 @@ class NoteObserver
/**
* Listen to the Note deleting event.
*
* @param \App\Note $note
* @param Note $note
*/
public function deleting(Note $note)
{
@ -72,8 +72,8 @@ class NoteObserver
/**
* Retrieve the tags from a notes text, tag for form #tag.
*
* @param string $note
* @return \Illuminate\Support\Collection
* @param string $note
* @return Collection
*/
private function getTagsFromNote(string $note): Collection
{

View file

@ -3,11 +3,14 @@
namespace App\Providers;
use App\Models\Note;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Observers\NoteObserver;
use Laravel\Dusk\DuskServiceProvider;
use Codebird\Codebird;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\Dusk\DuskServiceProvider;
class AppServiceProvider extends ServiceProvider
{
@ -29,6 +32,47 @@ class AppServiceProvider extends ServiceProvider
$this->app->bind('Intervention\Image\ImageManager', function () {
return new \Intervention\Image\ImageManager(['driver' => config('image.driver')]);
});
// Bind the Codebird client
$this->app->bind('Codebird\Codebird', function () {
Codebird::setConsumerKey(
env('TWITTER_CONSUMER_KEY'),
env('TWITTER_CONSUMER_SECRET')
);
$cb = Codebird::getInstance();
$cb->setToken(
env('TWITTER_ACCESS_TOKEN'),
env('TWITTER_ACCESS_TOKEN_SECRET')
);
return $cb;
});
/**
* Paginate a standard Laravel Collection.
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
/**

View file

@ -12,7 +12,7 @@ class AuthServiceProvider extends ServiceProvider
* @var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**

View file

@ -2,8 +2,8 @@
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
/**
* @codeCoverageIgnore

View file

@ -2,8 +2,10 @@
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
@ -13,8 +15,8 @@ class EventServiceProvider extends ServiceProvider
* @var array
*/
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
Registered::class => [
SendEmailVerificationNotification::class,
],
];

View file

@ -2,8 +2,8 @@
namespace App\Providers;
use Laravel\Horizon\Horizon;
use Illuminate\Support\Facades\Gate;
use Laravel\Horizon\Horizon;
use Laravel\Horizon\HorizonApplicationServiceProvider;
class HorizonServiceProvider extends HorizonApplicationServiceProvider

View file

@ -2,8 +2,11 @@
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
@ -12,9 +15,9 @@ class RouteServiceProvider extends ServiceProvider
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
* @var string|null
*/
protected $namespace = 'App\Http\Controllers';
// protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
@ -23,51 +26,29 @@ class RouteServiceProvider extends ServiceProvider
*/
public function boot()
{
//
$this->configureRateLimiting();
parent::boot();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
/**
* Define the routes for the application.
* Configure the rate limiters for the application.
*
* @return void
*/
public function map()
protected function configureRateLimiting()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60);
});
}
}

View file

@ -0,0 +1,70 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
use Laravel\Telescope\TelescopeApplicationServiceProvider;
class TelescopeServiceProvider extends TelescopeApplicationServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
Telescope::night();
$this->hideSensitiveRequestDetails();
Telescope::filter(function (IncomingEntry $entry) {
if ($this->app->isLocal()) {
return true;
}
return $entry->isReportableException() ||
$entry->isFailedJob() ||
$entry->isScheduledTask() ||
$entry->hasMonitoredTag();
});
}
/**
* Prevent sensitive request details from being logged by Telescope.
*
* @return void
*/
protected function hideSensitiveRequestDetails()
{
if ($this->app->isLocal()) {
return;
}
Telescope::hideRequestParameters(['_token']);
Telescope::hideRequestHeaders([
'cookie',
'x-csrf-token',
'x-xsrf-token',
]);
}
/**
* Register the Telescope gate.
*
* This gate determines who can access Telescope in non-local environments.
*
* @return void
*/
protected function gate()
{
Gate::define('viewTelescope', function ($user) {
return in_array($user->name, [
'jonny',
]);
});
}
}

View file

@ -4,24 +4,24 @@ declare(strict_types=1);
namespace App\Services;
use Ramsey\Uuid\Uuid;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Jobs\ProcessBookmark;
use App\Models\{Bookmark, Tag};
use Illuminate\Support\{Arr, Str};
use Spatie\Browsershot\Browsershot;
use App\Jobs\SyndicateBookmarkToTwitter;
use GuzzleHttp\Exception\ClientException;
use App\Exceptions\InternetArchiveException;
use App\Jobs\ProcessBookmark;
use App\Jobs\SyndicateBookmarkToTwitter;
use App\Models\{Bookmark, Tag};
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\{Arr, Str};
use Ramsey\Uuid\Uuid;
use Spatie\Browsershot\Browsershot;
use Spatie\Browsershot\Exceptions\CouldNotTakeBrowsershot;
class BookmarkService
{
/**
* Create a new Bookmark.
*
* @param array $request Data from request()->all()
* @return Bookmark $bookmark
* @param array $request Data from request()->all()
* @return Bookmark
*/
public function createBookmark(array $request): Bookmark
{
@ -81,8 +81,9 @@ class BookmarkService
/**
* Given a URL, use browsershot to save an image of the page.
*
* @param string $url
* @param string $url
* @return string The uuid for the screenshot
* @throws CouldNotTakeBrowsershot
*/
public function saveScreenshot(string $url): string
{
@ -102,8 +103,9 @@ class BookmarkService
/**
* Given a URL, attempt to save it to the Internet Archive.
*
* @param string $url
* @param string $url
* @return string
* @throws InternetArchiveException
*/
public function getArchiveLink(string $url): string
{
@ -112,7 +114,7 @@ class BookmarkService
$response = $client->request('GET', 'https://web.archive.org/save/' . $url);
} catch (ClientException $e) {
//throw an exception to be caught
throw new InternetArchiveException;
throw new InternetArchiveException();
}
if ($response->hasHeader('Content-Location')) {
if (Str::startsWith(Arr::get($response->getHeader('Content-Location'), 0), '/web')) {
@ -121,6 +123,6 @@ class BookmarkService
}
//throw an exception to be caught
throw new InternetArchiveException;
throw new InternetArchiveException();
}
}

View file

@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Services;
use App\Models\Like;
use App\Jobs\ProcessLike;
use App\Models\Like;
use Illuminate\Support\Arr;
class LikeService

View file

@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Services\Micropub;
use Illuminate\Support\Arr;
use App\Services\PlaceService;
use Illuminate\Support\Arr;
class HCardService
{

View file

@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Services\Micropub;
use Illuminate\Support\Arr;
use App\Services\{BookmarkService, LikeService, NoteService};
use Illuminate\Support\Arr;
class HEntryService
{

View file

@ -5,8 +5,8 @@ declare(strict_types=1);
namespace App\Services\Micropub;
use App\Models\{Media, Note};
use Illuminate\Support\{Arr, Str};
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\{Arr, Str};
class UpdateService
{

View file

@ -4,9 +4,9 @@ declare(strict_types=1);
namespace App\Services;
use Illuminate\Support\{Arr, Str};
use App\Models\{Media, Note, Place};
use App\Jobs\{SendWebMentions, SyndicateNoteToTwitter};
use App\Models\{Media, Note, Place};
use Illuminate\Support\{Arr, Str};
class NoteService
{
@ -15,7 +15,7 @@ class NoteService
*
* @param array $request Data from request()->all()
* @param string $client
* @return \App\Note
* @return Note
*/
public function createNote(array $request, ?string $client = null): Note
{
@ -61,7 +61,7 @@ class NoteService
/**
* Get the content from the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return string|null
*/
private function getContent(array $request): ?string
@ -79,7 +79,7 @@ class NoteService
/**
* Get the in-reply-to from the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return string|null
*/
private function getInReplyTo(array $request): ?string
@ -94,7 +94,7 @@ class NoteService
/**
* Get the published time from the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return string|null
*/
private function getPublished(array $request): ?string
@ -113,7 +113,7 @@ class NoteService
/**
* Get the location data from the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return string|null
*/
private function getLocation(array $request): ?string
@ -135,8 +135,8 @@ class NoteService
/**
* Get the checkin data from the request to create a new note. This will be a Place.
*
* @param array $request Data from request()->all()
* @return \App\Models\Place|null
* @param array $request Data from request()->all()
* @return Place|null
*/
private function getCheckin(array $request): ?Place
{
@ -181,7 +181,7 @@ class NoteService
/**
* Get the Swarm URL from the syndication data in the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return string|null
*/
private function getSwarmUrl(array $request): ?string
@ -196,7 +196,7 @@ class NoteService
/**
* Get the syndication targets from the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return array
*/
private function getSyndicationTargets(array $request): array
@ -225,7 +225,7 @@ class NoteService
/**
* Get the media URLs from the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return array
*/
private function getMedia(array $request): array
@ -255,7 +255,7 @@ class NoteService
/**
* Get the Instagram photo URL from the request to create a new note.
*
* @param array $request Data from request()->all()
* @param array $request Data from request()->all()
* @return string|null
*/
private function getInstagramUrl(array $request): ?string

View file

@ -6,15 +6,14 @@ namespace App\Services;
use App\Models\Place;
use Illuminate\Support\Arr;
use Phaza\LaravelPostgis\Geometries\Point;
class PlaceService
{
/**
* Create a place.
*
* @param array $data
* @return \App\Place
* @param array $data
* @return Place
*/
public function createPlace(array $data): Place
{
@ -32,16 +31,17 @@ class PlaceService
$place = new Place();
$place->name = $data['name'];
$place->description = $data['description'];
$place->location = new Point((float) $data['latitude'], (float) $data['longitude']);
$place->latitude = $data['latitude'];
$place->longitude = $data['longitude'];
$place->save();
return $place;
}
/**
* Create a place from a h-card checkin, for exameple from OwnYourSwarm.
* Create a place from a h-card checkin, for example from OwnYourSwarm.
*
* @param array
* @param array
* @return Place
*/
public function createPlaceFromCheckin(array $checkin): Place
@ -62,10 +62,8 @@ class PlaceService
$place = new Place();
$place->name = Arr::get($checkin, 'properties.name.0');
$place->external_urls = Arr::get($checkin, 'properties.url.0');
$place->location = new Point(
(float) Arr::get($checkin, 'properties.latitude.0'),
(float) Arr::get($checkin, 'properties.longitude.0')
);
$place->latitude = Arr::get($checkin, 'properties.latitude.0');
$place->longitude = Arr::get($checkin, 'properties.longitude.0');
$place->save();
return $place;

View file

@ -4,9 +4,9 @@ declare(strict_types=1);
namespace App\Services;
use App\Exceptions\InvalidTokenException;
use App\Jobs\AddClientToDatabase;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use App\Exceptions\InvalidTokenException;
use Lcobucci\JWT\{Builder, Parser, Token};
class TokenService

View file

@ -1,7 +1,7 @@
{
"name": "jonnybarnes/jonnybarnes.uk",
"type": "project",
"description": "The code for jonnybanres.uk, based on Laravel 5.4",
"description": "The code for jonnybarnes.uk, based on Laravel 8",
"keywords": [
"framework",
"laravel",
@ -9,45 +9,46 @@
],
"license": "CC0-1.0",
"require": {
"php": ">=7.2.0",
"cviebrock/eloquent-sluggable": "~4.3",
"php": "^7.4",
"ext-intl": "*",
"ext-json": "*",
"ext-dom": "*",
"cviebrock/eloquent-sluggable": "^8.0",
"fideloper/proxy": "~4.0",
"guzzlehttp/guzzle": "~6.0",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"indieauth/client": "~0.1",
"intervention/image": "^2.4",
"jonnybarnes/emoji-a11y": "^0.3",
"jonnybarnes/indieweb": "dev-master",
"jonnybarnes/webmentions-parser": "0.4.*",
"laravel/framework": "5.8.*",
"laravel/horizon": "^3.0",
"laravel/scout": "^7.0",
"laravel/tinker": "^1.0",
"jonnybarnes/indieweb": "~0.2",
"jonnybarnes/webmentions-parser": "~0.5",
"jublonet/codebird-php": "4.0.0-beta.1",
"laravel/framework": "^8.0",
"laravel/horizon": "^5.0",
"laravel/scout": "^8.0",
"laravel/telescope": "^4.0",
"laravel/tinker": "^2.0",
"lcobucci/jwt": "^3.1",
"league/commonmark": "^0.18.0",
"league/commonmark-ext-autolink": "^0.2.0",
"league/commonmark": "^1.0",
"league/flysystem-aws-s3-v3": "^1.0",
"mf2/mf2": "~0.3",
"phaza/laravel-postgis": "~3.1",
"pmatseykanets/laravel-scout-postgres": "~5.0",
"pmatseykanets/laravel-scout-postgres": "^7.0",
"predis/predis": "~1.0",
"ramsey/uuid": "^3.5",
"sensiolabs/security-checker": "^5.0",
"sensiolabs/security-checker": "^6.0",
"spatie/browsershot": "~3.0",
"spatie/commonmark-highlighter": "^1.0",
"tgalopin/html-sanitizer": "^1.1",
"thujohn/twitter": "~2.0"
"spatie/commonmark-highlighter": "^2.0",
"tgalopin/html-sanitizer": "^1.1"
},
"require-dev": {
"barryvdh/laravel-debugbar": "^3.0",
"barryvdh/laravel-ide-helper": "^2.6",
"beyondcode/laravel-dump-server": "^1.0",
"barryvdh/laravel-debugbar": "~3.0",
"codedungeon/phpunit-result-printer": "^0.26.0",
"filp/whoops": "~2.0",
"fzaninotto/faker": "~1.4",
"laravel/dusk": "^5.0",
"mockery/mockery": "~1.0",
"nunomaduro/collision": "^3.0",
"phpunit/phpunit": "~8.0",
"symfony/thanks": "~1.0"
"facade/ignition": "^2.3.6",
"fzaninotto/faker": "^1.9.1",
"laravel/dusk": "^6.0",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^5.0",
"phpunit/phpunit": "^9.0",
"vimeo/psalm": "^4.0"
},
"config": {
"optimize-autoloader": true,
@ -61,12 +62,10 @@
},
"autoload": {
"psr-4": {
"App\\": "app/"
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"helpers.php"
]
@ -88,6 +87,9 @@
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
],
"test": [
"vendor/bin/phpunit --stop-on-failure"
]
}
}

8825
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -13,7 +13,7 @@ return [
|
*/
'name' => 'jonnybarnes.uk',
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
@ -22,7 +22,7 @@ return [
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
| services the application utilizes. Set this in your ".env" file.
|
*/
@ -39,7 +39,7 @@ return [
|
*/
'debug' => env('APP_DEBUG', false),
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
@ -100,7 +100,7 @@ return [
|
*/
'timezone' => env('APP_TIMEZONE', 'UTC'),
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
@ -113,7 +113,7 @@ return [
|
*/
'locale' => env('APP_LANG', 'en'),
'locale' => 'en',
/*
|--------------------------------------------------------------------------
@ -156,6 +156,18 @@ return [
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Font Link
|--------------------------------------------------------------------------
|
| If you have a css link to Adobes Typekit or Hoefler&Cos Typography
| then specify the link here.
|
*/
'font_link' => env('FONT_LINK', null),
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
@ -195,6 +207,10 @@ return [
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
@ -202,13 +218,9 @@ return [
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\HorizonServiceProvider::class,
App\Providers\RouteServiceProvider::class,
/*
* Thujohns Twitter API client
*/
Thujohn\Twitter\TwitterServiceProvider::class,
App\Providers\HorizonServiceProvider::class,
App\Providers\TelescopeServiceProvider::class,
],
@ -230,6 +242,7 @@ return [
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
@ -241,6 +254,7 @@ return [
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Http' => Illuminate\Support\Facades\Http::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
@ -260,8 +274,6 @@ return [
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Twitter' => Thujohn\Twitter\Facades\Twitter::class,
],
'piwik' => env('PIWIK', false),

View file

@ -44,6 +44,7 @@ return [
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
@ -96,7 +97,21 @@ return [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

View file

@ -36,7 +36,8 @@ return [
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
//
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
],
],

View file

@ -13,7 +13,8 @@ return [
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
| Supported: "apc", "array", "database", "file", "memcached", "redis"
| Supported: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb"
|
*/
@ -38,6 +39,7 @@ return [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
@ -72,7 +74,16 @@ return [
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'connection' => 'cache',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
],

View file

@ -1,5 +1,7 @@
<?php
use Illuminate\Support\Str;
return [
/*
@ -35,6 +37,7 @@ return [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
@ -42,7 +45,8 @@ return [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
@ -61,7 +65,8 @@ return [
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
@ -75,6 +80,7 @@ return [
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
@ -85,17 +91,6 @@ return [
'prefix_indexes' => true,
],
'travis' => [
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'travis_ci_test',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
]
],
/*
@ -124,20 +119,27 @@ return [
'redis' => [
'client' => 'predis',
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_CACHE_DB', 1),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],

7
config/fathom.php Normal file
View file

@ -0,0 +1,7 @@
<?php
return [
'id' => env('FATHOM_ID', null),
];

View file

@ -8,8 +8,8 @@ return [
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. A "local" driver, as well as a variety of cloud
| based drivers are available for your choosing. Just store away!
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
@ -37,7 +37,7 @@ return [
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "s3", "rackspace"
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
@ -51,17 +51,18 @@ return [
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'url' => env('APP_URL') . '/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_S3_KEY'),
'secret' => env('AWS_S3_SECRET'),
'region' => env('AWS_S3_REGION'),
'bucket' => env('AWS_S3_BUCKET'),
'url' => env('AWS_S3_URL'),
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
],
'media' => [
@ -71,4 +72,19 @@ return [
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

View file

@ -11,10 +11,42 @@ return [
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon"
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 10),
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 1024,
'threads' => 2,
'time' => 2,
],
];

258
config/ide-helper.php Normal file
View file

@ -0,0 +1,258 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Filename & Format
|--------------------------------------------------------------------------
|
| The default filename (without extension) and the format (php or json)
|
*/
'filename' => '_ide_helper',
'format' => 'php',
/*
|--------------------------------------------------------------------------
| Where to write the PhpStorm specific meta file
|--------------------------------------------------------------------------
|
| PhpStorm also supports the directory `.phpstorm.meta.php/` with arbitrary
| files in it, should you need additional files for your project; e.g.
| `.phpstorm.meta.php/laravel_ide_Helper.php'.
|
*/
'meta_filename' => '.phpstorm.meta.php',
/*
|--------------------------------------------------------------------------
| Fluent helpers
|--------------------------------------------------------------------------
|
| Set to true to generate commonly used Fluent methods
|
*/
'include_fluent' => false,
/*
|--------------------------------------------------------------------------
| Factory Builders
|--------------------------------------------------------------------------
|
| Set to true to generate factory generators for better factory()
| method auto-completion.
|
*/
'include_factory_builders' => false,
/*
|--------------------------------------------------------------------------
| Write Model Magic methods
|--------------------------------------------------------------------------
|
| Set to false to disable write magic methods of model
|
*/
'write_model_magic_where' => true,
/*
|--------------------------------------------------------------------------
| Write Model relation count properties
|--------------------------------------------------------------------------
|
| Set to false to disable writing of relation count properties to model DocBlocks.
|
*/
'write_model_relation_count_properties' => true,
/*
|--------------------------------------------------------------------------
| Write Eloquent Model Mixins
|--------------------------------------------------------------------------
|
| This will add the necessary DocBlock mixins to the model class
| contained in the Laravel Framework. This helps the IDE with
| auto-completion.
|
| Please be aware that this setting changes a file within the /vendor directory.
|
*/
'write_eloquent_model_mixins' => false,
/*
|--------------------------------------------------------------------------
| Helper files to include
|--------------------------------------------------------------------------
|
| Include helper files. By default not included, but can be toggled with the
| -- helpers (-H) option. Extra helper files can be included.
|
*/
'include_helpers' => false,
'helper_files' => [
base_path() . '/vendor/laravel/framework/src/Illuminate/Support/helpers.php',
],
/*
|--------------------------------------------------------------------------
| Model locations to include
|--------------------------------------------------------------------------
|
| Define in which directories the ide-helper:models command should look
| for models.
|
| glob patterns are supported to easier reach models in sub-directories,
| e.g. `app/Services/* /Models` (without the space)
|
*/
'model_locations' => [
'app',
],
/*
|--------------------------------------------------------------------------
| Models to ignore
|--------------------------------------------------------------------------
|
| Define which models should be ignored.
|
*/
'ignored_models' => [
],
/*
|--------------------------------------------------------------------------
| Extra classes
|--------------------------------------------------------------------------
|
| These implementations are not really extended, but called with magic functions
|
*/
'extra' => [
'Eloquent' => ['Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'],
'Session' => ['Illuminate\Session\Store'],
],
'magic' => [],
/*
|--------------------------------------------------------------------------
| Interface implementations
|--------------------------------------------------------------------------
|
| These interfaces will be replaced with the implementing class. Some interfaces
| are detected by the helpers, others can be listed below.
|
*/
'interfaces' => [
],
/*
|--------------------------------------------------------------------------
| Support for custom DB types
|--------------------------------------------------------------------------
|
| This setting allow you to map any custom database type (that you may have
| created using CREATE TYPE statement or imported using database plugin
| / extension to a Doctrine type.
|
| Each key in this array is a name of the Doctrine2 DBAL Platform. Currently valid names are:
| 'postgresql', 'db2', 'drizzle', 'mysql', 'oracle', 'sqlanywhere', 'sqlite', 'mssql'
|
| This name is returned by getName() method of the specific Doctrine/DBAL/Platforms/AbstractPlatform descendant
|
| The value of the array is an array of type mappings. Key is the name of the custom type,
| (for example, "jsonb" from Postgres 9.4) and the value is the name of the corresponding Doctrine2 type (in
| our case it is 'json_array'. Doctrine types are listed here:
| http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html
|
| So to support jsonb in your models when working with Postgres, just add the following entry to the array below:
|
| "postgresql" => array(
| "jsonb" => "json_array",
| ),
|
*/
'custom_db_types' => [
'postgresql' => [
'geography' => 'array',
],
],
/*
|--------------------------------------------------------------------------
| Support for camel cased models
|--------------------------------------------------------------------------
|
| There are some Laravel packages (such as Eloquence) that allow for accessing
| Eloquent model properties via camel case, instead of snake case.
|
| Enabling this option will support these packages by saving all model
| properties as camel case, instead of snake case.
|
| For example, normally you would see this:
|
| * @property \Illuminate\Support\Carbon $created_at
| * @property \Illuminate\Support\Carbon $updated_at
|
| With this enabled, the properties will be this:
|
| * @property \Illuminate\Support\Carbon $createdAt
| * @property \Illuminate\Support\Carbon $updatedAt
|
| Note, it is currently an all-or-nothing option.
|
*/
'model_camel_case_properties' => false,
/*
|--------------------------------------------------------------------------
| Property Casts
|--------------------------------------------------------------------------
|
| Cast the given "real type" to the given "type".
|
*/
'type_overrides' => [
'integer' => 'int',
'boolean' => 'bool',
],
/*
|--------------------------------------------------------------------------
| Include DocBlocks from classes
|--------------------------------------------------------------------------
|
| Include DocBlocks from classes to allow additional code inspection for
| magic methods and properties.
|
*/
'include_class_docblocks' => false,
/*
|--------------------------------------------------------------------------
| Force FQN usage
|--------------------------------------------------------------------------
|
| Use the fully qualified (class) name in docBlock,
| event if class exists in a given file
| or there is an import (use className) of a given class
|
*/
'force_fqn' => false,
];

View file

@ -1,6 +1,6 @@
<?php
return array(
return [
/*
|--------------------------------------------------------------------------
@ -15,6 +15,6 @@ return array(
|
*/
'driver' => 'imagick'
'driver' => 'imagick',
);
];

View file

@ -1,5 +1,6 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
@ -36,19 +37,20 @@ return [
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'level' => env('LOG_LEVEL', 'debug'),
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
],
@ -57,12 +59,12 @@ return [
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
'level' => env('LOG_LEVEL', 'critical'),
],
'papertrail' => [
'driver' => 'monolog',
'level' => 'debug',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
@ -81,13 +83,24 @@ return [
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
'level' => env('LOG_LEVEL', 'debug'),
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
'level' => env('LOG_LEVEL', 'debug'),
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
'slack' => env('LOG_SLACK_WEBHOOK_URL'),
];

View file

@ -4,45 +4,73 @@ return [
/*
|--------------------------------------------------------------------------
| Mail Driver
| Default Mailer
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses"
| "sparkpost", "log", "array"
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'driver' => env('MAIL_DRIVER', 'smtp'),
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| SMTP Host Address
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array"
|
*/
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/
'ses' => [
'transport' => 'ses',
],
'port' => env('MAIL_PORT', 587),
'mailgun' => [
'transport' => 'mailgun',
],
'postmark' => [
'transport' => 'postmark',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
],
/*
|--------------------------------------------------------------------------
@ -54,52 +82,12 @@ return [
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
@ -119,17 +107,4 @@ return [
],
],
/*
|--------------------------------------------------------------------------
| Log Channel
|--------------------------------------------------------------------------
|
| If you are using the "log" driver, you may specify the logging channel
| if you prefer to keep mail messages separate from other log entries
| for simpler reading. Otherwise, the default channel will be used.
|
*/
'log_channel' => env('MAIL_LOG_CHANNEL'),
];

View file

@ -46,15 +46,17 @@ return [
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('SQS_KEY', 'your-public-key'),
'secret' => env('SQS_SECRET', 'your-secret-key'),
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('SQS_REGION', 'us-east-1'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
@ -79,6 +81,7 @@ return [
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],

View file

@ -8,9 +8,9 @@ return [
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
@ -20,24 +20,14 @@ return [
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
'webhook' => [
'secret' => env('STRIPE_WEBHOOK_SECRET'),
'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300),
],
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

View file

@ -14,7 +14,7 @@ return [
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "array"
| "memcached", "redis", "dynamodb", "array"
|
*/
@ -31,7 +31,7 @@ return [
|
*/
'lifetime' => 60 * 24 * 7,
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
@ -92,9 +92,11 @@ return [
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc" or "memcached" session drivers, you may specify a
| cache store that should be used for these sessions. This value must
| correspond with one of the application's configured cache stores.
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
@ -126,7 +128,7 @@ return [
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
Str::slug(env('APP_NAME', 'laravel'), '_') . '_session'
),
/*
@ -166,7 +168,7 @@ return [
|
*/
'secure' => env('SESSION_SECURE_COOKIE', false),
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
@ -188,12 +190,12 @@ return [
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| do not enable this as other CSRF protection services are in place.
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict"
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => null,
'same_site' => 'lax',
];

155
config/telescope.php Normal file
View file

@ -0,0 +1,155 @@
<?php
use Laravel\Telescope\Watchers;
use Laravel\Telescope\Http\Middleware\Authorize;
return [
/*
|--------------------------------------------------------------------------
| Telescope Domain
|--------------------------------------------------------------------------
|
| This is the subdomain where Telescope will be accessible from. If the
| setting is null, Telescope will reside under the same domain as the
| application. Otherwise, this value will be used as the subdomain.
|
*/
'domain' => null,
/*
|--------------------------------------------------------------------------
| Telescope Path
|--------------------------------------------------------------------------
|
| This is the URI path where Telescope will be accessible from. Feel free
| to change this path to anything you like. Note that the URI will not
| affect the paths of its internal API that aren't exposed to users.
|
*/
'path' => 'telescope',
/*
|--------------------------------------------------------------------------
| Telescope Storage Driver
|--------------------------------------------------------------------------
|
| This configuration options determines the storage driver that will
| be used to store Telescope's data. In addition, you may set any
| custom options as needed by the particular driver you choose.
|
*/
'driver' => env('TELESCOPE_DRIVER', 'database'),
'storage' => [
'database' => [
'connection' => env('DB_CONNECTION', 'mysql'),
],
],
/*
|--------------------------------------------------------------------------
| Telescope Master Switch
|--------------------------------------------------------------------------
|
| This option may be used to disable all Telescope watchers regardless
| of their individual configuration, which simply provides a single
| and convenient way to enable or disable Telescope data storage.
|
*/
'enabled' => env('TELESCOPE_ENABLED', true),
/*
|--------------------------------------------------------------------------
| Telescope Route Middleware
|--------------------------------------------------------------------------
|
| These middleware will be assigned to every Telescope route, giving you
| the chance to add your own middleware to this list or change any of
| the existing middleware. Or, you can simply stick with this list.
|
*/
'middleware' => [
'web',
Authorize::class,
],
/*
|--------------------------------------------------------------------------
| Ignored Paths & Commands
|--------------------------------------------------------------------------
|
| The following array lists the URI paths and Artisan commands that will
| not be watched by Telescope. In addition to this list, some Laravel
| commands, like migrations and queue commands, are always ignored.
|
*/
'ignore_paths' => [
//
],
'ignore_commands' => [
//
],
/*
|--------------------------------------------------------------------------
| Telescope Watchers
|--------------------------------------------------------------------------
|
| The following array lists the "watchers" that will be registered with
| Telescope. The watchers gather the application's profile data when
| a request or task is executed. Feel free to customize this list.
|
*/
'watchers' => [
Watchers\CacheWatcher::class => env('TELESCOPE_CACHE_WATCHER', true),
Watchers\CommandWatcher::class => [
'enabled' => env('TELESCOPE_COMMAND_WATCHER', true),
'ignore' => [],
],
Watchers\DumpWatcher::class => env('TELESCOPE_DUMP_WATCHER', true),
Watchers\EventWatcher::class => env('TELESCOPE_EVENT_WATCHER', true),
Watchers\ExceptionWatcher::class => env('TELESCOPE_EXCEPTION_WATCHER', true),
Watchers\JobWatcher::class => env('TELESCOPE_JOB_WATCHER', true),
Watchers\LogWatcher::class => env('TELESCOPE_LOG_WATCHER', true),
Watchers\MailWatcher::class => env('TELESCOPE_MAIL_WATCHER', true),
Watchers\ModelWatcher::class => [
'enabled' => env('TELESCOPE_MODEL_WATCHER', true),
'events' => ['eloquent.*'],
],
Watchers\NotificationWatcher::class => env('TELESCOPE_NOTIFICATION_WATCHER', true),
Watchers\QueryWatcher::class => [
'enabled' => env('TELESCOPE_QUERY_WATCHER', true),
'ignore_packages' => true,
'slow' => 100,
],
Watchers\RedisWatcher::class => env('TELESCOPE_REDIS_WATCHER', true),
Watchers\RequestWatcher::class => [
'enabled' => env('TELESCOPE_REQUEST_WATCHER', true),
'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64),
],
Watchers\GateWatcher::class => [
'enabled' => env('TELESCOPE_GATE_WATCHER', true),
'ignore_abilities' => [],
'ignore_packages' => true,
],
Watchers\ScheduleWatcher::class => env('TELESCOPE_SCHEDULE_WATCHER', true),
],
];

View file

@ -1,12 +1,35 @@
<?php
use App\Models\Bookmark;
use Faker\Generator as Faker;
namespace Database\Factories;
$factory->define(Bookmark::class, function (Faker $faker) {
return [
'url' => $faker->url,
'name' => $faker->sentence,
'content' => $faker->text,
];
});
use App\Models\Bookmark;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
class BookmarkFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Bookmark::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
$now = Carbon::now()->subDays(rand(5, 15));
return [
'url' => $this->faker->url,
'name' => $this->faker->sentence,
'content' => $this->faker->text,
'created_at' => $now->toDateTimeString(),
'updated_at' => $now->toDateTimeString(),
];
}
}

View file

@ -1,13 +1,36 @@
<?php
use App\Models\Like;
use Faker\Generator as Faker;
namespace Database\Factories;
$factory->define(Like::class, function (Faker $faker) {
return [
'url' => $faker->url,
'author_name' => $faker->name,
'author_url' => $faker->url,
'content' => '<html><body><div class="h-entry"><div class="e-content">' . $faker->realtext() . '</div></div></body></html>',
];
});
use App\Models\Like;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
class LikeFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Like::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
$now = Carbon::now()->subDays(rand(5, 15));
return [
'url' => $this->faker->url,
'author_name' => $this->faker->name,
'author_url' => $this->faker->url,
'content' => '<html><body><div class="h-entry"><div class="e-content">' . $this->faker->realtext() . '</div></div></body></html>',
'created_at' => $now->toDateTimeString(),
'updated_at' => $now->toDateTimeString(),
];
}
}

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