Merge branch 'release/0.0.1'

This commit is contained in:
Jonny Barnes 2016-05-25 15:39:33 +01:00
commit 342a71c976
293 changed files with 17485 additions and 0 deletions

52
.env.example Normal file
View file

@ -0,0 +1,52 @@
APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString
APP_TIMEZONE=UTC
APP_LANG=en
APP_LOG=daily
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
DB_CONNECTION=pgsql
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAILGUN_DOMAIN=null
MAILGUN_SECRET=null
AWS_S3_KEY=your-key
AWS_S3_SECRET=your-secret
AWS_S3_REGION=region
AWS_S3_BUCKET=your-bucket
AWS_S3_URL=https://xxxxxxx.s3-region.amazonaws.com
APP_URL=https://example.com
APP_LONGURL=example.com
APP_SHORTURL=examp.le
ADMIN_USER=admin
ADMIN_PASS=password
PIWIK_URL=
PIWIK_SITE_ID=
TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=

11
.env.travis Normal file
View file

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

3
.gitattributes vendored Normal file
View file

@ -0,0 +1,3 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored

11
.gitignore vendored Normal file
View file

@ -0,0 +1,11 @@
/vendor
/node_modules
/bower_components
/public/storage
Homestead.yaml
Homestead.json
.env
/.sass-cache
/public/files
/public/keybase.txt
/coverage

7
.styleci.yml Normal file
View file

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

42
.travis.yml Normal file
View file

@ -0,0 +1,42 @@
language: php
sudo: false
addons:
postgresql: "9.4"
services:
- postgresql
env:
global:
- setup=basic
php:
- 7.0
- nightly
matrix:
allow_failures:
- php: nightly
before_install:
- phpenv config-rm xdebug.ini
- travis_retry composer self-update --preview
install:
- if [[ $setup = 'basic' ]]; then travis_retry composer install --no-interaction --prefer-dist; fi
- if [[ $setup = 'stable' ]]; then travis_retry composer update --no-interaction --prefer-dist --prefer-stable; fi
- if [[ $setup = 'lowest' ]]; then travis_retry composer update --no-interaction --prefer-dist --prefer-lowest --prefer-stable; fi
before_script:
- psql -U travis -c 'create database travis_ci_test'
- psql -U travis -d travis_ci_test -c 'create extension postgis'
- cp .env.travis .env
- php artisan key:generate
- php artisan migrate
- php artisan db:seed
- php artisan serve &
- sleep 5 # Give artisan some time to start serving
script:
- phpdbg -qrr vendor/bin/phpunit --coverage-text

148
app/Article.php Normal file
View file

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

22
app/Client.php Normal file
View file

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

View file

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

30
app/Console/Kernel.php Normal file
View file

@ -0,0 +1,30 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
// Commands\Inspire::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
}

22
app/Contact.php Normal file
View file

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

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

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

View file

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

View file

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

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

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

@ -0,0 +1,55 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\LinkHeadersMiddleware::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'myauth' => \App\Http\Middleware\MyAuthMiddleware::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

View file

@ -0,0 +1,30 @@
<?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

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends BaseEncrypter
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

View file

@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use Closure;
class LinkHeadersMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Link', '<https://indieauth.com/auth>; rel="authorization_endpoint"', false);
$response->header('Link', config('app.url') . '/api/token>; rel="token_endpoint"', false);
$response->header('Link', config('app.url') . '/api/post>; rel="micropub"', false);
$response->header('Link', config('app.url') . '/webmention>; rel="webmention"', false);
return $response;
}
}

View file

@ -0,0 +1,25 @@
<?php
namespace App\Http\Middleware;
use Closure;
class MyAuthMiddleware
{
/**
* Check the user is logged in.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->session()->has('loggedin') !== true) {
//theyre not logged in, so send them to login form
return redirect()->route('login');
}
return $next($request);
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* 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)->check()) {
return redirect('/');
}
return $next($request);
}
}

View file

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

View file

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

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

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

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

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

View file

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

View file

@ -0,0 +1,86 @@
<?php
namespace App\Jobs;
use GuzzleHttp\Client;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendWebMentions extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $url;
protected $source;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($url, $source)
{
$this->url = $url;
$this->source = $source;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Client $client)
{
$endpoint = $this->discoverWebmentionEndpoint($this->url, $client);
if ($endpoint) {
$client->post($endpoint, [
'form_params' => [
'source' => $this->source,
'target' => $this->url,
],
]);
}
}
/**
* Discover if a URL has a webmention endpoint.
*
* @param string The URL
* @param \GuzzleHttp\Client $client
* @return string The webmention endpoint URL
*/
private function discoverWebmentionEndpoint($url, $client)
{
$endpoint = null;
$response = $client->get($url);
//check HTTP Headers for webmention endpoint
$links = \GuzzleHttp\Psr7\parse_header($response->getHeader('Link'));
foreach ($links as $link) {
if ($link['rel'] == 'webmention') {
return trim($link[0], '<>');
}
}
//failed to find a header so parse HTML
$html = (string) $response->getBody();
$mf2 = new \Mf2\Parser($html, $url);
$rels = $mf2->parseRelsAndAlternates();
if (array_key_exists('webmention', $rels[0])) {
$endpoint = $rels[0]['webmention'][0];
} elseif (array_key_exists('http://webmention.org/', $rels[0])) {
$endpoint = $rels[0]['http://webmention.org/'][0];
}
if ($endpoint) {
if (filter_var($endpoint, FILTER_VALIDATE_URL)) {
return $endpoint;
}
//it must be a relative url, so resolve with php-mf2
return $mf2->resolveUrl($endpoint);
}
return false;
}
}

View file

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

1
app/Listeners/.gitkeep Normal file
View file

@ -0,0 +1 @@

230
app/Note.php Normal file
View file

@ -0,0 +1,230 @@
<?php
namespace App;
use Normalizer;
use Jonnybarnes\IndieWeb\Numbers;
use Illuminate\Database\Eloquent\Model;
use Jonnybarnes\UnicodeTools\UnicodeTools;
use League\CommonMark\CommonMarkConverter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMedia;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Note extends Model implements HasMedia
{
use SoftDeletes;
use HasMediaTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'notes';
/**
* Define the relationship with tags.
*
* @var array
*/
public function tags()
{
return $this->belongsToMany('App\Tag');
}
/**
* Define the relationship with webmentions.
*
* @var array
*/
public function webmentions()
{
return $this->morphMany('App\WebMention', 'commentable');
}
/**
* Definte the relationship with places.
*
* @var array
*/
public function place()
{
return $this->belongsTo('App\Place');
}
/**
* We shall set a blacklist of non-modifiable model attributes.
*
* @var array
*/
protected $guarded = ['id'];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* A mutator to ensure that in-reply-to is always non-empty or null.
*
* @param string value
* @return string
*/
public function setInReplyToAttribute($value)
{
$this->attributes['in_reply_to'] = empty($value) ? null : $value;
}
/**
* Normalize the note to Unicode FORM C.
*
* @param string $value
* @return string
*/
public function setNoteAttribute($value)
{
$this->attributes['note'] = normalizer_normalize($value, Normalizer::FORM_C);
}
/**
* Pre-process notes for web-view.
*
* @param string
* @return string
*/
public function getNoteAttribute($value)
{
$unicode = new UnicodeTools();
$codepoints = $unicode->convertUnicodeCodepoints($value);
$markdown = new CommonMarkConverter();
$html = $markdown->convertToHtml($codepoints);
$hcards = $this->makeHCards($html);
$hashtags = $this->autoLinkHashtag($hcards);
return $hashtags;
}
/**
* Generate the NewBase60 ID from primary ID.
*
* @return string
*/
public function getNb60idAttribute()
{
$numbers = new Numbers();
return $numbers->numto60($this->id);
}
/**
* The Long URL for a note.
*
* @return string
*/
public function getLongurlAttribute()
{
return config('app.url') . '/notes/' . $this->nb60id;
}
/**
* The Short URL for a note.
*
* @return string
*/
public function getShorturlAttribute()
{
return config('app.shorturl') . '/notes/' . $this->nb60id;
}
/**
* Get the relavent client name assocaited with the client id.
*
* @return string|null
*/
public function getClientNameAttribute()
{
if ($this->client_id == null) {
return;
}
$name = Client::where('client_url', $this->client_id)->value('client_name');
if ($name == null) {
$url = parse_url($this->client_id);
if (isset($url['path'])) {
return $url['host'] . $url['path'];
}
return $url['host'];
}
return $name;
}
/**
* Take note that this method does two things, given @username (NOT [@username](URL)!)
* we try to create a fancy hcard from our contact info. If this is not possible
* due to lack of contact info, we assume @username is a twitter handle and link it
* as such.
*
* @param string The notes text
* @return string
*/
private function makeHCards($text)
{
$regex = '/\[.*?\](*SKIP)(*F)|@(\w+)/'; //match @alice but not [@bob](...)
$hcards = preg_replace_callback(
$regex,
function ($matches) {
try {
$contact = Contact::where('nick', '=', mb_strtolower($matches[1]))->firstOrFail();
} catch (ModelNotFoundException $e) {
return '<a href="https://twitter.com/' . $matches[1] . '">' . $matches[0] . '</a>';
}
$path = parse_url($contact->homepage)['host'];
$contact->photo = (file_exists(public_path() . '/assets/profile-images/' . $path . '/image')) ?
'/assets/profile-images/' . $path . '/image'
:
'/assets/profile-images/default-image';
return trim(view('mini-hcard-template', ['contact' => $contact])->render());
},
$text
);
return $hcards;
}
/**
* Given a string and section, finds all hashtags matching
* `#[\-_a-zA-Z0-9]+` and wraps them in an `a` element with
* `rel=tag` set and a `href` of 'section/tagged/' + tagname without the #.
*
* @param string The note
* @return string
*/
private function autoLinkHashtag($text)
{
// $replacements = ["#tag" => "<a rel="tag" href="/tags/tag">#tag</a>]
$replacements = [];
$matches = [];
if (preg_match_all('/(?<=^|\s)\#([a-zA-Z0-9\-\_]+)/i', $text, $matches, PREG_PATTERN_ORDER)) {
// Look up #tags, get Full name and URL
foreach ($matches[0] as $name) {
$name = str_replace('#', '', $name);
$replacements[$name] =
'<a rel="tag" class="p-category" href="/notes/tagged/' . $name . '">#' . $name . '</a>';
}
// Replace #tags with valid microformat-enabled link
foreach ($replacements as $name => $replacement) {
$text = str_replace('#' . $name, $replacement, $text);
}
}
return $text;
}
}

133
app/Place.php Normal file
View file

@ -0,0 +1,133 @@
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
use Phaza\LaravelPostgis\Geometries\Point;
use MartinBean\Database\Eloquent\Sluggable;
use Phaza\LaravelPostgis\Geometries\Polygon;
use Phaza\LaravelPostgis\Eloquent\PostgisTrait;
class Place extends Model
{
use PostgisTrait;
/*
* We want to turn the names into slugs.
*/
use Sluggable;
const DISPLAY_NAME = 'name';
const SLUG = 'slug';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'slug'];
/**
* The attributes that are Postgis geometry objects.
*
* @var array
*/
protected $postgisFields = [Point::class, Polygon::class];
/**
* Define the relationship with Notes.
*
* @var array
*/
public function notes()
{
return $this->hasMany('App\Note');
}
/**
* Get all places within a specified distance.
*
* @param float latitude
* @param float longitude
* @param int maximum distance
* @todo Check this shit.
*/
public static function near(float $lat, float $lng, int $distance)
{
$point = $lng . ' ' . $lat;
$distace = $distance ?? 1000;
$places = DB::select(DB::raw("select
name,
slug,
ST_AsText(location) AS location,
ST_Distance(
ST_GeogFromText('SRID=4326;POINT($point)'),
location
) AS distance
from places
where ST_DWithin(
ST_GeogFromText('SRID=4326;POINT($point)'),
location,
$distance
) ORDER BY distance"));
return $places;
}
/**
* Convert location to text.
*
* @param text $value
* @return text
*/
public function getLocationAttribute($value)
{
$result = DB::select(DB::raw("SELECT ST_AsText('$value')"));
return $result[0]->st_astext;
}
/**
* Get the latitude from the `location` property.
*
* @return string latitude
*/
public function getLatitudeAttribute()
{
preg_match('/\((.*)\)/', $this->location, $latlng);
return explode(' ', $latlng[1])[1];
}
/**
* Get the longitude from the `location` property.
*
* @return string longitude
*/
public function getLongitudeAttribute()
{
preg_match('/\((.*)\)/', $this->location, $latlng);
return explode(' ', $latlng[1])[0];
}
/**
* The Long URL for a place.
*
* @return string
*/
public function getLongurlAttribute()
{
return config('app.url') . '/places/' . $this->slug;
}
/**
* The Short URL for a place.
*
* @return string
*/
public function getShorturlAttribute()
{
return config('app.shorturl') . '/places/' . $this->slug;
}
}

1
app/Policies/.gitkeep Normal file
View file

@ -0,0 +1 @@

View file

@ -0,0 +1,57 @@
<?php
namespace App\Providers;
use App\Tag;
use App\Note;
use Validator;
use Jonnybarnes\IndieWeb\NotePrep;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Validate photos for a maximum filesize
Validator::extend('photosize', function ($attribute, $value, $parameters, $validator) {
if ($value[0] !== null) {
foreach ($value as $file) {
if ($file->getSize() > 5000000) {
return false;
}
}
}
return true;
});
//Add tags for notes
Note::created(function ($note) {
$noteprep = new NotePrep();
$tagsToAdd = [];
$tags = $noteprep->getTags($note->note);
foreach ($tags as $text) {
$tag = Tag::firstOrCreate(['tag' => $text]);
$tagsToAdd[] = $tag->id;
}
if (count($tagsToAdd > 0)) {
$note->tags()->attach($tagsToAdd);
}
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace App\Providers;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
//
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$this->mapWebRoutes($router);
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
}

View file

@ -0,0 +1,113 @@
<?php
namespace App\Services;
class IndieAuthService
{
/**
* Given a domain, determing the assocaited authorization endpoint,
* if one exists.
*
* @param string The domain
* @param \IndieAuth\Client $client
* @return string|null
*/
public function getAuthorizationEndpoint($domain, $client)
{
return $client->discoverAuthorizationEndpoint($client->normalizeMeURL($domain));
}
/**
* Given an authorization endpoint, build the appropriate authorization URL.
*
* @param string $authEndpoint
* @param string $domain
* @param \IndieAuth\Client $client
* @return string
*/
public function buildAuthorizationURL($authEndpoint, $domain, $client)
{
$domain = $client->normalizeMeURL($domain);
$state = bin2hex(openssl_random_pseudo_bytes(16));
session(['state' => $state]);
$redirectURL = config('app.url') . '/indieauth';
$clientId = config('app.url') . '/notes/new';
$scope = 'post';
$authorizationURL = $client->buildAuthorizationURL(
$authEndpoint,
$domain,
$redirectURL,
$clientId,
$state,
$scope
);
return $authorizationURL;
}
/**
* Discover the token endpoint for a given domain.
*
* @param string The domain
* @param \IndieAuth\Client $client
* @return string|null
*/
public function getTokenEndpoint($domain, $client)
{
return $client->discoverTokenEndpoint($domain);
}
/**
* Retrieve a token from the token endpoint.
*
* @param array The relavent data
* @param \IndieAuth\Client $client
* @return array
*/
public function getAccessToken(array $data, $client)
{
return $client->getAccessToken(
$data['endpoint'],
$data['code'],
$data['me'],
$data['redirect_url'],
$data['client_id'],
$data['state']
);
}
/**
* Determine the Authorization endpoint, then verify the suplied code is
* valid.
*
* @param array The data.
* @param \IndieAuth\Client $client
* @return array|null
*/
public function verifyIndieAuthCode(array $data, $client)
{
$authEndpoint = $client->discoverAuthorizationEndpoint($data['me']);
if ($authEndpoint) {
return $client->verifyIndieAuthCode(
$authEndpoint,
$data['code'],
$data['me'],
$data['redirect_url'],
$data['client_id'],
$data['state']
);
}
}
/**
* Determine the micropub endpoint.
*
* @param string $domain
* @param \IndieAuth\Client $client
* @return string The endpoint
*/
public function discoverMicropubEndpoint($domain, $client)
{
return $client->discoverMicropubEndpoint($client->normalizeMeURL($domain));
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace App\Services;
use App\Note;
use App\Place;
use Illuminate\Http\Request;
use App\Jobs\SyndicateToTwitter;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Http\Controllers\WebMentionsController;
class NoteService
{
use DispatchesJobs;
/**
* Create a new note.
*
* @param \Illuminate\Http\Request $request
* @param string $clientId
* @return \App\Note $note
*/
public function createNote(Request $request, $clientId = null)
{
$note = Note::create(
[
'note' => $request->input('content'),
'in_reply_to' => $request->input('in-reply-to'),
'client_id' => $clientId,
]
);
$placeSlug = $request->input('location');
if ($placeSlug !== null && $placeSlug !== 'no-location') {
$place = Place::where('slug', '=', $placeSlug)->first();
$note->place()->associate($place);
$note->save();
}
//add images to media library
if ($request->hasFile('photo')) {
$files = $request->file('photo');
foreach ($files as $file) {
$note->addMedia($file)->toMediaLibraryOnDisk('images', 's3');
}
}
if ($request->input('webmentions')) {
$wmc = new WebMentionsController();
$wmc->send($note);
}
if (//micropub request, syndication sent as array
(is_array($request->input('mp-syndicate-to'))
&&
(in_array('twitter.com/jonnybarnes', $request->input('mp-syndicate-to')))
|| //micropub request, syndication sent as string
($request->input('mp-syndicate-to') == 'twitter.com/jonnybarnes')
|| //local admin cp request
($request->input('twitter') == true))
) {
$this->dispatch(new SyndicateToTwitter($note));
}
return $note;
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Services;
use App\Place;
use Illuminate\Http\Request;
use Phaza\LaravelPostgis\Geometries\Point;
class PlaceService
{
/**
* Create a place.
*
* @param \Illuminate\Http\Request $request
* @return \App\Place
*/
public function createplace(Request $request)
{
//well either have latitude and longitude sent together in a
//geo-url (micropub), or seperatley (/admin)
if ($request->input('geo') !== null) {
$parts = explode(':', $request->input('geo'));
$latlng = explode(',', $parts[1]);
$latitude = $latlng[0];
$longitude = $latlng[1];
}
if ($request->input('latitude') !== null) {
$latitude = $request->input('latitude');
$longitude = $request->input('longitude');
}
$place = new Place();
$place->name = $request->input('name');
$place->description = $request->input('description');
$place->location = new Point((float) $latitude, (float) $longitude);
$place->save();
return $place;
}
}

View file

@ -0,0 +1,54 @@
<?php
namespace App\Services;
use RuntimeException;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Builder;
use InvalidArgumentException;
use Lcobucci\JWT\Signer\Hmac\Sha256;
class TokenService
{
/**
* Generate a JWT token.
*
* @param array The data to be encoded
* @return string The signed token
*/
public function getNewToken(array $data): string
{
$signer = new Sha256();
$token = (new Builder())->set('me', $data['me'])
->set('client_id', $data['client_id'])
->set('scope', $data['scope'])
->set('date_issued', time())
->set('nonce', bin2hex(random_bytes(8)))
->sign($signer, env('APP_KEY'))
->getToken();
return $token;
}
/**
* Check the token signature is valid.
*
* @param string The token
* @return mixed
*/
public function validateToken($token)
{
$signer = new Sha256();
try {
$token = (new Parser())->parse((string) $token);
} catch (InvalidArgumentException $e) {
return;
} catch (RuntimeException $e) {
return;
}
if ($token->verify($signer, env('APP_KEY'))) {
//signuture valid
return $token;
}
}
}

39
app/Tag.php Normal file
View file

@ -0,0 +1,39 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'tags';
/**
* Define the relationship with tags.
*
* @var array
*/
public function notes()
{
return $this->belongsToMany('App\Note');
}
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['deleted'];
/**
* We shall set a blacklist of non-modifiable model attributes.
*
* @var array
*/
protected $guarded = ['id'];
}

26
app/User.php Normal file
View file

@ -0,0 +1,26 @@
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}

32
app/WebMention.php Normal file
View file

@ -0,0 +1,32 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class WebMention extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'webmentions';
/**
* Define the relationship.
*
* @var array
*/
public function commentable()
{
return $this->morphTo();
}
/**
* We shall set a blacklist of non-modifiable model attributes.
*
* @var array
*/
protected $guarded = ['id'];
}

51
artisan Executable file
View file

@ -0,0 +1,51 @@
#!/usr/bin/env php
<?php
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running. We will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php Normal file
View file

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

34
bootstrap/autoload.php Normal file
View file

@ -0,0 +1,34 @@
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Include The Compiled Class File
|--------------------------------------------------------------------------
|
| To dramatically increase your application's performance, you may use a
| compiled class file which contains all of the classes commonly used
| by a request. The Artisan "optimize" is used to create this file.
|
*/
$compiledPath = __DIR__.'/cache/compiled.php';
if (file_exists($compiledPath)) {
require $compiledPath;
}

2
bootstrap/cache/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

26
bower.json Normal file
View file

@ -0,0 +1,26 @@
{
"name": "jbuk-frontend",
"description": "",
"main": "",
"authors": [
"Jonny Barnes <jonny@jonnybarnes.uk>"
],
"license": "CC0-1.0",
"homepage": "https://github.com/jonnybarnes/jbl5",
"moduleType": [],
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"fetch": "~0.11.0",
"alertify.js": "alertifyjs#~1.0.5",
"store2": "~2.3.2",
"Autolinker.js": "~0.24.0",
"marked": "~0.3.5",
"sanitize-css": "^3.2.0"
}
}

4
changelog.md Normal file
View file

@ -0,0 +1,4 @@
# Changelog
## Version 0.0.1 (2016-05-25)
Initial release

74
composer.json Normal file
View file

@ -0,0 +1,74 @@
{
"name": "jonnybarnes/jonnybarnes.uk",
"description": "The code for jonnybanres.uk, based on Laravel 5.2",
"keywords": ["framework", "laravel", "indieweb"],
"license": "CC0-1.0",
"type": "project",
"require": {
"ext-intl": "*",
"php": ">=7.0.0",
"laravel/framework": "5.2.*",
"jonnybarnes/unicode-tools": "dev-master",
"jonnybarnes/indieweb": "dev-master",
"jonnybarnes/webmentions-parser": "dev-master",
"guzzlehttp/guzzle": "~6.0",
"predis/predis": "~1.0",
"thujohn/twitter": "~2.0",
"mf2/mf2": "~0.3",
"martinbean/laravel-sluggable-trait": "0.2.*",
"indieauth/client": "~0.1",
"ezyang/htmlpurifier": "~4.6",
"league/commonmark": "^0.13.0",
"spatie/laravel-medialibrary": "^3.5",
"league/flysystem-aws-s3-v3": "^1.0",
"phaza/laravel-postgis": "dev-master",
"lcobucci/jwt": "^3.1"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~4.0",
"symfony/css-selector": "2.8.*|3.0.*",
"symfony/dom-crawler": "2.8.*|3.0.*",
"barryvdh/laravel-debugbar": "~2.0",
"filp/whoops": "~2.0"
},
"repositories": [
{
"type": "vcs",
"url": "https://github.com/njbarrett/laravel-postgis"
}
],
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/TestCase.php"
]
},
"scripts": {
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
],
"post-install-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postInstall",
"php artisan optimize"
],
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan optimize"
]
},
"config": {
"preferred-install": "dist"
}
}

5039
composer.lock generated Normal file

File diff suppressed because it is too large Load diff

241
config/app.php Normal file
View file

@ -0,0 +1,241 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Short URL
|--------------------------------------------------------------------------
|
| The short URL for the application
|
*/
'shorturl' => env('APP_SHORTURL', 'http://shorturl.local'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => env('APP_TIMEZONE', 'UTC'),
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => env('APP_LANG', 'en'),
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'single'),
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
/*
* Laravel Debugbar
*/
Barryvdh\Debugbar\ServiceProvider::class,
/*
* Thujohns Twitter API client
*/
Thujohn\Twitter\TwitterServiceProvider::class,
/*
* Laravel Medialibrary
*/
Spatie\MediaLibrary\MediaLibraryServiceProvider::class,
/*
* Phazas Postgis library
*/
Phaza\LaravelPostgis\DatabaseServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Debugbar' => Barryvdh\Debugbar\Facade::class,
'Twitter' => Thujohn\Twitter\Facades\Twitter::class,
],
];

107
config/auth.php Normal file
View file

@ -0,0 +1,107 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| 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
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];

52
config/broadcasting.php Normal file
View file

@ -0,0 +1,52 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
*/
'default' => env('BROADCAST_DRIVER', 'pusher'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
//
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
],
];

81
config/cache.php Normal file
View file

@ -0,0 +1,81 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache'),
],
'memcached' => [
'driver' => 'memcached',
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => 'laravel',
];

35
config/compile.php Normal file
View file

@ -0,0 +1,35 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Additional Compiled Classes
|--------------------------------------------------------------------------
|
| Here you may specify additional classes to include in the compiled file
| generated by the `artisan optimize` command. These should be classes
| that are included on basically every request into the application.
|
*/
'files' => [
//
],
/*
|--------------------------------------------------------------------------
| Compiled File Providers
|--------------------------------------------------------------------------
|
| Here you may list service providers which define a "compiles" function
| that returns additional files that should be compiled, providing an
| easy way to get common files from any packages you are utilizing.
|
*/
'providers' => [
//
],
];

131
config/database.php Normal file
View file

@ -0,0 +1,131 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
],
'travis' => [
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'travis_ci_test',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
]
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'cluster' => false,
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
];

145
config/debugbar.php Normal file
View file

@ -0,0 +1,145 @@
<?php
return array(
/*
|--------------------------------------------------------------------------
| Debugbar Settings
|--------------------------------------------------------------------------
|
| Debugbar is enabled by default, when debug is set to true in app.php.
| You can override the value by setting enable to true or false instead of null.
|
*/
'enabled' => null,
/*
|--------------------------------------------------------------------------
| Storage settings
|--------------------------------------------------------------------------
|
| DebugBar stores data for session/ajax requests.
| You can disable this, so the debugbar stores data in headers/session,
| but this can cause problems with large data collectors.
| By default, file storage (in the storage folder) is used. Redis and PDO
| can also be used. For PDO, run the package migrations first.
|
*/
'storage' => array(
'enabled' => true,
'driver' => 'file', // redis, file, pdo
'path' => storage_path() . '/debugbar', // For file driver
'connection' => null, // Leave null for default connection (Redis/PDO)
),
/*
|--------------------------------------------------------------------------
| Vendors
|--------------------------------------------------------------------------
|
| Vendor files are included by default, but can be set to false.
| This can also be set to 'js' or 'css', to only include javascript or css vendor files.
| Vendor files are for css: font-awesome (including fonts) and highlight.js (css files)
| and for js: jquery and and highlight.js
| So if you want syntax highlighting, set it to true.
| jQuery is set to not conflict with existing jQuery scripts.
|
*/
'include_vendors' => true,
/*
|--------------------------------------------------------------------------
| Capture Ajax Requests
|--------------------------------------------------------------------------
|
| The Debugbar can capture Ajax requests and display them. If you don't want this (ie. because of errors),
| you can use this option to disable sending the data through the headers.
|
*/
'capture_ajax' => true,
/*
|--------------------------------------------------------------------------
| DataCollectors
|--------------------------------------------------------------------------
|
| Enable/disable DataCollectors
|
*/
'collectors' => array(
'phpinfo' => true, // Php version
'messages' => true, // Messages
'time' => true, // Time Datalogger
'memory' => true, // Memory usage
'exceptions' => true, // Exception displayer
'log' => true, // Logs from Monolog (merged in messages if enabled)
'db' => true, // Show database (PDO) queries and bindings
'views' => true, // Views with their data
'route' => true, // Current route information
'laravel' => false, // Laravel version and environment
'events' => false, // All events fired
'default_request' => false, // Regular or special Symfony request logger
'symfony_request' => true, // Only one can be enabled..
'mail' => true, // Catch mail messages
'logs' => false, // Add the latest log messages
'files' => false, // Show the included files
'config' => false, // Display config settings
'auth' => false, // Display Laravel authentication status
'session' => false, // Display session data in a separate tab
),
/*
|--------------------------------------------------------------------------
| Extra options
|--------------------------------------------------------------------------
|
| Configure some DataCollectors
|
*/
'options' => array(
'auth' => array(
'show_name' => false, // Also show the users name/email in the debugbar
),
'db' => array(
'with_params' => true, // Render SQL with the parameters substituted
'timeline' => false, // Add the queries to the timeline
'backtrace' => false, // EXPERIMENTAL: Use a backtrace to find the origin of the query in your files.
'explain' => array( // EXPERIMENTAL: Show EXPLAIN output on queries
'enabled' => false,
'types' => array('SELECT'), // array('SELECT', 'INSERT', 'UPDATE', 'DELETE'); for MySQL 5.6.3+
),
'hints' => true, // Show hints for common mistakes
),
'mail' => array(
'full_log' => false
),
'views' => array(
'data' => false, //Note: Can slow down the application, because the data can be quite large..
),
'route' => array(
'label' => true // show complete route on bar
),
'logs' => array(
'file' => null
),
),
/*
|--------------------------------------------------------------------------
| Inject Debugbar in Response
|--------------------------------------------------------------------------
|
| Usually, the debugbar is added just before <body>, by listening to the
| Response after the App is done. If you disable this, you have to add them
| in your template yourself. See http://phpdebugbar.com/docs/rendering.html
|
*/
'inject' => true,
);

72
config/filesystems.php Normal file
View file

@ -0,0 +1,72 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. A "local" driver, as well as a variety of cloud
| based drivers are available for your choosing. Just store away!
|
| Supported: "local", "ftp", "s3", "rackspace"
|
*/
'default' => 'local',
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => 's3',
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_S3_KEY'),
'secret' => env('AWS_S3_SECRET'),
'region' => env('AWS_S3_REGION'),
'bucket' => env('AWS_S3_BUCKET'),
],
'media' => [
'driver' => 'local',
'root' => public_path() . '/media',
],
],
];

View file

@ -0,0 +1,40 @@
<?php
return [
/*
* The filesystems on which to store added files and derived images by default. Choose
* one or more of the filesystems you configured in app/config/filesystems.php
*/
'defaultFilesystem' => 'media',
/*
* The maximum file size of an item in bytes. Adding a file
* that is larger will result in an exception.
*/
'max_file_size' => 1024 * 1024 * 10,
/*
* This queue will used to generate derived images.
* Leave empty to use the default queue.
*/
'queue_name' => '',
/*
* The class name of the media model to be used.
*/
'media_model' => Spatie\MediaLibrary\Media::class,
/*
* When urls to files get generated this class will be called. Leave empty
* if your files are stored locally above the site root or on s3.
*/
'custom_url_generator_class' => '',
's3' => [
/*
* The domain that should be prepended when generating urls.
*/
'domain' => env('AWS_S3_URL'),
],
];

112
config/mail.php Normal file
View file

@ -0,0 +1,112 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill",
| "ses", "sparkpost", "log"
|
*/
'driver' => env('MAIL_DRIVER', 'smtp'),
/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/
'port' => env('MAIL_PORT', 587),
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => ['address' => null, 'name' => null],
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
'username' => env('MAIL_USERNAME'),
/*
|--------------------------------------------------------------------------
| SMTP Server Password
|--------------------------------------------------------------------------
|
| Here you may set the password required by your SMTP server to send out
| messages from your application. This will be given to the server on
| connection so that the application will be able to send messages.
|
*/
'password' => env('MAIL_PASSWORD'),
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
];

85
config/queue.php Normal file
View file

@ -0,0 +1,85 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Driver
|--------------------------------------------------------------------------
|
| The Laravel queue API supports a variety of back-ends via an unified
| API, giving you convenient access to each back-end using the same
| syntax for each one. Here you may set the default queue driver.
|
| Supported: "null", "sync", "database", "beanstalkd", "sqs", "redis"
|
*/
'default' => env('QUEUE_DRIVER', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'ttr' => 60,
],
'sqs' => [
'driver' => 'sqs',
'key' => 'your-public-key',
'secret' => 'your-secret-key',
'prefix' => 'https://sqs.us-east-1.amazonaws.com/your-account-id',
'queue' => 'your-queue-name',
'region' => 'us-east-1',
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'expire' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

38
config/services.php Normal file
View file

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, Mandrill, and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
];

166
config/session.php Normal file
View file

@ -0,0 +1,166 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => 60 * 24 * 7,
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => null,
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => 'laravel_session',
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => null,
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => true,
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
];

18
config/ttwitter.php Normal file
View file

@ -0,0 +1,18 @@
<?php
// You can find the keys here : https://dev.twitter.com/
return [
'API_URL' => 'api.twitter.com',
'API_VERSION' => '1.1',
'AUTHENTICATE_URL' => 'https://api.twitter.com/oauth/authenticate',
'AUTHORIZE_URL' => 'https://api.twitter.com/oauth/authorize',
'ACCESS_TOKEN_URL' => 'oauth/access_token',
'REQUEST_TOKEN_URL' => 'oauth/request_token',
'USE_SSL' => true,
'CONSUMER_KEY' => env('TWITTER_CONSUMER_KEY'),
'CONSUMER_SECRET' => env('TWITTER_CONSUMER_SECRET'),
'ACCESS_TOKEN' => env('TWITTER_ACCESS_TOKEN'),
'ACCESS_TOKEN_SECRET' => env('TWITTER_ACCESS_TOKEN_SECRET'),
];

11
config/url.php Normal file
View file

@ -0,0 +1,11 @@
<?php
/*
* Here we set the long and short URLs our app shall use
* You can override these settings in the .env file
*/
return [
'longurl' => env('APP_LONGURL', 'jonnybarnes.uk'),
'shorturl' => env('APP_SHORTURL', 'jmb.so')
];

33
config/view.php Normal file
View file

@ -0,0 +1,33 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
realpath(base_path('resources/views')),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => realpath(storage_path('framework/views')),
];

1
database/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*.sqlite

View file

@ -0,0 +1,28 @@
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'password' => bcrypt(str_random(10)),
'remember_token' => str_random(10),
];
});
$factory->define(App\Note::class, function (Faker\Generator $faker) {
return [
'note' => $faker->paragraph,
'tweet_id' => $faker->randomNumber(9),
];
});

View file

@ -0,0 +1 @@

View file

@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (! Schema::hasTable('articles')) {
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('titleurl', 50)->unique();
$table->string('url', 120)->nullable();
$table->string('title');
$table->longText('main');
$table->tinyInteger('published')->default(0);
$table->timestamps();
$table->softDeletes();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('articles');
}
}

View file

@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (! Schema::hasTable('notes')) {
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->text('note');
$table->string('in_reply_to')->nullable();
$table->string('shorturl', 20)->nullable();
$table->string('location')->nullable();
$table->tinyInteger('photo')->nullable();
$table->string('tweet_id')->nullable();
$table->string('client_id')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('notes');
}
}

View file

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tag');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tags');
}
}

View file

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNoteTagTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('note_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('note_id')->unsigned();
$table->integer('tag_id')->unsigned();
$table->foreign('note_id')->references('id')->on('notes');
$table->foreign('tag_id')->references('id')->on('tags');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('note_tag');
}
}

View file

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateContactsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->string('nick');
$table->string('name');
$table->string('homepage')->nullable();
$table->string('twitter')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('contacts');
}
}

View file

@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateWebMentionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('webmentions', function (Blueprint $table)
{
$table->increments('id');
$table->string('source');
$table->string('target');
$table->integer('commentable_id')->nullable();
$table->string('commentable_type')->nullable();
$table->string('type')->nullable();
$table->text('content');
$table->tinyInteger('verified')->default(1);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('webmentions');
}
}

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClientsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->increments('id');
$table->string('client_url');
$table->string('client_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('clients');
}
}

View file

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFailedJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->increments('id');
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->timestamp('failed_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('failed_jobs');
}
}

View file

@ -0,0 +1,35 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMediaTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('media', function (Blueprint $table) {
$table->increments('id');
$table->morphs('model');
$table->string('collection_name');
$table->string('name');
$table->string('file_name');
$table->string('disk');
$table->unsignedInteger('size');
$table->text('manipulations');
$table->text('custom_properties');
$table->unsignedInteger('order_column')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::drop('media');
}
}

View file

@ -0,0 +1,35 @@
<?php
use Phaza\LaravelPostgis\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlacesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('places', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->point('location');
$table->polygon('polygon')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('places');
}
}

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