Initial commit to new repo

This commit is contained in:
Jonny Barnes 2016-05-19 15:01:28 +01:00
parent a267f9bfcc
commit a5173c981b
292 changed files with 17472 additions and 0 deletions

View file

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

View file

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

View file

@ -0,0 +1,69 @@
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Response;
use Jonnybarnes\IndieWeb\Numbers;
class ArticlesController extends Controller
{
/**
* Show all articles (with pagination).
*
* @return \Illuminate\View\Factory view
*/
public function showAllArticles($year = null, $month = null)
{
$articles = Article::where('published', '1')
->date($year, $month)
->orderBy('updated_at', 'desc')
->simplePaginate(5);
return view('multipost', ['data' => $articles]);
}
/**
* Show a single article.
*
* @return \Illuminate\View\Factory view
*/
public function singleArticle($year, $month, $slug)
{
$article = Article::where('titleurl', $slug)->first();
if ($article->updated_at->year != $year || $article->updated_at->month != $month) {
throw new \Exception;
}
return view('singlepost', ['article' => $article]);
}
/**
* We only have the ID, work out post title, year and month
* and redirect to it.
*
* @return \Illuminte\Routing\RedirectResponse redirect
*/
public function onlyIdInUrl($inURLId)
{
$numbers = new Numbers();
$realId = $numbers->b60tonum($inURLId);
$article = Article::findOrFail($realId);
return redirect($article->link);
}
/**
* Returns the RSS feed.
*
* @return \Illuminate\Http\Response
*/
public function makeRSS()
{
$articles = Article::where('published', '1')->orderBy('updated_at', 'desc')->get();
$buildDate = $articles->first()->updated_at->toRssString();
$contents = (string) view('rss', ['articles' => $articles, 'buildDate' => $buildDate]);
return (new Response($contents, '200'))->header('Content-Type', 'application/rss+xml');
}
}

View file

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

View file

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

View file

@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
/**
* Log in a user, set a sesion variable, check credentials against
* the .env file.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function login(Request $request)
{
if ($request->input('username') === env('ADMIN_USER')
&&
$request->input('password') === env('ADMIN_PASS')
) {
session(['loggedin' => true]);
return redirect()->intended('admin');
}
return redirect()->route('login');
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,14 @@
<?php
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\Auth\Access\AuthorizesResources;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
}

View file

@ -0,0 +1,164 @@
<?php
namespace App\Http\Controllers;
use IndieAuth\Client;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Services\TokenService;
use Illuminate\Cookie\CookieJar;
use App\Services\IndieAuthService;
class IndieAuthController extends Controller
{
/**
* This service isolates the IndieAuth Client code.
*/
protected $indieAuthService;
/**
* The IndieAuth Client implementation.
*/
protected $client;
/**
* The Token handling service.
*/
protected $tokenService;
/**
* Inject the dependencies.
*
* @param \App\Services\IndieAuthService $indieAuthService
* @param \IndieAuth\Client $client
* @return void
*/
public function __construct(
IndieAuthService $indieAuthService = null,
Client $client = null,
TokenService $tokenService = null
) {
$this->indieAuthService = $indieAuthService ?? new IndieAuthService();
$this->client = $client ?? new Client();
$this->tokenService = $tokenService ?? new TokenService();
}
/**
* Begin the indie auth process. This method ties in to the login page
* from our micropub client. Here we then query the users homepage
* for their authorisation endpoint, and redirect them there with a
* unique secure state value.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function beginauth(Request $request)
{
$authorizationEndpoint = $this->indieAuthService->getAuthorizationEndpoint(
$request->input('me'),
$this->client
);
if ($authorizationEndpoint) {
$authorizationURL = $this->indieAuthService->buildAuthorizationURL(
$authorizationEndpoint,
$request->input('me'),
$this->client
);
if ($authorizationURL) {
return redirect($authorizationURL);
}
}
return redirect('/notes/new')->withErrors('Unable to determine authorisation endpoint', 'indieauth');
}
/**
* Once they have verified themselves through the authorisation endpint
* the next step is retreiveing a token from the token endpoint.
*
* @param \Illuminate\Http\Rrequest $request
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function indieauth(Request $request)
{
if ($request->session()->get('state') != $request->input('state')) {
return redirect('/notes/new')->withErrors(
'Invalid <code>state</code> value returned from indieauth server',
'indieauth'
);
}
$tokenEndpoint = $this->indieAuthService->getTokenEndpoint($request->input('me'), $this->client);
$redirectURL = config('app.url') . '/indieauth';
$clientId = config('app.url') . '/notes/new';
$data = [
'endpoint' => $tokenEndpoint,
'code' => $request->input('code'),
'me' => $request->input('me'),
'redirect_url' => $redirectURL,
'client_id' => $clientId,
'state' => $request->input('state'),
];
$token = $this->indieAuthService->getAccessToken($data, $this->client);
if (array_key_exists('access_token', $token)) {
$request->session()->put('me', $token['me']);
$request->session()->put('token', $token['access_token']);
return redirect('/notes/new');
}
return redirect('/notes/new')->withErrors('Unable to get a token from the endpoint', 'indieauth');
}
/**
* If the user has authd via IndieAuth, issue a valid token.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function tokenEndpoint(Request $request)
{
$authData = [
'code' => $request->input('code'),
'me' => $request->input('me'),
'redirect_url' => $request->input('redirect_uri'),
'client_id' => $request->input('client_id'),
'state' => $request->input('state'),
];
$auth = $this->indieAuthService->verifyIndieAuthCode($authData, $this->client);
if (array_key_exists('me', $auth)) {
$scope = $auth['scope'] ?? '';
$tokenData = [
'me' => $request->input('me'),
'client_id' => $request->input('client_id'),
'scope' => $auth['scope'],
];
$token = $this->tokenService->getNewToken($tokenData);
$content = http_build_query([
'me' => $request->input('me'),
'scope' => $scope,
'access_token' => $token,
]);
return (new Response($content, 200))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
$content = 'There was an error verifying the authorisation code.';
return new Response($content, 400);
}
/**
* Log out the user, flush an session data, and overwrite any cookie data.
*
* @param \Illuminate\Cookie\CookieJar $cookie
* @return \Illuminate\Routing\RedirectResponse redirect
*/
public function indieauthLogout(Request $request, CookieJar $cookie)
{
$request->session()->flush();
$cookie->queue('me', 'loggedout', 5);
return redirect('/notes/new');
}
}

View file

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

View file

@ -0,0 +1,143 @@
<?php
namespace App\Http\Controllers;
use App\Place;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Services\NoteService;
use App\Services\TokenService;
use App\Services\PlaceService;
class MicropubController extends Controller
{
/**
* The Token service container.
*/
protected $tokenService;
/**
* The Note service container.
*/
protected $noteService;
/**
* The Place service container.
*/
protected $placeService;
/**
* Injest the dependency.
*/
public function __construct(
TokenService $tokenService = null,
NoteService $noteService = null,
PlaceService $placeService = null
) {
$this->tokenService = $tokenService ?? new TokenService();
$this->noteService = $noteService ?? new NoteService();
$this->placeService = $placeService ?? new PlaceService();
}
/**
* This function receives an API request, verifies the authenticity
* then passes over the info to the relavent Service class.
*
* @param \Illuminate\Http\Request request
* @return \Illuminate\Http\Response
*/
public function post(Request $request)
{
$httpAuth = $request->header('Authorization');
if (preg_match('/Bearer (.+)/', $httpAuth, $match)) {
$token = $match[1];
$tokenData = $this->tokenService->validateToken($token);
if ($tokenData->hasClaim('scope')) {
$scopes = explode(' ', $tokenData->getClaim('scope'));
if (array_search('post', $scopes) !== false) {
$clientId = $tokenData->getClaim('client_id');
$type = $request->input('h');
if ($type == 'entry') {
$note = $this->noteService->createNote($request, $clientId);
$content = 'Note created at ' . $note->longurl;
return (new Response($content, 201))
->header('Location', $note->longurl);
}
if ($type == 'card') {
$place = $this->placeService->createPlace($request);
$content = 'Place created at ' . $place->longurl;
return (new Response($content, 201))
->header('Location', $place->longurl);
}
}
}
$content = http_build_query([
'error' => 'invalid_token',
'error_description' => 'The token provided is not valid or does not have the necessary scope',
]);
return (new Response($content, 400))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
$content = 'No OAuth token sent with request.';
return new Response($content, 400);
}
/**
* A GET request has been made to `api/post` with an accompanying
* token, here we check wether the token is valid and respond
* appropriately. Further if the request has the query parameter
* synidicate-to we respond with the known syndication endpoints.
*
* @todo Move the syndication endpoints into a .env variable
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function getEndpoint(Request $request)
{
$httpAuth = $request->header('Authorization');
if (preg_match('/Bearer (.+)/', $httpAuth, $match)) {
$token = $match[1];
$valid = $this->tokenService->validateToken($token);
if ($valid === null) {
return new Response('Invalid token', 400);
}
//we have a valid token, is `syndicate-to` set?
if ($request->input('q') === 'syndicate-to') {
$content = http_build_query([
'mp-syndicate-to' => 'twitter.com/jonnybarnes',
]);
return (new Response($content, 200))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
//nope, how about a geo URL?
if (substr($request->input('q'), 0, 4) === 'geo:') {
$geo = explode(':', $request->input('q'));
$latlng = explode(',', $geo[1]);
$latitude = $latlng[0];
$longitude = $latlng[1];
$places = Place::near($latitude, $longitude, 1000);
return (new Response(json_encode($places), 200))
->header('Content-Type', 'application/json');
}
//nope, just return the token
$content = http_build_query([
'me' => $valid->getClaim('me'),
'scope' => $valid->getClaim('scope'),
'client_id' => $valid->getClaim('client_id'),
]);
return (new Response($content, 200))
->header('Content-Type', 'application/x-www-form-urlencoded');
}
$content = 'No OAuth token sent with request.';
return new Response($content, 400);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,100 @@
<?php
namespace App\Http\Controllers;
use App\Note;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Jobs\SendWebMentions;
use App\Jobs\ProcessWebMention;
use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class WebMentionsController extends Controller
{
/**
* Receive and process a webmention.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Respone
*/
public function receive(Request $request)
{
//first we trivially reject requets that lack all required inputs
if (($request->has('target') !== true) || ($request->has('source') !== true)) {
return new Response(
'You need both the target and source parameters',
400
);
}
//next check the $target is valid
$path = parse_url($request->input('target'))['path'];
$pathParts = explode('/', $path);
switch ($pathParts[1]) {
case 'notes':
//we have a note
$noteId = $pathParts[2];
$numbers = new Numbers();
$realId = $numbers->b60tonum($noteId);
try {
$note = Note::findOrFail($realId);
$this->dispatch(new ProcessWebMention($note, $request->input('source')));
} catch (ModelNotFoundException $e) {
return new Response('This note doesnt exist.', 400);
}
return new Response(
'Webmention received, it will be processed shortly',
202
);
break;
case 'blog':
return new Response(
'I dont accept webmentions for blog posts yet.',
501
);
break;
default:
return new Response(
'Invalid request',
400
);
break;
}
}
/**
* Send a webmention.
*
* @param \App\Note $note
* @return array An array of successful then failed URLs
*/
public function send(Note $note)
{
//grab the URLs
$urlsInReplyTo = explode(' ', $note->in_reply_to);
$urlsNote = $this->getLinks($note->note);
$urls = array_filter(array_merge($urlsInReplyTo, $urlsNote)); //filter out none URLs
foreach ($urls as $url) {
$this->dispatch(new SendWebMentions($url, $note->longurl));
}
}
/**
* Get the URLs from a note.
*/
private function getLinks($html)
{
$urls = [];
$dom = new \DOMDocument();
$dom->loadHTML($html);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$urls[] = ($anchor->hasAttribute('href')) ? $anchor->getAttribute('href') : false;
}
return $urls;
}
}