Merge branch 'release/0.0.9'

This commit is contained in:
Jonny Barnes 2016-09-06 17:44:07 +01:00
commit 4ac589528b
46 changed files with 1405 additions and 674 deletions

View file

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

View file

@ -13,7 +13,7 @@ class Kernel extends ConsoleKernel
* @var array * @var array
*/ */
protected $commands = [ protected $commands = [
// Commands\Inspire::class, //
]; ];
/** /**
@ -27,4 +27,14 @@ class Kernel extends ConsoleKernel
// $schedule->command('inspire') // $schedule->command('inspire')
// ->hourly(); // ->hourly();
} }
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
} }

View file

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

View file

@ -3,12 +3,8 @@
namespace App\Exceptions; namespace App\Exceptions;
use Exception; use Exception;
use Illuminate\Validation\ValidationException; use Illuminate\Auth\AuthenticationException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Auth\Access\AuthorizationException;
use Symfony\Component\Debug\Exception\FlattenException; use Symfony\Component\Debug\Exception\FlattenException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
@ -19,10 +15,12 @@ class Handler extends ExceptionHandler
* @var array * @var array
*/ */
protected $dontReport = [ protected $dontReport = [
AuthorizationException::class, \Illuminate\Auth\AuthenticationException::class,
HttpException::class, \Illuminate\Auth\Access\AuthorizationException::class,
ModelNotFoundException::class, \Symfony\Component\HttpKernel\Exception\HttpException::class,
ValidationException::class, \Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
]; ];
/** /**
@ -30,38 +28,40 @@ class Handler extends ExceptionHandler
* *
* This is a great spot to send exceptions to Sentry, Bugsnag, etc. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
* *
* @param \Exception $exc * @param \Exception $exception
* @return void * @return void
*/ */
public function report(Exception $exc) public function report(Exception $exception)
{ {
parent::report($exc); parent::report($exception);
} }
/** /**
* Render an exception into an HTTP response. * Render an exception into an HTTP response.
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param \Exception $exc * @param \Exception $exception
* @return \Illuminate\Http\Response * @return \Illuminate\Http\Response
*/ */
public function render($request, Exception $exc) public function render($request, Exception $exception)
{ {
if (config('app.debug')) { return parent::render($request, $exception);
return $this->renderExceptionWithWhoops($exc); }
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
} }
if ($exc instanceof ModelNotFoundException) { return redirect()->guest('login');
$exc = new NotFoundHttpException($exc->getMessage(), $exc);
}
if ($exc instanceof TokenMismatchException) {
return redirect()->back()
->withInput($request->except('password', '_token'))
->withErrors('Validation Token has expired. Please try again', 'csrf');
}
return parent::render($request, $exc);
} }
/** /**
@ -70,7 +70,7 @@ class Handler extends ExceptionHandler
* @param \Exception $exc * @param \Exception $exc
* @return \Illuminate\Http\Response * @return \Illuminate\Http\Response
*/ */
protected function renderExceptionWithWhoops(Exception $exc) protected function renderExceptionWithWhoops(Exception $exception)
{ {
$whoops = new \Whoops\Run; $whoops = new \Whoops\Run;
$handler = new \Whoops\Handler\PrettyPageHandler(); $handler = new \Whoops\Handler\PrettyPageHandler();
@ -79,7 +79,7 @@ class Handler extends ExceptionHandler
}); });
$whoops->pushHandler($handler); $whoops->pushHandler($handler);
$flattened = FlattenException::create($exc); $flattened = FlattenException::create($exception);
return new \Illuminate\Http\Response( return new \Illuminate\Http\Response(
$whoops->handleException($exc), $whoops->handleException($exc),

View file

@ -0,0 +1,32 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}

View file

@ -5,39 +5,38 @@ namespace App\Http\Controllers\Auth;
use App\User; use App\User;
use Validator; use Validator;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller class RegisterController extends Controller
{ {
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Registration & Login Controller | Register Controller
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| This controller handles the registration of new users, as well as the | This controller handles the registration of new users as well as their
| authentication of existing users. By default, this controller uses | validation and creation. By default this controller uses a trait to
| a simple trait to add these behaviors. Why don't you explore it? | provide this functionality without requiring any additional code.
| |
*/ */
use AuthenticatesAndRegistersUsers, ThrottlesLogins; use RegistersUsers;
/** /**
* Where to redirect users after login / registration. * Where to redirect users after login / registration.
* *
* @var string * @var string
*/ */
protected $redirectTo = '/'; protected $redirectTo = '/home';
/** /**
* Create a new authentication controller instance. * Create a new controller instance.
* *
* @return void * @return void
*/ */
public function __construct() public function __construct()
{ {
$this->middleware($this->guestMiddleware(), ['except' => 'logout']); $this->middleware('guest');
} }
/** /**

View file

@ -5,7 +5,7 @@ namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords; use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller class ResetPasswordController extends Controller
{ {
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -21,12 +21,12 @@ class PasswordController extends Controller
use ResetsPasswords; use ResetsPasswords;
/** /**
* Create a new password controller instance. * Create a new controller instance.
* *
* @return void * @return void
*/ */
public function __construct() public function __construct()
{ {
$this->middleware($this->guestMiddleware()); $this->middleware('guest');
} }
} }

View file

@ -6,9 +6,8 @@ use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
class Controller extends BaseController class Controller extends BaseController
{ {
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests; use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
} }

View file

@ -7,6 +7,8 @@ use Twitter;
use App\Tag; use App\Tag;
use App\Note; use App\Note;
use Jonnybarnes\IndieWeb\Numbers; use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Filesystem\Filesystem;
use Jonnybarnes\WebmentionsParser\Authorship;
// Need to sort out Twitter and webmentions! // Need to sort out Twitter and webmentions!
@ -23,8 +25,8 @@ class NotesController extends Controller
foreach ($notes as $note) { foreach ($notes as $note) {
$replies = 0; $replies = 0;
foreach ($note->webmentions as $webmention) { foreach ($note->webmentions as $webmention) {
if ($webmention->type == 'reply') { if ($webmention->type == 'in-reply-to') {
$replies = $replies + 1; $replies++;
} }
} }
$note->replies = $replies; $note->replies = $replies;
@ -67,31 +69,51 @@ class NotesController extends Controller
public function singleNote($urlId) public function singleNote($urlId)
{ {
$numbers = new Numbers(); $numbers = new Numbers();
$authorship = new Authorship();
$realId = $numbers->b60tonum($urlId); $realId = $numbers->b60tonum($urlId);
$note = Note::find($realId); $note = Note::find($realId);
$replies = []; $replies = [];
$reposts = []; $reposts = [];
$likes = []; $likes = [];
foreach ($note->webmentions as $webmention) { foreach ($note->webmentions as $webmention) {
/*
reply->url |
reply->photo | Author
reply->name |
reply->source
reply->date
reply->reply
repost->url |
repost->photo | Author
repost->name |
repost->date
repost->source
like->url |
like->photo | Author
like->name |
*/
$microformats = json_decode($webmention->mf2);
$authorHCard = $authorship->findAuthor($microformats);
$content['url'] = $authorHCard['properties']['url'][0];
$content['photo'] = $this->createPhotoLink($authorHCard['properties']['photo'][0]);
$content['name'] = $authorHCard['properties']['name'][0];
switch ($webmention->type) { switch ($webmention->type) {
case 'reply': case 'in-reply-to':
$content = unserialize($webmention->content); $content['source'] = $webmention->source;
$content['source'] = $this->bridgyReply($webmention->source);
$content['photo'] = $this->createPhotoLink($content['photo']);
$content['date'] = $carbon->parse($content['date'])->toDayDateTimeString(); $content['date'] = $carbon->parse($content['date'])->toDayDateTimeString();
$content['reply'] = $microformats['items'][0]['properties']['content'][0]['html_purified'];
$replies[] = $content; $replies[] = $content;
break; break;
case 'repost': case 'repost-of':
$content = unserialize($webmention->content);
$content['photo'] = $this->createPhotoLink($content['photo']);
$content['date'] = $carbon->parse($content['date'])->toDayDateTimeString(); $content['date'] = $carbon->parse($content['date'])->toDayDateTimeString();
$content['source'] = $webmention->source;
$reposts[] = $content; $reposts[] = $content;
break; break;
case 'like': case 'like-of':
$content = unserialize($webmention->content);
$content['photo'] = $this->createPhotoLink($content['photo']);
$likes[] = $content; $likes[] = $content;
break; break;
} }
@ -164,41 +186,43 @@ class NotesController extends Controller
return view('taggednotes', ['notes' => $notes, 'tag' => $tag]); return view('taggednotes', ['notes' => $notes, 'tag' => $tag]);
} }
/**
* Swap a brid.gy URL shim-ing a twitter reply to a real twitter link.
*
* @param string
* @return string
*/
public function bridgyReply($source)
{
$url = $source;
if (mb_substr($source, 0, 28, 'UTF-8') == 'https://brid-gy.appspot.com/') {
$parts = explode('/', $source);
$tweetId = array_pop($parts);
if ($tweetId) {
$url = 'https://twitter.com/_/status/' . $tweetId;
}
}
return $url;
}
/** /**
* Create the photo link. * Create the photo link.
* *
* We shall leave twitter.com and twimg.com links as they are. Then we shall
* check for local copies, if that fails leave the link as is.
*
* @param string * @param string
* @return string * @return string
*/ */
public function createPhotoLink($url) public function createPhotoLink($url)
{ {
$host = parse_url($url)['host']; $host = parse_url($url, PHP_URL_HOST);
if ($host != 'twitter.com' && $host != 'pbs.twimg.com') { if ($host == 'pbs.twimg.com') {
return '/assets/profile-images/' . $host . '/image'; //make sure we use HTTPS, we know twitter supports it
}
if (mb_substr($url, 0, 20) == 'http://pbs.twimg.com') {
return str_replace('http://', 'https://', $url); return str_replace('http://', 'https://', $url);
} }
if ($host == 'twitter.com') {
if (Cache::has($url)) {
return Cache::get($url);
}
$username = parse_url($url, PHP_URL_PATH);
try {
$info = Twitter::getUsers(['screen_name' => $username]);
$profile_image = $info->profile_image_url_https;
Cache::put($url, $profile_image, 10080); //1 week
} catch (Exception $e) {
return $url; //not sure here
}
return $profile_image;
}
$filesystem = new Filesystem();
if ($filesystem->exists(public_path() . '/assets/profile-images/' . $host . '/image')) {
return '/assets/profile-images/' . $host . '/image';
}
return $url;
} }
/** /**

View file

@ -28,7 +28,7 @@ class WebMentionsController extends Controller
} }
//next check the $target is valid //next check the $target is valid
$path = parse_url($request->input('target'))['path']; $path = parse_url($request->input('target'), PHP_URL_PATH);
$pathParts = explode('/', $path); $pathParts = explode('/', $path);
switch ($pathParts[1]) { switch ($pathParts[1]) {
@ -36,9 +36,8 @@ class WebMentionsController extends Controller
//we have a note //we have a note
$noteId = $pathParts[2]; $noteId = $pathParts[2];
$numbers = new Numbers(); $numbers = new Numbers();
$realId = $numbers->b60tonum($noteId);
try { try {
$note = Note::findOrFail($realId); $note = Note::findOrFail($numbers->b60tonum($noteId));
$this->dispatch(new ProcessWebMention($note, $request->input('source'))); $this->dispatch(new ProcessWebMention($note, $request->input('source')));
} catch (ModelNotFoundException $e) { } catch (ModelNotFoundException $e) {
return new Response('This note doesnt exist.', 400); return new Response('This note doesnt exist.', 400);

View file

@ -29,11 +29,13 @@ class Kernel extends HttpKernel
\Illuminate\Session\Middleware\StartSession::class, \Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class, \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\LinkHeadersMiddleware::class, \App\Http\Middleware\LinkHeadersMiddleware::class,
], ],
'api' => [ 'api' => [
'throttle:60,1', 'throttle:60,1',
'bindings',
], ],
]; ];
@ -47,7 +49,7 @@ class Kernel extends HttpKernel
protected $routeMiddleware = [ protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class, 'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'myauth' => \App\Http\Middleware\MyAuthMiddleware::class, 'myauth' => \App\Http\Middleware\MyAuthMiddleware::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

View file

@ -1,30 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}

View file

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

View file

@ -2,8 +2,8 @@
namespace App\Jobs; namespace App\Jobs;
use Mf2;
use App\Note; use App\Note;
use Mf2\parse;
use HTMLPurifier; use HTMLPurifier;
use App\WebMention; use App\WebMention;
use GuzzleHttp\Client; use GuzzleHttp\Client;
@ -11,14 +11,18 @@ use HTMLPurifier_Config;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Jonnybarnes\WebmentionsParser\Parser; use Jonnybarnes\WebmentionsParser\Parser;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Exceptions\RemoteContentNotFoundException;
class ProcessWebMention extends Job implements ShouldQueue class ProcessWebMention extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels, DispatchesJobs;
protected $note; protected $note;
protected $source; protected $source;
protected $guzzle;
/** /**
* Create a new job instance. * Create a new job instance.
@ -27,10 +31,11 @@ class ProcessWebMention extends Job implements ShouldQueue
* @param string $source * @param string $source
* @return void * @return void
*/ */
public function __construct(Note $note, $source) public function __construct(Note $note, $source, Client $guzzle = null)
{ {
$this->note = $note; $this->note = $note;
$this->source = $source; $this->source = $source;
$this->guzzle = $guzzle ?? new Client();
} }
/** /**
@ -44,113 +49,83 @@ class ProcessWebMention extends Job implements ShouldQueue
$sourceURL = parse_url($this->source); $sourceURL = parse_url($this->source);
$baseURL = $sourceURL['scheme'] . '://' . $sourceURL['host']; $baseURL = $sourceURL['scheme'] . '://' . $sourceURL['host'];
$remoteContent = $this->getRemoteContent($this->source); $remoteContent = $this->getRemoteContent($this->source);
$microformats = $this->parseHTML($remoteContent, $baseURL); if ($remoteContent === null) {
$count = WebMention::where('source', '=', $this->source)->count(); throw new RemoteContentNotFoundException;
if ($count > 0) { }
//we already have a webmention from this source $microformats = Mf2\parse($remoteContent, $baseURL);
$webmentions = WebMention::where('source', '=', $this->source)->get(); $webmentions = WebMention::where('source', $this->source)->get();
foreach ($webmentions as $webmention) { foreach ($webmentions as $webmention) {
//now check it still 'mentions' this target //check webmention still references target
//we switch for each type of mention (reply/like/repost) //we try each type of mention (reply/like/repost)
switch ($webmention->type) { if ($webmention->type == 'in-reply-to') {
case 'reply': if ($parser->checkInReplyTo($microformats, $this->note->longurl) == false) {
if ($parser->checkInReplyTo($microformats, $note->longurl) == false) { //it doesn't so delete
//it doesn't so delete $webmention->delete();
$webmention->delete();
return true; return;
} }
//webmenion is still a reply, so update content //webmenion is still a reply, so update content
$content = $parser->replyContent($microformats); $microformats = $this->filterHTML($microformats);
$this->saveImage($content); $this->dispatch(new SaveProfileImage($microformats));
$content['reply'] = $this->filterHTML($content['reply']); $webmention->mf2 = json_encode($microformats);
$content = serialize($content); $webmention->save();
$webmention->content = $content;
$webmention->save();
return true; return;
break; }
case 'like': if ($webmention->type == 'like-of') {
if ($parser->checkLikeOf($microformats, $note->longurl) == false) { if ($parser->checkLikeOf($microformats, $note->longurl) == false) {
//it doesn't so delete //it doesn't so delete
$webmention->delete(); $webmention->delete();
return true; return;
} //note we don't need to do anything if it still is a like } //note we don't need to do anything if it still is a like
break; }
case 'repost': if ($webmention->type == 'repost-of') {
if ($parser->checkRepostOf($microformats, $note->longurl) == false) { if ($parser->checkRepostOf($microformats, $note->longurl) == false) {
//it doesn't so delete //it doesn't so delete
$webmention->delete(); $webmention->delete();
return;
} //again, we don't need to do anything if it still is a repost
}
}//foreach
return true;
} //again, we don't need to do anything if it still is a repost
break;
}//switch
}//foreach
}//if
//no wemention in db so create new one //no wemention in db so create new one
$webmention = new WebMention(); $webmention = new WebMention();
//check it is in fact a reply $type = $parser->getMentionType($microformats); //throw error here?
if ($parser->checkInReplyTo($microformats, $note->longurl)) { $this->dispatch(new SaveProfileImage($microformats));
$content = $parser->replyContent($microformats); $microformats = $this->filterHTML($microformats);
$this->saveImage($content); $webmention->source = $this->source;
$content['reply'] = $this->filterHTML($content['reply']); $webmention->target = $this->note->longurl;
$content = serialize($content); $webmention->commentable_id = $this->note->id;
$webmention->source = $this->source; $webmention->commentable_type = 'App\Note';
$webmention->target = $note->longurl; $webmention->type = $type;
$webmention->commentable_id = $this->note->id; $webmention->mf2 = json_encode($microformats);
$webmention->commentable_type = 'App\Note'; $webmention->save();
$webmention->type = 'reply';
$webmention->content = $content;
$webmention->save();
return true;
} elseif ($parser->checkLikeOf($microformats, $note->longurl)) {
//it is a like
$content = $parser->likeContent($microformats);
$this->saveImage($content);
$content = serialize($content);
$webmention->source = $this->source;
$webmention->target = $note->longurl;
$webmention->commentable_id = $this->note->id;
$webmention->commentable_type = 'App\Note';
$webmention->type = 'like';
$webmention->content = $content;
$webmention->save();
return true;
} elseif ($parser->checkRepostOf($microformats, $note->longurl)) {
//it is a repost
$content = $parser->repostContent($microformats);
$this->saveImage($content);
$content = serialize($content);
$webmention->source = $this->source;
$webmention->target = $note->longurl;
$webmention->commentable_id = $this->note->id;
$webmention->commentable_type = 'App\Note';
$webmention->type = 'repost';
$webmention->content = $content;
$webmention->save();
return true;
}
} }
/** /**
* Retreive the remote content from a URL, and caches the result. * Retreive the remote content from a URL, and caches the result.
* *
* @param string The URL to retreive content from * @param string The URL to retreive content from
* @return string The HTML from the URL * @return string|null The HTML from the URL (or null if error)
*/ */
private function getRemoteContent($url) private function getRemoteContent($url)
{ {
$client = new Client(); try {
$response = $this->guzzle->request('GET', $url);
$response = $client->get($url); } catch (RequestException $e) {
return;
}
$html = (string) $response->getBody(); $html = (string) $response->getBody();
$path = storage_path() . '/HTML/' . $this->createFilenameFromURL($url); $path = storage_path() . '/HTML/' . $this->createFilenameFromURL($url);
$this->fileForceContents($path, $html); $parts = explode('/', $path);
$name = array_pop($parts);
$dir = implode('/', $parts);
if (! is_dir($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents("$dir/$name", $html);
return $html; return $html;
} }
@ -173,79 +148,29 @@ class ProcessWebMention extends Job implements ShouldQueue
} }
/** /**
* Save a file, and create any necessary folders. * Filter the HTML in a reply webmention.
* *
* @param string The directory to save to * @param array The unfiltered microformats
* @param binary The file to save * @return array The filtered microformats
*/ */
private function fileForceContents($dir, $contents) private function filterHTML($microformats)
{ {
$parts = explode('/', $dir); if (isset($microformats['items'][0]['properties']['content'][0]['html'])) {
$name = array_pop($parts); $microformats['items'][0]['properties']['content'][0]['html_purified'] = $this->useHTMLPurifier(
$dir = implode('/', $parts); $microformats['items'][0]['properties']['content'][0]['html']
if (! is_dir($dir)) { );
mkdir($dir, 0755, true);
} }
file_put_contents("$dir/$name", $contents);
}
/**
* A wrapper function for php-mf2s parse method.
*
* @param string The HTML to parse
* @param string The base URL to resolve relative URLs in the HTML against
* @return array The porcessed microformats
*/
private function parseHTML($html, $baseurl)
{
$microformats = \Mf2\parse((string) $html, $baseurl);
return $microformats; return $microformats;
} }
/** /**
* Save a profile image to the local cache. * Set up and use HTMLPurifer on some HTML.
*
* @param array source content
* @return bool wether image was saved or not (we dont save twitter profiles)
*/
public function saveImage(array $content)
{
$photo = $content['photo'];
$home = $content['url'];
//dont save pbs.twimg.com links
if (parse_url($photo)['host'] != 'pbs.twimg.com'
&& parse_url($photo)['host'] != 'twitter.com') {
$client = new Client();
try {
$response = $client->get($photo);
$image = $response->getBody(true);
$path = public_path() . '/assets/profile-images/' . parse_url($home)['host'] . '/image';
$this->fileForceContents($path, $image);
} catch (Exception $e) {
// we are openning and reading the default image so that
// fileForceContent work
$default = public_path() . '/assets/profile-images/default-image';
$handle = fopen($default, 'rb');
$image = fread($handle, filesize($default));
fclose($handle);
$path = public_path() . '/assets/profile-images/' . parse_url($home)['host'] . '/image';
$this->fileForceContents($path, $image);
}
return true;
}
return false;
}
/**
* Purify HTML received from a webmention.
* *
* @param string The HTML to be processed * @param string The HTML to be processed
* @return string The processed HTML * @return string The processed HTML
*/ */
public function filterHTML($html) private function useHTMLPurifier($html)
{ {
$config = HTMLPurifier_Config::createDefault(); $config = HTMLPurifier_Config::createDefault();
$config->set('Cache.SerializerPath', storage_path() . '/HTMLPurifier'); $config->set('Cache.SerializerPath', storage_path() . '/HTMLPurifier');

View file

@ -0,0 +1,66 @@
<?php
namespace App\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Jonnybarnes\WebmentionsParser\Authorship;
use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
class SaveProfileImage extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $microformats;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($microformats)
{
$this->microformats = $microformats;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Authorship $authorship)
{
try {
$author = $authorship->findAuthor($microformats);
} catch (AuthorshipParserException $e) {
return;
}
$photo = $author['properties'][0]['photo'][0];
$home = $author['properties'][0]['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') {
$client = new Client();
try {
$response = $client->get($photo);
$image = $response->getBody(true);
} catch (RequestException $e) {
// we are openning and reading the default image so that
$default = public_path() . '/assets/profile-images/default-image';
$handle = fopen($default, 'rb');
$image = fread($handle, filesize($default));
fclose($handle);
}
$path = public_path() . '/assets/profile-images/' . parse_url($home, PHP_URL_HOST) . '/image';
$parts = explode('/', $path);
$name = array_pop($parts);
$dir = implode('/', $parts);
if (! is_dir($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents("$dir/$name", $image);
}
}
}

View file

@ -20,9 +20,10 @@ class SendWebMentions extends Job implements ShouldQueue
* @param Note $note * @param Note $note
* @return void * @return void
*/ */
public function __construct(Note $note) public function __construct(Note $note, Client $guzzle = null)
{ {
$this->note = $note; $this->note = $note;
$this->guzzle = $guzzle ?? new Client();
} }
/** /**
@ -31,16 +32,16 @@ class SendWebMentions extends Job implements ShouldQueue
* @param \GuzzleHttp\Client $guzzle * @param \GuzzleHttp\Client $guzzle
* @return void * @return void
*/ */
public function handle(Client $guzzle) public function handle()
{ {
//grab the URLs //grab the URLs
$urlsInReplyTo = explode(' ', $this->note->in_reply_to); $urlsInReplyTo = explode(' ', $this->note->in_reply_to);
$urlsNote = $this->getLinks($this->note->note); $urlsNote = $this->getLinks($this->note->note);
$urls = array_filter(array_merge($urlsInReplyTo, $urlsNote)); //filter out none URLs $urls = array_filter(array_merge($urlsInReplyTo, $urlsNote)); //filter out none URLs
foreach ($urls as $url) { foreach ($urls as $url) {
$endpoint = $this->discoverWebmentionEndpoint($url, $guzzle); $endpoint = $this->discoverWebmentionEndpoint($url, $this->guzzle);
if ($endpoint) { if ($endpoint) {
$guzzle->post($endpoint, [ $this->guzzle->post($endpoint, [
'form_params' => [ 'form_params' => [
'source' => $this->note->longurl, 'source' => $this->note->longurl,
'target' => $url, 'target' => $url,
@ -73,8 +74,8 @@ class SendWebMentions extends Job implements ShouldQueue
//check HTTP Headers for webmention endpoint //check HTTP Headers for webmention endpoint
$links = \GuzzleHttp\Psr7\parse_header($response->getHeader('Link')); $links = \GuzzleHttp\Psr7\parse_header($response->getHeader('Link'));
foreach ($links as $link) { foreach ($links as $link) {
if ($link['rel'] == 'webmention') { if (mb_stristr($link['rel'], 'webmention')) {
return trim($link[0], '<>'); return $this->resolveUri($link[0], $url);
} }
} }
@ -89,11 +90,7 @@ class SendWebMentions extends Job implements ShouldQueue
$endpoint = $rels[0]['http://webmention.org/'][0]; $endpoint = $rels[0]['http://webmention.org/'][0];
} }
if ($endpoint) { if ($endpoint) {
if (filter_var($endpoint, FILTER_VALIDATE_URL)) { return $this->resolveUri($endpoint, $url);
return $endpoint;
}
//it must be a relative url, so resolve with php-mf2
return $mf2->resolveUrl($endpoint);
} }
return false; return false;
@ -105,7 +102,7 @@ class SendWebMentions extends Job implements ShouldQueue
* @param string $html * @param string $html
* @return array $urls * @return array $urls
*/ */
private function getLinks($html) public function getLinks($html)
{ {
$urls = []; $urls = [];
$dom = new \DOMDocument(); $dom = new \DOMDocument();
@ -117,4 +114,24 @@ class SendWebMentions extends Job implements ShouldQueue
return $urls; return $urls;
} }
/**
* Resolve a URI if necessary.
*
* @param string $url
* @param string $base
* @return string
*/
public function resolveUri(string $url, string $base): string
{
$endpoint = \GuzzleHttp\Psr7\uri_for($url);
if ($endpoint->getScheme() !== null) {
return (string) $endpoint;
}
return (string) \GuzzleHttp\Psr7\Uri::resolve(
\GuzzleHttp\Psr7\uri_for($base),
$endpoint
);
}
} }

View file

@ -1 +0,0 @@

View file

@ -1 +0,0 @@

View file

@ -2,7 +2,6 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider class AuthServiceProvider extends ServiceProvider
@ -19,12 +18,11 @@ class AuthServiceProvider extends ServiceProvider
/** /**
* Register any application authentication / authorization services. * Register any application authentication / authorization services.
* *
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void * @return void
*/ */
public function boot(GateContract $gate) public function boot()
{ {
$this->registerPolicies($gate); $this->registerPolicies();
// //
} }

View file

@ -0,0 +1,26 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
/*
* Authenticate the user's personal channel...
*/
Broadcast::channel('App.User.*', function ($user, $userId) {
return (int) $user->id === (int) $userId;
});
}
}

View file

@ -2,7 +2,7 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider class EventServiceProvider extends ServiceProvider
@ -21,12 +21,11 @@ class EventServiceProvider extends ServiceProvider
/** /**
* Register any other events for your application. * Register any other events for your application.
* *
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void * @return void
*/ */
public function boot(DispatcherContract $events) public function boot()
{ {
parent::boot($events); parent::boot();
// //
} }

View file

@ -2,7 +2,7 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Routing\Router; use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider class RouteServiceProvider extends ServiceProvider
@ -22,22 +22,23 @@ class RouteServiceProvider extends ServiceProvider
* @param \Illuminate\Routing\Router $router * @param \Illuminate\Routing\Router $router
* @return void * @return void
*/ */
public function boot(Router $router) public function boot()
{ {
// //
parent::boot($router); parent::boot();
} }
/** /**
* Define the routes for the application. * Define the routes for the application.
* *
* @param \Illuminate\Routing\Router $router
* @return void * @return void
*/ */
public function map(Router $router) public function map()
{ {
$this->mapWebRoutes($router); $this->mapWebRoutes();
$this->mapApiRoutes();
// //
} }
@ -47,15 +48,33 @@ class RouteServiceProvider extends ServiceProvider
* *
* These routes all receive session state, CSRF protection, etc. * These routes all receive session state, CSRF protection, etc.
* *
* @param \Illuminate\Routing\Router $router
* @return void * @return void
*/ */
protected function mapWebRoutes(Router $router) protected function mapWebRoutes()
{ {
$router->group([ Route::group([
'namespace' => $this->namespace, 'middleware' => 'web', 'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) { ], function ($router) {
require app_path('Http/routes.php'); require base_path('routes/web.php');
});
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::group([
'middleware' => 'api',
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
require base_path('routes/api.php');
}); });
} }
} }

View file

@ -2,10 +2,13 @@
namespace App; namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable class User extends Authenticatable
{ {
use Notifiable;
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
* *

View file

@ -1,5 +1,12 @@
# Changelog # Changelog
## Version 0.0.9 (2016-09-06)
- Adding jsonb column to store webmentions mf2.
* As of L5.2 this needs a custom command to drop NOT NULL from content, L5.3 should allow a fix for this
- Refactor receiving webmention code
- Refactor sending webmention code to pass webmention.rocks
- Update to use Laravel 5.3
## Version 0.0.8.5 (2016-07-18) ## Version 0.0.8.5 (2016-07-18)
- Set the size of the textarea in a form better - Set the size of the textarea in a form better
- Update to latest Guzzle to fix CVE-2016-5385 - Update to latest Guzzle to fix CVE-2016-5385

View file

@ -1,13 +1,13 @@
{ {
"name": "jonnybarnes/jonnybarnes.uk", "name": "jonnybarnes/jonnybarnes.uk",
"description": "The code for jonnybanres.uk, based on Laravel 5.2", "description": "The code for jonnybanres.uk, based on Laravel 5.3",
"keywords": ["framework", "laravel", "indieweb"], "keywords": ["framework", "laravel", "indieweb"],
"license": "CC0-1.0", "license": "CC0-1.0",
"type": "project", "type": "project",
"require": { "require": {
"ext-intl": "*", "ext-intl": "*",
"php": ">=7.0.0", "php": ">=7.0.0",
"laravel/framework": "5.2.*", "laravel/framework": "5.3.*",
"jonnybarnes/indieweb": "dev-master", "jonnybarnes/indieweb": "dev-master",
"jonnybarnes/webmentions-parser": "dev-master", "jonnybarnes/webmentions-parser": "dev-master",
"guzzlehttp/guzzle": "~6.0", "guzzlehttp/guzzle": "~6.0",
@ -27,8 +27,8 @@
"fzaninotto/faker": "~1.4", "fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*", "mockery/mockery": "0.9.*",
"phpunit/phpunit": "~5.0", "phpunit/phpunit": "~5.0",
"symfony/css-selector": "2.8.*|3.0.*", "symfony/css-selector": "3.1.*",
"symfony/dom-crawler": "2.8.*|3.0.*", "symfony/dom-crawler": "3.1.*",
"barryvdh/laravel-debugbar": "~2.0", "barryvdh/laravel-debugbar": "~2.0",
"filp/whoops": "~2.0" "filp/whoops": "~2.0"
}, },

920
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,18 @@
return [ return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
*/
'name' => 'jonnybarnes.uk',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Application Environment | Application Environment
@ -151,6 +163,7 @@ return [
Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class, Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class,
@ -166,6 +179,7 @@ return [
*/ */
App\Providers\AppServiceProvider::class, App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class, App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class, App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class, App\Providers\RouteServiceProvider::class,
@ -221,6 +235,7 @@ return [
'Lang' => Illuminate\Support\Facades\Lang::class, 'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class, 'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class, 'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class, 'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class, 'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class,

View file

@ -81,10 +81,6 @@ return [
| Resetting Passwords | Resetting Passwords
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more | You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have | than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types. | separate password reset settings based on the specific user types.
@ -94,11 +90,9 @@ return [
| they have less time to be guessed. You may change this as needed. | they have less time to be guessed. You may change this as needed.
| |
*/ */
'passwords' => [ 'passwords' => [
'users' => [ 'users' => [
'provider' => 'users', 'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets', 'table' => 'password_resets',
'expire' => 60, 'expire' => 60,
], ],

View file

@ -11,11 +11,11 @@ return [
| framework when an event needs to be broadcast. You may set this to | framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below. | any of the connections defined in the "connections" array below.
| |
| Supported: "pusher", "redis", "log" | Supported: "pusher", "redis", "log", "null"
| |
*/ */
'default' => env('BROADCAST_DRIVER', 'pusher'), 'default' => env('BROADCAST_DRIVER', 'null'),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -49,6 +49,10 @@ return [
'driver' => 'log', 'driver' => 'log',
], ],
'null' => [
'driver' => 'null',
],
], ],
]; ];

View file

@ -51,6 +51,14 @@ return [
'memcached' => [ 'memcached' => [
'driver' => 'memcached', 'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [ 'servers' => [
[ [
'host' => env('MEMCACHED_HOST', '127.0.0.1'), 'host' => env('MEMCACHED_HOST', '127.0.0.1'),

View file

@ -53,29 +53,30 @@ return [
], ],
'mysql' => [ 'mysql' => [
'driver' => 'mysql', 'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'), 'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'), 'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'), 'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'), 'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''), 'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4', 'charset' => 'utf8',
'collation' => 'utf8mb4_unicode_ci', 'collation' => 'utf8_unicode_ci',
'prefix' => '', 'prefix' => '',
'strict' => false, 'strict' => true,
'engine' => null, 'engine' => null,
], ],
'pgsql' => [ 'pgsql' => [
'driver' => 'pgsql', 'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'), 'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '5432'), 'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'), 'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'), 'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''), 'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8', 'charset' => 'utf8',
'prefix' => '', 'prefix' => '',
'schema' => 'public', 'schema' => 'public',
'sslmode' => 'prefer',
], ],
'travis' => [ 'travis' => [

View file

@ -54,8 +54,10 @@ return [
| used globally for all e-mails that are sent by your application. | used globally for all e-mails that are sent by your application.
| |
*/ */
'from' => [
'from' => ['address' => null, 'name' => null], 'address' => 'hello@example.com',
'name' => 'Example',
],
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View file

@ -11,7 +11,7 @@ return [
| API, giving you convenient access to each back-end using the same | API, giving you convenient access to each back-end using the same
| syntax for each one. Here you may set the default queue driver. | syntax for each one. Here you may set the default queue driver.
| |
| Supported: "null", "sync", "database", "beanstalkd", "sqs", "redis" | Supported: "sync", "database", "beanstalkd", "sqs", "redis", "null"
| |
*/ */
@ -38,14 +38,14 @@ return [
'driver' => 'database', 'driver' => 'database',
'table' => 'jobs', 'table' => 'jobs',
'queue' => 'default', 'queue' => 'default',
'expire' => 90, 'retry_after' => 90,
], ],
'beanstalkd' => [ 'beanstalkd' => [
'driver' => 'beanstalkd', 'driver' => 'beanstalkd',
'host' => 'localhost', 'host' => 'localhost',
'queue' => 'default', 'queue' => 'default',
'ttr' => 90, 'retry_after' => 90,
], ],
'sqs' => [ 'sqs' => [
@ -61,7 +61,7 @@ return [
'driver' => 'redis', 'driver' => 'redis',
'connection' => 'default', 'connection' => 'default',
'queue' => 'default', 'queue' => 'default',
'expire' => 90, 'retry_after' => 90,
], ],
], ],

View file

@ -19,10 +19,6 @@ return [
'secret' => env('MAILGUN_SECRET'), 'secret' => env('MAILGUN_SECRET'),
], ],
'mandrill' => [
'secret' => env('MANDRILL_SECRET'),
],
'ses' => [ 'ses' => [
'key' => env('SES_KEY'), 'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'), 'secret' => env('SES_SECRET'),

View file

@ -44,7 +44,7 @@ return [
| |
*/ */
'encrypt' => false, 'encrypt' => true,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View file

@ -7,5 +7,5 @@
return [ return [
'longurl' => env('APP_LONGURL', 'jonnybarnes.uk'), 'longurl' => env('APP_LONGURL', 'jonnybarnes.uk'),
'shorturl' => env('APP_SHORTURL', 'jmb.so') 'shorturl' => env('APP_SHORTURL', 'jmb.lv')
]; ];

View file

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddJsonbMf2ColumnToWebmentionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('webmentions', function (Blueprint $table) {
$table->jsonb('mf2')->nullable();
$table->index(['mf2']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('webmentions', function (Blueprint $table) {
$table->dropIndex(['mf2']);
$table->dropColumn('mf2');
});
}
}

View file

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddExceptionColumnToFailedJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('failed_jobs', function (Blueprint $table) {
$table->text('exception');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('failed_jobs', function (Blueprint $table) {
$table->dropColumn('exception');
});
}
}

View file

@ -20,13 +20,13 @@
</div> </div>
@if(count($likes) > 0)<h1 class="notes-subtitle">Likes</h1>@endif @if(count($likes) > 0)<h1 class="notes-subtitle">Likes</h1>@endif
@foreach($likes as $like) @foreach($likes as $like)
<a href="{{ $like['url'] }}"><img src="{{ $like['photo'] }}" alt="" class="like-photo"></a> <a href="{{ $like['url'] }}"><img src="{{ $like['photo'] }}" alt="profile picture of {{ $like['name'] }}" class="like-photo"></a>
@endforeach @endforeach
@if(count($reposts) > 0)<h1 class="notes-subtitle">Reposts</h1>@endif @if(count($reposts) > 0)<h1 class="notes-subtitle">Reposts</h1>@endif
@foreach($reposts as $repost) @foreach($reposts as $repost)
<p><a class="h-card vcard mini-h-card p-author" href="{{ $repost['url'] }}"> <p><a class="h-card vcard mini-h-card p-author" href="{{ $repost['url'] }}">
<img src="{{ $repost['photo'] }}" alt="profile picture of {{ $repost['name'] }}" class="photo u-photo logo"> <span class="fn">{{ $repost['name'] }}</span> <img src="{{ $repost['photo'] }}" alt="profile picture of {{ $repost['name'] }}" class="photo u-photo logo"> <span class="fn">{{ $repost['name'] }}</span>
</a> reposted this at <a href="{{ $repost['repost'] }}">{{ $repost['date'] }}</a>.</p> </a> reposted this at <a href="{{ $repost['source'] }}">{{ $repost['date'] }}</a>.</p>
@endforeach @endforeach
@stop @stop

18
routes/api.php Normal file
View file

@ -0,0 +1,18 @@
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:api');

18
routes/console.php Normal file
View file

@ -0,0 +1,18 @@
<?php
use Illuminate\Foundation\Inspiring;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->describe('Display an inspiring quote');

View file

@ -2,12 +2,12 @@
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Application Routes | Web Routes
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Here is where you can register all of the routes for an application. | This file is where you may define all of the routes that are handled
| It's a breeze. Simply tell Laravel the URIs it should respond to | by your application. Just tell Laravel the URIs it should respond
| and give it the controller to call when that URI is requested. | to using a Closure or controller method. Build something great!
| |
*/ */

View file

@ -2,6 +2,7 @@
namespace App\Tests; namespace App\Tests;
use Cache;
use TestCase; use TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseMigrations;
@ -131,15 +132,15 @@ class NotesTest extends TestCase
} }
/** /**
* Test the bridgy url shim method. * Test a correct profile link is formed from a generic URL.
* *
* @return void * @return void
*/ */
public function testBridgy() public function testCreatePhotoLinkWithNonCachedImage()
{ {
$url = 'https://brid-gy.appspot.com/comment/twitter/jonnybarnes/497778866816299008/497781260937203712'; $homepage = 'https://example.org/profile.png';
$expected = 'https://twitter.com/_/status/497781260937203712'; $expected = 'https://example.org/profile.png';
$this->assertEquals($expected, $this->notesController->bridgyReply($url)); $this->assertEquals($expected, $this->notesController->createPhotoLink($homepage));
} }
/** /**
@ -147,10 +148,10 @@ class NotesTest extends TestCase
* *
* @return void * @return void
*/ */
public function testCreatePhotoLinkWithGenericURL() public function testCreatePhotoLinkWithCachedImage()
{ {
$homepage = 'https://example.org'; $homepage = 'https://aaronparecki.com/profile.png';
$expected = '/assets/profile-images/example.org/image'; $expected = '/assets/profile-images/aaronparecki.com/image';
$this->assertEquals($expected, $this->notesController->createPhotoLink($homepage)); $this->assertEquals($expected, $this->notesController->createPhotoLink($homepage));
} }
@ -159,7 +160,7 @@ class NotesTest extends TestCase
* *
* @return void * @return void
*/ */
public function testCreatePhotoLinkWithTwitterProfileImageURL() public function testCreatePhotoLinkWithTwimgProfileImageURL()
{ {
$twitterProfileImage = 'http://pbs.twimg.com/1234'; $twitterProfileImage = 'http://pbs.twimg.com/1234';
$expected = 'https://pbs.twimg.com/1234'; $expected = 'https://pbs.twimg.com/1234';
@ -171,9 +172,11 @@ class NotesTest extends TestCase
* *
* @return void * @return void
*/ */
public function testCreatePhotoLinkWithTwitterURL() public function testCreatePhotoLinkWithCachedTwitterURL()
{ {
$twitterURL = 'https://twitter.com/example'; $twitterURL = 'https://twitter.com/example';
$this->assertNull($this->notesController->createPhotoLink($twitterURL)); $expected = 'https://pbs.twimg.com/static_profile_link.jpg';
Cache::put($twitterURL, $expected, 1);
$this->assertEquals($expected, $this->notesController->createPhotoLink($twitterURL));
} }
} }

View file

@ -0,0 +1,29 @@
<?php
namespace App\Tests;
use TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ProcessWebMentionTest extends TestCase
{
protected $appurl;
public function setUp()
{
parent::setUp();
$this->appurl = config('app.url');
}
/**
* A basic test.
*
* @return void
*/
public function testExample()
{
}
}

92
tests/WebMentionsTest.php Normal file
View file

@ -0,0 +1,92 @@
<?php
namespace App\Tests;
use TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class WebMentionsTest extends TestCase
{
protected $appurl;
public function setUp()
{
parent::setUp();
$this->appurl = config('app.url');
}
/**
* Test webmentions without source and target are rejected.
*
* @return void
*/
public function testWebmentionsWithoutSourceAndTargetAreRejected()
{
$this->call('POST', $this->appurl . '/webmention', ['source' => 'https://example.org/post/123']);
$this->assertResponseStatus(400)
->see('You need both the target and source parameters');
}
/**
* Test invalid target gets a 400 response.
*
* @return void
*/
public function testInvalidTargetReturns400Response()
{
$this->call('POST', $this->appurl . '/webmention', [
'source' => 'https://example.org/post/123',
'target' => $this->appurl . '/invalid/target'
]);
$this->assertResponseStatus(400)
->see('Invalid request');
}
/**
* Test blog target gets a 501 response.
*
* @return void
*/
public function testBlogpostTargetReturns501Response()
{
$this->call('POST', $this->appurl . '/webmention', [
'source' => 'https://example.org/post/123',
'target' => $this->appurl . '/blog/target'
]);
$this->assertResponseStatus(501)
->see('I dont accept webmentions for blog posts yet.');
}
/**
* Test that a non-existant note gives a 400 response.
*
* @return void
*/
public function testNonexistantNoteReturns400Response()
{
$this->call('POST', $this->appurl . '/webmention', [
'source' => 'https://example.org/post/123',
'target' => $this->appurl . '/notes/ZZZZZ'
]);
$this->assertResponseStatus(400)
->see('This note doesnt exist.');
}
/**
* Test a legit webmention triggers the ProcessWebMention job.
*
* @return void
*/
public function testLegitimateWebmnetionTriggersProcessWebMentionJob()
{
$this->expectsJobs(\App\Jobs\ProcessWebMention::class);
$this->call('POST', $this->appurl . '/webmention', [
'source' => 'https://example.org/post/123',
'target' => $this->appurl . '/notes/B'
]);
$this->assertResponseStatus(202)
->see('Webmention received, it will be processed shortly');
}
}